问:
Understanding MVVM - How to bind data view ↔ ViewModel + catch Key pressed on view and start function in viewModel
I'm new in C# and created a simple app that works fine, but I wanna to learn C# using the pattern MVVM. So I'm trying to migrate my app to MVVM and I become confused

My Goal is simple:

1) When opened, the app scan a folder and index all the files in the format
"[number] [name]" - It's working fine!

2) I have a window with just one textBox. The user types a number and press ENTER. In this moment I have a CatalogViewModel that is a set o File and should select the file specified by the number in textBox and open it.

Problem 1: In MVVM I can't pass the data from my view Main to my ViewModel CatalogViewModel (I'm not sure if I made correct)

Problem 2: I can't handle the ENTER key and trigger a function inside CatalogViewModel

I'm a little confused with MVVM and can't go ahead. I know that it's simple. Please, how to resolve this 2 problem (in detail please, I'm a beginner in C# and in all its concept)

UPDATE 1:

tryed the janonimus' Solution to problem 1 But the databind is just ONE WAY.
The value from VM goes to the VIEW, but the changes on the VIEW don't to to VM.
I've implemented INotifyPropertyChanged this way

```<code>using Prism.Mvvm;
...

    public class CatalogViewModel: BindableBase
    {

        private string selectedValue = "100";
        public string SelectedValue
        {
            get { return selectedValue; }
            set { SetProperty(ref selectedValue, value); }
        }
</code>```

But the Databind becomes just ON WAY
the XAML

```<code><TextBox x:Name="tbSelectedValue" Text="{Binding SelectedValue, Mode=TwoWay}"
</code>```

UPDATE 2

I found the solution for the problem 1. The code provided by janonimus works just in ONE WAY because the default behavior of TextBox.Text is to upadte when it lose the focus, but in my case it will never lose the focus see this post

The following code resolved the problem 1:

```<code>Text="{Binding Path=SelectedValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}
</code>```

The problem 2 Can be resolved with Pedro Silva's answer

```<code>if (e.Key == Key.Enter && tbSelectedValue.Text != String.Empty)
            {
                vm.OpenSelectedFile();
                tbSelectedValue.Text = String.Empty;
            }
</code>```

But I wanna to implement it using a more sofisticated way, using ICommand.
Following the advise sent by janonimus, I created the BaseCommand Class Exactly like this but it throws a mismatch error when I call the function OpenSelectedFile

```<code>private BaseCommand<CatalogViewModel> _selectFileCommand;
public ICommand SelectFileCommand
{
    get
    {
        if (_selectFileCommand == null)
        {
            _selectFileCommand = new BaseCommand<CatalogViewModel>(OpenSelectedFile, true);
        }
        return _selectFileCommand;
    }
}
public void OpenSelectedFile()
{
    try
    {
        OpenFileByNumber(Int32.Parse(SelectedValue));
    }
    catch (Exception e)
    {
        MessageBox.Show("Número inválido: \'" + SelectedValue + "\"",
           "ERRO", MessageBoxButton.OK, MessageBoxImage.Warning);
    }

}
</code>```

That's my code for reference...

Main.xaml.cs

```<code>namespace SLMT.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class Main : Window
    {

        public Main()
        {
            InitializeComponent();
            DataContext = new CatalogViewModel();
            chosenNumber.Focus();
        }

        // Permite inserir somente números
        private void ChosenNumber_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^ 0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        private void ChosenNumber_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && chosenNumber.Text != String.Empty)
            {
                //catalog.OpenFileByNumber(ConvertToInt(numeroEscolhido.Text));
                //catalog.OpenSelectedFile(); // Will become someting like this
                chosenNumber.Text = String.Empty;

            }
        }

        private int ConvertToInt(string value)
        {
            try
            {
                var str = value.Replace(" ", String.Empty);
                return Int32.Parse(str);
            }
            catch (Exception exc)
            {
                MessageBox.Show("O número: \"" + chosenNumber.Text + "\" é inválido", "ERRO", MessageBoxButton.OK, MessageBoxImage.Error);
                chosenNumber.Text = String.Empty;

                return 0;
            }
        }

        /// <summary>
        /// Controll what wil lhappen if some KEYS are pressed on APP
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GMain_KeyUp(object sender, KeyEventArgs e)
        {

            switch (e.Key){

                case Key.Escape:
                    Environment.Exit(0);
                    break;

                case Key.F1:
                    //wListFiles = new ListFiles(catalog);
                    //wListFiles.ShowDialog();
                    //numeroEscolhido.Text = wListFiles.SelectFile();
                    //numeroEscolhido.SelectAll();
                    break;
            }

        }
    }
}
</code>```

ps: The commented lines, I imported from the version without MVVM

Main.xaml

```<code><Window x:Name="wMain" x:Class="SLMT.Views.Main"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SLMT.Views"
        mc:Ignorable="d"
        Title="Ministério Tons" Height="364" Width="700" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowStyle="None">
    <Grid x:Name="gMain" KeyUp="GMain_KeyUp">
        <Image x:Name="imgBackground" HorizontalAlignment="Left" Height="364" VerticalAlignment="Top" Width="700" Source="/SLMT;component/Resources/img/background2.jpg" Opacity="100"/>
        <TextBox x:Name="chosenNumber" HorizontalAlignment="Center" Height="34" Margin="500,294,56,36" TextWrapping="Wrap" VerticalAlignment="Center" Width="144" BorderBrush="{x:Null}" Background="{x:Null}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" UndoLimit="50" ForceCursor="True" PreviewTextInput="ChosenNumber_PreviewTextInput" KeyUp="ChosenNumber_KeyUp" BorderThickness="0" FontSize="20" Opacity="0.6" FontWeight="Bold"/>

    </Grid>
</Window>
</code>```

And the Relevant part of CatalogViewModel.cs

```<code>namespace SLMT.ViewModel
{
    public class CatalogViewModel: ObservableCollection <File>
    {

        private int selectedNumber;

        /// <summary>
        /// Contain the selected number in the View
        /// </summary>
        public int SelectedNumber
        {
            get { return selectedNumber; }
            set { selectedNumber = value; }
        }

        // REMOVED CODE TO SCAN AND INDEX THE FILES

        public CatalogViewModel() : base()
        {
            ScanFiles();
            ValidateAndAddFiles();
            ShowAlerts();
        }

        public void OpenSelectedFile()
        {
            OpenFileByNumber(SelectedNumber);
        }

        /// <summary>
        /// Get the file from catalog identified my the number
        /// </summary>
        /// <param name="number"></param>
        /// <returns>File|null</returns>
        private File GetFileByNumber(int number)
        {
            foreach (var file in this)
            {
                if (file.number == number){
                    return file;
                }
            }

            return null;
        }

        private void OpenFileByNumber(int number)
        {
            var file = GetFileByNumber(number);

            if (file == null)
            {
                MessageBox.Show("Nenhum arquivo encontrado com o número: \'" + number +"\"",
                   "ARQUIVO NÃO ENCONTRADO", MessageBoxButton.OK, MessageBoxImage.Warning);
            } else
            {
                file.Open();
            }
        }
    }
}
</code>```

答:
Try the following to have access to the view model that you created in your constructor.

```<code>CatalogViewModel vm = new CatalogViewModel();

public Main()
{
    InitializeComponent();
    DataContext = vm;
    chosenNumber.Focus();
}
</code>```

Then in  your key handler, you can do this:

```<code>private void ChosenNumber_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter && chosenNumber.Text != String.Empty)
    {
        //catalog.OpenFileByNumber(ConvertToInt(numeroEscolhido.Text));
        //catalog.OpenSelectedFile(); // Will become someting like this

        vm.OpenSelectedFile();
        chosenNumber.Text = String.Empty;
    }
}
</code>```

Update: Using ICommand

Using the BaseCommand class you pointed to from here. I added the following code to the CatalogViewModel and got it working. You had the type in BaseCommand as the view model, but that's supposed to be the type of the command parameter (based on examples in that post).

```<code>private BaseCommand<object> _selectFileCommand;
public ICommand SelectFileCommand
{
    get
    {
        if (_selectFileCommand == null)
        {
            _selectFileCommand = new BaseCommand<object>((commandParam) => OpenSelectedFile(commandParam),
                                                         (commandParam) => CanOpenSelectedFile(commandParam));
        }
        return _selectFileCommand;
    }
}

public void OpenSelectedFile(object commandParam = null)
{
    Debug.WriteLine("CatalogViewModel.OpenSelectedFile was called.");
    Debug.WriteLine("SelectedValue = " + this.SelectedValue);
}

public bool CanOpenSelectedFile(object commandParam = null)
{
    return true;
}
</code>```

Once you get into the OpenSelectedFile method, you should be able to hook it up to the functionality that you want.

ContentLicense: CC BY-SA 4.0

Body:
I'm new in C# and created a simple app that works fine, but I wanna to learn C# using the pattern MVVM. So I'm trying to migrate my app to MVVM and I become confused

My Goal is simple:

1) When opened, the app scan a folder and index all the files in the format
"[number] [name]" - It's working fine!

2) I have a window with just one textBox. The user types a number and press ENTER. In this moment I have a CatalogViewModel that is a set o File and should select the file specified by the number in textBox and open it.

Problem 1: In MVVM I can't pass the data from my view Main to my ViewModel CatalogViewModel (I'm not sure if I made correct)

Problem 2: I can't handle the ENTER key and trigger a function inside CatalogViewModel

I'm a little confused with MVVM and can't go ahead. I know that it's simple. Please, how to resolve this 2 problem (in detail please, I'm a beginner in C# and in all its concept)

UPDATE 1:

tryed the janonimus' Solution to problem 1 But the databind is just ONE WAY.
The value from VM goes to the VIEW, but the changes on the VIEW don't to to VM.
I've implemented INotifyPropertyChanged this way

using Prism.Mvvm;
...

    public class CatalogViewModel: BindableBase
    {

        private string selectedValue = "100";
        public string SelectedValue
        {
            get { return selectedValue; }
            set { SetProperty(ref selectedValue, value); }
        }

But the Databind becomes just ON WAY
the XAML

<TextBox x:Name="tbSelectedValue" Text="{Binding SelectedValue, Mode=TwoWay}"

UPDATE 2

I found the solution for the problem 1. The code provided by janonimus works just in ONE WAY because the default behavior of TextBox.Text is to upadte when it lose the focus, but in my case it will never lose the focus see this post

The following code resolved the problem 1:

Text="{Binding Path=SelectedValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}

The problem 2 Can be resolved with Pedro Silva's answer

if (e.Key == Key.Enter && tbSelectedValue.Text != String.Empty)
            {
                vm.OpenSelectedFile();
                tbSelectedValue.Text = String.Empty;
            }

But I wanna to implement it using a more sofisticated way, using ICommand.
Following the advise sent by janonimus, I created the BaseCommand Class Exactly like this but it throws a mismatch error when I call the function OpenSelectedFile

private BaseCommand<CatalogViewModel> _selectFileCommand;
public ICommand SelectFileCommand
{
    get
    {
        if (_selectFileCommand == null)
        {
            _selectFileCommand = new BaseCommand<CatalogViewModel>(OpenSelectedFile, true);
        }
        return _selectFileCommand;
    }
}
public void OpenSelectedFile()
{
    try
    {
        OpenFileByNumber(Int32.Parse(SelectedValue));
    }
    catch (Exception e)
    {
        MessageBox.Show("Número inválido: \'" + SelectedValue + "\"",
           "ERRO", MessageBoxButton.OK, MessageBoxImage.Warning);
    }

}

That's my code for reference...

Main.xaml.cs

namespace SLMT.Views
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class Main : Window
    {

        public Main()
        {
            InitializeComponent();
            DataContext = new CatalogViewModel();
            chosenNumber.Focus();
        }

        // Permite inserir somente números
        private void ChosenNumber_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^ 0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        private void ChosenNumber_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && chosenNumber.Text != String.Empty)
            {
                //catalog.OpenFileByNumber(ConvertToInt(numeroEscolhido.Text));
                //catalog.OpenSelectedFile(); // Will become someting like this
                chosenNumber.Text = String.Empty;

            }
        }

        private int ConvertToInt(string value)
        {
            try
            {
                var str = value.Replace(" ", String.Empty);
                return Int32.Parse(str);
            }
            catch (Exception exc)
            {
                MessageBox.Show("O número: \"" + chosenNumber.Text + "\" é inválido", "ERRO", MessageBoxButton.OK, MessageBoxImage.Error);
                chosenNumber.Text = String.Empty;

                return 0;
            }
        }

        ///
        /// Controll what wil lhappen if some KEYS are pressed on APP
        ///
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GMain_KeyUp(object sender, KeyEventArgs e)
        {

            switch (e.Key){

                case Key.Escape:
                    Environment.Exit(0);
                    break;

                case Key.F1:
                    //wListFiles = new ListFiles(catalog);
                    //wListFiles.ShowDialog();
                    //numeroEscolhido.Text = wListFiles.SelectFile();
                    //numeroEscolhido.SelectAll();
                    break;
            }

        }
    }
}

ps: The commented lines, I imported from the version without MVVM

Main.xaml

<Window x:Name="wMain" x:Class="SLMT.Views.Main"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SLMT.Views"
        mc:Ignorable="d"
        Title="Ministério Tons" Height="364" Width="700" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowStyle="None">
    <Grid x:Name="gMain" KeyUp="GMain_KeyUp">
        <Image x:Name="imgBackground" HorizontalAlignment="Left" Height="364" VerticalAlignment="Top" Width="700" Source="/SLMT;component/Resources/img/background2.jpg" Opacity="100"/>
        <TextBox x:Name="chosenNumber" HorizontalAlignment="Center" Height="34" Margin="500,294,56,36" TextWrapping="Wrap" VerticalAlignment="Center" Width="144" BorderBrush="{x:Null}" Background="{x:Null}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" UndoLimit="50" ForceCursor="True" PreviewTextInput="ChosenNumber_PreviewTextInput" KeyUp="ChosenNumber_KeyUp" BorderThickness="0" FontSize="20" Opacity="0.6" FontWeight="Bold"/>

    </Grid>
</Window>

And the Relevant part of CatalogViewModel.cs

namespace SLMT.ViewModel
{
    public class CatalogViewModel: ObservableCollection <File>
    {

        private int selectedNumber;

        ///
        /// Contain the selected number in the View
        ///
        public int SelectedNumber
        {
            get { return selectedNumber; }
            set { selectedNumber = value; }
        }

        // REMOVED CODE TO SCAN AND INDEX THE FILES

        public CatalogViewModel() : base()
        {
            ScanFiles();
            ValidateAndAddFiles();
            ShowAlerts();
        }

        public void OpenSelectedFile()
        {
            OpenFileByNumber(SelectedNumber);
        }

        ///
        /// Get the file from catalog identified my the number
        ///
        /// <param name="number"></param>
        /// <returns>File|null</returns>
        private File GetFileByNumber(int number)
        {
            foreach (var file in this)
            {
                if (file.number == number){
                    return file;
                }
            }

            return null;
        }

        private void OpenFileByNumber(int number)
        {
            var file = GetFileByNumber(number);

            if (file == null)
            {
                MessageBox.Show("Nenhum arquivo encontrado com o número: \'" + number +"\"",
                   "ARQUIVO NÃO ENCONTRADO", MessageBoxButton.OK, MessageBoxImage.Warning);
            } else
            {
                file.Open();
            }
        }
    }
}

Body:
Try the following to have access to the view model that you created in your constructor.

CatalogViewModel vm = new CatalogViewModel();

public Main()
{
    InitializeComponent();
    DataContext = vm;
    chosenNumber.Focus();
}

Then in  your key handler, you can do this:

private void ChosenNumber_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter && chosenNumber.Text != String.Empty)
    {
        //catalog.OpenFileByNumber(ConvertToInt(numeroEscolhido.Text));
        //catalog.OpenSelectedFile(); // Will become someting like this

        vm.OpenSelectedFile();
        chosenNumber.Text = String.Empty;
    }
}

Update: Using ICommand

Using the BaseCommand class you pointed to from here. I added the following code to the CatalogViewModel and got it working. You had the type in BaseCommand as the view model, but that's supposed to be the type of the command parameter (based on examples in that post).

private BaseCommand<object> _selectFileCommand;
public ICommand SelectFileCommand
{
    get
    {
        if (_selectFileCommand == null)
        {
            _selectFileCommand = new BaseCommand<object>((commandParam) => OpenSelectedFile(commandParam),
                                                         (commandParam) => CanOpenSelectedFile(commandParam));
        }
        return _selectFileCommand;
    }
}

public void OpenSelectedFile(object commandParam = null)
{
    Debug.WriteLine("CatalogViewModel.OpenSelectedFile was called.");
    Debug.WriteLine("SelectedValue = " + this.SelectedValue);
}

public bool CanOpenSelectedFile(object commandParam = null)
{
    return true;
}

Once you get into the OpenSelectedFile method, you should be able to hook it up to the functionality that you want.


来源: stackexchange

问:
How to create a sentence with list of position and a list of words
I wanted to create a code which ask a user to enter a list of position on a plain text file, save the position the user entered in the text file as list than ask the user to enter the word each position represent (the same order as the list of position) end re-create the sentence. However when  i run this code:

```<code>import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
p =open("list_of_numbers.txt","r")
l = p.read()
p.close()
positions = list(l)
subprocess.Popen(["notepad","list_of_words.txt"])
s = open("list_of_words.txt","r")
s.read()
s.close()

sentence = str(s)
print (sentence)

mapping = {}

words = sentence.split()

for (position, word) in zip(positions, words):
    mapping[position] = word

output = [mapping[position] for position in positions]

print(' '.join(output))
</code>```

and i run

```<code> 1 2 3 4 5 1 2 3 4 5
</code>```

as list of position

and this as the list of words:

```<code> this is a repeated sentence
</code>```

the output should be:

```<code> this is a repeated sentence this is a repeated sentence
</code>```

but i get

```<code>"key error:3"
</code>```

Im think they problem is i didnt store the list of position into a list properly but im not sure. Can somebody help me?

答:
try this one

```<code>import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
with open("list_of_numbers.txt","r") as p:
    l = p.read()
positions = l.split() # see you had to create list by spliting the string

subprocess.Popen(["notepad","list_of_words.txt"])
with open("list_of_words.txt","r") as s:
    sentence = s.read() # you had to assign the string to variable
print (sentence)

mapping = {}

words = sentence.split()

for position, word in zip(positions, words):
    mapping[position] = word

output = [mapping[position] for position in positions]

print(' '.join(output))
</code>```

but also it could be

```<code>import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
with open("list_of_numbers.txt","r") as pos_file:
    positions = pos_file.read().spllit()

subprocess.Popen(["notepad","list_of_words.txt"])
with open("list_of_words.txt","r") as sentence_file:
    words = sentence_file.read().split()

mapping = dict(zip(positions, words))
output = [mapping[position] for position in positions]

print(' '.join(output))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wanted to create a code which ask a user to enter a list of position on a plain text file, save the position the user entered in the text file as list than ask the user to enter the word each position represent (the same order as the list of position) end re-create the sentence. However when  i run this code:

import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
p =open("list_of_numbers.txt","r")
l = p.read()
p.close()
positions = list(l)
subprocess.Popen(["notepad","list_of_words.txt"])
s = open("list_of_words.txt","r")
s.read()
s.close()

sentence = str(s)
print (sentence)

mapping = {}

words = sentence.split()

for (position, word) in zip(positions, words):
    mapping[position] = word

output = [mapping[position] for position in positions]

print(' '.join(output))

and i run

 1 2 3 4 5 1 2 3 4 5

as list of position

and this as the list of words:

 this is a repeated sentence

the output should be:

 this is a repeated sentence this is a repeated sentence

but i get

"key error:3"

Im think they problem is i didnt store the list of position into a list properly but im not sure. Can somebody help me?

Body:
try this one

import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
with open("list_of_numbers.txt","r") as p:
    l = p.read()
positions = l.split() # see you had to create list by spliting the string

subprocess.Popen(["notepad","list_of_words.txt"])
with open("list_of_words.txt","r") as s:
    sentence = s.read() # you had to assign the string to variable
print (sentence)

mapping = {}

words = sentence.split()

for position, word in zip(positions, words):
    mapping[position] = word

output = [mapping[position] for position in positions]

print(' '.join(output))

but also it could be

import subprocess
subprocess.Popen(["notepad","list_of_numbers.txt"])
with open("list_of_numbers.txt","r") as pos_file:
    positions = pos_file.read().spllit()

subprocess.Popen(["notepad","list_of_words.txt"])
with open("list_of_words.txt","r") as sentence_file:
    words = sentence_file.read().split()

mapping = dict(zip(positions, words))
output = [mapping[position] for position in positions]

print(' '.join(output))


问:
save to localStorage
i'm curious if its possible to save the text input a user types in the field to localStorage , so in this html example , i'd want to save the innner html from the div#match_player_id , that is created when you click the button</p>

```<code><input type="text" id="contract_year" placeholder="Contract" autocomplete="off">

<input value="Submit" onclick="document.querySelector('#match_player_id').innerHTML = document.querySelector('#contract_year').value" type="button">

<div id="match_player_id"></div>
</code>```

答:
I recommend you to use a javascript function instead:

```<code><script type="text/javascript">
function updateMatchPlayerId() {
    var matchPlayerId = document.querySelector('#contract_year').value;
    document.querySelector('#match_player_id').innerHTML =  matchPlayerId;
    if (typeof Storage !== "undefined") {
        localStorage.setItem("matchPlayerId", matchPlayerId);
    }
}
</script>
</code>```

HTML:

```<code><input type="text" id="contract_year" placeholder="Contract" autocomplete="off">

<input value="Submit" onclick="updateMatchPlayerId()" type="button">

<div id="match_player_id"></div>
</code>```

Title: save to localStorage

Body:
i'm curious if its possible to save the text input a user types in the field to localStorage , so in this html example , i'd want to save the innner html from the div#match_player_id , that is created when you click the button

<input type="text" id="contract_year" placeholder="Contract" autocomplete="off">

<input value="Submit" onclick="document.querySelector('#match_player_id').innerHTML = document.querySelector('#contract_year').value" type="button">

Body:
I recommend you to use a javascript function instead:

<script type="text/javascript">
function updateMatchPlayerId() {
    var matchPlayerId = document.querySelector('#contract_year').value;
    document.querySelector('#match_player_id').innerHTML =  matchPlayerId;
    if (typeof Storage !== "undefined") {
        localStorage.setItem("matchPlayerId", matchPlayerId);
    }
}
</script>

HTML:

<input type="text" id="contract_year" placeholder="Contract" autocomplete="off">

<input value="Submit" onclick="updateMatchPlayerId()" type="button">

<div id="match_player_id"></div>


问:
Custom Dialog filling the screen height
I am trying to create a custom Dialog, and is working just fine, but the Dialog is filling the whole screen height. I've done some unsuccessful research on the internet but I don't have a lot of time for this task, if anyone knows why is this happening I appreciate it hard.

here is the onCreateDialog():

```<code>public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder= new AlertDialog.Builder(getContext());
    LayoutInflater inflater= (LayoutInflater) builder.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.dialog__warning, mContainer, false);
    txtWarning = (TextView)view.findViewById(R.id.txtWarning);
    if(messageWarning.length()>0)
    {
        txtWarning.setText(messageWarning);
    }
    btnOkDialog = (Button) view.findViewById(R.id.btnOkDialog);
    btnOkDialog.setOnClickListener(MyListener);
    btnCancelDialog = (Button) view.findViewById(R.id.btnCancelDialog);
    btnCancelDialog.setOnClickListener(MyListener);
    builder.setView(view);
    return builder.create();
}
</code>```

and the xml of dialog_warning:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dp"
android:layout_height="300dp"
android:background="#b1b0b0"
tools:context="ipat.johanbayona.gca.ipat.NewEvidence.Dialog_Warning">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:textSize="25sp"
    android:id="@+id/txtWarning"
    android:text="Mensaje error" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="OK"
    android:id="@+id/btnOkDialog"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="10dp"
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Cancel"
    android:id="@+id/btnCancelDialog"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="10dp"
    />
</RelativeLayout>
</code>```

答:
```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dp"
android:layout_height="300dp"
android:background="#b1b0b0"
tools:context="ipat.johanbayona.gca.ipat.NewEvidence.Dialog_Warning">
</code>```

Change "layout_height" to wrap_content. You fixed height and width, that may be the problem depending on your screen size.

Title: Custom Dialog filling the screen height

Body:
I am trying to create a custom Dialog, and is working just fine, but the Dialog is filling the whole screen height. I've done some unsuccessful research on the internet but I don't have a lot of time for this task, if anyone knows why is this happening I appreciate it hard.

here is the onCreateDialog():

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder= new AlertDialog.Builder(getContext());
    LayoutInflater inflater= (LayoutInflater) builder.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.dialog__warning, mContainer, false);
    txtWarning = (TextView)view.findViewById(R.id.txtWarning);
    if(messageWarning.length()>0)
    {
        txtWarning.setText(messageWarning);
    }
    btnOkDialog = (Button) view.findViewById(R.id.btnOkDialog);
    btnOkDialog.setOnClickListener(MyListener);
    btnCancelDialog = (Button) view.findViewById(R.id.btnCancelDialog);
    btnCancelDialog.setOnClickListener(MyListener);
    builder.setView(view);
    return builder.create();
}

and the xml of dialog_warning:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dp"
android:layout_height="300dp"
android:background="#b1b0b0"
tools:context="ipat.johanbayona.gca.ipat.NewEvidence.Dialog_Warning">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:textSize="25sp"
    android:id="@+id/txtWarning"
    android:text="Mensaje error" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="OK"
    android:id="@+id/btnOkDialog"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="10dp"
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Cancel"
    android:id="@+id/btnCancelDialog"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="10dp"
    />
</RelativeLayout>

Body:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dp"
android:layout_height="300dp"
android:background="#b1b0b0"
tools:context="ipat.johanbayona.gca.ipat.NewEvidence.Dialog_Warning">

Change "layout_height" to wrap_content. You fixed height and width, that may be the problem depending on your screen size.


问:
Show Message if successful sql request is done
I want to show message if my sql request is done with no problems. In this moment i have code that show MessageBox for every successful done request, but if there is no username and is didn't done again it's showing the same messagebox.

```<code>try
{
    using (SqlConnection con = new SqlConnection(constring))
    {
        con.Open();
        using (SqlCommand command = new SqlCommand("DELETE FROM dbo.Admin WHERE UserName  = '" + txtUserName.Text +"'", con))
        {
            command.ExecuteNonQuery();
            MessageBox.Show("Successful operation!");
        }
        con.Close();
    }
</code>```

How can i fix that? I want to show successful operation only if there is result from sql request, not everytime when i am doing that command.

答:
You should check on the number of rows affected which is retuned from ExecuteNonQuery command as follows:</p>

```<code>   using (SqlConnection con = new    SqlConnection(constring))
   {
       con.Open();
       using (SqlCommand command = new   SqlCommand("DELETE FROM dbo.Admin WHERE  UserName  = '" + txtUserName.Text +"'", con))
       {
           if( command.ExecuteNonQuery() > 0)
              MessageBox.Show("Successful operation!");
       }
       con.Close();
  }
</code>```

Body:
I want to show message if my sql request is done with no problems. In this moment i have code that show MessageBox for every successful done request, but if there is no username and is didn't done again it's showing the same messagebox.

try
{
    using (SqlConnection con = new SqlConnection(constring))
    {
        con.Open();
        using (SqlCommand command = new SqlCommand("DELETE FROM dbo.Admin WHERE UserName  = '" + txtUserName.Text +"'", con))
        {
            command.ExecuteNonQuery();
            MessageBox.Show("Successful operation!");
        }
        con.Close();
    }

How can i fix that? I want to show successful operation only if there is result from sql request, not everytime when i am doing that command.

Body:
You should check on the number of rows affected which is retuned from ExecuteNonQuery command as follows:

   using (SqlConnection con = new    SqlConnection(constring))
   {
       con.Open();
       using (SqlCommand command = new   SqlCommand("DELETE FROM dbo.Admin WHERE  UserName  = '" + txtUserName.Text +"'", con))
       {
           if( command.ExecuteNonQuery() > 0)
              MessageBox.Show("Successful operation!");
       }
       con.Close();
  }


问:
STL std::map, pass by ref to const and the necessity of const_casting
I have a simple question regarding const_cast and best practices regarding STL containers. Consider the following where class Foo has a private STL std::map from Widget* to int:

Declaration:

```<code>#include <map>
using std::map;

class Widget;

class Foo {
public:
     Foo(int n);
     virtual ~Foo();

     bool hasWidget(const Widget&);

private:
     map<Widget*,int> widget_map;
};
</code>```

Definition:

```<code>#include <map>
#include "Foo.h"
#include "Widget.h"

using std::map;

Foo::Foo(int n)
{
     for (int i = 0; i < n; i++) {
          widget_map[new Widget()] = 1;
     }
}

Foo::~Foo()
{
     map<Widget*, int>::iterator it;
     for (it = widget_map.begin(); it != widget_map.end(); it++) {
          delete it->first;
     }
}

bool Foo::hasWidget(const Widget& w)
{
     map<Widget*, int>::iterator it;
     it = this->widget_map.find(const_cast<Widget*>(&w));
     return ( ! ( it == widget_map.end() ) );
}
</code>```

Given that hasWidget takes a reference to const as its parameter, the constness needs to be cast away when calling map::find (wiget_map being from Wiget* to int). As far as I can tell, this approach is both sensible and desirable -- but I'm reluctant to accept it as such without feedback from more experienced C++ programmers.

It seems to me that this is one of the few cases of using const_cast appropriately given that we're passing the result of the cast to an STL method. Am I correct?

I realise that other permutations of this question have been posed already (for example, const_cast for vector with object) but none seem to directly address the above.

Thanks in advance.

答: Yes, that's a reasonable use of const_cast<>.  You should consider making hasWidget const.

ContentLicense: CC BY-SA 2.5

Body:
I have a simple question regarding const_cast and best practices regarding STL containers. Consider the following where class Foo has a private STL std::map from Widget* to int:

Declaration:

#include <map>
using std::map;

class Widget;

class Foo {
public:
     Foo(int n);
     virtual ~Foo();

     bool hasWidget(const Widget&);

private:
     map<Widget*,int> widget_map;
};

Definition:

#include <map>
#include "Foo.h"
#include "Widget.h"

using std::map;

Foo::Foo(int n)
{
     for (int i = 0; i < n; i++) {
          widget_map[new Widget()] = 1;
     }
}

Foo::~Foo()
{
     map<Widget*, int>::iterator it;
     for (it = widget_map.begin(); it != widget_map.end(); it++) {
          delete it->first;
     }
}

bool Foo::hasWidget(const Widget& w)
{
     map<Widget*, int>::iterator it;
     it = this->widget_map.find(const_cast<Widget*>(&w));
     return ( ! ( it == widget_map.end() ) );
}

Given that hasWidget takes a reference to const as its parameter, the constness needs to be cast away when calling map::find (wiget_map being from Wiget* to int). As far as I can tell, this approach is both sensible and desirable -- but I'm reluctant to accept it as such without feedback from more experienced C++ programmers.

It seems to me that this is one of the few cases of using const_cast appropriately given that we're passing the result of the cast to an STL method. Am I correct?

I realise that other permutations of this question have been posed already (for example, const_cast for vector with object) but none seem to directly address the above.

Thanks in advance.


问:
Adding fragments to a fragment
I am very new to Android (been at it for 1 week), and I can't seem to find the answer to what I am after.

I have in my main activity 3 tabs:

Home

Trending

Profile

When clicking each tab, I effectively load a fragment (corresponding to each one of my tabs) into my Main activity layout.

Additionally I have a fragment called articleEntryFragment.

For every one of my tab fragments I would like to load multiple article entries.

But as I understand it. Nested fragments don't work on APIs earlier than 17, and I want to have as much backward compatibility as possible.

Therefore, how is this very basic principal achieved?

For instance, when you go on the YouTube app, there are tabs, each tab has different videos.

It's my assumption that like in my app. Every tab is its own fragment, and every video listing uses a similar concept to my articleEntry fragment.

What's the proper way to achieve what I am after?

Thank you.

p.s. not looking for anyone to write code for me, but rather, direct me in the right path.

答:
Excellent question.

This doubt is very common.

In the documentation have everything you need, look at this:

Nested Fragments And Fragment Pager Adapter And Fragment

For your answer, I understand that I wanted to do something like this:

There are two libraries in github with can help you:

Pager Sliding Tab Strip

Material Tabs

Review and use these examples that will be very useful.

I found these links here, if you want to take a look, there are other different libraries that can help you.

I hope it helps.

Title: Adding fragments to a fragment


问:
Element width decreasing in one direction
I ran into situation earlier where I have a position relative container with a position absolute element inside. The element inside contains an image that has a max width of 100%. If I move this element which I have called "item" in the fiddle below using "left" the width of the element decreases the further I go to the right (does not happen if moving to the left with negative values). This happens the opposite way if use the css rule "right". If I take the width declaration off the image this no longer occurs. Does anyone know why this is the case. Here is a fiddle I created to show the issue.

```<code>.container {
  position:relative;
  overflow:hidden;
  padding-bottom:32%;
}

.item {
  position:absolute;
}

.content {
  width:400px;
  margin:auto;

}

img {
  max-width:100%;
}

<div class="content">
<div class = "container">
  <div class = "item">
    <a href='https://postimg.org/image/h3h0e82rx/' target='_blank'><img src='https://s22.postimg.org/kabjxun81/banner.jpg' border='0' alt='banner'/><br /><a target='_blank' href='https://postimage.org/'></a><br /><br />
  </div>
</div>
</div>
</code>```

https://jsfiddle.net/rv9wcqh2/

An explanation would be greatly appreciated.

答:
If I'm understanding you correctly, I think you could use the css for clip-path. Is this in essence what you're looking for?

body {background:rgba(255,255,255,1);}

.container {
  position:relative;
  overflow:hidden;
  padding-bottom:32%;
}

.item {
  position:absolute;
}

.content {
  width:400px;
  margin:auto;
    -webkit-clip-path: polygon(0 0, 0% 100%, 100% 50%);
  clip-path: polygon(0 0, 0% 100%, 100% 50%);

}

img {
  max-width:100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
<div class = "container">
  <div class = "item">
    <img src='https://s22.postimg.org/kabjxun81/banner.jpg' border='0' alt='banner'/><br />target='_blank' href='https://postimage.org/'><br /><br />
  </div>
</div>
</div></code>```

Body:
I ran into situation earlier where I have a position relative container with a position absolute element inside. The element inside contains an image that has a max width of 100%. If I move this element which I have called "item" in the fiddle below using "left" the width of the element decreases the further I go to the right (does not happen if moving to the left with negative values). This happens the opposite way if use the css rule "right". If I take the width declaration off the image this no longer occurs. Does anyone know why this is the case. Here is a fiddle I created to show the issue.

.container {
  position:relative;
  overflow:hidden;
  padding-bottom:32%;
}

.item {
  position:absolute;
}

.content {
  width:400px;
  margin:auto;

}

img {
  max-width:100%;
}

https://jsfiddle.net/rv9wcqh2/

An explanation would be greatly appreciated.

Body:
If I'm understanding you correctly, I think you could use the css for clip-path. Is this in essence what you're looking for?

body {background:rgba(255,255,255,1);}

.container {
  position:relative;
  overflow:hidden;
  padding-bottom:32%;
}

.item {
  position:absolute;
}

.content {
  width:400px;
  margin:auto;
    -webkit-clip-path: polygon(0 0, 0% 100%, 100% 50%);
  clip-path: polygon(0 0, 0% 100%, 100% 50%);

}

img {
  max-width:100%;
}

<div class="content">
<div class = "container">
  <div class = "item">
    <a href='https://postimg.org/image/h3h0e82rx/' target='_blank'><img src='https://s22.postimg.org/kabjxun81/banner.jpg' border='0' alt='banner'/><br /><a target='_blank' href='https://postimage.org/'></a><br /><br />
  </div>
</div>
</div>


问:
Bootstrap 3 merge rows and columns
I can't figure out what is the problem with my code. I'm very new in bootstrap my problem is kinda trivial. One of my field is out of position. I have tried a different route by making only one row and instead of increasing the div sizes I reduced them, but it had the exact same problem. (Run the code in full screen mode).

Please if you can help me out!

.row {
    background-color: yellow;
}

.col-sm-3, .col-sm-6 {
    border:solid 2px black;
}

div {
    height:200px;
}
.two-div {
    height:400px;
}
.three-div {
    height:600px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
    <head>
        <title>Bootstrap Example</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-sm-3 three-div pull-left">Works</div>
            <div class="col-sm-6">Works</div>
            <div class="col-sm-3 two-div pull-right">Works</div>
        </div>
        <div class="row">
            <div class="col-sm-3 two-div">Works</div>
            <div class="col-sm-3 three-div">Works</div>
        </div>
        <div class="row">
            <div class="col-sm-3 two-div pull-right">Works</div>
        </div>
        <div class="row">
            <div class="col-sm-6">:(</div>
        </div>
    </div>
    </body>
</html></code>```

答:
Your unhappy smiley box is off because your setting different heights for the containers. I altered your code to explain how you work with BS grid system. See comments.

.row {
    background-color: yellow;
}

.col-sm-3,.col-sm-6 {
    border:solid 2px black;
}
div { height:200px; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Bootstrap Example</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-sm-3 three-div">Works</div> <!-- no need for pulling left. BS does that already -->
            <div class="col-sm-6">Works</div>
            <div class="col-sm-3 two-div">Works</div> <!-- no need for pulling right -->
        </div>
        <div class="row">
            <div class="col-sm-3 two-div">Works</div>
            <div class="col-sm-3 three-div">Works</div>
        </div>
        <div class="row">
            <div class="col-sm-3 col-sm-offset-9">Works</div> <!-- use -offset-X to move your divs horizontally along the grid -->
        </div>
        <div class="row">
           <div class="col-sm-6">:(</div>
        </div>
    </div>
    </body>
</html></code>```

Title: Bootstrap 3 merge rows and columns

Body:
I can't figure out what is the problem with my code. I'm very new in bootstrap my problem is kinda trivial. One of my field is out of position. I have tried a different route by making only one row and instead of increasing the div sizes I reduced them, but it had the exact same problem. (Run the code in full screen mode).

Please if you can help me out!

.row {
    background-color: yellow;
}

.col-sm-3, .col-sm-6 {
    border:solid 2px black;
}

div {
    height:200px;
}
.two-div {
    height:400px;
}
.three-div {
    height:600px;
}

<!DOCTYPE html>

        <title>Bootstrap Example</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Works

Works

Works

Works

Works

Works

:(

Body:
Your unhappy smiley box is off because your setting different heights for the containers. I altered your code to explain how you work with BS grid system. See comments.

.row {
    background-color: yellow;
}

.col-sm-3,.col-sm-6 {
    border:solid 2px black;
}
div { height:200px; }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Bootstrap Example</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-sm-3 three-div">Works</div> <!-- no need for pulling left. BS does that already -->
            <div class="col-sm-6">Works</div>
            <div class="col-sm-3 two-div">Works</div> <!-- no need for pulling right -->
        </div>
        <div class="row">
            <div class="col-sm-3 two-div">Works</div>
            <div class="col-sm-3 three-div">Works</div>
        </div>
        <div class="row">
            <div class="col-sm-3 col-sm-offset-9">Works</div> <!-- use -offset-X to move your divs horizontally along the grid -->
        </div>
        <div class="row">
           <div class="col-sm-6">:(</div>
        </div>
    </div>
    </body>
</html>


问:
Conflicting versions of Data.Map
I'm working with this module Algorithms.Geometry.LineSegmentIntersection.BentleyOttman using the function "intersections"  that returns something of type Intersections which in turn is an alias for Map (Point 2 r) (Associated p r). So, I try to manipulate that result with the corresponding functions of the Data.Map.Lazy module, but I get the following error:

Any ideas on how to fix it? Thanks!

答:
You have two versions of the containers package installed, and have  ended up referencing both of them. A Map produced by containers 0.5.7.1 can't be passed to a Map-consuming function from containers 0.5.10.1 (or any mismatched versions), even if their definition of Map in source code is the same.

Without knowing more about your installation history, it's impossible to say exactly why that happened. I would guess you're just using cabal install to install packages as you need them, into the default user-wide package environment? That almost inevitably results in problems like this, eventually.

The easiest immediate solution is to delete your entire store of installed packages and then reinstall everything you need again (preferably all at the same time, not with multiple separate invocations of cabal install).

To prevent this from happening again, to could change your work practices to use tools like cabal sandbox or stack, which facilitate having separate package environments for each project.

Title: Conflicting versions of Data.Map


问:
UNIQUE constraint failed (Omit)
Attempting to compile a data base but on output in command prompt I am getting the following:

```<code>DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port
</code>```

I understand why it is doing this due to there being duplicates attempted to being added to the database, but I am wondering how I can omit this from the output on the command line.

A portion of the current output:

```<code>DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2832.
DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2840.
DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2841.
DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2842.
DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2845.
DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2886.
The file contained 628 records
</code>```

The output I wish to receive:

```<code>The file contained 628 records
</code>```

The code for reference:

```<code># Modules used ------------------
use DBI;
use warnings;
use strict;
# End of Modules used -----------

# Variables Used ----------------
my $DBPath;
my $RecCount;
my $ProbedDB;
my $Line;
my $ipAddr;
my $portNum;
my $insertPortDB;
my $StatHandle;
# End of Variables Used ---------

# Creats a path for the database
$DBPath = 'D:\Everything\Fleming College\Semester 2\PERL\Lab 8\lab8.db';

# Used to keep track of records in log file
$RecCount = 0;

# Creates database handle and connects database to be used by program
$ProbedDB = DBI->connect("dbi:SQLite:dbname=$DBPath","","")
        or die "Can't connect to the database: $DBI::errstr\n";

# Creates the table
$ProbedDB->do("CREATE TABLE Probes (Source Char(15) NOT NULL,
        Port Char(5) NOT NULL, PRIMARY KEY (Source, Port))");

# Opens up the specified file that contains all of the logs used,
# if unable to open, notifies the user.
open Lab4File, "<sample.log"
    or die "Unable to open sample.log\n", $!;

# Scans text file
while($Line = <Lab4File>)
{
    if($Line =~ /INext-DROP/)  # Filters out the ports that were scanned
    {
            if($Line =~ /SRC=([\d+\.]*).*DPT=([\d+\.]*)/) # Filters out the IP
                                                          # address & the port number only
            {
                $ipAddr = $1;   # Stores the info following SRC= into variable
                $portNum = $2;  # Stores the info following DPT= into variable

                # This variable determines ports and values
                $insertPortDB = 'INSERT INTO Probes (Source, Port) Values(?,?)';

                # Create statement handle
                $StatHandle = $ProbedDB->prepare($insertPortDB);

                # Puts info into database
                $StatHandle->execute($ipAddr,$portNum);

                # Incremented to keep track
                $RecCount++;
            };
    };
}
printf("The file contained %i records", "$RecCount");
</code>```

Any ideas?

答: Change your statement to "INSERT OR IGNORE INTO..."</p>

Title: UNIQUE constraint failed (Omit)

Body:
Attempting to compile a data base but on output in command prompt I am getting the following:

DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port

I understand why it is doing this due to there being duplicates attempted to being added to the database, but I am wondering how I can omit this from the output on the command line.

A portion of the current output:

DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2832.
DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2840.
DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2841.
DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2842.
DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2845.
DBD::SQLite::st execute failed: UNIQUE constraint failed: Probes.Source, Probes.Port at lab8.pl line 67, <Lab4File> line 2886.
The file contained 628 records

The output I wish to receive:

The file contained 628 records

The code for reference:

# Modules used ------------------
use DBI;
use warnings;
use strict;
# End of Modules used -----------

# Variables Used ----------------
my $DBPath;
my $RecCount;
my $ProbedDB;
my $Line;
my $ipAddr;
my $portNum;
my $insertPortDB;
my $StatHandle;
# End of Variables Used ---------

# Creats a path for the database
$DBPath = 'D:\Everything\Fleming College\Semester 2\PERL\Lab 8\lab8.db';

# Used to keep track of records in log file
$RecCount = 0;

# Creates database handle and connects database to be used by program
$ProbedDB = DBI->connect("dbi:SQLite:dbname=$DBPath","","")
        or die "Can't connect to the database: $DBI::errstr\n";

# Creates the table
$ProbedDB->do("CREATE TABLE Probes (Source Char(15) NOT NULL,
        Port Char(5) NOT NULL, PRIMARY KEY (Source, Port))");

# Opens up the specified file that contains all of the logs used,
# if unable to open, notifies the user.
open Lab4File, "<sample.log"
    or die "Unable to open sample.log\n", $!;

# Scans text file
while($Line = <Lab4File>)
{
    if($Line =~ /INext-DROP/)  # Filters out the ports that were scanned
    {
            if($Line =~ /SRC=([\d+\.]*).*DPT=([\d+\.]*)/) # Filters out the IP
                                                          # address & the port number only
            {
                $ipAddr = $1;   # Stores the info following SRC= into variable
                $portNum = $2;  # Stores the info following DPT= into variable

                # This variable determines ports and values
                $insertPortDB = 'INSERT INTO Probes (Source, Port) Values(?,?)';

                # Create statement handle
                $StatHandle = $ProbedDB->prepare($insertPortDB);

                # Puts info into database
                $StatHandle->execute($ipAddr,$portNum);

                # Incremented to keep track
                $RecCount++;
            };
    };
}
printf("The file contained %i records", "$RecCount");

Any ideas?


问:
Does multiple sizeMapping work?
I have configured mapping like this:

```<code>var mapping = googletag.sizeMapping().
    addSize([972, 0], [750, 100], [728, 90]).
    addSize([752, 0], [728, 90], [468, 60]).build();
</code>```

I would expect for resolution greater than 972 DFP to choose 750x100 or 728x90 ad. To me it looks like it only considers the first size i.e. 750x100. Even though I have better paying and with higher priority creative of size 728x90. When I get to delivery diagnostics there's information about request and it says "Request sizes 750x100". I would expect to have there both sizes. Am I missing something or in fact those multiple sizes are not supported?

Title: Does multiple sizeMapping work?

Body:
I have configured mapping like this:

var mapping = googletag.sizeMapping().
    addSize([972, 0], [750, 100], [728, 90]).
    addSize([752, 0], [728, 90], [468, 60]).build();

I would expect for resolution greater than 972 DFP to choose 750x100 or 728x90 ad. To me it looks like it only considers the first size i.e. 750x100. Even though I have better paying and with higher priority creative of size 728x90. When I get to delivery diagnostics there's information about request and it says "Request sizes 750x100". I would expect to have there both sizes. Am I missing something or in fact those multiple sizes are not supported?

Body:
Try

addSize([972, 0], [[750, 100], [728, 90]]).

Wrap the sizes in an array.


问:
Adding Bootstrap Margin
This seems so simple, but I can't seem to get it to work.  All I want is to apply spacing between the right side of the screen and the four wide column I have created.  I have tried adding:

```<code>.spacer{
    margin-right: 2%;
}
</code>```

onto a containing div unsuccessfully.  I have it working on my eight wide column but I can't seem to replicate it.  Jfiddle: https://jsfiddle.net/fru2yv1f/

```<code><div class="col-lg-12">
    <div class="row row-top">
        <div class="col-lg-8">
            <div class="horizontal-spacer text-center border-green">
                <div class="vert-center">
                    <h1 id="page-two-heading">Page two Heading</h1>
                    <p id="page-two-sub-heading">Information that is useful, hopefully!</p>
                </div>
            </div>
    </div>
        <div id="side-text" class="col-lg-4 hidden-md hidden-sm hidden-xs border-green">
            <div class="vert-center">
            <h3>This Area Will Disappear on Screen Resize</h3>
            <p>text text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text text</p>
            </div>
        </div>
        </div>
</code>```

答:
The solution was to add a class to the div with class col-lg-12 and then style the div with padding-right: 2%;

Ex.

```<code><div class="col-lg-12 spacer">

.spacer{
  padding-right: 2%;
}
</code>```

Title: Adding Bootstrap Margin

Body:
This seems so simple, but I can't seem to get it to work.  All I want is to apply spacing between the right side of the screen and the four wide column I have created.  I have tried adding:

.spacer{
    margin-right: 2%;
}

onto a containing div unsuccessfully.  I have it working on my eight wide column but I can't seem to replicate it.  Jfiddle: https://jsfiddle.net/fru2yv1f/

Page two Heading

Information that is useful, hopefully!

This Area Will Disappear on Screen Resize

text text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text texttext text text text text text text text

Body:
The solution was to add a class to the div with class col-lg-12 and then style the div with padding-right: 2%;

Ex.

<div class="col-lg-12 spacer">

.spacer{
  padding-right: 2%;
}


答:
Assuming this is my dataframe df

```<code>                     One           Two
Date
2015-11-15  (3, 10.0, 0)           NaN
2015-11-16           NaN           NaN
2015-11-17           NaN           NaN
2015-11-18  (3, 10.0, 0)           NaN
2015-11-19  (3, 10.0, 0)           NaN
2015-11-20   (4, 8.2, 0)           NaN
2015-11-21   (4, 8.2, 0)           NaN
2015-11-22   (4, 8.2, 0)   (1, 1.4, 1)
2015-11-23  (3, 18.0, 1)  (3, 10.0, 0)
2015-11-26   (4, 8.2, 0)   (1, 1.4, 1)
2015-11-27   (4, 8.2, 0)  (3, 10.0, 0)
2015-11-28           NaN   (1, 1.4, 1)
2015-11-29   (4, 8.2, 0)  (3, 10.0, 0)
2015-11-30   (4, 8.2, 0)   (1, 1.4, 1)
</code>```

```<code># 'W-Sat' tells pandas to end weeks on Saturday.
df.stack().groupby(
    [pd.Grouper(level=0, freq='W-Sat'), pd.Grouper(level=1)]
).apply(lambda s: s.value_counts().idxmax()).unstack()

                     One           Two
Date
2015-11-21  (3, 10.0, 0)          None
2015-11-28   (4, 8.2, 0)   (1, 1.4, 1)
2015-12-05   (4, 8.2, 0)  (3, 10.0, 0)
</code>```

Another way to have done this would be to stack it first and manipulate level values

```<code>ds = df.stack()
g1 = (ds.index.get_level_values(0) - ds.index.levels[0].min()).days // 7
g2 = ds.index.get_level_values(1)
ds.groupby([g1, g2]).apply(lambda s: s.value_counts().idxmax()).unstack()

            One           Two
0  (3, 10.0, 0)          None
1   (4, 8.2, 0)   (1, 1.4, 1)
2   (4, 8.2, 0)  (3, 10.0, 0)
</code>```

In the event you have np.nan that span an entire week and you want to return np.nan for those weeks, we need to tell stack not to dropna and pass a function to apply that can handle those np.nan

```<code>def value_counts_idxmax(s):
    try:
        return s.value_counts().idxmax()
    except ValueError:
        return np.nan

df.stack(dropna=False).groupby(
    [pd.Grouper(level=0, freq='W-Sat'), pd.Grouper(level=1)]
).apply(value_counts_idxmax).unstack()

           3046920017503 3046920017541
index
2015-11-21           NaN           NaN
2015-11-28           NaN           NaN
2015-12-05  (3, 10.0, 0)  (3, 10.0, 0)
2015-12-12  (3, 10.0, 0)  (3, 10.0, 0)
</code>```

Or with the second method

```<code>ds = df.stack(dropna=False)
g1 = (ds.index.get_level_values(0) - ds.index.levels[0].min()).days // 7
g2 = ds.index.get_level_values(1)
ds.groupby([g1, g2]).apply(value_counts_idxmax).unstack()

  3046920017503 3046920017541
0           NaN           NaN
1           NaN           NaN
2  (3, 10.0, 0)  (3, 10.0, 0)
3  (3, 10.0, 0)  (3, 10.0, 0)
</code>```

Title: Within-week operation on a pandas DataFrame indexed by datetime

Body:
I want to get the most frequent value in each week from every column of a DataFrame indexed by datetime. I know this can be done when entries of the DataFrame are all int or float. But I am looking for a general method that does not take advantage of the data type being int or float.

Here is an example, where each entry in the DataFrame is a tuple:

2015-11-15 00:00:00   (3, 10.0, 0)   nan
2015-11-16 00:00:00   nan            nan
2015-11-17 00:00:00   nan            nan
2015-11-18 00:00:00   (3, 10.0, 0)   nan
2015-11-19 00:00:00   (3, 10.0, 0)   nan
2015-11-20 00:00:00   (4, 8.2, 0)    nan
2015-11-21 00:00:00   (4, 8.2, 0)    nan
2015-11-22 00:00:00   (4, 8.2, 0)    (1, 1.4, 1)
2015-11-23 00:00:00   (3, 18.0, 1)   (3, 10.0, 0)
2015-11-26 00:00:00   (4, 8.2, 0)    (1, 1.4, 1)
2015-11-27 00:00:00   (4, 8.2, 0)    (3, 10.0, 0)
2015-11-28 00:00:00   nan            (1, 1.4, 1)
2015-11-29 00:00:00   (4, 8.2, 0)    (3, 10.0, 0)
2015-11-30 00:00:00   (4, 8.2, 0)    (1, 1.4, 1)

This should be transformed into a DataFrame consisting of the within-week most frequent tuple as follows:

2015-11-15 00:00:00   (3, 10.0, 0)   nan
2015-11-22 00:00:00   (4, 8.2, 0)    (1, 1.4, 1)

My preference is for efficiency, speed really matters in my application.

EDIT

           3046920017503 3046920017541
index
2015-11-15           NaN           NaN
2015-11-16           NaN           NaN
2015-11-17           NaN           NaN
2015-11-18           NaN           NaN
2015-11-19           NaN           NaN
2015-11-20           NaN           NaN
2015-11-21           NaN           NaN
2015-11-22           NaN           NaN
2015-11-23           NaN           NaN
2015-11-24           NaN           NaN
2015-11-25           NaN           NaN
2015-11-26           NaN           NaN
2015-11-27           NaN           NaN
2015-11-28           NaN           NaN
2015-11-29           NaN           NaN
2015-11-30           NaN           NaN
2015-12-01  (3, 10.0, 0)  (3, 10.0, 0)
2015-12-02  (3, 10.0, 0)  (3, 10.0, 0)
2015-12-03  (3, 10.0, 0)  (3, 10.0, 0)
2015-12-04  (3, 10.0, 0)  (3, 10.0, 0)
2015-12-05  (3, 10.0, 0)  (3, 10.0, 0)
2015-12-06  (3, 10.0, 0)  (3, 10.0, 0)

should be transformed into:

2015-11-15           NaN           NaN
2015-11-22           NaN           NaN
2015-11-29           (3, 10.0, 0)  (3, 10.0, 0)

but the method suggested yields:

           3046920017503 3046920017541
index
2015-12-05  (3, 10.0, 0)  (3, 10.0, 0)
2015-12-12  (3, 10.0, 0)  (3, 10.0, 0)

Body:
Assuming this is my dataframe df

                     One           Two
Date
2015-11-15  (3, 10.0, 0)           NaN
2015-11-16           NaN           NaN
2015-11-17           NaN           NaN
2015-11-18  (3, 10.0, 0)           NaN
2015-11-19  (3, 10.0, 0)           NaN
2015-11-20   (4, 8.2, 0)           NaN
2015-11-21   (4, 8.2, 0)           NaN
2015-11-22   (4, 8.2, 0)   (1, 1.4, 1)
2015-11-23  (3, 18.0, 1)  (3, 10.0, 0)
2015-11-26   (4, 8.2, 0)   (1, 1.4, 1)
2015-11-27   (4, 8.2, 0)  (3, 10.0, 0)
2015-11-28           NaN   (1, 1.4, 1)
2015-11-29   (4, 8.2, 0)  (3, 10.0, 0)
2015-11-30   (4, 8.2, 0)   (1, 1.4, 1)

# 'W-Sat' tells pandas to end weeks on Saturday.
df.stack().groupby(
    [pd.Grouper(level=0, freq='W-Sat'), pd.Grouper(level=1)]
).apply(lambda s: s.value_counts().idxmax()).unstack()

                     One           Two
Date
2015-11-21  (3, 10.0, 0)          None
2015-11-28   (4, 8.2, 0)   (1, 1.4, 1)
2015-12-05   (4, 8.2, 0)  (3, 10.0, 0)

Another way to have done this would be to stack it first and manipulate level values

ds = df.stack()
g1 = (ds.index.get_level_values(0) - ds.index.levels[0].min()).days // 7
g2 = ds.index.get_level_values(1)
ds.groupby([g1, g2]).apply(lambda s: s.value_counts().idxmax()).unstack()

            One           Two
0  (3, 10.0, 0)          None
1   (4, 8.2, 0)   (1, 1.4, 1)
2   (4, 8.2, 0)  (3, 10.0, 0)

In the event you have np.nan that span an entire week and you want to return np.nan for those weeks, we need to tell stack not to dropna and pass a function to apply that can handle those np.nan

def value_counts_idxmax(s):
    try:
        return s.value_counts().idxmax()
    except ValueError:
        return np.nan

df.stack(dropna=False).groupby(
    [pd.Grouper(level=0, freq='W-Sat'), pd.Grouper(level=1)]
).apply(value_counts_idxmax).unstack()

           3046920017503 3046920017541
index
2015-11-21           NaN           NaN
2015-11-28           NaN           NaN
2015-12-05  (3, 10.0, 0)  (3, 10.0, 0)
2015-12-12  (3, 10.0, 0)  (3, 10.0, 0)

Or with the second method

ds = df.stack(dropna=False)
g1 = (ds.index.get_level_values(0) - ds.index.levels[0].min()).days // 7
g2 = ds.index.get_level_values(1)
ds.groupby([g1, g2]).apply(value_counts_idxmax).unstack()

  3046920017503 3046920017541
0           NaN           NaN
1           NaN           NaN
2  (3, 10.0, 0)  (3, 10.0, 0)
3  (3, 10.0, 0)  (3, 10.0, 0)


问:
How to determine on one sample or two sample test, Z or t test
If you would like to know if there is significant difference on an attitude between two diverse groups (Let's say A and B). I drew a sample of 31 from  A and a sample of 33 B. Two sample are independent from each other, given the facts:

1) Do I need to run one sample or two sample test, and why?
2-)Considering sample sizes, should i run a T test or Z, and why?
3) Is it a one tailed or two tailed test, and why?

答: this link will explain to you when to use one or two sample test. Since you are comparing the responses from two groups (A and B), two sample test is more appropriate.  2) Run a T-test if population standard deviation is unknown or if known, sample observation is less than 30. Use z-test if population standard deviation is known and sample size is equal or greater than 30 (link). 3) When you have a null hypothesis that group A is not equal to group B, then use two tailed test, if your null hypothesis is one sided (mean of group A > mean of group B or vice-versa) then it is a one-tailed test.  Also, you did not mention that your observation is numerical or categorical.  If categorical, you use [chi-square][3] test rather than t-test.  Hope this helps.</p>


问:
Python Flask - Increment request.path
```<code><a href="{{ request.path }}"></a>
</code>```

Iam essentially looking to do the following:

```<code><a href="{{ request.path = request.path +1 }}"></a>
</code>```

request.path is returning "/image/". I need to increment the . So I need to increment .

This is the route:

```<code>@app.route('/image', methods=['GET', 'POST'])
@app.route('/image/<int:image_id>',methods=['GET', 'POST'])
def image(image_id):
    image = Images.query.filter_by(id=image_id).first_or_404()
    return render_template('image.html', image=image)
</code>```

Should I be looking into splitting the path?

答:
Answering my own question:

On the route pass image_id into the template:

```<code>m=image_id
</code>```

In the template:

```<code><a href="{{ m+1 }}"> xx </a></li>
</code>```

Title: Python Flask - Increment request.path

Body:
Iam essentially looking to do the following:

request.path is returning "/image/". I need to increment the . So I need to increment .

This is the route:

@app.route('/image', methods=['GET', 'POST'])
@app.route('/image/<int:image_id>',methods=['GET', 'POST'])
def image(image_id):
    image = Images.query.filter_by(id=image_id).first_or_404()
    return render_template('image.html', image=image)

Should I be looking into splitting the path?

Body:
Answering my own question:

On the route pass image_id into the template:

m=image_id

In the template:

<a href="{{ m+1 }}"> xx </a></li>


问:
Error handling between web api and angular 2 client
So I am looking for a pattern on how to handle exceptions.  Specifically I want to be able to pass the exception message on to the client from a Web API controller.

The client is using a third party library which deals with a call to the API
as

this.msgs = [];
let xhr = new XMLHttpRequest(),
formData = new FormData();

for(let i = 0; i < this.files.length; i++) {
    formData.append(this.name, this.files[i], this.files[i].name);
}

xhr.upload.addEventListener('progress', (e: ProgressEvent) => {
    if(e.lengthComputable) {
      this.progress = Math.round((e.loaded * 100) / e.total);
    }
  }, false);

xhr.onreadystatechange = () => {
    if(xhr.readyState == 4) {
        this.progress = 0;

        if(xhr.status == 200)
            this.onUpload.emit({xhr: xhr, files: this.files});
        else
            this.onError.emit({xhr: xhr, files: this.files});

        this.clear();
    }
};

xhr.open('POST', this.url, true);
xhr.send(formData);
```

<p>My current call back function is such</p>

```errorComplete(event: any) {
    console.log("upload error");
}
```

<p>notice that on error the library just wraps up the XMLHttpRequest and passes it on to my call back function.</p>

<p>so in the controller I have created a test line as follows</p>

```throw new Exception("This is a test message");
```

This is to simulate an unexpected exception

currently the return code in the XMLHttpRequest is a 500 and the text is the html that .Net generates when an exception occurs.

yes the method in my controller will need to wrapper in a try-catch but I am not sure of what code to put in the catch so I can send the error message down to the client and it can handle it and not take down the application.

the current use case I am looking at is the user uploads a file to the system but there is already a file with the specified name in the system.  And renaming the file is not an option!  I need to notify the user that there is already a file with that name in the system.

google has not revealed a way to pass the message back so I can process it.

答:
Thank you Nkosi- your comment got me on the right track.
I implemented some middleware.

```<code>public class UIExceptionHandler
{
    RequestDelegate _next;
    public UIExceptionHandler(RequestDelegate next)
    {
        this._next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await this._next(context);
        }
        catch (Exception x)
        {
            if (!context.Response.HasStarted)
            {
                context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                context.Response.Headers["Message"] = x.Message;
            }
        }
    }
}

public static class UIExcetionHandlerExtensions
{
    public static IApplicationBuilder UseUIExceptionHandler(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<UIExceptionHandler>();
    }
}
</code>```

and in the configure method of the startup

```<code>app.UseUIExceptionHandler();
</code>```

then on the client I can do

```<code>errorComplete(event: any) {
    var errorMessage = event.xhr.getResponseHeader('Message');
    console.log(errorMessage);
}
</code>```

If anyone sees an issue with this solution please let me know

Body:
So I am looking for a pattern on how to handle exceptions.  Specifically I want to be able to pass the exception message on to the client from a Web API controller.

The client is using a third party library which deals with a call to the API
as

this.msgs = [];
let xhr = new XMLHttpRequest(),
formData = new FormData();

for(let i = 0; i < this.files.length; i++) {
    formData.append(this.name, this.files[i], this.files[i].name);
}

xhr.upload.addEventListener('progress', (e: ProgressEvent) => {
    if(e.lengthComputable) {
      this.progress = Math.round((e.loaded * 100) / e.total);
    }
  }, false);

xhr.onreadystatechange = () => {
    if(xhr.readyState == 4) {
        this.progress = 0;

        if(xhr.status == 200)
            this.onUpload.emit({xhr: xhr, files: this.files});
        else
            this.onError.emit({xhr: xhr, files: this.files});

        this.clear();
    }
};

xhr.open('POST', this.url, true);
xhr.send(formData);

My current call back function is such

errorComplete(event: any) {
    console.log("upload error");
}

notice that on error the library just wraps up the XMLHttpRequest and passes it on to my call back function.

so in the controller I have created a test line as follows

throw new Exception("This is a test message");

This is to simulate an unexpected exception

currently the return code in the XMLHttpRequest is a 500 and the text is the html that .Net generates when an exception occurs.

yes the method in my controller will need to wrapper in a try-catch but I am not sure of what code to put in the catch so I can send the error message down to the client and it can handle it and not take down the application.

the current use case I am looking at is the user uploads a file to the system but there is already a file with the specified name in the system.  And renaming the file is not an option!  I need to notify the user that there is already a file with that name in the system.

google has not revealed a way to pass the message back so I can process it.

Body:
Thank you Nkosi- your comment got me on the right track.
I implemented some middleware.

public class UIExceptionHandler
{
    RequestDelegate _next;
    public UIExceptionHandler(RequestDelegate next)
    {
        this._next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await this._next(context);
        }
        catch (Exception x)
        {
            if (!context.Response.HasStarted)
            {
                context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                context.Response.Headers["Message"] = x.Message;
            }
        }
    }
}

public static class UIExcetionHandlerExtensions
{
    public static IApplicationBuilder UseUIExceptionHandler(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<UIExceptionHandler>();
    }
}

and in the configure method of the startup

app.UseUIExceptionHandler();

then on the client I can do

errorComplete(event: any) {
    var errorMessage = event.xhr.getResponseHeader('Message');
    console.log(errorMessage);
}

If anyone sees an issue with this solution please let me know


问:
Array Unique for Array of Objects with exclude option for certain keys in Object
I have an Object Array with few fields.

I was able to get the Array unique for this Object Array using below code:

```<code>$aa = array_unique($dd,SORT_REGULAR);
</code>```

But what i am trying to achieve is, i want to exclude certain keys in object from "unique check". Lets say all object values are matching except "valid_from" and "valid_to" date fields.

Below is array structure:

```<code>Array
(
    [9948] => stdClass Object
        (
            [payrate] => 78.00000
            [valid_from] => 03/01/2017
            [valid_to] => 03/31/2017
        )

    [15133] => stdClass Object
        (
            [payrate] => 78.00000
            [valid_from] => 04/01/2017
            [valid_to] => 04/31/2017
        )

)
</code>```

So as per above case as my pay rate is same in both object, but as valid from and valid to are different it will be still considered different entries.

Is there anyway we can specify exclude certain fields out for Array Unique for Array of Objects.

答:
See also array_unique for objects?

In case you work with non-stdClass object you could implement __toString to use array_unique to filter.

To filter on unique stdClass, using only a few of the attributes you could try something like:

From PHP 7 onwards you could use array_column to get a value from a stdClass, so if you use PHP7:

```<code>array_unique(array_column($array,'payrate'));
</code>```

Before PHP 7 you could try:

```<code>array_unique(array_map(function($item) {return $item->payrate;},$array);
</code>```

In case there are more attributes to compare there are different ways. array_reduce is just one of them.

The outcome of this one will not have any duplicates. So if all attributes match, the item will be filtered.

```<code>$attributes = ['payrate','date']
$filtered = array_reduce($array,function($carry,$item) use ($attributes) {
    if(count(array_filter($attributes,function ($attribute) use ($carry, $item) {
            return !in_array($item->$attribute,array_map(function($carriedItem) use ($attribute) {
                return $carriedItem->$attribute;
            },$carry));
        }))) {
        $carry[] = $item;
    }
    return $carry;
},[]);
</code>```

see http://sandbox.onlinephpfunctions.com/code/5f8171d76362ada7e165afeaadbecffc6cdd497a

Body:
I have an Object Array with few fields.

I was able to get the Array unique for this Object Array using below code:

$aa = array_unique($dd,SORT_REGULAR);

But what i am trying to achieve is, i want to exclude certain keys in object from "unique check". Lets say all object values are matching except "valid_from" and "valid_to" date fields.

Below is array structure:

Array
(
    [9948] => stdClass Object
        (
            [payrate] => 78.00000
            [valid_from] => 03/01/2017
            [valid_to] => 03/31/2017
        )

    [15133] => stdClass Object
        (
            [payrate] => 78.00000
            [valid_from] => 04/01/2017
            [valid_to] => 04/31/2017
        )

)

So as per above case as my pay rate is same in both object, but as valid from and valid to are different it will be still considered different entries.

Is there anyway we can specify exclude certain fields out for Array Unique for Array of Objects.

Body:
See also array_unique for objects?

In case you work with non-stdClass object you could implement __toString to use array_unique to filter.

To filter on unique stdClass, using only a few of the attributes you could try something like:

From PHP 7 onwards you could use array_column to get a value from a stdClass, so if you use PHP7:

array_unique(array_column($array,'payrate'));

Before PHP 7 you could try:

array_unique(array_map(function($item) {return $item->payrate;},$array);

In case there are more attributes to compare there are different ways. array_reduce is just one of them.

The outcome of this one will not have any duplicates. So if all attributes match, the item will be filtered.

$attributes = ['payrate','date']
$filtered = array_reduce($array,function($carry,$item) use ($attributes) {
    if(count(array_filter($attributes,function ($attribute) use ($carry, $item) {
            return !in_array($item->$attribute,array_map(function($carriedItem) use ($attribute) {
                return $carriedItem->$attribute;
            },$carry));
        }))) {
        $carry[] = $item;
    }
    return $carry;
},[]);

see http://sandbox.onlinephpfunctions.com/code/5f8171d76362ada7e165afeaadbecffc6cdd497a


问:
Javascript month difference
How do I calculate difference in months in Javascript?

Please note there are similar questions such as:
What's the best way to calculate date difference in Javascript

But these are based around MS difference, when some months have different number of days than others!

Any easy way to calculate month difference between 2 dates?

Just to be clear, I need to know how many months the dates span, for example:

```<code>Jan 29th 2010, and Feb 1st 2010 = 2 months
Jan 1st 2010, and Jan 2nd 2010 = 1 month
Feb 14th 2010, Feb 1st 2011 = 13 months
Feb 1st 2010, March 30th 2011 = 14 months
</code>```

答:
```<code>DisplayTo.getMonth() - DisplayFrom.getMonth() + (12 * (DisplayTo.getFullYear() - DisplayFrom.getFullYear())));
</code>```

getMonth minus getMonth gives you the month difference between the dates two months.

We then multiply 12 by the number of years difference and add this to the result giving us the full month span.

Title: Javascript month difference

Body:
How do I calculate difference in months in Javascript?

Please note there are similar questions such as:
What's the best way to calculate date difference in Javascript

But these are based around MS difference, when some months have different number of days than others!

Any easy way to calculate month difference between 2 dates?

Just to be clear, I need to know how many months the dates span, for example:

Jan 29th 2010, and Feb 1st 2010 = 2 months
Jan 1st 2010, and Jan 2nd 2010 = 1 month
Feb 14th 2010, Feb 1st 2011 = 13 months
Feb 1st 2010, March 30th 2011 = 14 months

Body:
DisplayTo.getMonth() - DisplayFrom.getMonth() + (12 * (DisplayTo.getFullYear() - DisplayFrom.getFullYear())));

getMonth minus getMonth gives you the month difference between the dates two months.

We then multiply 12 by the number of years difference and add this to the result giving us the full month span.


问:
pcolormesh ticks center for each data point/tile
I have some z=f(x,y) data that I would like to display in a heat map. So I am using np.meshgrid to create a (x,y)-grid and then call pcolormesh. However the ticks are not centered for each "tile" that correspond to a data point -- in the docs, I did not find any instructions on how to center the ticks for each tile so that I can immediately read off the corresponding value. Any ideas?

In the image attached for instance, it is not clear to which x-value the tick corresponds.

答:
In a pcolormesh the grid is defined by the edge values. In the following example the value of 6 in the lower left corner is the value between 0 and 1 in each dimension. I think this is perfectly understandable to everyone.

```<code>import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.arange(5)
y = np.arange(3)
X,Y = np.meshgrid(x,y)
Z = np.random.randint(1,9, size=(2,4))

plt.pcolormesh(X,Y,Z)

plt.show()
</code>```

Now if you want to (only) have the ticks in the middle of the cell, you can set them as follows

```<code>plt.xticks(x[:-1]+0.5)
plt.yticks(y[:-1]+0.5)
</code>```

If the lower left pixel actually does not correspond to the data between 0 and 1, but to the data at 0, the grid is 'wrong'; a solution would be to fix it by translating it by half the pixel width.

```<code>plt.pcolormesh(X-0.5,Y-0.5,Z)
</code>```

As above, the ticks could be adapted to show only certain numbers, using plt.xticks.

Body:
In a pcolormesh the grid is defined by the edge values. In the following example the value of 6 in the lower left corner is the value between 0 and 1 in each dimension. I think this is perfectly understandable to everyone.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.arange(5)
y = np.arange(3)
X,Y = np.meshgrid(x,y)
Z = np.random.randint(1,9, size=(2,4))

plt.pcolormesh(X,Y,Z)

plt.show()

Now if you want to (only) have the ticks in the middle of the cell, you can set them as follows

plt.xticks(x[:-1]+0.5)
plt.yticks(y[:-1]+0.5)

If the lower left pixel actually does not correspond to the data between 0 and 1, but to the data at 0, the grid is 'wrong'; a solution would be to fix it by translating it by half the pixel width.

plt.pcolormesh(X-0.5,Y-0.5,Z)

As above, the ticks could be adapted to show only certain numbers, using plt.xticks.


问:
Create one Nuget Package for both ASP.NET 4 & ASP.NET Core 1.0
We have a library which works in ASP.NET 4 and uses HttpContext.Current. We are aware that we can't use HttpContext.Current in ASP.NET Core but should use IHttpContextAccessor.

How can we change this library so we both support ASP.NET 4 (by using HttpContext.Current) and ASP.NET Core (IHttpContextAccessor) and packaged as one NuGet package?

答:
The answer is that it isn't possible. The same that you can't create a one NuGet package to target both MVC1 and MVC2 (both not as Nuget package available)

Of course you could use assembly bindings, but only when there aren't breaking changes.

Microsoft is naming there ASP.NET Core packages with "AspNetCore", e.g. Microsoft.AspNetCore.Mvc vs Microsoft.AspNet.Mvc


问:
The Outlook data file (.pst) failed to load for this session
i am using Microsoft.Office.Interop.Outlook Version 12.0.0.0  to read my outlook pst file but when compiler reaches this code  outlookNs.AddStore(pstFilePath);  it gives exception that
         "The Outlook data file (.pst) failed to load for this session."  i have tried outlookNs.AddStoreEx(pstFilePath); also but the error was same ....any sugession ??

```<code>using System;
using System.Collections.Generic;
using Microsoft.Office.Interop.Outlook;

namespace PSTReader {
    class Program {
        static void Main () {
            try {
                IEnumerable<MailItem> mailItems = readPst(@"C:\temp\PST\Test.pst", "Test PST");
                foreach (MailItem mailItem in mailItems) {
                    Console.WriteLine(mailItem.SenderName + " - " + mailItem.Subject);
                }
            } catch (System.Exception ex) {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

        private static IEnumerable<MailItem> readPst(string pstFilePath, string pstName) {
            List<MailItem> mailItems = new List<MailItem>();
            Application app = new Application();
            NameSpace outlookNs = app.GetNamespace("MAPI");
            // Add PST file (Outlook Data File) to Default Profile
            outlookNs.AddStore(pstFilePath);
            MAPIFolder rootFolder = outlookNs.Stores[pstName].GetRootFolder();
            // Traverse through all folders in the PST file
            // TODO: This is not recursive, refactor
            Folders subFolders = rootFolder.Folders;
            foreach (Folder folder in subFolders) {
                Items items = folder.Items;
                foreach (object item in items) {
                    if (item is MailItem) {
                        MailItem mailItem = item as MailItem;
                        mailItems.Add(mailItem);
                    }
                }
            }
            // Remove PST file from Default Profile
            outlookNs.RemoveStore(rootFolder);
            return mailItems;
        }
    }
}
</code>```

答:
In my case, neither credentials were the issue nor that the PST file was opened in another process.  I could not figure out what caused this but ...

... solution for me was to open Outlook->New Items->More Items->Outlook Data File...

In the popup, select Outlook data file (.pst) and hit OK

This will open Windows Expolorer, navigate to the location where your PST used to be created, name your PST file the way you used to name it and save it to that location.  Make sure you save as type Outlook Data File (*.pst).

Restart Outlook

This should restart outlook and your PST should be loaded now.  After this, I was also able to delete all from the location where my PST was located (including PST) and restarting outlook would not create it without any issues.

Body:
i am using Microsoft.Office.Interop.Outlook Version 12.0.0.0  to read my outlook pst file but when compiler reaches this code  outlookNs.AddStore(pstFilePath);  it gives exception that
         "The Outlook data file (.pst) failed to load for this session."  i have tried outlookNs.AddStoreEx(pstFilePath); also but the error was same ....any sugession ??

using System;
using System.Collections.Generic;
using Microsoft.Office.Interop.Outlook;

namespace PSTReader {
    class Program {
        static void Main () {
            try {
                IEnumerable<MailItem> mailItems = readPst(@"C:\temp\PST\Test.pst", "Test PST");
                foreach (MailItem mailItem in mailItems) {
                    Console.WriteLine(mailItem.SenderName + " - " + mailItem.Subject);
                }
            } catch (System.Exception ex) {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

        private static IEnumerable<MailItem> readPst(string pstFilePath, string pstName) {
            List<MailItem> mailItems = new List<MailItem>();
            Application app = new Application();
            NameSpace outlookNs = app.GetNamespace("MAPI");
            // Add PST file (Outlook Data File) to Default Profile
            outlookNs.AddStore(pstFilePath);
            MAPIFolder rootFolder = outlookNs.Stores[pstName].GetRootFolder();
            // Traverse through all folders in the PST file
            // TODO: This is not recursive, refactor
            Folders subFolders = rootFolder.Folders;
            foreach (Folder folder in subFolders) {
                Items items = folder.Items;
                foreach (object item in items) {
                    if (item is MailItem) {
                        MailItem mailItem = item as MailItem;
                        mailItems.Add(mailItem);
                    }
                }
            }
            // Remove PST file from Default Profile
            outlookNs.RemoveStore(rootFolder);
            return mailItems;
        }
    }
}


问:
couchdb show underlying document conflicts in views
I'd like to use a view to compute a summary of bigger documents.
Every document produced by the view corresponds to one source document.
The view output is used to populate table in the UI, clicking a row of the table opens the bigger document.
When there's a conflict in the underlying document I'd like to show it in the table row, so user can open the full document and resolve the conflict.
How can I efficiently obtain the conflicts to show in the table? (all the conflicts for the underlying docs)

Thanks

答:
You can use the conflicts option in the view parameters, together with include_docs. You can find more info about view params in the CouchDB docs.

E.g. http://localhost:5984/mydatabase/_design/documents/_view/posts?conflicts=true&include_docs=true adds the property _conflicts to each document that has a conflict.

Pro tip: In that case you don't need to emit the whole document in the view itself, as the include_docs parameter returns the complete document anyway.

Another possibility is to emit the _conflicts property itself. You can do that like this:

```<code>function (doc) {
  if (doc._conflicts) emit(doc._id, doc._conflicts);
}
</code>```

This is a handy view for finding only documents with conflicts.

Body:
You can use the conflicts option in the view parameters, together with include_docs. You can find more info about view params in the CouchDB docs.

E.g. http://localhost:5984/mydatabase/_design/documents/_view/posts?conflicts=true&include_docs=true adds the property _conflicts to each document that has a conflict.

Pro tip: In that case you don't need to emit the whole document in the view itself, as the include_docs parameter returns the complete document anyway.

Another possibility is to emit the _conflicts property itself. You can do that like this:

function (doc) {
  if (doc._conflicts) emit(doc._id, doc._conflicts);
}

This is a handy view for finding only documents with conflicts.


问:
Set Cassandra 3.10 cluster
I am new to Cassandra, I am setting up a cluster on Cassandra 3.10 (2 nodes) but from log looks like the seed cannot talk to each other. I am able to ping server from other host.
Getting following error in the log
DEBUG [MessagingService-Outgoing-/ip_adress-Gossip] 2017-03-30 14:23:19,880 OutboundTcpConnection.java:495 - Unable to connect to /ip_address
java.net.NoRouteToHostException: No route to host

I do not know, why there is / before the ip_address
I have substituted the real ip_address with word ip_address

答: [No route to host] apparently, it looks like nodes cannot communicate with each other. make sure you can ssh/ping from both servers to each other. Certainly, you'll need to address network issues first before taking next steps.</p>

Title: Set Cassandra 3.10 cluster


问:
Build error resource directory not found
I'v created a new android project in vs 2013 and installed Android.Support.Library.v7.AppCompat package and dependencies. But when I build the project, I got an error that says

resource directory
  '[ProjectPath]\obj\Debug\resourcecache\B81A750477D10031D1844681B0F7EB17\res'
  does not exist    file: [ProjectPath]\AAPT

I'v cleaned the project

reopen it

rebuild it

but not help me.

答:
I have encountered the same issue as you and have found a solution. I know this has been a long time since your post. Just put the solution here to help someone encounter similar issues.
My project can be built successfully previously, so this error must be caused by some kind of settings. A reasonable explanation and solution can be found in this link: http://smstuebe.de/2016/10/29/fix-android-app-compat/

This is caused by the incomplete Android SDK packages. The normal clean/rebuild won't help. Even if I reinstalled VS2015+Xamarin, I still have this issue.
So try the above solution if you came across similar issues.