问:
Python 3: How to generate a table from a nested list as input
So, I've got the following nested list (which I've parsed from an Nmap XML output file). It's basically a list of IP addresses, and all their open ports:

```<code>[['192.168.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
 ['192.168.27.243', ['135', '139', '445', '3389', '5800', '5900']],
 ['192.168.99.164', ['135', '139', '445', '3389', '5800', '5900']],
 ['192.168.228.211', ['80']],
 ['192.168.171.74', ['135', '139', '445', '3389', '5800', '5900']]]
</code>```

I would like to create a table from this data, where each first item (all IP addresses) are printed as rows. I then wish to iterate over each second item (a list of all ports per IP address), and count each unique port number. I wish this new counted unique list of ports to be printed as column headers of my table. My empty table should then roughly look like this:

```<code>                 53  80  88  135  139  389  445  3389  5800  5900
192.168.23.78
192.168.27.243
192.168.99.164
192.168.228.211
192.168.171.74
</code>```

And then I wish to place X's in each correct cell for each IP address that has a given open port, like so:

```<code>                 53  80  88  135  139  389  445  3389  5800  5900
192.168.23.78    X   X       X    X    X         X
192.168.27.243               X    X         X    X     X     X
192.168.99.164               X    X         X    X     X     X
192.168.228.211      X
192.168.171.74               X    X         X    X     X     X
</code>```

How would I do this with my data set?

I'm a total newbie, but I could likely figure out how to iterate over all the port numbers and get a unique port list. But I have absolutely not clue how to then plot X's on the table, in the correct cells

This is my code so far:

#!/usr/bin/env python

from pprint import pprint
import xml.etree.ElementTree as ET

def loopy(item):
    for port in host.findall('ports/port'):
        if port.get('protocol') == "tcp":
            portid = port.get('portid')
            for state in port.findall('state'):
                if state.get('state') == "open":
                    if item == "address":
                        list_addr.append(addr)
                        return
                    elif item == "portid":
                        list_portid.append(portid)

root = ET.parse('scan5.xml').getroot()
result = []
for host in root.findall('host'):
    list_portid = []
    list_addr = []
    address = host.find('address')
    addr = address.get('addr')
    loopy("address")
    loopy("portid")
    if list_addr:
        result.append([list_addr[0], list_portid])

pprint(result)
```

<p>My nested list is in now <code>result</code>, but I have no clue how to create a table from this.</p>

<p>So far my code only produces the raw list:</p>

```[['10.133.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
 ['10.133.27.243', ['135', '139', '445', '3389', '5800', '5900']],
 ['10.133.99.164', ['135', '139', '445', '3389', '5800', '5900']],
 ['10.135.228.211', ['80']],
 ['10.133.171.74', ['135', '139', '445', '3389', '5800', '5900']]]
```

答:
Using numpy and pandas you could do

```<code>import pandas as pd
import numpy as np

table = [['192.168.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
         ['192.168.27.243', ['135', '139', '445', '3389', '5800', '5900']],
         ['192.168.99.164', ['135', '139', '445', '3389', '5800', '5900']],
         ['192.168.228.211', ['80']],
         ['192.168.171.74', ['135', '139', '445', '3389', '5800', '5900']]]

# Collect the ip_addresses
ip_addresses = [el[0] for el in table]

# Collect the column names. Temporarily convert to integers to sort them properly
columns = sorted(np.unique([c for el in table for c in el[1]]), key = lambda x: int(x))

# Initialize numpy matrix to hold strings
table_matrix = np.zeros((len(ip_addresses), len(columns)), str)

for row in table:
    # Get the row index of the IP address
    for i, ip in enumerate(ip_addresses):
        if row[0] == ip:
            rdx = i
    # Check which columns have values in the row that corresponds to the IP address
    for c in row[1]:
        for j, col in enumerate(columns):
            # Add an X if the row has that column
            if c == col:
                table_matrix[rdx, j] = 'X'

# Create DataFrame
df = pd.DataFrame(table_matrix, index = ip_addresses, columns = columns)
</code>```

Output:

```<code>Out[24]:
                53 80 88 135 139 389 445 3389 5800 5900
192.168.23.78    X     X   X   X   X   X    X
192.168.27.243             X   X       X    X    X    X
192.168.99.164             X   X       X    X    X    X
192.168.228.211     X
192.168.171.74             X   X       X    X    X    X
</code>```

Body:
So, I've got the following nested list (which I've parsed from an Nmap XML output file). It's basically a list of IP addresses, and all their open ports:

[['192.168.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
 ['192.168.27.243', ['135', '139', '445', '3389', '5800', '5900']],
 ['192.168.99.164', ['135', '139', '445', '3389', '5800', '5900']],
 ['192.168.228.211', ['80']],
 ['192.168.171.74', ['135', '139', '445', '3389', '5800', '5900']]]

I would like to create a table from this data, where each first item (all IP addresses) are printed as rows. I then wish to iterate over each second item (a list of all ports per IP address), and count each unique port number. I wish this new counted unique list of ports to be printed as column headers of my table. My empty table should then roughly look like this:

                 53  80  88  135  139  389  445  3389  5800  5900
192.168.23.78
192.168.27.243
192.168.99.164
192.168.228.211
192.168.171.74

And then I wish to place X's in each correct cell for each IP address that has a given open port, like so:

                 53  80  88  135  139  389  445  3389  5800  5900
192.168.23.78    X   X       X    X    X         X
192.168.27.243               X    X         X    X     X     X
192.168.99.164               X    X         X    X     X     X
192.168.228.211      X
192.168.171.74               X    X         X    X     X     X

How would I do this with my data set?

I'm a total newbie, but I could likely figure out how to iterate over all the port numbers and get a unique port list. But I have absolutely not clue how to then plot X's on the table, in the correct cells

This is my code so far:

#!/usr/bin/env python

from pprint import pprint
import xml.etree.ElementTree as ET

def loopy(item):
    for port in host.findall('ports/port'):
        if port.get('protocol') == "tcp":
            portid = port.get('portid')
            for state in port.findall('state'):
                if state.get('state') == "open":
                    if item == "address":
                        list_addr.append(addr)
                        return
                    elif item == "portid":
                        list_portid.append(portid)

root = ET.parse('scan5.xml').getroot()
result = []
for host in root.findall('host'):
    list_portid = []
    list_addr = []
    address = host.find('address')
    addr = address.get('addr')
    loopy("address")
    loopy("portid")
    if list_addr:
        result.append([list_addr[0], list_portid])

pprint(result)

My nested list is in now result, but I have no clue how to create a table from this.

So far my code only produces the raw list:

[['10.133.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
 ['10.133.27.243', ['135', '139', '445', '3389', '5800', '5900']],
 ['10.133.99.164', ['135', '139', '445', '3389', '5800', '5900']],
 ['10.135.228.211', ['80']],
 ['10.133.171.74', ['135', '139', '445', '3389', '5800', '5900']]]

Body:
Using numpy and pandas you could do

import pandas as pd
import numpy as np

table = [['192.168.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
         ['192.168.27.243', ['135', '139', '445', '3389', '5800', '5900']],
         ['192.168.99.164', ['135', '139', '445', '3389', '5800', '5900']],
         ['192.168.228.211', ['80']],
         ['192.168.171.74', ['135', '139', '445', '3389', '5800', '5900']]]

# Collect the ip_addresses
ip_addresses = [el[0] for el in table]

# Collect the column names. Temporarily convert to integers to sort them properly
columns = sorted(np.unique([c for el in table for c in el[1]]), key = lambda x: int(x))

# Initialize numpy matrix to hold strings
table_matrix = np.zeros((len(ip_addresses), len(columns)), str)

for row in table:
    # Get the row index of the IP address
    for i, ip in enumerate(ip_addresses):
        if row[0] == ip:
            rdx = i
    # Check which columns have values in the row that corresponds to the IP address
    for c in row[1]:
        for j, col in enumerate(columns):
            # Add an X if the row has that column
            if c == col:
                table_matrix[rdx, j] = 'X'

# Create DataFrame
df = pd.DataFrame(table_matrix, index = ip_addresses, columns = columns)

Output:

Out[24]:
                53 80 88 135 139 389 445 3389 5800 5900
192.168.23.78    X     X   X   X   X   X    X
192.168.27.243             X   X       X    X    X    X
192.168.99.164             X   X       X    X    X    X
192.168.228.211     X
192.168.171.74             X   X       X    X    X    X


来源: stackexchange

问:
Is there any way to set kerning to SKLabelNode for iOS 10 and newer?
I'd like to set some kerning to SKLabelNode. I used NSAttributedString and this solution working fine on iOS 11 or newer.

But I need to support iOS 10 too. Is there any way to set kerning that support iOS 10 and newer?

class Caption: SKLabelNode {

    static func addNode(at position: CGPoint, isBold: Bool, text: String) -> Caption {

        let font = isBold ? "Roboto-Bold" : "Roboto-Regular"

        let attr: [NSAttributedString.Key: Any] = [
            .font: UIFont(name: font, size: 16)!,
            .foregroundColor: SKColor.white,
            .kern: 2.0
        ]

        let caption = Caption(attributedText: NSAttributedString(string: text.uppercased(), attributes: attr))
        caption.horizontalAlignmentMode = .center
        caption.verticalAlignmentMode = .top
        caption.position = position
        return caption
    }
}
```

<p>Xcode says: <code>'init(attributedText:)' is only available on iOS 11 or newer.</code></p>

<pre class="lang-swift prettyprint-override"><code>let caption = Caption(attributedText: NSAttributedString(string: text.uppercased(), attributes: attr))
</code>```

答:
The answer is no.  You are going to have to come up with a different method like render with a UILabel, extract a UIImage out of it, use the UIImage on an SKSpriteNode.

Of course, the most simple solution is to just abandon iOS 10 support  (something like 5% of iOS users are on iOS 10)

ContentLicense: CC BY-SA 4.0

Body:
I'd like to set some kerning to SKLabelNode. I used NSAttributedString and this solution working fine on iOS 11 or newer.

But I need to support iOS 10 too. Is there any way to set kerning that support iOS 10 and newer?

class Caption: SKLabelNode {

    static func addNode(at position: CGPoint, isBold: Bool, text: String) -> Caption {

        let font = isBold ? "Roboto-Bold" : "Roboto-Regular"

        let attr: [NSAttributedString.Key: Any] = [
            .font: UIFont(name: font, size: 16)!,
            .foregroundColor: SKColor.white,
            .kern: 2.0
        ]

        let caption = Caption(attributedText: NSAttributedString(string: text.uppercased(), attributes: attr))
        caption.horizontalAlignmentMode = .center
        caption.verticalAlignmentMode = .top
        caption.position = position
        return caption
    }
}

Xcode says: 'init(attributedText:)' is only available on iOS 11 or newer.

let caption = Caption(attributedText: NSAttributedString(string: text.uppercased(), attributes: attr))


问:
Insert if not exists, if exists update
I'm getting usersfrom this API.

https://redmine-mock-api.herokuapp.com/api/v1/users

There are 100 in total (100 different ids). I added them to my mongodb database using mongoose but the problem is that it's always adding (i already have 5000 users (50 times repeated 100 users)

I want to add if the id does not exist or update if it exists.

What am I doing wrong? users is the array of users from the API

```<code> db.collection("users").insertMany(users, function (error, response) {
                        if (error) throw error;
                        console.log("Number of users inserted: " + response.insertedCount);
                        db.close();
                    });
</code>```

答:
Looking at the mongo db docs it looks like insertMany is not what you want to use here. You probably want to use updateMany as it supports upserts where insertMany doesn't.

You should be able to use something like this:

```<code>db.collection("users").updateMany(
   {},
   users,
   {
     upsert: true
   }
)
</code>```

This is using an empty filter so will insert if the item doesn't exist or update if it does.

Title: Insert if not exists, if exists update

Body:
I'm getting usersfrom this API.

https://redmine-mock-api.herokuapp.com/api/v1/users

There are 100 in total (100 different ids). I added them to my mongodb database using mongoose but the problem is that it's always adding (i already have 5000 users (50 times repeated 100 users)

I want to add if the id does not exist or update if it exists.

What am I doing wrong? users is the array of users from the API

 db.collection("users").insertMany(users, function (error, response) {
                        if (error) throw error;
                        console.log("Number of users inserted: " + response.insertedCount);
                        db.close();
                    });

Body:
Looking at the mongo db docs it looks like insertMany is not what you want to use here. You probably want to use updateMany as it supports upserts where insertMany doesn't.

You should be able to use something like this:

db.collection("users").updateMany(
   {},
   users,
   {
     upsert: true
   }
)

This is using an empty filter so will insert if the item doesn't exist or update if it does.


问:
Call smart contract function by web3.js without response
I was watching the tutorial on Youtube and following the instruction:
https://www.youtube.com/watch?time_continue=1350&v=msT3tpwnyv8

When I try to call the function with the js file below, it returned nothing on the console. Does anyone know what happened?

I am using,
web3.js 1.0.0 beta. 52
infura to connect

```<code>var Tx = require('ethereumjs-tx')

const Web3 = require('web3');
const web3 = new Web3('https://ropsten.infura.io/v3/project_id')

const contractAddress = '0xd03696B53924972b9903eB17Ac5033928Be7D3Bc'
const contractABI = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"standard","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"}]

var contract = new web3.eth.Contract(contractABI, contractAddress)

contract.methods.totalSupply().call((err, result)=> {
  console.log(result)
})
</code>```

答:
Try:

contract.methods.totalSupply().call().then((result) => {console.log(result) });
```

It should return a BigNumber.

Body:
I was watching the tutorial on Youtube and following the instruction:
https://www.youtube.com/watch?time_continue=1350&v=msT3tpwnyv8

When I try to call the function with the js file below, it returned nothing on the console. Does anyone know what happened?

I am using,
web3.js 1.0.0 beta. 52
infura to connect

var Tx = require('ethereumjs-tx')

const Web3 = require('web3');
const web3 = new Web3('https://ropsten.infura.io/v3/project_id')

const contractAddress = '0xd03696B53924972b9903eB17Ac5033928Be7D3Bc'
const contractABI = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"standard","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"}]

var contract = new web3.eth.Contract(contractABI, contractAddress)

contract.methods.totalSupply().call((err, result)=> {
  console.log(result)
})

Body:
Try:

contract.methods.totalSupply().call().then((result) => {console.log(result) });

It should return a BigNumber.


问:
Entity Framework Core not adding records
I am trying to add a set of records with Entity Framework Core. For some reason I cannot get the records to actually save to the database.

Below is the code running. There are not exceptions thrown.

```<code>using (var context = new UserEntity.UsersContext())
{
    foreach(var u in users)
    {
        var tempUser = await context.User.FirstOrDefaultAsync(x => x.Username == u.Username);

        if (tempUser == null)
        {
            context.Add(u);
        }

        await context.SaveChangesAsync();
    }
}
</code>```

When I watch the debugger, the program stops running when it gets to the FirstOrDefaultAsync call. If I remove that, the program will run fine, but SaveChangesAsync still does not actually insert the records to the database.

Could someone advise? Thanks

Edit 1:

```<code>await DataWork(smallList);
</code>```

Edit 2 RESOLUTION!:

This is completely my fault from over looking the fact that this is a console app, as it is going to be used once and never seen again. The main method on a console app cannot be truly asynchronous.

My solution below:

```<code>MyAsyncMethod().Wait();
</code>```

That's it. It works after this. Thank you all for spending the time to try to help me, it pushed me in the right direction

答:
You are currently mixing async and non async calls. Currently the Add methods should be AddAsync

If you want async operation your code should be :

```<code>using (var context = new UserEntity.UsersContext())
        {
            foreach(var u in users)
            {
                var tempUser = await context.User.FirstOrDefaultAsync(x => x.Username == u.Username);
                if (tempUser == null)
                {
                    await context.AddAsync(u);
                }

                await context.SaveChangesAsync();
            }
        }
</code>```

Body:
I am trying to add a set of records with Entity Framework Core. For some reason I cannot get the records to actually save to the database.

Below is the code running. There are not exceptions thrown.

using (var context = new UserEntity.UsersContext())
{
    foreach(var u in users)
    {
        var tempUser = await context.User.FirstOrDefaultAsync(x => x.Username == u.Username);

        if (tempUser == null)
        {
            context.Add(u);
        }

        await context.SaveChangesAsync();
    }
}

When I watch the debugger, the program stops running when it gets to the FirstOrDefaultAsync call. If I remove that, the program will run fine, but SaveChangesAsync still does not actually insert the records to the database.

Could someone advise? Thanks

Edit 1:

await DataWork(smallList);

Edit 2 RESOLUTION!:

This is completely my fault from over looking the fact that this is a console app, as it is going to be used once and never seen again. The main method on a console app cannot be truly asynchronous.

My solution below:

MyAsyncMethod().Wait();

That's it. It works after this. Thank you all for spending the time to try to help me, it pushed me in the right direction

Body:
You are currently mixing async and non async calls. Currently the Add methods should be AddAsync

If you want async operation your code should be :

using (var context = new UserEntity.UsersContext())
        {
            foreach(var u in users)
            {
                var tempUser = await context.User.FirstOrDefaultAsync(x => x.Username == u.Username);
                if (tempUser == null)
                {
                    await context.AddAsync(u);
                }

                await context.SaveChangesAsync();
            }
        }


问:
Tab control mouse over
I am trying to create a tab control with a style like Google's kitchen sink example.
When the mouse goes over a tab i want to be able to change its color and when i click that tab its content background color changes to match and the tab changes. However, if you don't click the tab and the mouse moves i want it to go back to its original color. I want the tabs to be different colors.

What i have right now is when i hover over the intro tab content "Content for intro"

that content font changes to red. I had to change it to foreground so i could see that it was working. Keep in mind i am very new to xaml and wpf. I am trying to teach myself and the book i have has a very small section on styles.

Here is Google's kitchen sin example hat i am trying to achieve.
http://gwt.google.com/samples/KitchenSink/KitchenSink.html

Any help is much appreciated.

```<code><Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <SolidColorBrush x:Key="mouseOverColor"
            Color="Red" />
        <Style x:Key="myStyle" TargetType="TabItem">
            <Setter Property="BorderThickness" Value="3"/>
            <Setter Property="BorderBrush" Value="Red"/>
            <Setter Property="Background" Value="LightBlue"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TabItem">
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver"
                                     Value="True">
                                <Setter Property="Foreground"
                                        Value="{StaticResource mouseOverColor}" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                        <ContentPresenter />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <TabControl  Background="AliceBlue"  Grid.Column="1"
             Grid.ColumnSpan="2" Margin="92,40,37,80"
             Grid.Row="2">
            <TabItem  Header="Intro" >
                <TabItem Style="{StaticResource myStyle}" >
                    Content for intro
                </TabItem>
            </TabItem>
            <TabItem Header="Widgets">
                Content for widget
            </TabItem>
            <TabItem Header="Panels">
                content for panel
            </TabItem>
        </TabControl>
    </Grid>
</Window>
</code>```

答:
This is a bit complex because the background of the selected tab is colourless by default, so you need to override the control template. It is best to modify the default style so you do not need to start over, which in any case is quite verbose:

```<code><ControlTemplate x:Key="TabItemControlTemplate" TargetType="{x:Type TabItem}">
    <Grid SnapsToDevicePixels="True">
        <Border x:Name="Bd" BorderBrush="White" BorderThickness="1,1,1,0" Padding="{TemplateBinding Padding}">
            <Border.Style>
                <Style TargetType="{x:Type Border}">
                    <Setter Property="Background" Value="Gray"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected}" Value="True">
                            <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}" />
                        </DataTrigger>
                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsMouseOver}" Value="True">
                            <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Border.Style>
            <ContentPresenter x:Name="Content" ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" ContentStringFormat="{TemplateBinding HeaderStringFormat}" ContentSource="Header" HorizontalAlignment="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ItemsControl}}}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{Binding VerticalContentAlignment, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ItemsControl}}}"/>
        </Border>
    </Grid>
    <ControlTemplate.Triggers>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsSelected" Value="False"/>
                <Condition Property="IsMouseOver" Value="True"/>
            </MultiTrigger.Conditions>
            <Setter Property="BorderBrush" TargetName="Bd" Value="#FF3C7FB1"/>
        </MultiTrigger>
        <Trigger Property="TabStripPlacement" Value="Bottom">
            <Setter Property="BorderThickness" TargetName="Bd" Value="1,0,1,1"/>
        </Trigger>
        <Trigger Property="TabStripPlacement" Value="Left">
            <Setter Property="BorderThickness" TargetName="Bd" Value="1,1,0,1"/>
        </Trigger>
        <Trigger Property="TabStripPlacement" Value="Right">
            <Setter Property="BorderThickness" TargetName="Bd" Value="0,1,1,1"/>
        </Trigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsSelected" Value="True"/>
                <Condition Property="TabStripPlacement" Value="Top"/>
            </MultiTrigger.Conditions>
            <Setter Property="Margin" Value="-2,-2,-2,-1"/>
            <Setter Property="Margin" TargetName="Content" Value="0,0,0,1"/>
        </MultiTrigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsSelected" Value="True"/>
                <Condition Property="TabStripPlacement" Value="Bottom"/>
            </MultiTrigger.Conditions>
            <Setter Property="Margin" Value="-2,-1,-2,-2"/>
            <Setter Property="Margin" TargetName="Content" Value="0,1,0,0"/>
        </MultiTrigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsSelected" Value="True"/>
                <Condition Property="TabStripPlacement" Value="Left"/>
            </MultiTrigger.Conditions>
            <Setter Property="Margin" Value="-2,-2,-1,-2"/>
            <Setter Property="Margin" TargetName="Content" Value="0,0,1,0"/>
        </MultiTrigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsSelected" Value="True"/>
                <Condition Property="TabStripPlacement" Value="Right"/>
            </MultiTrigger.Conditions>
            <Setter Property="Margin" Value="-1,-2,-2,-2"/>
            <Setter Property="Margin" TargetName="Content" Value="1,0,0,0"/>
        </MultiTrigger>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Background" TargetName="Bd" Value="#FFF4F4F4"/>
            <Setter Property="BorderBrush" TargetName="Bd" Value="#FFC9C7BA"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>
</code>```

If you want to change the default colour, change the setter on the border which specifies that the background should be grey.

Also to make the content part the same colour as the tab an additional binding in the TabControl is needed. Further this control template needs to be applied to the items, either via an automatic style or direct reference:

```<code><TabControl x:Name="MyControl" Height="200"
            Background="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem.Background}">
    <TabItem Header="tab1" Background="Red"   Template="{DynamicResource TabItemControlTemplate}"/>
    <TabItem Header="tab2" Background="Green" Template="{DynamicResource TabItemControlTemplate}"/>
    <TabItem Header="tab3" Background="Blue" Template="{DynamicResource TabItemControlTemplate}"/>
</TabControl>
</code>```

First tab selected, mouse over last tab:

Usage annotation:

```<code><Window ...>
    <Window.Resources>
        <ControlTemplate x:Key="TabItemControlTemplate" TargetType="{x:Type TabItem}">
            ...
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <!-- You can reference the template anywhere inside the visual tree
             of the Window if it has been declared in the Resources of the
             window, most XML elemnts that are children of the Window element
             are inside its visual tree -->
        <TabControl ...>
            <TabItem Template="{StaticResource TabItemControlTemplate}" .../>
        </TabControl>
    </Grid>
</Window>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Tab control mouse over

Body:
I am trying to create a tab control with a style like Google's kitchen sink example.
When the mouse goes over a tab i want to be able to change its color and when i click that tab its content background color changes to match and the tab changes. However, if you don't click the tab and the mouse moves i want it to go back to its original color. I want the tabs to be different colors.

What i have right now is when i hover over the intro tab content "Content for intro"

that content font changes to red. I had to change it to foreground so i could see that it was working. Keep in mind i am very new to xaml and wpf. I am trying to teach myself and the book i have has a very small section on styles.

Here is Google's kitchen sin example hat i am trying to achieve.
http://gwt.google.com/samples/KitchenSink/KitchenSink.html

Any help is much appreciated.

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <SolidColorBrush x:Key="mouseOverColor"
            Color="Red" />

    </Window.Resources>
    <Grid>
        <TabControl  Background="AliceBlue"  Grid.Column="1"
             Grid.ColumnSpan="2" Margin="92,40,37,80"
             Grid.Row="2">
            <TabItem  Header="Intro" >
                <TabItem Style="{StaticResource myStyle}" >
                    Content for intro
                </TabItem>
            </TabItem>
            <TabItem Header="Widgets">
                Content for widget
            </TabItem>
            <TabItem Header="Panels">
                content for panel
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Body:
This is a bit complex because the background of the selected tab is colourless by default, so you need to override the control template. It is best to modify the default style so you do not need to start over, which in any case is quite verbose:

<ControlTemplate x:Key="TabItemControlTemplate" TargetType="{x:Type TabItem}">
    <Grid SnapsToDevicePixels="True">
        <Border x:Name="Bd" BorderBrush="White" BorderThickness="1,1,1,0" Padding="{TemplateBinding Padding}">
            <Border.Style>
                <Style TargetType="{x:Type Border}">
                    <Setter Property="Background" Value="Gray"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected}" Value="True">
                            <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}" />
                        </DataTrigger>
                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsMouseOver}" Value="True">
                            <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Border.Style>
            <ContentPresenter x:Name="Content" ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" ContentStringFormat="{TemplateBinding HeaderStringFormat}" ContentSource="Header" HorizontalAlignment="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ItemsControl}}}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{Binding VerticalContentAlignment, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ItemsControl}}}"/>
        </Border>
    </Grid>
    <ControlTemplate.Triggers>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsSelected" Value="False"/>
                <Condition Property="IsMouseOver" Value="True"/>
            </MultiTrigger.Conditions>
            <Setter Property="BorderBrush" TargetName="Bd" Value="#FF3C7FB1"/>
        </MultiTrigger>
        <Trigger Property="TabStripPlacement" Value="Bottom">
            <Setter Property="BorderThickness" TargetName="Bd" Value="1,0,1,1"/>
        </Trigger>
        <Trigger Property="TabStripPlacement" Value="Left">
            <Setter Property="BorderThickness" TargetName="Bd" Value="1,1,0,1"/>
        </Trigger>
        <Trigger Property="TabStripPlacement" Value="Right">
            <Setter Property="BorderThickness" TargetName="Bd" Value="0,1,1,1"/>
        </Trigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsSelected" Value="True"/>
                <Condition Property="TabStripPlacement" Value="Top"/>
            </MultiTrigger.Conditions>
            <Setter Property="Margin" Value="-2,-2,-2,-1"/>
            <Setter Property="Margin" TargetName="Content" Value="0,0,0,1"/>
        </MultiTrigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsSelected" Value="True"/>
                <Condition Property="TabStripPlacement" Value="Bottom"/>
            </MultiTrigger.Conditions>
            <Setter Property="Margin" Value="-2,-1,-2,-2"/>
            <Setter Property="Margin" TargetName="Content" Value="0,1,0,0"/>
        </MultiTrigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsSelected" Value="True"/>
                <Condition Property="TabStripPlacement" Value="Left"/>
            </MultiTrigger.Conditions>
            <Setter Property="Margin" Value="-2,-2,-1,-2"/>
            <Setter Property="Margin" TargetName="Content" Value="0,0,1,0"/>
        </MultiTrigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsSelected" Value="True"/>
                <Condition Property="TabStripPlacement" Value="Right"/>
            </MultiTrigger.Conditions>
            <Setter Property="Margin" Value="-1,-2,-2,-2"/>
            <Setter Property="Margin" TargetName="Content" Value="1,0,0,0"/>
        </MultiTrigger>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Background" TargetName="Bd" Value="#FFF4F4F4"/>
            <Setter Property="BorderBrush" TargetName="Bd" Value="#FFC9C7BA"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

If you want to change the default colour, change the setter on the border which specifies that the background should be grey.

Also to make the content part the same colour as the tab an additional binding in the TabControl is needed. Further this control template needs to be applied to the items, either via an automatic style or direct reference:

<TabControl x:Name="MyControl" Height="200"
            Background="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem.Background}">
    <TabItem Header="tab1" Background="Red"   Template="{DynamicResource TabItemControlTemplate}"/>
    <TabItem Header="tab2" Background="Green" Template="{DynamicResource TabItemControlTemplate}"/>
    <TabItem Header="tab3" Background="Blue" Template="{DynamicResource TabItemControlTemplate}"/>
</TabControl>

First tab selected, mouse over last tab:

Usage annotation:

<Window ...>
    <Window.Resources>
        <ControlTemplate x:Key="TabItemControlTemplate" TargetType="{x:Type TabItem}">
            ...
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <!-- You can reference the template anywhere inside the visual tree
             of the Window if it has been declared in the Resources of the
             window, most XML elemnts that are children of the Window element
             are inside its visual tree -->
        <TabControl ...>
            <TabItem Template="{StaticResource TabItemControlTemplate}" .../>
        </TabControl>
    </Grid>
</Window>


问:
How to make ScrollView consume touch event even when it's scrolled to the end?
I have an FSPagerView, which has an item that contains scrollable barchart (scrollview having multiple stackviews). When I scroll barchart, if there is a scrollable space, then touch event is consumed by the barchart and it scrolls. If there is no scrollable space on a side and I keep scrolling to that side touching barchart, it does not consume touch event anymore and instead the whole FSPagerView scrolls. How can I make scrollview consume touch event even in such case? In short, I don't want to scroll FSPagerView when touching barchart.

Here is a video:
https://streamable.com/kuxta

答:
FSPagerView exposes panGestureRecognizer that is essentially the underlying UICollectionView's panGestureRecognizer.

I think you can just disable it while you are seeing the barchart.

Not very familiar with FSPagerView, but I think you can detect in which page you are by monitoring FSPagerViewDelegate callbacks. For example, if the bar chart is in the first page (i.e., index == 0), probably you can do something like this.

```<code>override func pagerView(_ pagerView: FSPagerView, willDisplay cell: FSPagerViewCell, forItemAt index: Int) {
    // FSPagerView's gesture recognizer is only enabled for index > 0.
    pagerView.panGestureRecognizer.isEnabled = (index != 0)
}
</code>```

If that callback does not work, I would try the same thing with func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) callback.

Body:
FSPagerView exposes panGestureRecognizer that is essentially the underlying UICollectionView's panGestureRecognizer.

I think you can just disable it while you are seeing the barchart.

Not very familiar with FSPagerView, but I think you can detect in which page you are by monitoring FSPagerViewDelegate callbacks. For example, if the bar chart is in the first page (i.e., index == 0), probably you can do something like this.

override func pagerView(_ pagerView: FSPagerView, willDisplay cell: FSPagerViewCell, forItemAt index: Int) {
    // FSPagerView's gesture recognizer is only enabled for index > 0.
    pagerView.panGestureRecognizer.isEnabled = (index != 0)
}

If that callback does not work, I would try the same thing with func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) callback.


问:
making an image within a card fill in the space
I am making a website using react and reactstrap, I have a card containing an image, the card is a square and the image is a rectangle, i want the image to fill in the card in the same fashion as an image set to fill in the background of a screen (cropping the edges to fit, thus avoiding the image getting stretched).

I have tried setting the width to auto while the height is at 100%, but the image only ends up smaller than it's normal size but overflows from the card, and not centered.

```<code><Row ClassName="posts">
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>
      <a href="#"><img className="img-fluid" src={media_picture} width="auto" height="100%"/></a>
    </Card>
  </Col>
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>
      <a href="#"><img className="img-fluid" src={media_picture} width="auto" height="100%"/></a>
    </Card>
  </Col>
</Row>
</code>```

I want the resulting image to be contained in the card, centered and filled in like a background image.

答:
Firstly make sure that  not have any padding

```<code>padding:0
</code>```

then make  position is absolute

```<code>height:'100%'
marginLeft:auto
marginRight:auto
display:'block'
</code>```

Body:
I am making a website using react and reactstrap, I have a card containing an image, the card is a square and the image is a rectangle, i want the image to fill in the card in the same fashion as an image set to fill in the background of a screen (cropping the edges to fit, thus avoiding the image getting stretched).

I have tried setting the width to auto while the height is at 100%, but the image only ends up smaller than it's normal size but overflows from the card, and not centered.

<Row ClassName="posts">
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>

    </Card>
  </Col>
  <Col>
    <Card style={{ height:"460px", width:"460px"}}>

    </Card>
  </Col>
</Row>

I want the resulting image to be contained in the card, centered and filled in like a background image.

Body:
Firstly make sure that  not have any padding

padding:0

then make  position is absolute

height:'100%'
marginLeft:auto
marginRight:auto
display:'block'


问:
Is it possible to apply a decorator to a line in python?
As you may now, the common usage of decorator is for example:

```<code>@log
def func(...)
</code>```

What actualy takes func as parameter returns a function what takes func as an argument, like :

```<code>def log(func):
    def function_wrapper(*args , **kwargs):
    log_enter_func(func, args, kwargs)

    result = func(*args, **kwargs)
    log_exit_func(func, result )
    return result
</code>```

In code above, logging of function calls and returns are fine, without hand- made log (...) entries with just @log decorator over a function.
So its easy to remove after testing, so logging does not consume time.

But is it possible to hang it just to lines of code?
Like for loops, etc, so something like :

```<code>def func(...):
 ...
@log
    for x in range(whatever)
</code>```

Taking the line as soft of a function, accessing in some kinf of args to x, whatever ( variables and code in the line) cause actualy everything is a function in python?

Or maybe there is some kind of method to apply decorator to a method and propagate it to source lines in a function ?

The idea is to make a brief logging of whats happens in every line without lots of hand- written log entries like
log.info(msg)
in many lines of code

Any ideas about that?
I v tryed to inspect the func. __ code __  built- in, but its python byte- code there , not source code...

答:
This is exactly what context managers are for. These are triggered with a with block, and define code that runs on entering and exiting the block.

See the documentation.

Body:
As you may now, the common usage of decorator is for example:

@log
def func(...)

What actualy takes func as parameter returns a function what takes func as an argument, like :

def log(func):
    def function_wrapper(*args , **kwargs):
    log_enter_func(func, args, kwargs)

    result = func(*args, **kwargs)
    log_exit_func(func, result )
    return result

In code above, logging of function calls and returns are fine, without hand- made log (...) entries with just @log decorator over a function.
So its easy to remove after testing, so logging does not consume time.

But is it possible to hang it just to lines of code?
Like for loops, etc, so something like :

def func(...):
 ...
@log
    for x in range(whatever)

Taking the line as soft of a function, accessing in some kinf of args to x, whatever ( variables and code in the line) cause actualy everything is a function in python?

Or maybe there is some kind of method to apply decorator to a method and propagate it to source lines in a function ?

The idea is to make a brief logging of whats happens in every line without lots of hand- written log entries like
log.info(msg)
in many lines of code

Any ideas about that?
I v tryed to inspect the func. __ code __  built- in, but its python byte- code there , not source code...


问:
Radio Button grouping in the multi column list view
I have a list view with 3 following columns:
1. a Text Column
2. Radio button
3. Radio button

I am trying to group the two radio Button but all the radio button gets in one group.
e.g. if there are two listview items (two rows), then all the 4 radio button gets grouped as one.

```<code><ListView Name="ruleListView"  ScrollViewer.HorizontalScrollBarVisibility="Auto"
                    ScrollViewer.VerticalScrollBarVisibility="Auto"
 Margin="10">
                <ListView.View>
                    <GridView>
                        <GridView.ColumnHeaderContainerStyle>
                            <Style TargetType="{x:Type GridViewColumnHeader}">
                                <Setter Property="IsEnabled" Value="False"/>
                            </Style>
                        </GridView.ColumnHeaderContainerStyle>
                        <GridViewColumn
                                Header="Rule"

                                >
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBlock
                                        HorizontalAlignment="Right"
                                        Width="410"
                                        TextWrapping="Wrap" Text="{Binding Rule}" TextAlignment="Left"
                                        />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                        <GridViewColumn
                                Header="Configuration Key"
                            Width="140"

                                >

                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                        <RadioButton GroupName="Rule"
                                                     VerticalAlignment="Center"
                                                     HorizontalAlignment="Center" />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                        <GridViewColumn
                                Header="Event"
                                Width="100"
                                >
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                        <RadioButton GroupName="Rule"
                                                 VerticalAlignment="Center"
                                                 HorizontalAlignment="Center"
                                                 IsChecked="True"
                                                 />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
</code>```

I expect that grouping should be done as per the particular row.

答:
As I understand it, the RadioButton.GroupName applies to all active controls. That is why you are seeing all the radio buttons linked together. In order to get each row to be linked you need a unique GroupName for each row. In MVVM you could bind the GroupName to a property on the underlying item, or bind the RadioButton's IsChecked property to the ViewModel and manage the switching in code.

Since your not using ViewModels it is a little more complicated. You still need to create a unique GroupName per row. The easiest way I can think of to do this is to use a IValueConverter to get the row index.

```<code>public class RadioGroupIndexConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is ListViewItem lvi)
        {
            var listView = ItemsControl.ItemsControlFromItemContainer(lvi);
            var index = listView.ItemContainerGenerator.IndexFromContainer(lvi);
            return string.Format("{0}{1}", parameter, index);
        }
        return parameter;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

Then you'll need to bind to the GroupName to the ListViewItem using the converter.

First you need to add the converter as a resources in xaml. Where <converters: is a reference to the namespace of the RadioGroupIndexConverter class. If you created the class in the same namespace as your ListView you can just use <local:

```<code><ListView.Resources>
    <converters:RadioGroupIndexConverter x:Key="GroupConverter"/>
</ListView.Resources>
</code>```

Then you'll change your RadioButton.GroupName to use a relative binding.

```<code><RadioButton GroupName="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}, Converter={StaticResource GroupConverter}}"/>
</code>```

Body:
I have a list view with 3 following columns:
1. a Text Column
2. Radio button
3. Radio button

I am trying to group the two radio Button but all the radio button gets in one group.
e.g. if there are two listview items (two rows), then all the 4 radio button gets grouped as one.

<ListView Name="ruleListView"  ScrollViewer.HorizontalScrollBarVisibility="Auto"
                    ScrollViewer.VerticalScrollBarVisibility="Auto"
 Margin="10">
                <ListView.View>
                    <GridView>
                        <GridView.ColumnHeaderContainerStyle>

                        </GridView.ColumnHeaderContainerStyle>
                        <GridViewColumn
                                Header="Rule"

                                >
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBlock
                                        HorizontalAlignment="Right"
                                        Width="410"
                                        TextWrapping="Wrap" Text="{Binding Rule}" TextAlignment="Left"
                                        />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                        <GridViewColumn
                                Header="Configuration Key"
                            Width="140"

                                >

                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                        <RadioButton GroupName="Rule"
                                                     VerticalAlignment="Center"
                                                     HorizontalAlignment="Center" />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                        <GridViewColumn
                                Header="Event"
                                Width="100"
                                >
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                        <RadioButton GroupName="Rule"
                                                 VerticalAlignment="Center"
                                                 HorizontalAlignment="Center"
                                                 IsChecked="True"
                                                 />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>

I expect that grouping should be done as per the particular row.

Body:
As I understand it, the RadioButton.GroupName applies to all active controls. That is why you are seeing all the radio buttons linked together. In order to get each row to be linked you need a unique GroupName for each row. In MVVM you could bind the GroupName to a property on the underlying item, or bind the RadioButton's IsChecked property to the ViewModel and manage the switching in code.

Since your not using ViewModels it is a little more complicated. You still need to create a unique GroupName per row. The easiest way I can think of to do this is to use a IValueConverter to get the row index.

public class RadioGroupIndexConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is ListViewItem lvi)
        {
            var listView = ItemsControl.ItemsControlFromItemContainer(lvi);
            var index = listView.ItemContainerGenerator.IndexFromContainer(lvi);
            return string.Format("{0}{1}", parameter, index);
        }
        return parameter;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Then you'll need to bind to the GroupName to the ListViewItem using the converter.

First you need to add the converter as a resources in xaml. Where <converters: is a reference to the namespace of the RadioGroupIndexConverter class. If you created the class in the same namespace as your ListView you can just use <local:

<ListView.Resources>
    <converters:RadioGroupIndexConverter x:Key="GroupConverter"/>
</ListView.Resources>

Then you'll change your RadioButton.GroupName to use a relative binding.

<RadioButton GroupName="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}, Converter={StaticResource GroupConverter}}"/>


问:
White background when Android app start up
Every when my app starts up, there's a white background displays in a short time.
Despite of using splash screen, the problem is still exists.
I would like to set the start up screen to black instead of white as default!

This is my splash's screen activity:

```<code>public class SplashActivity extends Activity {

private static String TAG = SplashActivity.class.getName();
private static long SLEEP_TIME = 1;    // Sleep for some time

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);    // Removes title bar
    setContentView(R.layout.splash);

    // Start timer and launch main activity
    IntentLauncher launcher = new IntentLauncher();
    launcher.start();
}

private class IntentLauncher extends Thread {

    /**
      * Sleep for some time and than start new activity.
      */
    @Override
    public void run() {
        try {
            // Sleeping
            Thread.sleep(SLEEP_TIME*1000);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

        // Start main activity
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        SplashActivity.this.startActivity(intent);
        SplashActivity.this.finish();
    }

}

@Override
protected void onPause() {
    super.onPause();
    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
}
</code>```

答:
In styles.xml, theme applied for SplashActivity, add the following line

```<code><item name="android:windowBackground">@drawable/background</item>
</code>```

where @drawable/background is the background you applied for your Splash Screen or it could be any color you need.

Body:
Every when my app starts up, there's a white background displays in a short time.
Despite of using splash screen, the problem is still exists.
I would like to set the start up screen to black instead of white as default!

This is my splash's screen activity:

public class SplashActivity extends Activity {

private static String TAG = SplashActivity.class.getName();
private static long SLEEP_TIME = 1;    // Sleep for some time

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);    // Removes title bar
    setContentView(R.layout.splash);

    // Start timer and launch main activity
    IntentLauncher launcher = new IntentLauncher();
    launcher.start();
}

private class IntentLauncher extends Thread {

    /**
      * Sleep for some time and than start new activity.
      */
    @Override
    public void run() {
        try {
            // Sleeping
            Thread.sleep(SLEEP_TIME*1000);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

        // Start main activity
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        SplashActivity.this.startActivity(intent);
        SplashActivity.this.finish();
    }

}

@Override
protected void onPause() {
    super.onPause();
    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
}

Body:
In styles.xml, theme applied for SplashActivity, add the following line

<item name="android:windowBackground">@drawable/background</item>

where @drawable/background is the background you applied for your Splash Screen or it could be any color you need.


问:
mod-rewrite recursive loop
I want to change my website's dynamic urls to Search Engine Friendly URL's

Now the urls like this www.website.com/news.php?id=127591 ,
I want it became this www.website.com/news/127591/this-is-article-subject

I added this

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
</code>```

in my .htaccess file. Everything from /news.php?id=123 change to /new/123/this-is-article-subject

The problem is, now I have two links refer to the same contents. Both /news.php?id=123 and /new/123/this-is-article-subject are the exactly duplicate content

It is said that search engine will punish this if they found duplicated contents.

I check the answers online and found this,

```<code>RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

HTTP 301 permanent redirect from the old URL to the new URL.

But this still have problem. When I put those three lines together, it not works.

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

I guess the reason is the recursive loop. How could I solve this kind of problem?

Thanks!

Update

I changed to this

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

None of the two url work.

答:
If [L] doesn't work for you, the issue might be separate internal requests (not sub-requests that you could halt with [NS]).

See here.

Title: mod-rewrite recursive loop

Body:
I want to change my website's dynamic urls to Search Engine Friendly URL's

Now the urls like this www.website.com/news.php?id=127591 ,
I want it became this www.website.com/news/127591/this-is-article-subject

I added this

RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]

in my .htaccess file. Everything from /news.php?id=123 change to /new/123/this-is-article-subject

The problem is, now I have two links refer to the same contents. Both /news.php?id=123 and /new/123/this-is-article-subject are the exactly duplicate content

It is said that search engine will punish this if they found duplicated contents.

I check the answers online and found this,

RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

HTTP 301 permanent redirect from the old URL to the new URL.

But this still have problem. When I put those three lines together, it not works.

RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

I guess the reason is the recursive loop. How could I solve this kind of problem?

Thanks!

Update

I changed to this

RewriteRule ^news/([0-9]+) /news.php?id=$1 [L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

None of the two url work.


问:
Mysql statement not working with multiple AND clauses
So this sql is designed to return 1 random project from the projects table

```<code>$sql = "select title, id, user_id, priority from projects
where ( closed = 0 and priority between 7 and 9 AND  user_id=$user_id )
ORDER by rand(), priority
limit 1";
</code>```

No matter how I rearrange them with parenthesis etc. the query returns invalid error like

```<code>Notice: Undefined variable: user_id in /var/www/html/producerswip/includes/functions.php on line 734

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ORDER by rand(), priority limit 1' at line 2 in /var/www/html/producerswip/includes/functions.php:737 Stack trace: #0 /var/www/html/producerswip/includes/functions.php(737): PDO->prepare('select title, i...') #1 /var/www/html/producerswip/index.php(72): getRandomProject() #2 {main} thrown in /var/www/html/producerswip/includes/functions.php on line 737
</code>```

UPDATE
This is a total face palm moment. I was so focused on the sql statement error I ignored the first line which actually states the error. Thanks @David and others who have their eyes open. I have also taken @David advice and changed my sql to the following which is less attractive to sql injection

```<code>$sql = "select title, id, user_id, priority from projects
where ( closed = ? and priority between ? and ? AND user_id=? )
ORDER by rand(), priority
limit 1";
$results = $pdo->prepare($sql) or die(mysqli_error($pdo));
$results->execute([0,7,9,$user_id]);
</code>```

答:
Looks like your $user_id variable is not defined, meaning your resulting query would become the following:

```<code>where ( closed = 0 and priority between 7 and 9 AND  user_id= )
ORDER by rand(), priority
limit 1
</code>```

Since there is no value after the user_id=, the query is invalid.

Body:
So this sql is designed to return 1 random project from the projects table

$sql = "select title, id, user_id, priority from projects
where ( closed = 0 and priority between 7 and 9 AND  user_id=$user_id )
ORDER by rand(), priority
limit 1";

No matter how I rearrange them with parenthesis etc. the query returns invalid error like

Notice: Undefined variable: user_id in /var/www/html/producerswip/includes/functions.php on line 734

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ORDER by rand(), priority limit 1' at line 2 in /var/www/html/producerswip/includes/functions.php:737 Stack trace: #0 /var/www/html/producerswip/includes/functions.php(737): PDO->prepare('select title, i...') #1 /var/www/html/producerswip/index.php(72): getRandomProject() #2 {main} thrown in /var/www/html/producerswip/includes/functions.php on line 737

UPDATE
This is a total face palm moment. I was so focused on the sql statement error I ignored the first line which actually states the error. Thanks @David and others who have their eyes open. I have also taken @David advice and changed my sql to the following which is less attractive to sql injection

$sql = "select title, id, user_id, priority from projects
where ( closed = ? and priority between ? and ? AND user_id=? )
ORDER by rand(), priority
limit 1";
$results = $pdo->prepare($sql) or die(mysqli_error($pdo));
$results->execute([0,7,9,$user_id]);

Body:
Looks like your $user_id variable is not defined, meaning your resulting query would become the following:

where ( closed = 0 and priority between 7 and 9 AND  user_id= )
ORDER by rand(), priority
limit 1

Since there is no value after the user_id=, the query is invalid.


问:
Eigen + gmp looks for gmp_expr not mpq_class
I am unfamiliar with templates and C++ generally but want to get into using Eigen with gmp.  I followed the Eigen tutorial on custom types and want to output to the terminal.  I get a compilation error that makes reference to  __gmp_expr<__mpq_struct [1], __mpq_struct [1]> but I am using mpq_class.  It's beyond me to resolve what is going on.

I read gmp literature which convinced me there is more to using gmpxx than I can understand at this point.  I have managed to correctly output individual matrix elements and scalar calculations (determinants) correctly.

My header file mpfr_type.h is based on the Eigen tutorial,

```<code>#include <gmpxx.h>
#include <boost/operators.hpp>

namespace Eigen {
  template<> struct NumTraits<mpq_class> : GenericNumTraits<mpq_class>
  {
    typedef mpq_class Real;
    typedef mpq_class NonInteger;
    typedef mpq_class Nested;
    static inline Real epsilon() { return 0; }
    static inline Real dummy_precision() { return 0; }
    static inline Real digits10() { return 0; }
    enum {
      IsInteger = 0,
      IsSigned = 1,
      IsComplex = 0,
      RequireInitialization = 1,
      ReadCost = 6,
      AddCost = 150,
      MulCost = 100
    };
  };
}
</code>```

and my code is,

```<code>#include <Eigen/Dense>
#include <typeinfo>

#include "mpfr_type.h"

using namespace Eigen;

int main()
{
  // rational matrix
  Matrix<mpq_class,2,2> my_mat;

  my_mat(0,0) = mpq_class (2,3);
  my_mat(0,1) = mpq_class (7,1);
  my_mat(1,0) = mpq_class (5,1);
  my_mat(1,1) = mpq_class (11,1);

  auto my_det = my_mat.determinant();
  std::cout << my_det << std::endl; //works

  std::cout << "Here is my matrix:\n" << my_mat << std::endl; // error
  Return 0;
}
</code>```

I simply expect my code to compile but get,

```<code>g++ -c -g example1.cpp -o example1.o -I ~/Documents/eigen/
In file included from /home/user/Documents/eigen/Eigen/Core:433:0,
                 from /home/user/Documents/eigen/Eigen/Dense:1,
                 from example1.cpp:2:
/home/user/Documents/eigen/Eigen/src/Core/IO.h: In instantiation of ‘static int Eigen::internal::significant_decimals_impl<Scalar>::run() [with Scalar = __gmp_expr<__mpq_struct [1], __mpq_struct [1]>]’:
/home/user/Documents/eigen/Eigen/src/Core/IO.h:155:66:   required from ‘std::ostream& Eigen::internal::print_matrix(std::ostream&, const Derived&, const Eigen::IOFormat&) [with Derived = Eigen::Matrix<__gmp_expr<__mpq_struct [1], __mpq_struct [1]>, 2, 2>; std::ostream = std::basic_ostream<char>]’
/home/user/Documents/eigen/Eigen/src/Core/IO.h:220:32:   required from ‘std::ostream& Eigen::operator<<(std::ostream&, const Eigen::DenseBase<Derived>&) [with Derived = Eigen::Matrix<__gmp_expr<__mpq_struct [1], __mpq_struct [1]>, 2, 2>; std::ostream = std::basic_ostream<char>]’
example1.cpp:44:42:   required from here
/home/user/Documents/eigen/Eigen/src/Core/IO.h:122:40: error: cannot convert ‘Eigen::NumTraits<__gmp_expr<__mpq_struct [1], __mpq_struct [1]> >::Real {aka __gmp_expr<__mpq_struct [1], __mpq_struct [1]>}’ to ‘int’ in return
     return NumTraits<Scalar>::digits10();
                                        ^
Makefile:12: recipe for target 'example1.o' failed
make: *** [example1.o] Error 1
</code>```

答: This was a documentation bug. digits10() is supposed to return an integer.

Body:
I am unfamiliar with templates and C++ generally but want to get into using Eigen with gmp.  I followed the Eigen tutorial on custom types and want to output to the terminal.  I get a compilation error that makes reference to  __gmp_expr<__mpq_struct [1], __mpq_struct [1]> but I am using mpq_class.  It's beyond me to resolve what is going on.

I read gmp literature which convinced me there is more to using gmpxx than I can understand at this point.  I have managed to correctly output individual matrix elements and scalar calculations (determinants) correctly.

My header file mpfr_type.h is based on the Eigen tutorial,

#include <gmpxx.h>
#include <boost/operators.hpp>

namespace Eigen {
  template<> struct NumTraits<mpq_class> : GenericNumTraits<mpq_class>
  {
    typedef mpq_class Real;
    typedef mpq_class NonInteger;
    typedef mpq_class Nested;
    static inline Real epsilon() { return 0; }
    static inline Real dummy_precision() { return 0; }
    static inline Real digits10() { return 0; }
    enum {
      IsInteger = 0,
      IsSigned = 1,
      IsComplex = 0,
      RequireInitialization = 1,
      ReadCost = 6,
      AddCost = 150,
      MulCost = 100
    };
  };
}

and my code is,

#include <Eigen/Dense>
#include <typeinfo>

#include "mpfr_type.h"

using namespace Eigen;

int main()
{
  // rational matrix
  Matrix<mpq_class,2,2> my_mat;

  my_mat(0,0) = mpq_class (2,3);
  my_mat(0,1) = mpq_class (7,1);
  my_mat(1,0) = mpq_class (5,1);
  my_mat(1,1) = mpq_class (11,1);

  auto my_det = my_mat.determinant();
  std::cout << my_det << std::endl; //works

  std::cout << "Here is my matrix:\n" << my_mat << std::endl; // error
  Return 0;
}

I simply expect my code to compile but get,

g++ -c -g example1.cpp -o example1.o -I ~/Documents/eigen/
In file included from /home/user/Documents/eigen/Eigen/Core:433:0,
                 from /home/user/Documents/eigen/Eigen/Dense:1,
                 from example1.cpp:2:
/home/user/Documents/eigen/Eigen/src/Core/IO.h: In instantiation of ‘static int Eigen::internal::significant_decimals_impl<Scalar>::run() [with Scalar = __gmp_expr<__mpq_struct [1], __mpq_struct [1]>]’:
/home/user/Documents/eigen/Eigen/src/Core/IO.h:155:66:   required from ‘std::ostream& Eigen::internal::print_matrix(std::ostream&, const Derived&, const Eigen::IOFormat&) [with Derived = Eigen::Matrix<__gmp_expr<__mpq_struct [1], __mpq_struct [1]>, 2, 2>; std::ostream = std::basic_ostream<char>]’
/home/user/Documents/eigen/Eigen/src/Core/IO.h:220:32:   required from ‘std::ostream& Eigen::operator<<(std::ostream&, const Eigen::DenseBase<Derived>&) [with Derived = Eigen::Matrix<__gmp_expr<__mpq_struct [1], __mpq_struct [1]>, 2, 2>; std::ostream = std::basic_ostream<char>]’
example1.cpp:44:42:   required from here
/home/user/Documents/eigen/Eigen/src/Core/IO.h:122:40: error: cannot convert ‘Eigen::NumTraits<__gmp_expr<__mpq_struct [1], __mpq_struct [1]> >::Real {aka __gmp_expr<__mpq_struct [1], __mpq_struct [1]>}’ to ‘int’ in return
     return NumTraits<Scalar>::digits10();
                                        ^
Makefile:12: recipe for target 'example1.o' failed
make: *** [example1.o] Error 1


问:
Cannot read property of undefined on react
I am setting up a client code and the error "Cannot read property '' of undefined" keeps occur.

TypeError: Cannot read property ' ' of undefined

It is interesting that if I refresh the page several times then suddenly it works! For example, the home page is random within 10 times, menu page shows me an error page at the first time, half loaded at first refresh, fully loaded at second refresh.

I think props can't get data correctly right away. So I think I can solve this problem by refreshing automatically until props get correct data.

Is there any way refreshing until I get the props?

Or any other solution about this problem?

menu error

home error

答:
Try to change your if condition to:</p>

```<code>{loading || !data || !data.me ...
</code>```

Body:
Try to change your if condition to:

{loading || !data || !data.me ...


问:
Overloading input the base class inside overloading input derived class
I want to reuse a overloading input functions from Base class inside Derived class.

```<code>class Base
{
private:
    int m_value;

public:
    Base(int value)
        : m_value(value)
    {
    }

    friend std::istream& operator>> (std::istream &in,Base &b)
    {

        in>>b.m_value;
        return in;
    }
};

class Derived : public Base
{
    std::string id;
public:
    Derived(int value,std::string id)
        : Base(value),id(id)
    {
    }

    friend std::istream& operator>> (std::istream &in,Derived &d)
    {
        in>>static_cast<Base>(d);//not work
        in>>d.id;
        return in;
    }
};
</code>```

What wrong with my code when I write in>>static_cast<Base>(d)?

答:
When you do

```<code>static_cast<Base>(d);
</code>```

you get a Base prvalue that has the base part of d.  You can't pass that to

```<code>friend std::istream& operator>> (std::istream &in,Base &b)
</code>```

though since it needs an lvalue.  What you need to do is get a reference to the Base part of d instead like

```<code>in >> static_cast<Base&>(d);
</code>```

Body:
I want to reuse a overloading input functions from Base class inside Derived class.

class Base
{
private:
    int m_value;

public:
    Base(int value)
        : m_value(value)
    {
    }

    friend std::istream& operator>> (std::istream &in,Base &b)
    {

        in>>b.m_value;
        return in;
    }
};

class Derived : public Base
{
    std::string id;
public:
    Derived(int value,std::string id)
        : Base(value),id(id)
    {
    }

    friend std::istream& operator>> (std::istream &in,Derived &d)
    {
        in>>static_cast<Base>(d);//not work
        in>>d.id;
        return in;
    }
};

What wrong with my code when I write in>>static_cast<Base>(d)?

Body:
When you do

static_cast<Base>(d);

you get a Base prvalue that has the base part of d.  You can't pass that to

friend std::istream& operator>> (std::istream &in,Base &b)

though since it needs an lvalue.  What you need to do is get a reference to the Base part of d instead like

in >> static_cast<Base&>(d);


问:
Swift: conformance to the Protocol with Generic method with "where" clause
Summary:

I'd like to create a Class<T> which would have a corresponding ClassDelegate protocol with func<T> in it.

Goal:

To reuse a single object and behavior with multiple object classes. Receive a delegate callback with already a specialized class, without the need to cast the object to a specific class to work with it.

Sample Code:

A protocol with a generic method:

```<code>protocol GenericTableControllerDelegate: AnyObject {
    func controller<T>(controller: GenericTableController<T>, didSelect value: T)
}
</code>```

A generic base UITableViewController subclass:

```<code>open class GenericTableController<DataType>: UITableViewController {
    weak var delegate: GenericTableControllerDelegate?
    var data = [DataType]()

    open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.row]
        delegate?.controller(controller: self, didSelect: item)
    }
}
</code>```

A specialized version of the GenericTableController:

```<code>final class SpecializedTableController: GenericTableController<NSObject> {}
</code>```

Client of the SpecializedTableController - achieves the result, but requires type-casting to be able to access the specialized data type:

```<code>final class ClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) {
        if let value = value as? NSObject {
            // Requires unwrapping and casting
        }
    }
}
</code>```

Client of the SpecializedTableController, with "where" requirement - the only problem that it doesn't compile

```<code>final class AnotherClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) where T: NSObject {
        // `value` is String
    }
}
</code>```

Type 'AnotherClientOfTableController' does not conform to protocol
  'GenericTableControllerDelegate' Do you want to add protocol stubs?

Is there a way to have a protocol with a generic method and being able to have a concrete (specialized) type in that method implementation?

Are there close alternatives achieving satisfying similar requirement (having a generic class but being able to handle a concrete type in the delegate callback)?

答:
Your mistake is in the protocol:

```<code>protocol GenericTableControllerDelegate: AnyObject {
    func controller<T>(controller: GenericTableController<T>, didSelect value: T)
}
</code>```

This says that in order to be a GTCD, a type must accept any type T passed to this function. But you don't mean that. You meant this:

```<code>public protocol GenericTableControllerDelegate: AnyObject {
    associatedtype DataType
    func controller(controller: GenericTableController<DataType>, didSelect value: DataType)
}
</code>```

And then you wanted the delegate's DataType to match the table view's DataType. And that gets us into the world of PATs (protocols with associated types), type erasers, and generalized existentials (which don't exist yet in Swift), and really it just gets to be a mess.

While this is a use case that generalized existentials are particularly well suited for (if they're ever added to Swift), in a lot of cases you probably don't want this anyway. The delegation pattern is an ObjC pattern developed before the addition of closures. It used to be very hard to pass functions around in ObjC, so even very simple callbacks were turned into delegates. In most cases, I think Richard Topchiy's approach is exactly right. Just pass a function.

But what if you really want to keep the delegate style? We can (almost) do that. The one glitch is that you can't have a property called delegate. You can set it, but you can't fetch it.

```<code>open class GenericTableController<DataType>: UITableViewController
{
    // This is the function to actually call
    private var didSelect: ((DataType) -> Void)?

    // We can set the delegate using any implementer of the protocol
    // But it has to be called `controller.setDelegate(self)`.
    public func setDelegate<Delegate: GenericTableControllerDelegate>(_ d: Delegate?)
        where Delegate.DataType == DataType {
            if let d = d {
                didSelect = { [weak d, weak self] in
                    if let self = self { d?.controller(controller: self, didSelect: $0) }
                }
            } else {
                didSelect = nil
            }
    }

    var data = [DataType]()

    // and here, just call our internal method
    open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.row]
        didSelect?(item)
    }
}
</code>```

This is a useful technique to understand, but I probably wouldn't use it in most cases. There's definitely a headache as you add more methods, if those methods reference DataType. You require a lot of boilerplate. Note that there's a bit of messiness due to passing self to the delegate method. That's something delegate methods need, but closures do not (you can always capture the controller in the closure if the closure needs it).

As you explore this kind of reusable code, I encourage you to think more about encapsulating strategies rather than about objects and delegate protocols. An example of encapsulating a strategy would be to have a SelectionHandler type that you hand to the controller:

```<code>struct SelectionHandler<Element> {
    let didSelect: (Element) -> Void
}
</code>```

With that, you can build simple strategies like "print it out:"

```<code>extension SelectionHandler {
    static func printSelection() -> SelectionHandler {
        return SelectionHandler { print($0) }
    }
}
</code>```

Or more interestingly, update a label:

```<code>static func update(label: UILabel) -> SelectionHandler {
    return SelectionHandler { [weak label] in label?.text = "\($0)" }
}
</code>```

So then you get code like:

```<code>controller.selectionHandler = .update(label: self.nameLabel)
</code>```

Or, even more interestingly, you can build higher-order types:

```<code>static func combine(_ handlers: [SelectionHandler]) -> SelectionHandler {
    return SelectionHandler {
        for handler in handlers {
            handler.didSelect($0)
        }
    }
}

static func trace(_ handler: SelectionHandler) -> SelectionHandler {
    return .combine([.printSelection(), handler])
}

controller.selectionHandler = .trace(.update(label: self.nameLabel))
</code>```

This approach composes much more powerfully than delegation, and starts to unlock the real advantages of Swift.

Body:
Summary:

I'd like to create a Class<T> which would have a corresponding ClassDelegate protocol with func<T> in it.

Goal:

To reuse a single object and behavior with multiple object classes. Receive a delegate callback with already a specialized class, without the need to cast the object to a specific class to work with it.

Sample Code:

A protocol with a generic method:

protocol GenericTableControllerDelegate: AnyObject {
    func controller<T>(controller: GenericTableController<T>, didSelect value: T)
}

A generic base UITableViewController subclass:

open class GenericTableController<DataType>: UITableViewController {
    weak var delegate: GenericTableControllerDelegate?
    var data = [DataType]()

    open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.row]
        delegate?.controller(controller: self, didSelect: item)
    }
}

A specialized version of the GenericTableController:

final class SpecializedTableController: GenericTableController<NSObject> {}

Client of the SpecializedTableController - achieves the result, but requires type-casting to be able to access the specialized data type:

final class ClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) {
        if let value = value as? NSObject {
            // Requires unwrapping and casting
        }
    }
}

Client of the SpecializedTableController, with "where" requirement - the only problem that it doesn't compile

final class AnotherClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) where T: NSObject {
        // `value` is String
    }
}

Type 'AnotherClientOfTableController' does not conform to protocol
  'GenericTableControllerDelegate' Do you want to add protocol stubs?

Is there a way to have a protocol with a generic method and being able to have a concrete (specialized) type in that method implementation?

Are there close alternatives achieving satisfying similar requirement (having a generic class but being able to handle a concrete type in the delegate callback)?

Body:
Your mistake is in the protocol:

protocol GenericTableControllerDelegate: AnyObject {
    func controller<T>(controller: GenericTableController<T>, didSelect value: T)
}

This says that in order to be a GTCD, a type must accept any type T passed to this function. But you don't mean that. You meant this:

public protocol GenericTableControllerDelegate: AnyObject {
    associatedtype DataType
    func controller(controller: GenericTableController<DataType>, didSelect value: DataType)
}

And then you wanted the delegate's DataType to match the table view's DataType. And that gets us into the world of PATs (protocols with associated types), type erasers, and generalized existentials (which don't exist yet in Swift), and really it just gets to be a mess.

While this is a use case that generalized existentials are particularly well suited for (if they're ever added to Swift), in a lot of cases you probably don't want this anyway. The delegation pattern is an ObjC pattern developed before the addition of closures. It used to be very hard to pass functions around in ObjC, so even very simple callbacks were turned into delegates. In most cases, I think Richard Topchiy's approach is exactly right. Just pass a function.

But what if you really want to keep the delegate style? We can (almost) do that. The one glitch is that you can't have a property called delegate. You can set it, but you can't fetch it.

open class GenericTableController<DataType>: UITableViewController
{
    // This is the function to actually call
    private var didSelect: ((DataType) -> Void)?

    // We can set the delegate using any implementer of the protocol
    // But it has to be called `controller.setDelegate(self)`.
    public func setDelegate<Delegate: GenericTableControllerDelegate>(_ d: Delegate?)
        where Delegate.DataType == DataType {
            if let d = d {
                didSelect = { [weak d, weak self] in
                    if let self = self { d?.controller(controller: self, didSelect: $0) }
                }
            } else {
                didSelect = nil
            }
    }

    var data = [DataType]()

    // and here, just call our internal method
    open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.row]
        didSelect?(item)
    }
}

This is a useful technique to understand, but I probably wouldn't use it in most cases. There's definitely a headache as you add more methods, if those methods reference DataType. You require a lot of boilerplate. Note that there's a bit of messiness due to passing self to the delegate method. That's something delegate methods need, but closures do not (you can always capture the controller in the closure if the closure needs it).

As you explore this kind of reusable code, I encourage you to think more about encapsulating strategies rather than about objects and delegate protocols. An example of encapsulating a strategy would be to have a SelectionHandler type that you hand to the controller:

struct SelectionHandler<Element> {
    let didSelect: (Element) -> Void
}

With that, you can build simple strategies like "print it out:"

extension SelectionHandler {
    static func printSelection() -> SelectionHandler {
        return SelectionHandler { print($0) }
    }
}

Or more interestingly, update a label:

static func update(label: UILabel) -> SelectionHandler {
    return SelectionHandler { [weak label] in label?.text = "\($0)" }
}

So then you get code like:

controller.selectionHandler = .update(label: self.nameLabel)

Or, even more interestingly, you can build higher-order types:

static func combine(_ handlers: [SelectionHandler]) -> SelectionHandler {
    return SelectionHandler {
        for handler in handlers {
            handler.didSelect($0)
        }
    }
}

static func trace(_ handler: SelectionHandler) -> SelectionHandler {
    return .combine([.printSelection(), handler])
}

controller.selectionHandler = .trace(.update(label: self.nameLabel))

This approach composes much more powerfully than delegation, and starts to unlock the real advantages of Swift.


问:
Why this sprintf statement crashing?
```<code>char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here
</code>```

If I format only current, then it is ok.

```<code>sprintf(filebuf,"%s",current);
</code>```

Output:

```<code>CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release
</code>```

答: %s indicates a C string. You have a C++ string. You need to call .c_str()

Title: Why this sprintf statement crashing?

Body:
char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here

If I format only current, then it is ok.

sprintf(filebuf,"%s",current);

Output:

CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release


问:
Can't get checkpoint to load in Flink
I'd like for the latest checkpoint to be loaded in Flink but it just isn't. I've written a word count application that is meant to resume counting where it left off after a restart. I am running it from my IDE so I'm not starting a Flink cluster.

Here's the code I wrote https://github.com/edu05/wordcount/tree/simple
Which is inspired from the example provided by the Flink creators on checkpointing... https://github.com/streaming-with-flink/examples-scala

What am I missing? How can I also avoid re-printing some of the word counts? I don't see many contributors in Stackoverflow on Apache Flink, is there another more appropriate forum?

答:
Checkpoints are by default not retained and are only used to resume a job from failures.

If you need to start your job from a retained checkpoint you have to do it manually just as from savepoint by the following way:

$ bin/flink run -s :checkpointMetaDataPath [:runArgs]
```

Title: Can't get checkpoint to load in Flink


答:
First you need check exist of data, and then fields in this object:

```<code>loading || (data && (!data.me || !data.getPlaces)) ? ...
</code>```

Title: Cannot read property of undefined on react

Body:
I am setting up a client code and the error "Cannot read property '' of undefined" keeps occur.

TypeError: Cannot read property ' ' of undefined

It is interesting that if I refresh the page several times then suddenly it works! For example, the home page is random within 10 times, menu page shows me an error page at the first time, half loaded at first refresh, fully loaded at second refresh.

I think props can't get data correctly right away. So I think I can solve this problem by refreshing automatically until props get correct data.

Is there any way refreshing until I get the props?

Or any other solution about this problem?

menu error

home error

Body:
First you need check exist of data, and then fields in this object:

loading || (data && (!data.me || !data.getPlaces)) ? ...


问:
Exclude all email records from a domain except those that begin with a string
I'm trying to exclude all records in a table from a specific domain except for those that begin with a specific string.

So, for example I have a bunch of records with yopmail.com as the domain.  I want to exclude all records from yopmail.com except those that start with abc.

The current code to exclude is just WHERE emailAddress NOT LIKE '%yopmail.com', but now I need to figure out how to add to that except 'WHERE emailAddress LIKE abc%yopmail.com'.

I've wracked my brain for how to do this and I can't come up with anything useful.

Ben

答:
You just need to add another condition on your WHERE clause:

```<code>SELECT *
FROM MyTable
WHERE emailAddress NOT LIKE '%yopmail.com' OR emailAddress LIKE 'abc%yopmail.com'
</code>```

Body:
You just need to add another condition on your WHERE clause:

SELECT *
FROM MyTable
WHERE emailAddress NOT LIKE '%yopmail.com' OR emailAddress LIKE 'abc%yopmail.com'


问:
Need help in cypress to read data from excel/csv
I am trying to read the test cases from excel and then pass it to cypress to execute it.

What I want is that my excel will be consist of all sites

```<code>abc.com, example.com ,xyz.com
</code>```

like 50 to 100 such a sites

and then pass it to cypress and cypress will execute each site for 100 sites.

I tried to this by reading cypress plugins but not so sure on how I can do this. Any guidance will be very helpful

My goal is to run test cases like the site is loading for more than 100 sites

Any suggestions?

答:
You could use the Cypress Module API to do this programmatically, by changing the baseUrl of the tests each time.

Something like this should work, just as a Node script:

const cypress = require('cypress')

const baseUrlList = loadSitesFromExcel()

// create a recursive Promise chain
function runTests(i = 0) {
  if (i == baseUrlList.length) {
    return Promise.resolve()
  }

  return cypress.run({
    config: {
      baseUrl: baseUrlList[i]
    }
  })
  .then((results) => {
    // do something with results, then run next test
    return runTests(i + 1)
  })
}

// begin
runTests()
```

Body:
I am trying to read the test cases from excel and then pass it to cypress to execute it.

What I want is that my excel will be consist of all sites

abc.com, example.com ,xyz.com

like 50 to 100 such a sites

and then pass it to cypress and cypress will execute each site for 100 sites.

I tried to this by reading cypress plugins but not so sure on how I can do this. Any guidance will be very helpful

My goal is to run test cases like the site is loading for more than 100 sites

Any suggestions?