问:
Use RelayCommand of my ViewModel in another Class
I'm currently making a FileExplorer in C# WPF. My ViewModel loads up the directories of the Sidebar and the Directories of the main field of the explorer. I tried to make it look like the Windows File Explorer.
So let's say the application is starting at C:\users\myname. My application loads all the directories in this path and displays it as buttons. Now once I click on the button, I want to move to the directory I'm clicking on.

Example: C:\users\myname -> C:\users\myname\desktop
The path is linked to the Button and given as Command Parameter, but I can't access the button, as the ItemSource is a List inside my ViewModel and not the ViewModel itself.
So the compiler tells me it can't find the RelayCommand, because it's not part of NavigationDirectory.cs

NavigationDirectory.cs:

```<code>   public class NavigationDirectory
    {
        public NavigationDirectory(string directoryName, DateTime creationTime, DateTime changeTime, string path)
        {
            DirectoryName = directoryName;
            CreationTime = creationTime;
            ChangeTime = changeTime;
            Path = path;
        }

        public string DirectoryName { get; set; }

        public string Path { get; set; }

        public DateTime CreationTime { get; set; }

        public DateTime ChangeTime { get; set; }
    }
</code>```

Command in my ViewModel I'm trying to access:

```<code> public RelayCommand MainDirectoryLoad { get; set; }

 public MainViewModel()
        {
            LoadMainDirectory();
            MainDirectoryLoad = new RelayCommand(o => LoadMainDirectory());
        }
 public void LoadMainDirectory(string path = @"C:\Users\renes\")
        {
            NavigationPath = path;
            MainDirectory = new List<NavigationDirectory>();
            var directories = Directory.GetDirectories(NavigationPath);
            foreach (string file in directories)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(file);
                SidebarDirectory = new NavigationDirectory(
                    dirInfo.Name,
                    dirInfo.CreationTime,
                    dirInfo.LastWriteTime,
                    dirInfo.FullName);
                MainDirectory.Add(SidebarDirectory);
            }
        }

</code>```

The ListBox in my .xaml I want to use the Command in:

```<code>     <ListBox Grid.Row="3" Grid.Column="1" Margin="5" ItemsSource="{Binding MainDirectory}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal" IsItemsHost="True"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Button  Width="150" Height="50" HorizontalContentAlignment="Left" Style="{StaticResource NavigationButton}"
                             Command="{Binding MainDirectoryLoading}" CommandParameter="{Binding Path}">
                        <StackPanel Orientation="Horizontal">
                            <Image Source="/Images/icons/folder.png" Margin="5"/>
                            <StackPanel Orientation="Vertical">
                                <TextBlock Text="{Binding DirectoryName}" Style="{StaticResource NavigationTextBlock}"/>
                                <TextBlock Text="{Binding Path}" Style="{StaticResource NavigationTextBlock}" FontSize="10" Foreground="Gray"/>
                                <TextBlock Text="{Binding ChangeTime}" Style="{StaticResource NavigationTextBlock}" FontSize="8" Foreground="DarkGray"/>
                            </StackPanel>
                        </StackPanel>
                    </Button>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
</code>```

Is there any way on how to use the RelayCommand of my MainViewModel inside my NavigationDirectory Class or is there a way of passing the Command in the xaml, even though the ItemSource is not the MainViewModel?

If not, then what's a good way to solve this issue? Making a new Command in my NavigationDirectory would mean that I would have to pass parameters like the NavigationPath into it aswell.

答:
You could bind to a property of a visual ancestor using a {RelativeSource}:

```<code>Command="{Binding DataContext.MainDirectoryLoad,
    RelativeSource={RelativeSource AncestorType=ListBox}}"
</code>```

Make sure that the name of the properties match. In the XAML you have posted, you try to bind to some MainDirectoryLoading property but the property in your code seems to be called MainDirectoryLoad.

Body:
I'm currently making a FileExplorer in C# WPF. My ViewModel loads up the directories of the Sidebar and the Directories of the main field of the explorer. I tried to make it look like the Windows File Explorer.
So let's say the application is starting at C:\users\myname. My application loads all the directories in this path and displays it as buttons. Now once I click on the button, I want to move to the directory I'm clicking on.

Example: C:\users\myname -> C:\users\myname\desktop
The path is linked to the Button and given as Command Parameter, but I can't access the button, as the ItemSource is a List inside my ViewModel and not the ViewModel itself.
So the compiler tells me it can't find the RelayCommand, because it's not part of NavigationDirectory.cs

NavigationDirectory.cs:

   public class NavigationDirectory
    {
        public NavigationDirectory(string directoryName, DateTime creationTime, DateTime changeTime, string path)
        {
            DirectoryName = directoryName;
            CreationTime = creationTime;
            ChangeTime = changeTime;
            Path = path;
        }

        public string DirectoryName { get; set; }

        public string Path { get; set; }

        public DateTime CreationTime { get; set; }

        public DateTime ChangeTime { get; set; }
    }

Command in my ViewModel I'm trying to access:

 public RelayCommand MainDirectoryLoad { get; set; }

 public MainViewModel()
        {
            LoadMainDirectory();
            MainDirectoryLoad = new RelayCommand(o => LoadMainDirectory());
        }
 public void LoadMainDirectory(string path = @"C:\Users\renes\")
        {
            NavigationPath = path;
            MainDirectory = new List<NavigationDirectory>();
            var directories = Directory.GetDirectories(NavigationPath);
            foreach (string file in directories)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(file);
                SidebarDirectory = new NavigationDirectory(
                    dirInfo.Name,
                    dirInfo.CreationTime,
                    dirInfo.LastWriteTime,
                    dirInfo.FullName);
                MainDirectory.Add(SidebarDirectory);
            }
        }

The ListBox in my .xaml I want to use the Command in:

     <ListBox Grid.Row="3" Grid.Column="1" Margin="5" ItemsSource="{Binding MainDirectory}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal" IsItemsHost="True"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Button  Width="150" Height="50" HorizontalContentAlignment="Left" Style="{StaticResource NavigationButton}"
                             Command="{Binding MainDirectoryLoading}" CommandParameter="{Binding Path}">
                        <StackPanel Orientation="Horizontal">
                            <Image Source="/Images/icons/folder.png" Margin="5"/>
                            <StackPanel Orientation="Vertical">
                                <TextBlock Text="{Binding DirectoryName}" Style="{StaticResource NavigationTextBlock}"/>
                                <TextBlock Text="{Binding Path}" Style="{StaticResource NavigationTextBlock}" FontSize="10" Foreground="Gray"/>
                                <TextBlock Text="{Binding ChangeTime}" Style="{StaticResource NavigationTextBlock}" FontSize="8" Foreground="DarkGray"/>
                            </StackPanel>
                        </StackPanel>
                    </Button>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Is there any way on how to use the RelayCommand of my MainViewModel inside my NavigationDirectory Class or is there a way of passing the Command in the xaml, even though the ItemSource is not the MainViewModel?

If not, then what's a good way to solve this issue? Making a new Command in my NavigationDirectory would mean that I would have to pass parameters like the NavigationPath into it aswell.

Body:
You could bind to a property of a visual ancestor using a {RelativeSource}:

Command="{Binding DataContext.MainDirectoryLoad,
    RelativeSource={RelativeSource AncestorType=ListBox}}"

Make sure that the name of the properties match. In the XAML you have posted, you try to bind to some MainDirectoryLoading property but the property in your code seems to be called MainDirectoryLoad.


来源: stackexchange

问:
Heap corruption in HP-UX?
I'm trying to understand what's going wrong with a program run in HP-UX 11.11 that results in a SIGSEGV (11, segmentation fault):

```<code>(gdb) bt
#0  0x737390e8 in _sigfillset+0x618 () from /usr/lib/libc.2
#1  0x73736a8c in _sscanf+0x55c () from /usr/lib/libc.2
#2  0x7373c23c in malloc+0x18c () from /usr/lib/libc.2
#3  0x7379e3f8 in _findbuf+0x138 () from /usr/lib/libc.2
#4  0x7379c9f4 in _filbuf+0x34 () from /usr/lib/libc.2
#5  0x7379c604 in __fgets_unlocked+0x84 () from /usr/lib/libc.2
#6  0x7379c7fc in fgets+0xbc () from /usr/lib/libc.2
#7  0x7378ecec in __nsw_getoneconfig+0xf4 () from /usr/lib/libc.2
#8  0x7378f8b8 in __nsw_getconfig+0x150 () from /usr/lib/libc.2
#9  0x737903a8 in __thread_cond_init_default+0x100 () from /usr/lib/libc.2
#10 0x737909a0 in nss_search+0x80 () from /usr/lib/libc.2
#11 0x736e7320 in __gethostbyname_r+0x140 () from /usr/lib/libc.2
#12 0x736e74bc in gethostbyname+0x94 () from /usr/lib/libc.2
#13 0x11780 in dnetResolveName (name=0x400080d8 "smtp.org.com", hent=0x737f3334) at src/dnet.c:64
..
</code>```

The problem seems to be occurring somewhere inside libc! A system call trace ends with:

```<code>Connecting to server smtp.org.com on port 25
write(1, "C o n n e c t i n g   t o   s e ".., 51) .......................... = 51
open("/etc/nsswitch.conf", O_RDONLY, 0666) ............................... [entry]
open("/etc/nsswitch.conf", O_RDONLY, 0666) ................................... = 5
  Received signal 11, SIGSEGV, in user mode, [SIG_DFL], partial siginfo
    Siginfo: si_code: I_NONEXIST, faulting address: 0x400118fc, si_errno: 0
    PC: 0xc01980eb, instruction: 0x0d3f1280
exit(11) [implicit] ............................ WIFSIGNALED(SIGSEGV)|WCOREDUMP
</code>```

Last instruction by the program:

```<code>struct hostent *him;
him = gethostbyname(name); // name == "smtp.org.com" as shown by gdb
</code>```

Is this a problem with the system, or am I missing something?
Any guidance for digging deeper would be appreciated.

Thx.

答:
Your stack trace is in malloc which almost certainly means that somewhere you corrupted one of malloc's data structures. As a previous answer said, you likely have a buffer overrun or underrun and corrupted one of the items allocated off the heap.

Another explanation is that you tried to do a free on something that didn't come from the heap, but that's less likely--that would probably have crashed right in free.

ContentLicense: CC BY-SA 2.5

Title: Heap corruption in HP-UX?

Body:
I'm trying to understand what's going wrong with a program run in HP-UX 11.11 that results in a SIGSEGV (11, segmentation fault):

(gdb) bt
#0  0x737390e8 in _sigfillset+0x618 () from /usr/lib/libc.2
#1  0x73736a8c in _sscanf+0x55c () from /usr/lib/libc.2
#2  0x7373c23c in malloc+0x18c () from /usr/lib/libc.2
#3  0x7379e3f8 in _findbuf+0x138 () from /usr/lib/libc.2
#4  0x7379c9f4 in _filbuf+0x34 () from /usr/lib/libc.2
#5  0x7379c604 in __fgets_unlocked+0x84 () from /usr/lib/libc.2
#6  0x7379c7fc in fgets+0xbc () from /usr/lib/libc.2
#7  0x7378ecec in __nsw_getoneconfig+0xf4 () from /usr/lib/libc.2
#8  0x7378f8b8 in __nsw_getconfig+0x150 () from /usr/lib/libc.2
#9  0x737903a8 in __thread_cond_init_default+0x100 () from /usr/lib/libc.2
#10 0x737909a0 in nss_search+0x80 () from /usr/lib/libc.2
#11 0x736e7320 in __gethostbyname_r+0x140 () from /usr/lib/libc.2
#12 0x736e74bc in gethostbyname+0x94 () from /usr/lib/libc.2
#13 0x11780 in dnetResolveName (name=0x400080d8 "smtp.org.com", hent=0x737f3334) at src/dnet.c:64
..

The problem seems to be occurring somewhere inside libc! A system call trace ends with:

Connecting to server smtp.org.com on port 25
write(1, "C o n n e c t i n g   t o   s e ".., 51) .......................... = 51
open("/etc/nsswitch.conf", O_RDONLY, 0666) ............................... [entry]
open("/etc/nsswitch.conf", O_RDONLY, 0666) ................................... = 5
  Received signal 11, SIGSEGV, in user mode, [SIG_DFL], partial siginfo
    Siginfo: si_code: I_NONEXIST, faulting address: 0x400118fc, si_errno: 0
    PC: 0xc01980eb, instruction: 0x0d3f1280
exit(11) [implicit] ............................ WIFSIGNALED(SIGSEGV)|WCOREDUMP

Last instruction by the program:

struct hostent *him;
him = gethostbyname(name); // name == "smtp.org.com" as shown by gdb

Is this a problem with the system, or am I missing something?
Any guidance for digging deeper would be appreciated.

Thx.

OwnerDisplayName: Jared Oberhaus


问:
writing url to form input value
Problem: I don't know why my script is not loading a value into the selected input section of a form

Scenario:
The page, call it the host page, permanently displays a dialog with a link as the content. If a user clicks on the link another dialog, call it the "form dialog" opens with a form. Some items are inserted into the form by the code - platform, browser and url of the host page.

It’s the URL that is not working.

The URL is acquired on the host page and stored as a .data item for recovery by the "form dialog" script.
I tested this on a simpler set up and it worked perfectly however, it refuses to work on the current set up.

Symptoms:
The URL is read and stored as expected but the script is not writing it into the form. The approach I've used is to add a callback function when the dialog is first loaded. The callback uses a .val() function to write the data to the form, or at least that's the intention.
The value is written to the form during the dialog setup so that when the user clicks the information is already loaded into the form.

I'd appreciate any pointers or suggestions as to what might be the cause of the problem and/or how to correct it.

Thanks.

script:

```<code>enter <script type="text/javascript">
//Triggers a modal containing the feedback form.
$(document).ready(function() {
$('#target a').each(function() {
    var $link = $(this);
    var $dialog = $('<div></div>')
        .load($link.attr('href'))
        .dialog({
            autoOpen: false,
            title: $link.attr('title'),
            width: 600,
            height: 500,
            modal:  true,
            open:   function (event,ui) {
                $("input[name='url']").val($('body').data('value2'));

            }
        });

    $link.click(function() {
        $dialog.dialog('open');
        $( "#accordion" ).accordion({
            collapsible: true,
            active: false
        });
        return false;
    });
});
});
</script>
</code>```

HOST PAGE

```<code><html xmlns="http://www.w3.org/1999/xhtml">

</head>

<body>

<!--Script to get the url of the page and store it as a data item for use on the form -->
<script type="text/javascript">
<?php
     $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
     ?>
var pageAddress="<?php echo $url?>";

$('body').data('value2', pageAddress );

</script>
<p>The following just confirms that the  url is being stored on the page</p>
<div>
The URL value stored on the page is
<span id='urlcheck'></span>
<p>The location is
</p>

<script type="text/javascript">
$("span#urlcheck").html("<p>" +$("body").data("value2")+ "</p>");
</script>
</div>

<!--Check to see if the cookie is set -->
<?php include ('../_assets/include_files/checkreaderStatus.php');?>
<!-- The following file is for development only. It adds a navigation menu to pages in   which its included. -->
<?php  include('../_assets/include_files/navigation.html');?>
<!--------------------------------------------------------------------------->
<!-- Start The Page Display -->
<h1>Page 1 Of The Blog</h1>
<p>This page simulates the page on the blog where testers will land.</p>

<!--Dialog for the "Feedback Form Button -->
<script type="text/javascript">
//Reads the flag readerStatus, if set creates a dialog with a permanently displayed "Feedback Button". NOTE TO SELF: This has to be on the page in order for the php to be to be processed by the server!
var readerStatus="<?php echo $readerStatus; ?>";
if (readerStatus == "tester") {
    $(function(){
        $("#dialog").dialog();
                })
}
</script>

<!-- Content for the Feedback Form Button -->
<div id="dialog" title="Feedback Button">
<div  title="Feedback Form">
    <p id='target'><a href="feedbackform.php"  title='Feedback Form' >Feedback   Form</a></p>
    <p class="notes">This form is dragable and resizable</p>
</div>
</div>

<script type="text/javascript">
//Triggers a modal containing the feedback form.
$(document).ready(function() {
$('#target a').each(function() {
    var $link = $(this);
    var $dialog = $('<div></div>')
        .load($link.attr('href'))
        .dialog({
            autoOpen: false,
            title: $link.attr('title'),
            width: 600,
            height: 500,
            modal:  true,
            open:   function (event,ui) {
                $("input[name='url']").val($('body').data('value2'));

            }
        });

    $link.click(function() {
        $dialog.dialog('open');
        $( "#accordion" ).accordion({
            collapsible: true,
            active: false
        });
        return false;
    });
});
});
</script>
</body>
</html>
</code>```

Feedback Form

    Feedback Form

```<code><link rel="stylesheet" type="text/css" href="../_assets/scripts/black-tie/jquery-ui-1.8.4.custom.css" />
</head>

<body>

<?php
$browser = get_browser(null, true);
?>
<!-- ajax form next? -->
<script type="text/javascript">
$(document).ready(function() {
var options = {
    target : '#output1',
    url:    'comments.php',
    clearForm:  'true'
};
// bind 'myForm' and provide a simple callback function
$('#myform').ajaxForm(options);
return false;
});
</script>
<!-- Script to execute text prompts in the fields -->
<!-- optional name -->
<script type="text/javascript" id="demoscript">
$(document).ready(function(){
  //Optionsal Name
    $("#textTagDemo").fieldtag();
  //Textarea
    $("#area").fieldtag();
});
</script>

<div id="accordion">
<h3><a href="#">Instructions</a></h3>
    <div>
        <p>
        Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
        ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
        amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
        odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
        </p>
    </div>
<h3><a href="#">Broken Links</a></h3>
<div>
<form action="comments.php" method="post" name="broken_Links" id="myform" >
                <fieldset>
                    <p>
                        <input name="name" type="text" size="50" id="textTagDemo" title="OPTIONAL: Add your name" />

                    </p>
                    <p>
                        <input name="nowhere" type="radio" value="linknowhere" />Link is
                        broken and doesn't go anywhere
                    </p>
                    <p>
                        <input name="wrong_url" type="radio" value="linktowrongurl" />Link
                        goes to an unexpected destination
                    </p>
                    <p>
                        <input name="other" type="radio" value="linkother" />Other -
                        Please explain in the description box below
                    </p>
                    <em>Description</em>
                    <p>Please add as much descripton as you can about the problem you
                        noticed</p>
                    <textarea name="description" id="area" cols="50" rows="10" title="Please add as much description as you can."></textarea>
                    <p>
                        Page Address: <br /> <input name="url" type="text" value=""
                            id="targetURL" size="100" title="Page Address" />
                    </p>
                    <p>
                        Browser<input name="browser" type="text"
                            value="<?php echo $browser['browser'] ?>" />
                    </p>
                    <p>
                        Operating System<input name="operating_system" type="text"
                            value="<?php echo $browser['platform'] ?>" />
                    </p>
                    <p>
                        <input type="submit" name="submit" id="button" value="Submit" />
                    </p>
                </fieldset>
            </form>
    <!-- server response -->
            <h2>Output Response</h2>
            <p id="output1">

            </p>
            <!--End form 4 broken links-->
</div>
<h3><a href="#">Errors In The Text</a></h3>
<div>
    <p>
    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
    </p>
    <ul>
        <li>List item one</li>
        <li>List item two</li>
        <li>List item three</li>
    </ul>
</div>
<h3><a href="#">Confusing Layout</a></h3>
<div>
    <p>
    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.
    </p>
    <p>
    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.
    </p>
</div>
</div>
</body>
</html>
</code>```

答:
The problem I suppose is that you put the data onto the body without it being wrapped inside a  $(document).ready() clause.

For a quick fix you can define the url just as a variable, and then access that variable inside your script.

example:

http://jsfiddle.net/LF2rs/1/

Ps:
I would recommend reading into seperating your php code (using templates), your javascript (place them seperately in a .js file!). This will make it a lot easier and manageble to spot and prevent mistakes.

ContentLicense: CC BY-SA 3.0

Title: writing url to form input value

Body:
Problem: I don't know why my script is not loading a value into the selected input section of a form

Scenario:
The page, call it the host page, permanently displays a dialog with a link as the content. If a user clicks on the link another dialog, call it the "form dialog" opens with a form. Some items are inserted into the form by the code - platform, browser and url of the host page.

It’s the URL that is not working.

The URL is acquired on the host page and stored as a .data item for recovery by the "form dialog" script.
I tested this on a simpler set up and it worked perfectly however, it refuses to work on the current set up.

Symptoms:
The URL is read and stored as expected but the script is not writing it into the form. The approach I've used is to add a callback function when the dialog is first loaded. The callback uses a .val() function to write the data to the form, or at least that's the intention.
The value is written to the form during the dialog setup so that when the user clicks the information is already loaded into the form.

I'd appreciate any pointers or suggestions as to what might be the cause of the problem and/or how to correct it.

Thanks.

script:

enter

HOST PAGE

The following just confirms that the  url is being stored on the page

The URL value stored on the page is

The location is

<?php include ('../_assets/include_files/checkreaderStatus.php');?>

<?php  include('../_assets/include_files/navigation.html');?>

Page 1 Of The Blog

This page simulates the page on the blog where testers will land.

Feedback   Form

This form is dragable and resizable

Feedback Form

    Feedback Form

<link rel="stylesheet" type="text/css" href="../_assets/scripts/black-tie/jquery-ui-1.8.4.custom.css" />

<?php
$browser = get_browser(null, true);
?>

Instructions

        Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
        ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
        amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
        odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

Broken Links

<form action="comments.php" method="post" name="broken_Links" id="myform" >
                <fieldset>

                        <input name="name" type="text" size="50" id="textTagDemo" title="OPTIONAL: Add your name" />

                        <input name="nowhere" type="radio" value="linknowhere" />Link is
                        broken and doesn't go anywhere

                        <input name="wrong_url" type="radio" value="linktowrongurl" />Link
                        goes to an unexpected destination

                        <input name="other" type="radio" value="linkother" />Other -
                        Please explain in the description box below

                    Description

Please add as much descripton as you can about the problem you
                        noticed

                    <textarea name="description" id="area" cols="50" rows="10" title="Please add as much description as you can."></textarea>

                        Page Address:
 <input name="url" type="text" value=""
                            id="targetURL" size="100" title="Page Address" />

                        Browser<input name="browser" type="text"
                            value="<?php echo $browser['browser'] ?>" />

                        Operating System<input name="operating_system" type="text"
                            value="<?php echo $browser['platform'] ?>" />

                        <input type="submit" name="submit" id="button" value="Submit" />

                </fieldset>
            </form>

Output Response

Errors In The Text

    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.

List item one

List item two

List item three

Confusing Layout

    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.

    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.


问:
Checking schema on ingest Pyspark
I have a file that changes schema quite often.

For example, in the below, the invoice date can be of differing formats and invoice value can be of differing format (sometimes with a $ sometimes without and sometimes with other currency).

I want to be able to scan the dataframe column by column and say:
- If there is a non numeric character (except a . ) in the invoice value column, then.... I can then define the schema to apply to the file differently.

Is it possible?

答:
Check below code, here invoice value will be floating number and date format have taken for example, you can change it as per required.</p>

```<code>from pyspark.sql.functions import *
from pyspark.sql.functions import expr
import pyspark.sql.functions as f

df = sc.parallelize([["ThoughtStorm","11/23/2019","$6.09","true"],
["Talane","3/28/2019","£7.20","true"]]).toDF(("company_name","invoice_date","invoice_value","paid"))
df = df.withColumn("invoice_value",regexp_extract(col("invoice_value"), """([0-9]*[.])?[0-9]+""", 0))
df = df.withColumn("invoice_date", f.date_format(f.to_date(f.unix_timestamp(col("invoice_date"), "mm/dd/yyyy").cast("timestamp")), 'yyyy-MM-dd'))
df.show()
+------------+------------+-------------+----+
|company_name|invoice_date|invoice_value|paid|
+------------+------------+-------------+----+
|ThoughtStorm|  2019-01-23|         6.09|true|
|      Talane|  2019-01-28|         7.20|true|
+------------+------------+-------------+----+
</code>```

ContentLicense: CC BY-SA 4.0

Title: Checking schema on ingest Pyspark

Body:
Check below code, here invoice value will be floating number and date format have taken for example, you can change it as per required.

from pyspark.sql.functions import *
from pyspark.sql.functions import expr
import pyspark.sql.functions as f

df = sc.parallelize([["ThoughtStorm","11/23/2019","$6.09","true"],
["Talane","3/28/2019","£7.20","true"]]).toDF(("company_name","invoice_date","invoice_value","paid"))
df = df.withColumn("invoice_value",regexp_extract(col("invoice_value"), """([0-9]*[.])?[0-9]+""", 0))
df = df.withColumn("invoice_date", f.date_format(f.to_date(f.unix_timestamp(col("invoice_date"), "mm/dd/yyyy").cast("timestamp")), 'yyyy-MM-dd'))
df.show()
+------------+------------+-------------+----+
|company_name|invoice_date|invoice_value|paid|
+------------+------------+-------------+----+
|ThoughtStorm|  2019-01-23|         6.09|true|
|      Talane|  2019-01-28|         7.20|true|
+------------+------------+-------------+----+


问:
Grouping sets size cannot be greater than 64 : Hive
I have 70 columns in my hive table i want to fetch all the rows which have exactly all the 70 matching columns.i.e. if two rows contain same data in all the column then i need to find that row and count as '2'. I'm writing below query.

```<code>    SELECT (all 70 columns),COUNT(*) AS CountOf FROM tablename GROUP BY (all 70 columns)
    HAVING  COUNT(*)>1;
</code>```

but its showing

```<code>    Error: Error while compiling statement: FAILED: SemanticException [Error 10411]:
    Grouping sets size cannot be
    greater than 64 (state=42000,code=10411)
</code>```

is there any way to find the exact duplicate rows's count from hive table?

答:
It's a bug HIVE-21135 in Hive 3.1.0 version, it is fixed in the Hive 4.0.0, see HIVE-21018, not backported.

Try to concatenate columns using delimiter in the subquery before aggregation as a workaround, I'm not sure will it help or not.

like this, using concat() or concat_ws or || operator:

```<code>select concat_ws ('~', col1, col2, col3, col4)
...
group by concat_ws ('~', col1, col2, col3, col4)
</code>```

or

```<code>col1||'~'||col2||'~'||...||colN
</code>```

NULLs should be taken care also. Replace nulls with empty strings before concatenation using NVL function.

Body:
I have 70 columns in my hive table i want to fetch all the rows which have exactly all the 70 matching columns.i.e. if two rows contain same data in all the column then i need to find that row and count as '2'. I'm writing below query.

    SELECT (all 70 columns),COUNT(*) AS CountOf FROM tablename GROUP BY (all 70 columns)
    HAVING  COUNT(*)>1;

but its showing

    Error: Error while compiling statement: FAILED: SemanticException [Error 10411]:
    Grouping sets size cannot be
    greater than 64 (state=42000,code=10411)

is there any way to find the exact duplicate rows's count from hive table?

Body:
It's a bug HIVE-21135 in Hive 3.1.0 version, it is fixed in the Hive 4.0.0, see HIVE-21018, not backported.

Try to concatenate columns using delimiter in the subquery before aggregation as a workaround, I'm not sure will it help or not.

like this, using concat() or concat_ws or || operator:

select concat_ws ('~', col1, col2, col3, col4)
...
group by concat_ws ('~', col1, col2, col3, col4)

or

col1||'~'||col2||'~'||...||colN

NULLs should be taken care also. Replace nulls with empty strings before concatenation using NVL function.


问:
AWS SAM, how to run a state machine from an api gateway call?
I'm trying to set up a state machine for a workflow, but for the life of me I cannot seem to get it working, here is my SAM template:

```<code>AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
  strest

  Sample SAM Template for strest

Globals:
  Function:
    Timeout: 3

Resources:
  PublicApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      # TracingEnabled: true
      DefinitionBody:
        swagger: "2.0"
        info:
          version: "1.1"
          title: "StrestApi"
        schemes:
          - "http"
        paths:
          /start: # api gateway invokes lambda synchronously, which in turn invokes the stepfunction and waits for its final result
            get:
              produces:
                - "application/json"
              responses:
                "200":
                  description: "200 response"
                  schema:
                    $ref: "#/definitions/Empty"
                  headers:
                    Access-Control-Allow-Headers:
                    type: "string"

              security: []
              x-amazon-apigateway-integration:
                responses:
                  default:
                    statusCode: "200"
                    headers:
                      Access-Control-Allow-Headers:
                      type: "'*'"
                httpMethod: GET
                type: aws_proxy
                uri:
                  Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${StartFunction.Arn}/invocations

        definitions:
          Empty:
            type: "object"
            title: "Empty Schema"

  # Role which allows step functions to invoke lambda functions
  StatesExecutionRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Principal:
              Service:
                - !Sub states.${AWS::Region}.amazonaws.com
            Action: "sts:AssumeRole"
      Path: "/"
      Policies:
        - PolicyName: StatesExecutionPolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - "lambda:InvokeFunction"
                Resource: "*"

  # LAMBDAS
  StartFunction:
    Type: AWS::Serverless::Function
    Properties:
      Description: Starts the state machine
      CodeUri: dist/
      Handler: start/start.handler
      Runtime: nodejs12.x
      Environment:
        Variables:
          STEP_FUNCTION_ARN: !Ref StepFunctionsStateMachine
      Policies:
        - Version: "2012-10-17"
          Statement:
            - Effect: "Allow" # step function permissions open for now
              Action:
                - states:*
              Resource: "*"
      Events:
        ExecSFNResource:
          Type: Api
          Properties:
            RestApiId: !Ref PublicApi
            Path: /start
            Method: GET

  ExecutorFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: dist/
      Handler: executor/executor.handler
      Runtime: nodejs12.x
      # Events:
      #   HelloWorld:
      #     Type: Api
      #     Properties:
      #       Path: /execute
      #       Method: get

  # State machine
  StepFunctionsStateMachine:
    Type: AWS::StepFunctions::StateMachine
    Properties:
      RoleArn: !GetAtt [StatesExecutionRole, Arn]
      DefinitionString: !Sub |-
        {
          "StartAt": "execute",
          "Comment": "State machine for executing the strest main loop",
          "States": {
            "execute": {
              "Type": "Task",
              "Resource": "${ExecutorFunction.Arn}",
              "Comment": "Run the Executor Lambda function",
              "End": true
            }
          }
        }
</code>```

I either start the service by doing sam local start-api or sam local start-lambda.

is there any difference between starting the api with either of these commands?

In the template I pasted, I'm using !Ref to get the state machine ARN, however this is not working, the same string is returned, it works if I change it to !GetAtt StepFunctionsStateMachine.Arn

After changing 2. then I query the /start endpoint, the start lambda function starts running, I get the arn of the state machine, but when I try to start it I get a Service not valid in this context: lambda error (after the marker 2), here is the code for the start function:

import AWS from "aws-sdk";

export async function handler(event: any, context: any) {
  let stepFunctionArn = process.env.STEP_FUNCTION_ARN;

  console.log("marker0 stepFunctionArn", stepFunctionArn);

  let params = {
    stateMachineArn: stepFunctionArn!,
    name: "Execution lambda " + new Date().toString()
  };
  console.log("marker 1");

  let sf_client = new AWS.StepFunctions();
  console.log("marker 2");

  let res = await sf_client.startExecution(params).promise();

  console.log("marker 3", res);

  return {};
}
```

答:
It's viable to start a step function from a Lambda function, but i think in your case it's a better solution to start it directly from Api Gateway by using the DefinitionBody of API Gateway like this:

  /workflow:
    post:
      x-amazon-apigateway-integration:
        credentials:
          Fn::GetAtt: [ ApiGatewayStepFunctionsRole, Arn ]
        uri:
          Fn::Sub: arn:aws:apigateway:${AWS::Region}:states:action/StartExecution
        httpMethod: POST
        type: aws
        responses:
          default:
            statusCode: 200
            responseTemplates:
              application/json: |
                '{ "executionId": "$input.json('executionArn').split(':').get(7) }'
        requestTemplates:
          application/json:
            Fn::Sub: |-
              {
                "input": "$util.escapeJavaScript($input.json('$'))",
                "name": "$context.requestId",
                "stateMachineArn": "${Workflow}"
              }
      summary: Start workflow instance
      responses:
        200:
          $ref: '#/components/responses/200Execution'
        403:
          $ref: '#/components/responses/Error'
```

I have a working example commited in github in https://github.com/jvillane/aws-sam-step-functions-lambda/blob/master/openapi.yaml with an additional method for checking the execution state.

Body:
I'm trying to set up a state machine for a workflow, but for the life of me I cannot seem to get it working, here is my SAM template:

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
  strest

  Sample SAM Template for strest

Globals:
  Function:
    Timeout: 3

Resources:
  PublicApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      # TracingEnabled: true
      DefinitionBody:
        swagger: "2.0"
        info:
          version: "1.1"
          title: "StrestApi"
        schemes:
          - "http"
        paths:
          /start: # api gateway invokes lambda synchronously, which in turn invokes the stepfunction and waits for its final result
            get:
              produces:
                - "application/json"
              responses:
                "200":
                  description: "200 response"
                  schema:
                    $ref: "#/definitions/Empty"
                  headers:
                    Access-Control-Allow-Headers:
                    type: "string"

              security: []
              x-amazon-apigateway-integration:
                responses:
                  default:
                    statusCode: "200"
                    headers:
                      Access-Control-Allow-Headers:
                      type: "'*'"
                httpMethod: GET
                type: aws_proxy
                uri:
                  Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${StartFunction.Arn}/invocations

        definitions:
          Empty:
            type: "object"
            title: "Empty Schema"

  # Role which allows step functions to invoke lambda functions
  StatesExecutionRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Principal:
              Service:
                - !Sub states.${AWS::Region}.amazonaws.com
            Action: "sts:AssumeRole"
      Path: "/"
      Policies:
        - PolicyName: StatesExecutionPolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - "lambda:InvokeFunction"
                Resource: "*"

  # LAMBDAS
  StartFunction:
    Type: AWS::Serverless::Function
    Properties:
      Description: Starts the state machine
      CodeUri: dist/
      Handler: start/start.handler
      Runtime: nodejs12.x
      Environment:
        Variables:
          STEP_FUNCTION_ARN: !Ref StepFunctionsStateMachine
      Policies:
        - Version: "2012-10-17"
          Statement:
            - Effect: "Allow" # step function permissions open for now
              Action:
                - states:*
              Resource: "*"
      Events:
        ExecSFNResource:
          Type: Api
          Properties:
            RestApiId: !Ref PublicApi
            Path: /start
            Method: GET

  ExecutorFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: dist/
      Handler: executor/executor.handler
      Runtime: nodejs12.x
      # Events:
      #   HelloWorld:
      #     Type: Api
      #     Properties:
      #       Path: /execute
      #       Method: get

  # State machine
  StepFunctionsStateMachine:
    Type: AWS::StepFunctions::StateMachine
    Properties:
      RoleArn: !GetAtt [StatesExecutionRole, Arn]
      DefinitionString: !Sub |-
        {
          "StartAt": "execute",
          "Comment": "State machine for executing the strest main loop",
          "States": {
            "execute": {
              "Type": "Task",
              "Resource": "${ExecutorFunction.Arn}",
              "Comment": "Run the Executor Lambda function",
              "End": true
            }
          }
        }

I either start the service by doing sam local start-api or sam local start-lambda.

is there any difference between starting the api with either of these commands?

In the template I pasted, I'm using !Ref to get the state machine ARN, however this is not working, the same string is returned, it works if I change it to !GetAtt StepFunctionsStateMachine.Arn

After changing 2. then I query the /start endpoint, the start lambda function starts running, I get the arn of the state machine, but when I try to start it I get a Service not valid in this context: lambda error (after the marker 2), here is the code for the start function:

import AWS from "aws-sdk";

export async function handler(event: any, context: any) {
  let stepFunctionArn = process.env.STEP_FUNCTION_ARN;

  console.log("marker0 stepFunctionArn", stepFunctionArn);

  let params = {
    stateMachineArn: stepFunctionArn!,
    name: "Execution lambda " + new Date().toString()
  };
  console.log("marker 1");

  let sf_client = new AWS.StepFunctions();
  console.log("marker 2");

  let res = await sf_client.startExecution(params).promise();

  console.log("marker 3", res);

  return {};
}

Body:
It's viable to start a step function from a Lambda function, but i think in your case it's a better solution to start it directly from Api Gateway by using the DefinitionBody of API Gateway like this:

  /workflow:
    post:
      x-amazon-apigateway-integration:
        credentials:
          Fn::GetAtt: [ ApiGatewayStepFunctionsRole, Arn ]
        uri:
          Fn::Sub: arn:aws:apigateway:${AWS::Region}:states:action/StartExecution
        httpMethod: POST
        type: aws
        responses:
          default:
            statusCode: 200
            responseTemplates:
              application/json: |
                '{ "executionId": "$input.json('executionArn').split(':').get(7) }'
        requestTemplates:
          application/json:
            Fn::Sub: |-
              {
                "input": "$util.escapeJavaScript($input.json('$'))",
                "name": "$context.requestId",
                "stateMachineArn": "${Workflow}"
              }
      summary: Start workflow instance
      responses:
        200:
          $ref: '#/components/responses/200Execution'
        403:
          $ref: '#/components/responses/Error'

I have a working example commited in github in https://github.com/jvillane/aws-sam-step-functions-lambda/blob/master/openapi.yaml with an additional method for checking the execution state.


问:
"Go to Implementation" ending up with "The symbol has no implementations"
When right clicking on e.g. a method in Visual Studio and selecting Go To Implementation it tells me

The symbol has no implementations

I tried with

```<code>services.AddDbContext<RazorPagesMovieContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("RazorPagesMovieContext")));
</code>```

where AddDbContext is actually part of Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions

Is it possible to get Go To Implementation working, as .NET Core and ASP.NET Core are open source? I don't want to manually go to the Github repository for that. Ìf it's not directly possible with Visual Studio, are there maybe any plugins that make this possible?

For the sake of completeness: I am using Visual Studio 2019 Preview and .NET Core Preview 5.

答:
It's possible to debug the .NET Core code directly through Visual Studio. You need to enable two things in order to achieve that.

Allow symbols to be loaded from Microsoft symbol servers.

Enable debugging for Microsoft' source code.

Both options are available in Visual Studio and no need to use external tools.

In order to allow symbols to be loaded from Microsoft symbol server you need to go to Tools >> Options >> Debugging >> Symbols you will find the symbol servers listed. Put a checkbox to "Microsoft Symbol Servers" like shown in the screen shot below

Then go to Tools >> Options >> Debugging >> General and check the option "Enable .NET Framework for source stepping" This will automatically disable the option "Enable Just My Code" which is fine.

At this point you still won't be able to examine Microsoft code by just selecting the code of interest and pressing F12. However, you can step into Microsoft's code using F11 when debugging your application. This is the way it works.

Note: By enabling Microsoft's symbol servers like shown above will cause your Visual Studio to work way too slow. This is normal because of the many debugging symbols that needs to be downloaded from Microsoft' servers. So use this option only when you want to check something specific and disable it in your daily use.

Body:
When right clicking on e.g. a method in Visual Studio and selecting Go To Implementation it tells me

The symbol has no implementations

I tried with

services.AddDbContext<RazorPagesMovieContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("RazorPagesMovieContext")));

where AddDbContext is actually part of Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions

Is it possible to get Go To Implementation working, as .NET Core and ASP.NET Core are open source? I don't want to manually go to the Github repository for that. Ìf it's not directly possible with Visual Studio, are there maybe any plugins that make this possible?

For the sake of completeness: I am using Visual Studio 2019 Preview and .NET Core Preview 5.


问:
ORACLE NLS_LANG
How set and check NLS_LANG settings? I did

```<code>set NLS_LANG = DANISH_DENMARK.WE8ISO8859P2
</code>```

in command prompt but I don't know if it is correct.

答:
From Oracle documentation:

The NLS_LANG parameter uses the following format:

NLS_LANG = LANGUAGE_TERRITORY.CHARACTER_SET

where:

LANGUAGE - Specifies the language and conventions for displaying messages, day name, and month name.

TERRITORY - Specifies the territory and conventions for calculating week and day numbers.

CHARACTER_SET - Controls the character set used for displaying messages.

You will be able to find the commonly used NLS_LANG configurations in the Oracle documentation.

Title: ORACLE NLS_LANG

Body:
How set and check NLS_LANG settings? I did

set NLS_LANG = DANISH_DENMARK.WE8ISO8859P2

in command prompt but I don't know if it is correct.


问:
Can I deploy a Go project in Tomcat?
I have an application written in spring-boot and exposed it as rest API(s) by hosting it in tomcat. I want to rewrite this in Go and deploy it. How to deploy the Go project? </p>

答:
Java web projects using the Servet API require a servlet container to run, such as Tomcat. Further, Java is an interpreted language: programs written in Java require the Java Runtime Environment (JRE) to run.

Go on the other hand is a compiled language: programs written in Go can be compiled into an executable native binary that can be run directly by the operating system without any additional runtime. (Go also has a runtime but that's much smaller than JRE and is included in each executable binary.)

So web applications written in Go do not require other apps (such as servlet containers) to run. You just compile your Go app and run it like any other apps on your computer.

Title: Can I deploy a Go project in Tomcat?


问:
Is symbolic link between two git repositories possible?
I have gone through some documents regarding this topic and I was really confused with git submodules and how can it achieve  symbolic link.

Below is my scenario which I have to achieve:
I have two GitHub repositories repoA and repoB.
I have to link some files from repoA into repoB, so that whenever a change is made on those files in repoA, it should reflect on repoB also.

My first question is - Is this possible in GitHub?
If possible, how can we achieve this?

Most of the documents I have gone through are at least 5 years back. I know this is an old question, but I just want to know if anything is possible now to achieve this task.

答:
I have gone through some documents regarding this topic and I was really confused when most of the docs concluded in creation of submodules when asking about symbolic link.

And the docs are right. The scenario you want to achieve is possible via submodules and one more method. GitHub does not provide with any functionality in itself to implement what you want to do.

To do this with submodules, all you need to do is add the submodule and work with it. update the submodule from time-to-time to keep track of the changes on the submodule's upstream and sync those changes with your working tree's master.

I understand that submodules may be a bit intimidating at first but they are a great tool to use! The other solution can be to clone the desired repo into your working tree and keep pulling changed from its upstream when required. That won't create a symlink b/w the working tree and the new repo though.

Best


问:
Excel - VBA : How do I replace the last 3 characters if they are "..."
Please could you help me a little bit? I am a complete beginner, I don't know anything about programming.

I have the following code that changes double spaces into single spaces and deletes "..." if it's at the beginning of the selected cell(s).

```<code>Sub Test()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X - 1, 2).Text = "  " Then Cell.Characters(X, 1).Text = ""
      If Cell.Characters(1, 3).Text = "..." Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub
</code>```

Please could you tell me how I could change the part If Cell.Characters(1, 3).Text so that it removes "..." if it's at the end of the selected cell(s)?

答:
I think you can use Characters(1,3).Insert("") to change the text

```<code>Sub Test()
Dim c As Range
Selection.Value = Application.Trim(Selection)
For Each c In Selection
      If c.Characters(1,3).Text = "..." Then c.Characters(1,3).Insert("")
Next
End Sub

</code>```

Body:
Please could you help me a little bit? I am a complete beginner, I don't know anything about programming.

I have the following code that changes double spaces into single spaces and deletes "..." if it's at the beginning of the selected cell(s).

Sub Test()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X - 1, 2).Text = "  " Then Cell.Characters(X, 1).Text = ""
      If Cell.Characters(1, 3).Text = "..." Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub

Please could you tell me how I could change the part If Cell.Characters(1, 3).Text so that it removes "..." if it's at the end of the selected cell(s)?

Body:
I think you can use Characters(1,3).Insert("") to change the text

Sub Test()
Dim c As Range
Selection.Value = Application.Trim(Selection)
For Each c In Selection
      If c.Characters(1,3).Text = "..." Then c.Characters(1,3).Insert("")
Next
End Sub


问:
How to deal with ContentNotFoundError when using wkhtmltopdf?
Can someone tell me how to resolve following issues?

wkhtmltopdf don't have option to pass proxy info (-p or --proxy) unlike in previous versions and its not using system $http_proxy and $https_proxy env variable too.

wkhtmltopdf not working with HTTPS/SSL even though i set LD_LIBRARY_PATH for libssl.so and libcrypto.so

```<code>[deploy@localhost ~]$ wkhtmltopdf https://www.google.co.in google.pdf
loaded the Generic plugin
Loading page (1/2)
Error: Failed loading page https://www.google.co.in (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: UnknownNetworkError
</code>```

and

```<code>[deploy@localhost ~]$ wkhtmltoimage https://www.google.co.in sample.jpg
loaded the Generic plugin
Loading page (1/2)
Error: Failed loading page https://www.google.co.in (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: UnknownNetworkError
</code>```

wkhtmltopdf working partially with HTTP. The output pdf files missing some content/background/positions.

```<code>[deploy@localhost ~]$ wkhtmltopdf http://localhost:8880/ sample.pdf
loaded the Generic plugin
Loading page (1/2)
Printing pages (2/2)
Done
Exit with code 1 due to network error: ContentNotFoundError

[deploy@localhost ~]$ wkhtmltoimage http://localhost:8880/ sample.jpg
loaded the Generic plugin
Loading page (1/2)
Rendering (2/2)
Done
Exit with code 1 due to network error: ContentNotFoundError
</code>```

Note: Im using wkhtmltopdf-0.12.1-1.fc20.x86_64 and qt-4.8.6-10.fc20.x86_64

答:
I searched a lot but could not find but finally found over here. I was using (./name) but that created the contentnotfound error.

But finally used the complete address and got the desired result

Body:
Can someone tell me how to resolve following issues?

wkhtmltopdf don't have option to pass proxy info (-p or --proxy) unlike in previous versions and its not using system $http_proxy and $https_proxy env variable too.

wkhtmltopdf not working with HTTPS/SSL even though i set LD_LIBRARY_PATH for libssl.so and libcrypto.so

[deploy@localhost ~]$ wkhtmltopdf https://www.google.co.in google.pdf
loaded the Generic plugin
Loading page (1/2)
Error: Failed loading page https://www.google.co.in (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: UnknownNetworkError

and

[deploy@localhost ~]$ wkhtmltoimage https://www.google.co.in sample.jpg
loaded the Generic plugin
Loading page (1/2)
Error: Failed loading page https://www.google.co.in (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: UnknownNetworkError

wkhtmltopdf working partially with HTTP. The output pdf files missing some content/background/positions.

[deploy@localhost ~]$ wkhtmltopdf http://localhost:8880/ sample.pdf
loaded the Generic plugin
Loading page (1/2)
Printing pages (2/2)
Done
Exit with code 1 due to network error: ContentNotFoundError

[deploy@localhost ~]$ wkhtmltoimage http://localhost:8880/ sample.jpg
loaded the Generic plugin
Loading page (1/2)
Rendering (2/2)
Done
Exit with code 1 due to network error: ContentNotFoundError

Note: Im using wkhtmltopdf-0.12.1-1.fc20.x86_64 and qt-4.8.6-10.fc20.x86_64


问:
Detect line width in jupyter notebook?
For ipython I use this to detect console line width :

```<code>    ncols =  int(os.getenv('COLUMNS', 80))
</code>```

how do I do the same for jupyter notebook from python ?

答:
The width of a jupyter cell can be retrieved from the notebook's style.  You can use the browser's development tools to inspect the html or you could use the following code in a notebook cell to retrieve the width of a cell line and then calculate the number of characters it will hold.

The following will:

Use %%html magic to create a canvas and js script.

look up the div.CodeMirror-lines element and get its font and width.

set the canvas to the same font as the cell's line element.

use measureText to measure the length of one character.

alert you of the number of characters that will fit within the line's width.

%%html
<canvas id="canvas"></canvas>

```

Title: Detect line width in jupyter notebook?

Body:
For ipython I use this to detect console line width :

    ncols =  int(os.getenv('COLUMNS', 80))

how do I do the same for jupyter notebook from python ?

Body:
The width of a jupyter cell can be retrieved from the notebook's style.  You can use the browser's development tools to inspect the html or you could use the following code in a notebook cell to retrieve the width of a cell line and then calculate the number of characters it will hold.

The following will:

Use %%html magic to create a canvas and js script.

look up the div.CodeMirror-lines element and get its font and width.

set the canvas to the same font as the cell's line element.

use measureText to measure the length of one character.

alert you of the number of characters that will fit within the line's width.

%%html
<canvas id="canvas"></canvas>
<script>
    // retrieve the width and font
    var el = document.querySelector("div.CodeMirror-lines")
    var ff = window.getComputedStyle(el, null).getPropertyValue('font');
    var widthpxl = el.clientWidth

    //set up canvas to measure text width
    var can = document.getElementById('canvas');
    var ctx = can.getContext('2d');
    ctx.font = ff;

    //measure one char of text and compute num char in one line
    var txt = ctx.measureText('A');
    alert(Math.floor(widthpxl/txt.width))
    //EDIT: to populate python variable with the output:
    IPython.notebook.kernel.execute("ncols=" + Math.floor(widthpxl/txt.width));
</script>


问:
getting on duplicate key mysql to work
i am having trouble getting this to work,

can any one spot the issue?

```<code>INSERT INTO `page_category_link` (page_id,cat_id)
VALUES ('4','2')
ON DUPLICATE KEY UPDATE page_id=VALUES('4') AND cat_id=VALUES('2') WHERE id=2
</code>```

many thanks

答:
```<code>INSERT INTO `page_category_link`
(page_id,cat_id) VALUES ('4','2')
ON DUPLICATE KEY UPDATE page_id='4', cat_id='2'
</code>```

Title: getting on duplicate key mysql to work

Body:
i am having trouble getting this to work,

can any one spot the issue?

INSERT INTO `page_category_link` (page_id,cat_id)
VALUES ('4','2')
ON DUPLICATE KEY UPDATE page_id=VALUES('4') AND cat_id=VALUES('2') WHERE id=2

many thanks


问:
bit slicing: finding minimum value

Short version

I need to find the minimum value of 64 uint8_t variables encoded as bit slices.

i.e. each bit of the variables is encoded into eight separate uint64_t:

```<code>//Normal layout:
uint8_t values[64]; // This is what you normally use.
                    // Finding minimum would be a simple
                    // matter of a for loop

/***********************/

// BITSLICE layout:
uint64_t slices[8]; // This is what I have, due to performance
                    // reasons in other parts of the code (not shown here)

slice[0]; //LSB: Least signignificant bit (for all 64 values)
slice[7]; //MSB: Most significant bit (for all 64 values)
</code>```

Now, how do I find out the minimum value of these? (I do not care about it's position, only it's value)

More context:

In reality I have a much longer array (than 64) of values inside an algorithm which already uses bit-slicing for performance reasons.

So what I have is actually more like (the question above was simplified):

```<code>uint64_t slices[8][100];
</code>```

So what I really need is the minimum value out of all 100*64 values. But I figure this can be done in a regular for loop by applying the answer to the simplified question above.

EDIT: apparently my question wasn't as clear as I thought so It's been updated

答:
I can think of at least two ways to do it.  The simplest is to just brute-force it: reconstitute each of the 64 integers, one at a time, via the appropriate bitwise arithmetic, and keep track of the minimum result.  Something along these lines:

```<code>uint8_t min = 0xff;

// iterate over the collection of values
for (uint64_t which = 1; which; which <<= 1) {
    // reconstitute one value in 'test'
    uint8_t test = 0;

    for (int bit = 0; bit < 8; bit++) {
        // verify this decoding -- your bit order may be different:
        test += (!!(slices[bit] & which)) << bit;
    }

    // track the minimum
    if (test < min) {
        min = test;
    }
}
</code>```

On the other hand, it should also be possible to do it more quickly by scanning just once through slices and accumulating the minimum directly.  I haven't time to test this, but it should convey the general idea:

```<code>uint8_t min = 0xff;
uint64_t mask = ~(uint64_t)0;  // a mask of candidate positions; all bits initially set

for (int i = 7; i >= 0; i--) {  // assumes slice 7 is most significant
    // which of the remaining candidates have this bit set:
    uint64_t bits_set = slice[i] & mask;

    // If at least one of the remaining candidates does not have this bit set
    if (bits_set != mask) {
        min ^= (1 << i);   // turn off this bit in the result
        mask ^= bits_set;  // remove the candidates that do have this bit set
    }
}
</code>```

This latter is akin to a radix sort.

Title: bit slicing: finding minimum value

Body:
Short version

I need to find the minimum value of 64 uint8_t variables encoded as bit slices.

i.e. each bit of the variables is encoded into eight separate uint64_t:

//Normal layout:
uint8_t values[64]; // This is what you normally use.
                    // Finding minimum would be a simple
                    // matter of a for loop

/***********************/

// BITSLICE layout:
uint64_t slices[8]; // This is what I have, due to performance
                    // reasons in other parts of the code (not shown here)

slice[0]; //LSB: Least signignificant bit (for all 64 values)
slice[7]; //MSB: Most significant bit (for all 64 values)

Now, how do I find out the minimum value of these? (I do not care about it's position, only it's value)

More context:

In reality I have a much longer array (than 64) of values inside an algorithm which already uses bit-slicing for performance reasons.

So what I have is actually more like (the question above was simplified):

uint64_t slices[8][100];

So what I really need is the minimum value out of all 100*64 values. But I figure this can be done in a regular for loop by applying the answer to the simplified question above.

EDIT: apparently my question wasn't as clear as I thought so It's been updated

Body:
I can think of at least two ways to do it.  The simplest is to just brute-force it: reconstitute each of the 64 integers, one at a time, via the appropriate bitwise arithmetic, and keep track of the minimum result.  Something along these lines:

uint8_t min = 0xff;

// iterate over the collection of values
for (uint64_t which = 1; which; which <<= 1) {
    // reconstitute one value in 'test'
    uint8_t test = 0;

    for (int bit = 0; bit < 8; bit++) {
        // verify this decoding -- your bit order may be different:
        test += (!!(slices[bit] & which)) << bit;
    }

    // track the minimum
    if (test < min) {
        min = test;
    }
}

On the other hand, it should also be possible to do it more quickly by scanning just once through slices and accumulating the minimum directly.  I haven't time to test this, but it should convey the general idea:

uint8_t min = 0xff;
uint64_t mask = ~(uint64_t)0;  // a mask of candidate positions; all bits initially set

for (int i = 7; i >= 0; i--) {  // assumes slice 7 is most significant
    // which of the remaining candidates have this bit set:
    uint64_t bits_set = slice[i] & mask;

    // If at least one of the remaining candidates does not have this bit set
    if (bits_set != mask) {
        min ^= (1 << i);   // turn off this bit in the result
        mask ^= bits_set;  // remove the candidates that do have this bit set
    }
}

This latter is akin to a radix sort.


问:
convert JSON object to XML using javascript
I want to convert a JSON object to a XML String and I can't figure a proper way to do it.
I've found a neat little jQuery plugin called json2xml at https://gist.github.com/c4milo/3738875 but it doesn't escape the data.

How can I escape the data properly so that the browser's XML parser will work?

答:
you can use this function in your code to convert JSON to XML in js

var json2xml = function (o) {

```<code>            var tab = "\t";
            var toXml = function (v, name, ind) {
                var xml = "";
                if (v instanceof Array) {
                    for (var i = 0, n = v.length; i < n; i++)
                        xml += ind + toXml(v[i], name, ind + "\t") + "\n";
                }
                else if (typeof (v) == "object") {
                    var hasChild = false;
                    xml += ind + "<" + name;
                    for (var m in v) {
                        if (m.charAt(0) == "@")
                            xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
                        else
                            hasChild = true;
                    }
                    xml += hasChild ? ">" : "/>";
                    if (hasChild) {
                        for (var m in v) {
                            if (m == "#text")
                                xml += v[m];
                            else if (m == "#cdata")
                                xml += "<![CDATA[" + v[m] + "]]>";
                            else if (m.charAt(0) != "@")
                                xml += toXml(v[m], m, ind + "\t");
                        }
                        xml += (xml.charAt(xml.length - 1) == "\n" ? ind : "") + "</" + name + ">";
                    }
                }
                else {
                    xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
                }
            }
            return xml;
        };
</code>```

you get XML DOM in return, which in return you need to serialize

so in the main

```<code>            var xmlDOM = json2xml(eval(jsonObj));
            var oSerializer = new XMLSerializer();
            var sXML = oSerializer.serializeToString(xmlDOM);
</code>```

Body:
you can use this function in your code to convert JSON to XML in js

var json2xml = function (o) {

            var tab = "\t";
            var toXml = function (v, name, ind) {
                var xml = "";
                if (v instanceof Array) {
                    for (var i = 0, n = v.length; i < n; i++)
                        xml += ind + toXml(v[i], name, ind + "\t") + "\n";
                }
                else if (typeof (v) == "object") {
                    var hasChild = false;
                    xml += ind + "<" + name;
                    for (var m in v) {
                        if (m.charAt(0) == "@")
                            xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
                        else
                            hasChild = true;
                    }
                    xml += hasChild ? ">" : "/>";
                    if (hasChild) {
                        for (var m in v) {
                            if (m == "#text")
                                xml += v[m];
                            else if (m == "#cdata")
                                xml += "<![CDATA[" + v[m] + "]]>";
                            else if (m.charAt(0) != "@")
                                xml += toXml(v[m], m, ind + "\t");
                        }
                        xml += (xml.charAt(xml.length - 1) == "\n" ? ind : "") + "</" + name + ">";
                    }
                }
                else {
                    xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
                }
            }
            return xml;
        };

you get XML DOM in return, which in return you need to serialize

so in the main

            var xmlDOM = json2xml(eval(jsonObj));
            var oSerializer = new XMLSerializer();
            var sXML = oSerializer.serializeToString(xmlDOM);


问:
Is a non-block socket always writable after it finishes its connection in python?
I want to build a port map tool in python from scratch. Basically it is a TCP proxy that transits all the traffic between the client and the objective service or application.

Specifically, For every connection I create two sockets who are responsible to communicate to the client and objective service respectively. To implement IO-multiplexing feature, I use module selectors to monitor the EVENT_READ and EVENT_WRITE event on these two sockets. However I find that the sockets are always writable so that the main loop doesn't block at all. Is it normal? My code is as follows:

import socket
import selectors

def recv_from(sock):
    data = b''
    try:
        while True:
            chunk = sock.recv(4096)
            if not chunk:
                break
            data += chunk
    except:
        pass
    return data

class RelayHandlder:

    def __init__(self, client_sock, remote_sock, selector):
        '''
        client_sock and remote_sock have already finished the connection.
        '''
        self._client_sock = client_sock
        self._remote_sock = remote_sock
        self._selector = selector

        self._send_buffer = b''
        self._recv_buffer = b''

        self._selector.register(self._client_sock, selectors.EVENT_READ|selectors.EVENT_WRITE, self._client_handler)
        self._selector.register(self._remote_sock, selectors.EVENT_READ|selectors.EVENT_WRITE, self._remote_handler)

    def _client_handler(self, client_sock, mask):
        if mask & selectors.EVENT_READ:
            data = recv_from(client_sock)
            if data:
                self._send_buffer = data
            else:
                self._close()
        elif mask & selectors.EVENT_WRITE:
            if self._recv_buffer:
                try:
                    client_sock.send(self._recv_buffer)
                    self._recv_buffer = b''
                except OSError:
                    self._close()

    def _remote_handler(self, remote_sock, mask):
        if mask & selectors.EVENT_READ:
            data = recv_from(remote_sock)
            if data:
                self._recv_buffer = data
            else:
                self._close()
        elif mask & selectors.EVENT_WRITE:
            if self._send_buffer:
                try:
                    remote_sock.send(self._send_buffer)
                    self._send_buffer = b''
                except OSError:
                    self._close()

    def _close(self):
        print('Closing ...')
        self._selector.unregister(self._client_sock)
        self._client_sock.close()
        self._selector.unregister(self._remote_sock)
        self._remote_sock.close()
        self._send_buffer = b''
        self._recv_buffer = b''

class PortMapper:
    '''
    Map the remote port to local.
    '''

    def __init__(self, proxy_ip, proxy_port, remote_ip, remote_port):
        self.proxy_ip = proxy_ip
        self.proxy_port = proxy_port
        self.remote_ip = remote_ip
        self.remote_port = remote_port

        self._selector = selectors.DefaultSelector()

        self._proxy_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        while True:
            try:
                self._proxy_sock.bind((proxy_ip, proxy_port))
                break
            except OSError:
                proxy_port += 1
                self.proxy_port = proxy_port
        self._proxy_sock.listen(10)
        self._proxy_sock.setblocking(False)
        self._selector.register(self._proxy_sock, selectors.EVENT_READ, self._accept_handler)
        print('Listening at {}:{}'.format(proxy_ip, proxy_port))

    def _accept_handler(self, proxy_sock, mask):
        client_sock, addr = proxy_sock.accept()
        client_sock.setblocking(False)
        print('Accept from {}'.format(addr))

        remote_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        remote_sock.setblocking(False)
        try:
            remote_sock.connect((self.remote_ip, self.remote_port))
        except BlockingIOError:
            pass

        RelayHandlder(client_sock, remote_sock, self._selector)

    def loop(self):
        while True:
            events = self._selector.select()
            for key, mask in events:
                callback = key.data
                callback(key.fileobj, mask)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='Port Map Tool.')
    parser.add_argument('-H', '--remote-host', required=True, type=str, help='Remote host.')
    parser.add_argument('-P', '--remote-port', required=True, type=int, help='Remote port.')
    parser.add_argument('-p', '--local-port', default=1000, type=int, help='Local port.')
    args = parser.parse_args()

    PortMapper('0.0.0.0', args.local_port, args.remote_host, args.remote_port).loop()
```

In the code, self._send_buffer in RelayHandler is used to cache the data received from the client. If self._remote_sock is writable and self._send_buffer is not empty, the proxy will send self._send_buffer to the remote service. The logic is similar for self._client_sock. The main loop is defined on loop function in PortMapper.

I have two questions:

Is a non-block socket always writable after it finishes its connection in python?

In the above code, sockets are always writable while buffers are often empty. So for every single loop in the main loop, self._selector.select() will always return without blocking, and the callback is executed to do nothing but only to see if the buffer is empty, which may hurt the performance. Is there a better method or structure to do this?

答:
A socket is normally writable until the system buffer is full. That is the reason why many simple select multiplexed system only considere the read part and assume that they will be able to write or accept the possibility of being blocked if they are not.

If you want to be super safe and ensure that you will be able to write, you should ignore EVENT_WRITE unless you are ready to write something. But to prevent your code to exhaust the local memory buffer, the relay should stop reading (also ignore EVENT_READ) if the other channel cannot write.

Body:
I want to build a port map tool in python from scratch. Basically it is a TCP proxy that transits all the traffic between the client and the objective service or application.

Specifically, For every connection I create two sockets who are responsible to communicate to the client and objective service respectively. To implement IO-multiplexing feature, I use module selectors to monitor the EVENT_READ and EVENT_WRITE event on these two sockets. However I find that the sockets are always writable so that the main loop doesn't block at all. Is it normal? My code is as follows:

import socket
import selectors

def recv_from(sock):
    data = b''
    try:
        while True:
            chunk = sock.recv(4096)
            if not chunk:
                break
            data += chunk
    except:
        pass
    return data

class RelayHandlder:

    def __init__(self, client_sock, remote_sock, selector):
        '''
        client_sock and remote_sock have already finished the connection.
        '''
        self._client_sock = client_sock
        self._remote_sock = remote_sock
        self._selector = selector

        self._send_buffer = b''
        self._recv_buffer = b''

        self._selector.register(self._client_sock, selectors.EVENT_READ|selectors.EVENT_WRITE, self._client_handler)
        self._selector.register(self._remote_sock, selectors.EVENT_READ|selectors.EVENT_WRITE, self._remote_handler)

    def _client_handler(self, client_sock, mask):
        if mask & selectors.EVENT_READ:
            data = recv_from(client_sock)
            if data:
                self._send_buffer = data
            else:
                self._close()
        elif mask & selectors.EVENT_WRITE:
            if self._recv_buffer:
                try:
                    client_sock.send(self._recv_buffer)
                    self._recv_buffer = b''
                except OSError:
                    self._close()

    def _remote_handler(self, remote_sock, mask):
        if mask & selectors.EVENT_READ:
            data = recv_from(remote_sock)
            if data:
                self._recv_buffer = data
            else:
                self._close()
        elif mask & selectors.EVENT_WRITE:
            if self._send_buffer:
                try:
                    remote_sock.send(self._send_buffer)
                    self._send_buffer = b''
                except OSError:
                    self._close()

    def _close(self):
        print('Closing ...')
        self._selector.unregister(self._client_sock)
        self._client_sock.close()
        self._selector.unregister(self._remote_sock)
        self._remote_sock.close()
        self._send_buffer = b''
        self._recv_buffer = b''

class PortMapper:
    '''
    Map the remote port to local.
    '''

    def __init__(self, proxy_ip, proxy_port, remote_ip, remote_port):
        self.proxy_ip = proxy_ip
        self.proxy_port = proxy_port
        self.remote_ip = remote_ip
        self.remote_port = remote_port

        self._selector = selectors.DefaultSelector()

        self._proxy_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        while True:
            try:
                self._proxy_sock.bind((proxy_ip, proxy_port))
                break
            except OSError:
                proxy_port += 1
                self.proxy_port = proxy_port
        self._proxy_sock.listen(10)
        self._proxy_sock.setblocking(False)
        self._selector.register(self._proxy_sock, selectors.EVENT_READ, self._accept_handler)
        print('Listening at {}:{}'.format(proxy_ip, proxy_port))

    def _accept_handler(self, proxy_sock, mask):
        client_sock, addr = proxy_sock.accept()
        client_sock.setblocking(False)
        print('Accept from {}'.format(addr))

        remote_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        remote_sock.setblocking(False)
        try:
            remote_sock.connect((self.remote_ip, self.remote_port))
        except BlockingIOError:
            pass

        RelayHandlder(client_sock, remote_sock, self._selector)

    def loop(self):
        while True:
            events = self._selector.select()
            for key, mask in events:
                callback = key.data
                callback(key.fileobj, mask)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='Port Map Tool.')
    parser.add_argument('-H', '--remote-host', required=True, type=str, help='Remote host.')
    parser.add_argument('-P', '--remote-port', required=True, type=int, help='Remote port.')
    parser.add_argument('-p', '--local-port', default=1000, type=int, help='Local port.')
    args = parser.parse_args()

    PortMapper('0.0.0.0', args.local_port, args.remote_host, args.remote_port).loop()

In the code, self._send_buffer in RelayHandler is used to cache the data received from the client. If self._remote_sock is writable and self._send_buffer is not empty, the proxy will send self._send_buffer to the remote service. The logic is similar for self._client_sock. The main loop is defined on loop function in PortMapper.

I have two questions:

Is a non-block socket always writable after it finishes its connection in python?

In the above code, sockets are always writable while buffers are often empty. So for every single loop in the main loop, self._selector.select() will always return without blocking, and the callback is executed to do nothing but only to see if the buffer is empty, which may hurt the performance. Is there a better method or structure to do this?


问:
WPF TabControl How to change Tab on mouse up rather than mouse down?
In the WPF TabControl the default behavior is to change the selected tab on mouse down.

In my application changing the tab sometimes resizes things, and at times the mouse up event will get called on a another user control because the tabcontrol moved.

If i can set the tab pages to switch only on mouse up rather than mouse down it would solve the issue.

答:
You can use a custom TabItem like so:</p>

```<code>public class MyTabItem : TabItem {

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) {
        if (e.Source == this || !this.IsSelected)
            return;

        base.OnMouseLeftButtonDown(e);
    }

    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) {
        if (e.Source == this || !this.IsSelected)
            base.OnMouseLeftButtonDown(e); // OR just this.Focus(); OR this.IsSeleded = true;

        base.OnMouseLeftButtonUp(e);
    }
}
</code>```

Body:
You can use a custom TabItem like so:

public class MyTabItem : TabItem {

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) {
        if (e.Source == this || !this.IsSelected)
            return;

        base.OnMouseLeftButtonDown(e);
    }

    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) {
        if (e.Source == this || !this.IsSelected)
            base.OnMouseLeftButtonDown(e); // OR just this.Focus(); OR this.IsSeleded = true;

        base.OnMouseLeftButtonUp(e);
    }
}


问:
Is it possible for a Blazor WebAssembly PWA to run a local desktop app on the user's file system?
I really doubt it but I figure it never hurts to ask... what I want to do is create a game matchmaking site that is capable of launching the actual games from within the web app. If not I guess I can create a client/server desktop app or something instead...</p>

答:
No, the PWA sandbox prohibits it.

You could try building an Electron app that runs your Blazor WASM - https://github.com/aspnet/AspLabs/tree/master/src/ComponentsElectron

Or you could give the following link a try. It does something similar, but doesn't bundle the browser in order to reduce size - https://github.com/steveSandersonMS/BlazorDesktop

Steve Sanderson wrote a pretty informative blog on it
https://blog.stevensanderson.com/2019/11/01/exploring-lighter-alternatives-to-electron-for-hosting-a-blazor-desktop-app/


问:
chrome.storage.sync undefined error
I'm writing a simple extension and need to save user blacklisted keywords. I'm using the options_page for chrome to ask users for input, and save those words to the storage to be used later. However, when I press 'save', I get the error Uncaught TypeError: Cannot read property 'sync' of undefined, but I followed the instructions in the chrome extension documentation. I added "permissions": ["storage"]to the manifest.json file, and reloaded the extension and options page multiple times, yet I still get the same error. Here's my javascript code:

```<code>var save_options = function() {
  var blacklistWords = document.getElementById('word').value;
  chrome.storage.sync.set({'blacklistWords': blacklistWords}, function() {
    // Update status to let user know options were saved.
    alert("saved");
  });
};

document.getElementById('save').addEventListener('click', save_options);
</code>```

I would really appreciate it if someone could help me figure this out.

答: Always reload the extension whenever you update the manifest.json file.

Title: chrome.storage.sync undefined error

Body:
I'm writing a simple extension and need to save user blacklisted keywords. I'm using the options_page for chrome to ask users for input, and save those words to the storage to be used later. However, when I press 'save', I get the error Uncaught TypeError: Cannot read property 'sync' of undefined, but I followed the instructions in the chrome extension documentation. I added "permissions": ["storage"]to the manifest.json file, and reloaded the extension and options page multiple times, yet I still get the same error. Here's my javascript code:

var save_options = function() {
  var blacklistWords = document.getElementById('word').value;
  chrome.storage.sync.set({'blacklistWords': blacklistWords}, function() {
    // Update status to let user know options were saved.
    alert("saved");
  });
};

document.getElementById('save').addEventListener('click', save_options);

I would really appreciate it if someone could help me figure this out.


问:
Should unit tests be written for getter and setters?
Are we supposed to write tests for our getters and setters or is it overkill?</p>

答:
tl;dr: Yes you should, and with OpenPojo it's trivial.

You should be doing some validation in your getters and setters so you should be testing that. For example, setMom(Person p) should not allow setting anyone younger than themselves as their mother.

Even if you aren't doing any of that now, odds are you will in the future, then this will be a good for regression analysis. If you want to allow setting mothers to null you should have a test for that should someone change that later on, this will reinforce your assumptions.

A common bug is void setFoo( Object foo ){ foo = foo; } where it should be void setFoo( Object foo ){ this.foo = foo; }. (In the first case the foo that is being written to is the parameter not the foo field on the object).

If you are returning an array or collection you should be testing whether or not the getter is going to be performing defensive copies of the data passed into the setter before returning.

Otherwise, if you have the most basic setters/getters then unit-testing them will add maybe about 10 minutes at most per-object, so what is the loss? If you add behaviour you already have a skeleton test and you get this regression testing for free. If you are using Java, you have no excuse since there is OpenPojo. There are an existing set of rules you can enable and then scan your entire project with them to make sure they are applied consistently within your code.

From their examples:

final Validator pojoValidator = ValidatorBuilder.create()
        .with(
            new NoPublicFieldsRule  (),
            new NoPrimitivesRule    (),
            new GetterMustExistRule (),
            new SetterMustExistRule ()
        )
        .with(
            new DefaultValuesNullTester (),
            new SetterTester            (),
            new GetterTester            ()
        )
        .build();

pojoValidator.validate(  PojoClassFactory.getPojoClasses( "net.initech.app", new FilterPackageInfo() )  );
```