问:
What output and recording ports does the Java Sound API find on your computer?
I'm working with the Java Sound API, and it turns out if I want to adjust recording volumes I need to model the hardware that the OS exposes to Java. Turns out there's a lot of variety in what's presented.

Because of this I'm humbly asking that anyone able to help me run the following on their computer and post back the results so that I can get an idea of what's out there.

A thanks in advance to anyone that can assist :-)

```<code>import javax.sound.sampled.*;
public class SoundAudit {
  public static void main(String[] args) { try {
    System.out.println("OS: "+System.getProperty("os.name")+" "+
      System.getProperty("os.version")+"/"+
      System.getProperty("os.arch")+"\nJava: "+
      System.getProperty("java.version")+" ("+
      System.getProperty("java.vendor")+")\n");
      for (Mixer.Info thisMixerInfo : AudioSystem.getMixerInfo()) {
        System.out.println("Mixer: "+thisMixerInfo.getDescription()+
          " ["+thisMixerInfo.getName()+"]");
        Mixer thisMixer = AudioSystem.getMixer(thisMixerInfo);
        for (Line.Info thisLineInfo:thisMixer.getSourceLineInfo()) {
            if (thisLineInfo.getLineClass().getName().equals(
              "javax.sound.sampled.Port")) {
              Line thisLine = thisMixer.getLine(thisLineInfo);
              thisLine.open();
              System.out.println("  Source Port: "
                +thisLineInfo.toString());
              for (Control thisControl : thisLine.getControls()) {
                System.out.println(AnalyzeControl(thisControl));}
              thisLine.close();}}
        for (Line.Info thisLineInfo:thisMixer.getTargetLineInfo()) {
          if (thisLineInfo.getLineClass().getName().equals(
            "javax.sound.sampled.Port")) {
            Line thisLine = thisMixer.getLine(thisLineInfo);
            thisLine.open();
            System.out.println("  Target Port: "
              +thisLineInfo.toString());
            for (Control thisControl : thisLine.getControls()) {
              System.out.println(AnalyzeControl(thisControl));}
            thisLine.close();}}}
  } catch (Exception e) {e.printStackTrace();}}
  public static String AnalyzeControl(Control thisControl) {
    String type = thisControl.getType().toString();
    if (thisControl instanceof BooleanControl) {
      return "    Control: "+type+" (boolean)"; }
    if (thisControl instanceof CompoundControl) {
      System.out.println("    Control: "+type+
        " (compound - values below)");
      String toReturn = "";
      for (Control children:
        ((CompoundControl)thisControl).getMemberControls()) {
        toReturn+="  "+AnalyzeControl(children)+"\n";}
      return toReturn.substring(0, toReturn.length()-1);}
    if (thisControl instanceof EnumControl) {
      return "    Control:"+type+" (enum: "+thisControl.toString()+")";}
    if (thisControl instanceof FloatControl) {
      return "    Control: "+type+" (float: from "+
        ((FloatControl) thisControl).getMinimum()+" to "+
        ((FloatControl) thisControl).getMaximum()+")";}
    return "    Control: unknown type";}
}
</code>```

All the application does is print out a line about the OS, a line about the JVM, and a few lines about the hardware found that may pertain to recording hardware. For example on my PC at work I get the following:

OS: Windows XP 5.1/x86
Java: 1.6.0_07 (Sun Microsystems Inc.)

```
Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SoundMAX HD Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SoundMAX HD Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SoundMAX HD Audio]
  Source Port: MICROPHONE source port
    Control: Microphone (compound - values below)
      Control: Select (boolean)
      Control: Microphone Boost (boolean)
      Control: Front panel microphone (boolean)
      Control: Volume (float: from 0.0 to 1.0)
  Source Port: LINE_IN source port
    Control: Line In (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
```

答:
```<code>OS: Windows XP 5.1/x86
Java: 1.6.0_06 (Sun Microsystems Inc.)

Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SoundMAX HD Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SoundMAX HD Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SoundMAX HD Audio]
  Source Port: Stereo Mix source port
    Control: Stereo Mix (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
  Source Port: MICROPHONE source port
    Control: Microphone (compound - values below)
      Control: Select (boolean)
      Control: Microphone Boost (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
  Source Port: COMPACT_DISC source port
    Control: CD Player (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
  Target Port: SPEAKER target port
    Control: Volume (float: from 0.0 to 1.0)
    Control: Balance (float: from -1.0 to 1.0)
    Control: Mute (boolean)
    Control: Disable Digital Output (boolean)
    Control: Wave (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
    Control: SW Synth (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
    Control: Microphone (compound - values below)
      Control: Microphone Boost (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
    Control: CD Player (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
</code>```

OwnerDisplayName: Dave Carpeneto

Body:
I'm working with the Java Sound API, and it turns out if I want to adjust recording volumes I need to model the hardware that the OS exposes to Java. Turns out there's a lot of variety in what's presented.

Because of this I'm humbly asking that anyone able to help me run the following on their computer and post back the results so that I can get an idea of what's out there.

A thanks in advance to anyone that can assist :-)

import javax.sound.sampled.*;
public class SoundAudit {
  public static void main(String[] args) { try {
    System.out.println("OS: "+System.getProperty("os.name")+" "+
      System.getProperty("os.version")+"/"+
      System.getProperty("os.arch")+"\nJava: "+
      System.getProperty("java.version")+" ("+
      System.getProperty("java.vendor")+")\n");
      for (Mixer.Info thisMixerInfo : AudioSystem.getMixerInfo()) {
        System.out.println("Mixer: "+thisMixerInfo.getDescription()+
          " ["+thisMixerInfo.getName()+"]");
        Mixer thisMixer = AudioSystem.getMixer(thisMixerInfo);
        for (Line.Info thisLineInfo:thisMixer.getSourceLineInfo()) {
            if (thisLineInfo.getLineClass().getName().equals(
              "javax.sound.sampled.Port")) {
              Line thisLine = thisMixer.getLine(thisLineInfo);
              thisLine.open();
              System.out.println("  Source Port: "
                +thisLineInfo.toString());
              for (Control thisControl : thisLine.getControls()) {
                System.out.println(AnalyzeControl(thisControl));}
              thisLine.close();}}
        for (Line.Info thisLineInfo:thisMixer.getTargetLineInfo()) {
          if (thisLineInfo.getLineClass().getName().equals(
            "javax.sound.sampled.Port")) {
            Line thisLine = thisMixer.getLine(thisLineInfo);
            thisLine.open();
            System.out.println("  Target Port: "
              +thisLineInfo.toString());
            for (Control thisControl : thisLine.getControls()) {
              System.out.println(AnalyzeControl(thisControl));}
            thisLine.close();}}}
  } catch (Exception e) {e.printStackTrace();}}
  public static String AnalyzeControl(Control thisControl) {
    String type = thisControl.getType().toString();
    if (thisControl instanceof BooleanControl) {
      return "    Control: "+type+" (boolean)"; }
    if (thisControl instanceof CompoundControl) {
      System.out.println("    Control: "+type+
        " (compound - values below)");
      String toReturn = "";
      for (Control children:
        ((CompoundControl)thisControl).getMemberControls()) {
        toReturn+="  "+AnalyzeControl(children)+"\n";}
      return toReturn.substring(0, toReturn.length()-1);}
    if (thisControl instanceof EnumControl) {
      return "    Control:"+type+" (enum: "+thisControl.toString()+")";}
    if (thisControl instanceof FloatControl) {
      return "    Control: "+type+" (float: from "+
        ((FloatControl) thisControl).getMinimum()+" to "+
        ((FloatControl) thisControl).getMaximum()+")";}
    return "    Control: unknown type";}
}

All the application does is print out a line about the OS, a line about the JVM, and a few lines about the hardware found that may pertain to recording hardware. For example on my PC at work I get the following:

OS: Windows XP 5.1/x86
Java: 1.6.0_07 (Sun Microsystems Inc.)

Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SoundMAX HD Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SoundMAX HD Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SoundMAX HD Audio]
  Source Port: MICROPHONE source port
    Control: Microphone (compound - values below)
      Control: Select (boolean)
      Control: Microphone Boost (boolean)
      Control: Front panel microphone (boolean)
      Control: Volume (float: from 0.0 to 1.0)
  Source Port: LINE_IN source port
    Control: Line In (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)

LastEditorDisplayName: sqook


来源: stackexchange

问:
Singletons in multi threaded environment
when using singletons, if the class has instance fields should you be careful when several threads might be using the singleton? (And the fields are mutable and their values can be changed)

I havn't tried but in theory it seems like the answer is yes and you would need synchronization (or skip the singleton)

答:
When using a singleton, the instance is shared by all the threads in the application, so yes, extra care should be taken to ensure that no concurrency problem arise.

However, this proble, is not specific to singletons, and should be considered whenever an object instance is shared between multiple threads.

ContentLicense: CC BY-SA 3.0


问:
How do I add, save and load items to a listview in WPF
About two weeks ago I started to develop in WPF and, since I only developed in WinForms, I ran into common problems but managed to find the solution for them. However, currently I'm stuck at something: adding items with multiple columns (via visual basic code, not xaml) into a listview.

I'm not sure if it's best to use a Listview or a DataGrid control for this but basically I want the user to be able to add favourite songs to a list, save them to a file and load the file whenever the app is opened. The listview currently has three columns: Artist, Song and Status.

When I was programming in WinForms, I used to do this:

```<code>        Dim Song As New ListViewItem
        Form1.ListView1.Items.Add(Song)
        Song.Text = TextBox1.Text
        Song.SubItems.Add(TextBox2.Text)
        Song.SubItems.Add(TextBox3.Text)
</code>```

Then, to save:

   Dim Song As New ListViewItem
            Form1.ListView1.Items.Add(Song)
            Song.Text = TextBox1.Text
            Song.SubItems.Add(TextBox2.Text)
            Song.SubItems.Add(TextBox3.Text)
            Try
                Dim myWriter As New IO.StreamWriter(PATH_DATABASE)
                For Each myItem As ListViewItem In Form1.ListView1.Items
                    myWriter.WriteLine(myItem.Text & "|" & myItem.SubItems(1).Text & "|" & myItem.SubItems(2).Text & "|" & myItem.SubItems(3).Text
                Next
                myWriter.Close()
            Catch ex As Exception
                MsgBox("Error: " & ex.Message, vbCritical, "Error")
            End Try
```

<p>I've been searching and I've found that I need to use binding so I've tried this:</p>

<pre class="lang-vb prettyprint-override"><code>Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Windows

Public Structure Song

    Public _artist As String
    Public _title As String
    Public _status As String

    Property Artist() As String
        Get
            Return _artist
        End Get
        Set(ByVal Value As String)
            _artist = Value
        End Set
    End Property
    Property Title() As String
        Get
            Return _title
        End Get
        Set(ByVal Value As String)
            _title = Value
        End Set
    End Property
    Property Status() As String
        Get
            Return _status
        End Get
        Set(ByVal Value As String)
            _status = Value
        End Set
    End Property
End Structure

Public Class WINDOW_AddSong

    Dim songs As New ObservableCollection(Of Song)

    Private Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click
        Dim Song As New ListViewItem

        For Each wnd As Window In Application.Current.Windows
            If wnd.GetType Is GetType(MainWindow) Then

                DirectCast(wnd, MainWindow).Listview1.Items.Add(Alimento)
                Alimento.Content = New Song() With {._artist = "Lol", ._title = "Lol2", ._status = "Lol3"}

            End If
        Next
    End Sub
End Class

</code>```

And in the XAML listview:

<GridViewColumn Header="Artist" DisplayMemberBinding="{Binding Artist}"/>
<GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}"/>
<GridViewColumn Header="Status" DisplayMemberBinding="{Binding Status}"/>
```

<p>This works however I'm not sure if this is the WPF-way of doing things.</p>

<p>However, I'm stuck at the saving process:</p>

<pre class="lang-vb prettyprint-override"><code> Try
            Dim myWriter As New IO.StreamWriter(PATH_DATABASE)
            For Each wnd As Window In Application.Current.Windows
                If wnd.GetType Is GetType(MainWindow) Then
                    For Each myItem As ListViewItem In DirectCast(wnd, MainWindow).Listview1.Items
                        myWriter.WriteLine(Song, Artist, Status)
                    Next
                End If
            Next
            myWriter.Close()
        Catch ex As Exception
            MsgBox("Error: " & ex.Message, vbCritical, "Error")
        End Try
</code>```

This doesn't work.
Also, PATH_DATABASE is just a directory.

To summarise, could an expert review my code and check if I'm doing things "right" and, if possible, could you help me with the saving and loading process?

Thanks.

答:
I just updated your structure (I used a class, just force of habit) to use automatic property values which are available in recent versions of VS. The default implementation of properties is built in along with the backer fields. It is used just as before.

You are on the right track with ObservableCollection but you you need to implement INotifyPropertyChanged by adding the Event PropertyChanged and providing the Sub OnPropertyChanged to raise the event.

Set up the bindings on the controls and set the ItemsSource ot the ListView to your ObservableList.

To save Import System.Text so you can use a StringBuilder. The loop through the list to build the string to save to a text file.

I didn't spend any time trying to make the XAML Windows look nice. Pardon the ugliness.

```<code>Class MainWindow
    Public Songs As New ObservableCollection(Of Song)

    Protected Sub OnLoad(sender As Object, e As RoutedEventArgs)
        Songs.Add(New Song("Nirvana", "Smells Like Teen Spirit", "Open"))
        Songs.Add(New Song("John Lennon", "Imagine", "In Stock"))
        Songs.Add(New Song("U2", "One", "Unknown"))
        Songs.Add(New Song("Michael Jackson", "Billie Jean", "Open"))
        lvSongs.ItemsSource = Songs
    End Sub

    Private Sub BtnAdd_Click(sender As Object, e As RoutedEventArgs)
        Dim frm As New frmAdd
        frm.mainForm = Me 'send the instance of the current form to the new form
        frm.ShowDialog()
    End Sub

    Private Sub SaveList()
        Dim sb As New StringBuilder
        For Each item As Song In Songs
            sb.AppendLine($"{item.Artist}|{item.Title}|{item.Status}")
        Next
        'call sb.ToString and write it to a .txt file
    End Sub
End Class
</code>```

MainWindow XAML

```<code><Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_BindComboBox"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid Loaded="OnLoad"
          Name="root">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>

        </Grid.RowDefinitions>
        <ListView Margin="10" Name="lvSongs" Grid.Row="0">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <WrapPanel>
                        <TextBlock Text="Name: " />
                        <TextBox x:Name="txtArtist"
                                 Text="{Binding Artist, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                 FontWeight="Bold"/>
                        <TextBlock Text=", " />
                        <TextBlock Text="Age: " />
                        <TextBox Text="{Binding Title}"
                                 FontWeight="Bold" />
                        <TextBlock Text=" (" />
                        <TextBox Text="{Binding Status}"  />
                        <TextBlock Text=")" />
                    </WrapPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button x:Name="btnAdd" Grid.Row="1" Height="25" Width="100" Content="Add a Song" Click="BtnAdd_Click"/>
    </Grid>
</Window>
</code>```

The Song class

```<code>Public Class Song
    Implements INotifyPropertyChanged

    Public Property Artist() As String
    Public Property Title() As String
    Public Property Status() As String

    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Protected Sub OnPropertyChanged(ByVal name As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
    End Sub

    Public Sub New(art As String, Ttl As String, Stat As String)
        Artist = art
        Title = Ttl
        Status = Stat
    End Sub
End Class
</code>```

The Add Window

```<code>Public Class frmAdd

    Public mainForm As MainWindow

    Private Sub BtnAdd_Click(sender As Object, e As RoutedEventArgs)
        mainForm.Songs.Add(New Song(txtArtist.Text, txtTitle.Text, txtStatus.Text))
        ClearForm()
    End Sub

    Private Sub ClearForm()
        txtArtist.Clear()
        txtTitle.Clear()
        txtStatus.Clear()
    End Sub

End Class
</code>```

Add Window XAML

```<code><Window x:Class="frmAdd"
        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:WPF_BindComboBox"
        mc:Ignorable="d"
        Title="frmAdd" Height="172.641" Width="307.547">
    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0" Text="Artist" FontSize="16" FontWeight="Bold"/>
        <TextBox x:Name="txtArtist" Grid.Column="1" Grid.Row="0" FontSize="16" Width="150" />
        <TextBlock Grid.Column="0" Grid.Row="1" Text="Title" FontSize="16" FontWeight="Bold"/>
        <TextBox x:Name="txtTitle" Grid.Column="1" Grid.Row="1" FontSize="16" Width="150"/>
        <TextBlock Grid.Column="0" Grid.Row="2" Text="Status" FontSize="16" FontWeight="Bold"/>
        <TextBox x:Name="txtStatus" Grid.Column="1" Grid.Row="2" FontSize="16" Width="150"/>
        <Button x:Name="btnAdd" Grid.Column="1" Grid.Row="4" Content="Add Song" Click="BtnAdd_Click"/>
    </Grid>
</Window>
</code>```

EDIT
Required Imports

```<code>Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.Text
</code>```

ContentLicense: CC BY-SA 4.0

Body:
About two weeks ago I started to develop in WPF and, since I only developed in WinForms, I ran into common problems but managed to find the solution for them. However, currently I'm stuck at something: adding items with multiple columns (via visual basic code, not xaml) into a listview.

I'm not sure if it's best to use a Listview or a DataGrid control for this but basically I want the user to be able to add favourite songs to a list, save them to a file and load the file whenever the app is opened. The listview currently has three columns: Artist, Song and Status.

When I was programming in WinForms, I used to do this:

        Dim Song As New ListViewItem
        Form1.ListView1.Items.Add(Song)
        Song.Text = TextBox1.Text
        Song.SubItems.Add(TextBox2.Text)
        Song.SubItems.Add(TextBox3.Text)

Then, to save:

   Dim Song As New ListViewItem
            Form1.ListView1.Items.Add(Song)
            Song.Text = TextBox1.Text
            Song.SubItems.Add(TextBox2.Text)
            Song.SubItems.Add(TextBox3.Text)
            Try
                Dim myWriter As New IO.StreamWriter(PATH_DATABASE)
                For Each myItem As ListViewItem In Form1.ListView1.Items
                    myWriter.WriteLine(myItem.Text & "|" & myItem.SubItems(1).Text & "|" & myItem.SubItems(2).Text & "|" & myItem.SubItems(3).Text
                Next
                myWriter.Close()
            Catch ex As Exception
                MsgBox("Error: " & ex.Message, vbCritical, "Error")
            End Try

I've been searching and I've found that I need to use binding so I've tried this:

Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Windows

Public Structure Song

    Public _artist As String
    Public _title As String
    Public _status As String

    Property Artist() As String
        Get
            Return _artist
        End Get
        Set(ByVal Value As String)
            _artist = Value
        End Set
    End Property
    Property Title() As String
        Get
            Return _title
        End Get
        Set(ByVal Value As String)
            _title = Value
        End Set
    End Property
    Property Status() As String
        Get
            Return _status
        End Get
        Set(ByVal Value As String)
            _status = Value
        End Set
    End Property
End Structure

Public Class WINDOW_AddSong

    Dim songs As New ObservableCollection(Of Song)

    Private Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click
        Dim Song As New ListViewItem

        For Each wnd As Window In Application.Current.Windows
            If wnd.GetType Is GetType(MainWindow) Then

                DirectCast(wnd, MainWindow).Listview1.Items.Add(Alimento)
                Alimento.Content = New Song() With {._artist = "Lol", ._title = "Lol2", ._status = "Lol3"}

            End If
        Next
    End Sub
End Class

And in the XAML listview:

<GridViewColumn Header="Artist" DisplayMemberBinding="{Binding Artist}"/>
<GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}"/>
<GridViewColumn Header="Status" DisplayMemberBinding="{Binding Status}"/>

This works however I'm not sure if this is the WPF-way of doing things.

However, I'm stuck at the saving process:

 Try
            Dim myWriter As New IO.StreamWriter(PATH_DATABASE)
            For Each wnd As Window In Application.Current.Windows
                If wnd.GetType Is GetType(MainWindow) Then
                    For Each myItem As ListViewItem In DirectCast(wnd, MainWindow).Listview1.Items
                        myWriter.WriteLine(Song, Artist, Status)
                    Next
                End If
            Next
            myWriter.Close()
        Catch ex As Exception
            MsgBox("Error: " & ex.Message, vbCritical, "Error")
        End Try

This doesn't work.
Also, PATH_DATABASE is just a directory.

To summarise, could an expert review my code and check if I'm doing things "right" and, if possible, could you help me with the saving and loading process?

Thanks.

Body:
I just updated your structure (I used a class, just force of habit) to use automatic property values which are available in recent versions of VS. The default implementation of properties is built in along with the backer fields. It is used just as before.

You are on the right track with ObservableCollection but you you need to implement INotifyPropertyChanged by adding the Event PropertyChanged and providing the Sub OnPropertyChanged to raise the event.

Set up the bindings on the controls and set the ItemsSource ot the ListView to your ObservableList.

To save Import System.Text so you can use a StringBuilder. The loop through the list to build the string to save to a text file.

I didn't spend any time trying to make the XAML Windows look nice. Pardon the ugliness.

Class MainWindow
    Public Songs As New ObservableCollection(Of Song)

    Protected Sub OnLoad(sender As Object, e As RoutedEventArgs)
        Songs.Add(New Song("Nirvana", "Smells Like Teen Spirit", "Open"))
        Songs.Add(New Song("John Lennon", "Imagine", "In Stock"))
        Songs.Add(New Song("U2", "One", "Unknown"))
        Songs.Add(New Song("Michael Jackson", "Billie Jean", "Open"))
        lvSongs.ItemsSource = Songs
    End Sub

    Private Sub BtnAdd_Click(sender As Object, e As RoutedEventArgs)
        Dim frm As New frmAdd
        frm.mainForm = Me 'send the instance of the current form to the new form
        frm.ShowDialog()
    End Sub

    Private Sub SaveList()
        Dim sb As New StringBuilder
        For Each item As Song In Songs
            sb.AppendLine($"{item.Artist}|{item.Title}|{item.Status}")
        Next
        'call sb.ToString and write it to a .txt file
    End Sub
End Class

MainWindow XAML

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_BindComboBox"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid Loaded="OnLoad"
          Name="root">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>

        </Grid.RowDefinitions>
        <ListView Margin="10" Name="lvSongs" Grid.Row="0">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <WrapPanel>
                        <TextBlock Text="Name: " />
                        <TextBox x:Name="txtArtist"
                                 Text="{Binding Artist, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                 FontWeight="Bold"/>
                        <TextBlock Text=", " />
                        <TextBlock Text="Age: " />
                        <TextBox Text="{Binding Title}"
                                 FontWeight="Bold" />
                        <TextBlock Text=" (" />
                        <TextBox Text="{Binding Status}"  />
                        <TextBlock Text=")" />
                    </WrapPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button x:Name="btnAdd" Grid.Row="1" Height="25" Width="100" Content="Add a Song" Click="BtnAdd_Click"/>
    </Grid>
</Window>

The Song class

Public Class Song
    Implements INotifyPropertyChanged

    Public Property Artist() As String
    Public Property Title() As String
    Public Property Status() As String

    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Protected Sub OnPropertyChanged(ByVal name As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
    End Sub

    Public Sub New(art As String, Ttl As String, Stat As String)
        Artist = art
        Title = Ttl
        Status = Stat
    End Sub
End Class

The Add Window

Public Class frmAdd

    Public mainForm As MainWindow

    Private Sub BtnAdd_Click(sender As Object, e As RoutedEventArgs)
        mainForm.Songs.Add(New Song(txtArtist.Text, txtTitle.Text, txtStatus.Text))
        ClearForm()
    End Sub

    Private Sub ClearForm()
        txtArtist.Clear()
        txtTitle.Clear()
        txtStatus.Clear()
    End Sub

End Class

Add Window XAML

<Window x:Class="frmAdd"
        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:WPF_BindComboBox"
        mc:Ignorable="d"
        Title="frmAdd" Height="172.641" Width="307.547">
    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0" Text="Artist" FontSize="16" FontWeight="Bold"/>
        <TextBox x:Name="txtArtist" Grid.Column="1" Grid.Row="0" FontSize="16" Width="150" />
        <TextBlock Grid.Column="0" Grid.Row="1" Text="Title" FontSize="16" FontWeight="Bold"/>
        <TextBox x:Name="txtTitle" Grid.Column="1" Grid.Row="1" FontSize="16" Width="150"/>
        <TextBlock Grid.Column="0" Grid.Row="2" Text="Status" FontSize="16" FontWeight="Bold"/>
        <TextBox x:Name="txtStatus" Grid.Column="1" Grid.Row="2" FontSize="16" Width="150"/>
        <Button x:Name="btnAdd" Grid.Column="1" Grid.Row="4" Content="Add Song" Click="BtnAdd_Click"/>
    </Grid>
</Window>

EDIT
Required Imports

Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.Text


问:
How do I program tests in R so that they print nicely?
Statistical tests in R generate lists, but then when you call the test, the printing of these lists gives a special user-friendly structure to assist the reader.  To see what I'm talking about, consider an example where you use the t.test function in the stats package.

```<code>#Run a T-test on some example data
X <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
Y <- c(19, 20, 44, 45, 8, 29, 26, 59, 35, 50);
TEST <- stats::t.test(X,Y);

#Show structure of the TEST object
str(TEST);
List of 9
 $ statistic  : Named num -0.134
  ..- attr(*, "names")= chr "t"
 $ parameter  : Named num 10.2
  ..- attr(*, "names")= chr "df"
 $ p.value    : num 0.896
 $ conf.int   : num [1:2] -12.3 10.9
  ..- attr(*, "conf.level")= num 0.95
 $ estimate   : Named num [1:2] 32.8 33.5
  ..- attr(*, "names")= chr [1:2] "mean of x" "mean of y"
 $ null.value : Named num 0
  ..- attr(*, "names")= chr "difference in means"
 $ alternative: chr "two.sided"
 $ method     : chr "Welch Two Sample t-test"
 $ data.name  : chr "X and Y"
 - attr(*, "class")= chr "htest"
</code>```

This object is a list with nine elements, some of which are named via attributes.  However, when I print the TEST object, the returned information is structured in a different way than the standard printing of a list.

```<code>#Print the TEST object
TEST;

        Welch Two Sample t-test

data:  X and Y
t = -0.13444, df = 10.204, p-value = 0.8957
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -12.27046  10.87046
sample estimates:
mean of x mean of y
     32.8      33.5
</code>```

As you can see, this printed output is much more user-friendly than the standard printing for a list.  I would like to be able to program statistical tests in R which generate a list of outputs similar to the above, but which print in this user-friendly way.

My Questions: Why does R print the output of the list TEST in this special way?  If I create a list of outputs of a statistical test (e.g., like the above), how can I set the object to print in this way?

答:
This answer is put together from helpful comments and answers by other users, but I wanted to give an elaborated answer here to make things more explicit, for the benefit of users who are not already familiar with some of these issues.  The object created by the t.test function is an object of class htest, and this type of object has a special method of printing under the print.htest setting in the global environment.  That printing method draws out information from the list, but prints it in the user-friendly way you see in the output in the question.

If you want to replicate this type of printing for a new statistical test that you are programming yourself, then you will need to structure your new test so that it outputs a htest object, with the required elements of the list, and the required class.  Here is an example from another answer where a hypothesis test set out in Tarone (1979) is programmed as a htest object:

```<code>Tarone.test <- function(N, M) {

    #Check validity of inputs
    if(any(M > N)) { stop("Error: Observed count value exceeds binomial trials"); }

    #Set hypothesis test objects
    method      <- "Tarone's Z test";
    alternative <- "greater";
    null.value  <- 0;
    attr(null.value, "names") <- "dispersion parameter";
    data.name   <- paste0(deparse(substitute(M)), " successes from ",
                          deparse(substitute(N)), " counts");

    #Calculate test statistics
    estimate    <- sum(M)/sum(N);
    attr(estimate, "names") <- "proportion parameter";

    S           <- sum((M - N*estimate)^2/(estimate*(1 - estimate)));
    statistic   <- (S - sum(N))/sqrt(2*sum(N*(N-1)));
    attr(statistic, "names") <- "z";

    p.value     <- 2*pnorm(-abs(statistic), 0, 1);
    attr(p.value, "names") <- NULL;

    #Create htest object
    TEST        <- list(statistic = statistic, p.value = p.value, estimate = estimate,
                        null.value = null.value, alternative = alternative,
                        method = method, data.name = data.name);
    class(TEST) <- "htest";

    TEST; }
</code>```

In this example, the function calculates all the required elements of the htest object and then creates this object as a list with that class.  It is important to include the command class(TEST) <- "htest" in the code, so that the object created is not just a regular list.  Inclusion of that command will ensure that the output object is of the proper class, and so it will print in a user-friendly way.  To see this, we can generate some data and apply the test:

```<code>#Generate example data
N <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
M <- c( 9, 10, 22, 15,  8, 19, 16, 19, 15, 10);

#Apply Tarone's test to the example data
TEST <- Tarone.test(N, M);
TEST;

        Tarone's Z test

data:  M successes from N counts
z = 2.5988, p-value = 0.009355
alternative hypothesis: true dispersion parameter is greater than 0
sample estimates:
proportion parameter
           0.4359756
</code>```

Here we see that our newly created hypothesis-testing function gives us output that has a similar user-friendly structure to the t.test.  In this example we have given different names to the testing method and the elements of the test, and these appear in the descriptive output when printed.

Body:
Statistical tests in R generate lists, but then when you call the test, the printing of these lists gives a special user-friendly structure to assist the reader.  To see what I'm talking about, consider an example where you use the t.test function in the stats package.

#Run a T-test on some example data
X <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
Y <- c(19, 20, 44, 45, 8, 29, 26, 59, 35, 50);
TEST <- stats::t.test(X,Y);

#Show structure of the TEST object
str(TEST);
List of 9
 $ statistic  : Named num -0.134
  ..- attr(*, "names")= chr "t"
 $ parameter  : Named num 10.2
  ..- attr(*, "names")= chr "df"
 $ p.value    : num 0.896
 $ conf.int   : num [1:2] -12.3 10.9
  ..- attr(*, "conf.level")= num 0.95
 $ estimate   : Named num [1:2] 32.8 33.5
  ..- attr(*, "names")= chr [1:2] "mean of x" "mean of y"
 $ null.value : Named num 0
  ..- attr(*, "names")= chr "difference in means"
 $ alternative: chr "two.sided"
 $ method     : chr "Welch Two Sample t-test"
 $ data.name  : chr "X and Y"
 - attr(*, "class")= chr "htest"

This object is a list with nine elements, some of which are named via attributes.  However, when I print the TEST object, the returned information is structured in a different way than the standard printing of a list.

#Print the TEST object
TEST;

        Welch Two Sample t-test

data:  X and Y
t = -0.13444, df = 10.204, p-value = 0.8957
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -12.27046  10.87046
sample estimates:
mean of x mean of y
     32.8      33.5

As you can see, this printed output is much more user-friendly than the standard printing for a list.  I would like to be able to program statistical tests in R which generate a list of outputs similar to the above, but which print in this user-friendly way.

My Questions: Why does R print the output of the list TEST in this special way?  If I create a list of outputs of a statistical test (e.g., like the above), how can I set the object to print in this way?

Body:
This answer is put together from helpful comments and answers by other users, but I wanted to give an elaborated answer here to make things more explicit, for the benefit of users who are not already familiar with some of these issues.  The object created by the t.test function is an object of class htest, and this type of object has a special method of printing under the print.htest setting in the global environment.  That printing method draws out information from the list, but prints it in the user-friendly way you see in the output in the question.

If you want to replicate this type of printing for a new statistical test that you are programming yourself, then you will need to structure your new test so that it outputs a htest object, with the required elements of the list, and the required class.  Here is an example from another answer where a hypothesis test set out in Tarone (1979) is programmed as a htest object:

Tarone.test <- function(N, M) {

    #Check validity of inputs
    if(any(M > N)) { stop("Error: Observed count value exceeds binomial trials"); }

    #Set hypothesis test objects
    method      <- "Tarone's Z test";
    alternative <- "greater";
    null.value  <- 0;
    attr(null.value, "names") <- "dispersion parameter";
    data.name   <- paste0(deparse(substitute(M)), " successes from ",
                          deparse(substitute(N)), " counts");

    #Calculate test statistics
    estimate    <- sum(M)/sum(N);
    attr(estimate, "names") <- "proportion parameter";

    S           <- sum((M - N*estimate)^2/(estimate*(1 - estimate)));
    statistic   <- (S - sum(N))/sqrt(2*sum(N*(N-1)));
    attr(statistic, "names") <- "z";

    p.value     <- 2*pnorm(-abs(statistic), 0, 1);
    attr(p.value, "names") <- NULL;

    #Create htest object
    TEST        <- list(statistic = statistic, p.value = p.value, estimate = estimate,
                        null.value = null.value, alternative = alternative,
                        method = method, data.name = data.name);
    class(TEST) <- "htest";

    TEST; }

In this example, the function calculates all the required elements of the htest object and then creates this object as a list with that class.  It is important to include the command class(TEST) <- "htest" in the code, so that the object created is not just a regular list.  Inclusion of that command will ensure that the output object is of the proper class, and so it will print in a user-friendly way.  To see this, we can generate some data and apply the test:

#Generate example data
N <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
M <- c( 9, 10, 22, 15,  8, 19, 16, 19, 15, 10);

#Apply Tarone's test to the example data
TEST <- Tarone.test(N, M);
TEST;

        Tarone's Z test

data:  M successes from N counts
z = 2.5988, p-value = 0.009355
alternative hypothesis: true dispersion parameter is greater than 0
sample estimates:
proportion parameter
           0.4359756

Here we see that our newly created hypothesis-testing function gives us output that has a similar user-friendly structure to the t.test.  In this example we have given different names to the testing method and the elements of the test, and these appear in the descriptive output when printed.


问:
Is there a way to aggregate an xarrray DataArray by calculating the mode for each cell along the time dimension?
In the xarray python package, it is possible to reduce a DataArray's data by applying a function along some dimension (most commonly along the time dimension). Build-in functions include, among others, mean, min and max. I.e.:

DataArray.mean(dim = 'time')
DataArray.min(dim = 'time')
DataArray.max(dim = 'time')
```

<p>As far as I can see, there is no build-in way to calculate the mode in the same way. Is there a way to this otherwise, for example with the 'help' of other packages?</p>

<p>That is, some function that would be equivalent to:</p>

<pre class="lang-py prettyprint-override"><code>DataArray.mode(dim = 'time')
</code>```

答:
You can wrap Scipy's mode function using Xarray's apply_ufunc. More examples of how to use apply_ufunc can be found here.

```<code>def _mode(*args, **kwargs):
    vals = scipy.stats.mode(*args, **kwargs)
    # only return the mode (discard the count)
    return vals[0].squeeze()

def mode(obj, None):
    # note: apply always moves core dimensions to the end
    # usually axis is simply -1 but scipy's mode function doesn't seem to like that
    # this means that this version will only work for DataArray's (not Datasets)
    assert isinstance(obj, xr.DataArray)
    axis = obj.ndim - 1
    return xr.apply_ufunc(_mode, obj,
                          input_core_dims=[[dim]],
                          kwargs={'axis': axis})
</code>```

A quick example using xarray's tutorial datasets:

```<code>ds = xr.tutorial.load_dataset('air_temperature')

mode(ds, dim='time')
</code>```

yields:

```<code><xarray.Dataset>
Dimensions:  (lat: 25, lon: 53)
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
Data variables:
    air      (lat, lon) float32 271.5 272.4 272.5 272.1 ... 296.9 296.9 296.79
</code>```

Body:
In the xarray python package, it is possible to reduce a DataArray's data by applying a function along some dimension (most commonly along the time dimension). Build-in functions include, among others, mean, min and max. I.e.:

DataArray.mean(dim = 'time')
DataArray.min(dim = 'time')
DataArray.max(dim = 'time')

As far as I can see, there is no build-in way to calculate the mode in the same way. Is there a way to this otherwise, for example with the 'help' of other packages?

That is, some function that would be equivalent to:

DataArray.mode(dim = 'time')

Body:
You can wrap Scipy's mode function using Xarray's apply_ufunc. More examples of how to use apply_ufunc can be found here.

def _mode(*args, **kwargs):
    vals = scipy.stats.mode(*args, **kwargs)
    # only return the mode (discard the count)
    return vals[0].squeeze()

def mode(obj, None):
    # note: apply always moves core dimensions to the end
    # usually axis is simply -1 but scipy's mode function doesn't seem to like that
    # this means that this version will only work for DataArray's (not Datasets)
    assert isinstance(obj, xr.DataArray)
    axis = obj.ndim - 1
    return xr.apply_ufunc(_mode, obj,
                          input_core_dims=[[dim]],
                          kwargs={'axis': axis})

A quick example using xarray's tutorial datasets:

ds = xr.tutorial.load_dataset('air_temperature')

mode(ds, dim='time')

yields:

<xarray.Dataset>
Dimensions:  (lat: 25, lon: 53)
Coordinates:
  * lat      (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
  * lon      (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
Data variables:
    air      (lat, lon) float32 271.5 272.4 272.5 272.1 ... 296.9 296.9 296.79


问:
Next Gen Gallery Filter By Tag On Galleries
I have NextGen Gallery version 3.1.5 and NextGen Pro version 2.6.8.

I am trying to put a gallery on a page, and have filter buttons above the gallery so that users can filter the images by tag.

Does anybody know of something I'm missing, or have a bit of custom code that can make this work?

I tried using the NextGen Gallery PowerTags plugin, but that broke my site (made it go to a 500 error). I think that plugin doesn't work anymore because of how big this last update by NextGen Gallery was.

答: Check out justified image grid. Its a plugin to display different gallery sources including nextgen. You can have two levels of filtering. </p>


问:
how to mock DynamoDB mapper transactionwrite() method using Mockito?
My use-case is that I am using dynamoDB mapper's transactionWrite() method. I am doing 2 put operations in my TransactionWriteRequest.

Now, when I am trying to verify the same using  verify(dynamoDBmapper).transactionWrite(writeRequest);

Output

```<code> => Argument(s) are different! Wanted:
     [java] dynamoDBMapper.transactionWrite(
     [java]     ...dynamodbv2.datamodeling.TransactionWriteRequest@4ee37ca3
     [java] );
     [java] -> at
    ...MyTestClass.myMethod_withValidData_returnSuccess(MyTestClass.java:99)
     [java] Actual invocation has different arguments:
     [java] dynamoDBMapper.transactionWrite(
     [java]     ...dynamodbv2.datamodeling.TransactionWriteRequest@45c8d09f
</code>```

答: I was able to do this using Unitils ReflectionAssert which compares objects recursively using reflection.</p>

Body:
My use-case is that I am using dynamoDB mapper's transactionWrite() method. I am doing 2 put operations in my TransactionWriteRequest.

Now, when I am trying to verify the same using  verify(dynamoDBmapper).transactionWrite(writeRequest);

Output

 => Argument(s) are different! Wanted:
     [java] dynamoDBMapper.transactionWrite(
     [java]     ...dynamodbv2.datamodeling.TransactionWriteRequest@4ee37ca3
     [java] );
     [java] -> at
    ...MyTestClass.myMethod_withValidData_returnSuccess(MyTestClass.java:99)
     [java] Actual invocation has different arguments:
     [java] dynamoDBMapper.transactionWrite(
     [java]     ...dynamodbv2.datamodeling.TransactionWriteRequest@45c8d09f


问:
Pass a function with multiple parameters as an argument
I would like to call a function with multiple parameters as an argument of another function. The assignment asks to pass the counted value(which just so happens to be the same value that is returned from the type integer read_Events function ) as an argument of another function.  Although I could just call the function and store it and pass it, I figured it might be a little cleaner to pass the whole function as an argument.

This is for a project for a previous class that I am revising for learning purposes. So far I've tried to store the address of function 2 into a pointer and pass the pointer storing the address of function 2 as an argument of function 1. I've also tried to pass the entirety of function 2 an argument of function 1.

```<code>#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
struct Date {
    int month;
    int day;
    int year;
};
struct Time {
     int hour;
     int minute;
};
struct Event {
    char desc[80];
    Date date;
    Time time;
};

int read_Events(Event* Eptr[50], int MAX);
void display(Event* Eptr[50],int(*read_events)(Event , int )) //1. can i
do this?;
int main() {
    Event* Eptr[50];
     int *Fptr = &read_Events;//#2 Is this possible? (function address
to pass as arugement in display function)

    _getch();
    return 0;
}

int read_Events(Event* Eptr[50], int MAX) {
    bool repeat = true;
    char ans;
    char slash;
    char colon;
    int i = 0;

    while (repeat && i < MAX) {
        cout << "\nWould you like to add a new event [y/n]? ";
        cin >> ans;

        if (ans == 'Y' || 'y') {
            Eptr[i] = new Event;
            repeat = true;

            cout << "\nEnter description: ";
            cin.clear();
            cin.ignore(256, '\n');
            cin.getline(Eptr[i]->desc, sizeof(Eptr[i]->desc));

            cout << "\nEnter Date(MM/DD/YYYY): ";
            cin >> Eptr[i]->date.month >> slash >> Eptr[i]->date.day >>
slash >> Eptr[i]->date.year;

            cout << "\nEnter time(HH:MM): ";
            cin >> Eptr[i]->time.hour >> colon >> Eptr[i]->time.minute;
        }
        else {
            repeat = false;
            return i;
        }
            i++;
        }
        return i; //returning number of events
}

It seems as if what I have done so far is not syntactically correct.
</code>```

答:
```<code>void display(Event* Eptr[50],int(*read_events)(Event , int )) //1. can i  do this?;
</code>```

Yes, you can. Make sure that the declaration is terminated correctly.

```<code>void display(Event* Eptr[50],int(*read_events)(Event , int ));
</code>```

```<code>int *Fptr = &read_Events;//#2 Is this possible?
</code>```

That is not correct. &read_Events evaluates to a pointer to a function. You need

```<code>int(*Fptr)(Event , int ) = &read_Events;
</code>```

You may also use the simpler version.

```<code>int(*Fptr)(Event , int ) = read_Events;
</code>```

You can also use the compiler's ability to deduce types and use

```<code>auto Fptr = &read_Events;
</code>```

Having said that, it's not clear to me how you intend to use the fuction pointer. There is no call to display() in your posted code.

Body:
I would like to call a function with multiple parameters as an argument of another function. The assignment asks to pass the counted value(which just so happens to be the same value that is returned from the type integer read_Events function ) as an argument of another function.  Although I could just call the function and store it and pass it, I figured it might be a little cleaner to pass the whole function as an argument.

This is for a project for a previous class that I am revising for learning purposes. So far I've tried to store the address of function 2 into a pointer and pass the pointer storing the address of function 2 as an argument of function 1. I've also tried to pass the entirety of function 2 an argument of function 1.

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
struct Date {
    int month;
    int day;
    int year;
};
struct Time {
     int hour;
     int minute;
};
struct Event {
    char desc[80];
    Date date;
    Time time;
};

int read_Events(Event* Eptr[50], int MAX);
void display(Event* Eptr[50],int(*read_events)(Event , int )) //1. can i
do this?;
int main() {
    Event* Eptr[50];
     int *Fptr = &read_Events;//#2 Is this possible? (function address
to pass as arugement in display function)

    _getch();
    return 0;
}

int read_Events(Event* Eptr[50], int MAX) {
    bool repeat = true;
    char ans;
    char slash;
    char colon;
    int i = 0;

    while (repeat && i < MAX) {
        cout << "\nWould you like to add a new event [y/n]? ";
        cin >> ans;

        if (ans == 'Y' || 'y') {
            Eptr[i] = new Event;
            repeat = true;

            cout << "\nEnter description: ";
            cin.clear();
            cin.ignore(256, '\n');
            cin.getline(Eptr[i]->desc, sizeof(Eptr[i]->desc));

            cout << "\nEnter Date(MM/DD/YYYY): ";
            cin >> Eptr[i]->date.month >> slash >> Eptr[i]->date.day >>
slash >> Eptr[i]->date.year;

            cout << "\nEnter time(HH:MM): ";
            cin >> Eptr[i]->time.hour >> colon >> Eptr[i]->time.minute;
        }
        else {
            repeat = false;
            return i;
        }
            i++;
        }
        return i; //returning number of events
}

It seems as if what I have done so far is not syntactically correct.

Body:
void display(Event* Eptr[50],int(*read_events)(Event , int )) //1. can i  do this?;

Yes, you can. Make sure that the declaration is terminated correctly.

void display(Event* Eptr[50],int(*read_events)(Event , int ));

int *Fptr = &read_Events;//#2 Is this possible?

That is not correct. &read_Events evaluates to a pointer to a function. You need

int(*Fptr)(Event , int ) = &read_Events;

You may also use the simpler version.

int(*Fptr)(Event , int ) = read_Events;

You can also use the compiler's ability to deduce types and use

auto Fptr = &read_Events;

Having said that, it's not clear to me how you intend to use the fuction pointer. There is no call to display() in your posted code.


问:
Cannot turn off short_open_tag with ini_set
I'm embedding a javascript syntax highlighter to a PHP script that reads source file and echos it back. The js highlighter has this string on one line:

... [z,/^[^<?]+/], ...

The short_open_tag is on on this server and the <? in the string confuses the script and causes errors. I cannot turn off in php.ini or elsewhere.

I have used ini_set('short_open_tag', '0'); in the same script, but it does not take effect. What could be the problem?

Edit

In the end, I used what Col Shrapnel suggested in a comment:

I changed [z,/^[^<?]+/], to [z,/^[^<?php echo '<' .'?'; ?>]+/],

答:
According to a comment on this manual page:

libkhorse at gmail dot com 06-Aug-2009
  07:14:

For 'short_open_tag', though it
  is marked as PHP_INI_ALL in changable
  column, you should  note the
  CHANGE_LOG column also:

PHP_INI_ALL                in PHP <=
  4.0.0. PHP_INI_PERDIR            in PHP < 5.3.0

So as of 4.0, it will not work if you
  wanna use ini_set('short_open_tag') to
  change it's value on the fly.

Try using .htaccess instead:

```<code>php_flag short_open_tag off
</code>```

Body:
According to a comment on this manual page:

libkhorse at gmail dot com 06-Aug-2009
  07:14:

For 'short_open_tag', though it
  is marked as PHP_INI_ALL in changable
  column, you should  note the
  CHANGE_LOG column also:

PHP_INI_ALL                in PHP <=
  4.0.0. PHP_INI_PERDIR            in PHP < 5.3.0

So as of 4.0, it will not work if you
  wanna use ini_set('short_open_tag') to
  change it's value on the fly.

Try using .htaccess instead:

php_flag short_open_tag off


问:
How to find a value in a JSON and unset it?
So basically I have this page that takes values, json_encodes them and puts them in an array, in a file. Everything works fine, but the only thing I am having problems with is removing some values once they pass a certain date.

So basically, the code is a form, where someone enters their name, email, location, date and a small message. Next, the code takes the existing file, turns it into an array, and appends the new entry into the array, rewrites the file with the new array and closes it. The entries are turned into their own small array, so the main array in the file has arrays within it. The code checks $item[2], which is the date, and if the current date is after that time, then it needs to delete it. I'm just having trouble getting it to remove the JSON so it can delete the entry.

I know this is a lot, and my code is very messy, but I hope you can understand what I'm trying to do.

Here is the code that compares the date:

```<code>foreach ($arr as $help)
                      {
                        foreach ($help as $item)
                          {
                            if ($item[2] > date("Y-m-d H:i:s"))
                            {
                            //stuff happens here, ive just cut it out for simplicity.
}
                          else {
                            $delete = [$item[0],$item[1],$item[2],$item[3],$item[4]];
                            $delete2 = json_encode($delete);

                            $open = fopen('data.txt', 'r');
                            $inside = fread($open, filesize('data.txt'));
                            $newinside = json_decode($inside);
                            $newar = [$newinside];

                            $bean = array_search($delete, $newar);
                            echo $bean;

                          }
                          }

                      }
</code>```

That code is definitely wrong, but it's what I've tried already.

Here is the json file after being totally encoded:

```<code>[["Simon Long","simon@greatnessgroup.com","2018-01-01T01:01","test","aaa"],["test","test@gmail.com","2020-01-01T01:01","yeah","test\r\n"]]
</code>```

答:
I'm just guessing that we have an $arr similar to the output in the question.

Here, we loop through our arrays, then check one by one for a pattern than we wish to exclude, for example the dates, using a simple expression:

```<code>/([0-9]{4}.+)/m
</code>```

Then, we unset the dates, just as an example, and json_encode our array back to json.

```<code>$arr = '[["Simon Long", "simon@greatnessgroup.com", "2018-01-01T01:01", "test", "aaa"], ["test", "test@gmail.com", "2020-01-01T01:01", "yeah", "test\r\n"]]';
$arr = json_decode($arr, true);
foreach ($arr as $key => $value) {
    foreach ($value as $key2 => $value2) {
        $re = '/([0-9]{4}.+)/m';
        preg_match_all($re, $value2, $matches, PREG_SET_ORDER, 0);
        foreach ($matches as $key3 => $value3) {
            unset($arr[$key][$key2]);
        }

    }
}

print json_encode($arr);
</code>```

Output

```<code>[{"0":"Simon Long","1":"simon@greatnessgroup.com","3":"test","4":"aaa"},{"0":"test","1":"test@gmail.com","3":"yeah","4":"test\r\n"}]
</code>```

DEMO

Body:
So basically I have this page that takes values, json_encodes them and puts them in an array, in a file. Everything works fine, but the only thing I am having problems with is removing some values once they pass a certain date.

So basically, the code is a form, where someone enters their name, email, location, date and a small message. Next, the code takes the existing file, turns it into an array, and appends the new entry into the array, rewrites the file with the new array and closes it. The entries are turned into their own small array, so the main array in the file has arrays within it. The code checks $item[2], which is the date, and if the current date is after that time, then it needs to delete it. I'm just having trouble getting it to remove the JSON so it can delete the entry.

I know this is a lot, and my code is very messy, but I hope you can understand what I'm trying to do.

Here is the code that compares the date:

foreach ($arr as $help)
                      {
                        foreach ($help as $item)
                          {
                            if ($item[2] > date("Y-m-d H:i:s"))
                            {
                            //stuff happens here, ive just cut it out for simplicity.
}
                          else {
                            $delete = [$item[0],$item[1],$item[2],$item[3],$item[4]];
                            $delete2 = json_encode($delete);

                            $open = fopen('data.txt', 'r');
                            $inside = fread($open, filesize('data.txt'));
                            $newinside = json_decode($inside);
                            $newar = [$newinside];

                            $bean = array_search($delete, $newar);
                            echo $bean;

                          }
                          }

                      }

That code is definitely wrong, but it's what I've tried already.

Here is the json file after being totally encoded:

[["Simon Long","simon@greatnessgroup.com","2018-01-01T01:01","test","aaa"],["test","test@gmail.com","2020-01-01T01:01","yeah","test\r\n"]]

Body:
I'm just guessing that we have an $arr similar to the output in the question.

Here, we loop through our arrays, then check one by one for a pattern than we wish to exclude, for example the dates, using a simple expression:

/([0-9]{4}.+)/m

Then, we unset the dates, just as an example, and json_encode our array back to json.

$arr = '[["Simon Long", "simon@greatnessgroup.com", "2018-01-01T01:01", "test", "aaa"], ["test", "test@gmail.com", "2020-01-01T01:01", "yeah", "test\r\n"]]';
$arr = json_decode($arr, true);
foreach ($arr as $key => $value) {
    foreach ($value as $key2 => $value2) {
        $re = '/([0-9]{4}.+)/m';
        preg_match_all($re, $value2, $matches, PREG_SET_ORDER, 0);
        foreach ($matches as $key3 => $value3) {
            unset($arr[$key][$key2]);
        }

    }
}

print json_encode($arr);

Output

[{"0":"Simon Long","1":"simon@greatnessgroup.com","3":"test","4":"aaa"},{"0":"test","1":"test@gmail.com","3":"yeah","4":"test\r\n"}]

DEMO


问:
How to align label text with radio button
The label for each radio button is aligned until the label text is not displayed on a single line. I would like the alignment to look like this. However, it currently looks like this when viewed on a small screen.

This outputs data from a MySQL database into radiobuttons.

```<code><?php
$stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
$stmt->execute();
$stmt->bind_result($case_id, $case_name, $case_price);
while($stmt->fetch()) {
echo '<li>
<input id="'.$case_id.'" name="config-prod" value="'.$case_id.'" type="radio">
<label class="sub-label" for="'.$case_id.'">'.$case_name.'         [£'.$case_price.']</label>
</li>';
}
$stmt->close();
?>
</code>```

CSS:

```<code>label {
    margin-top: 5px;
    color: #cfcfcf;
}

.input-list {
    list-style-type: none;
    width: 100%;
    padding: 0;
    margin: 0;
}
    .input-list li input {
        margin-right: 22px;
    }
        .input-list li input:checked + label {
            color: rgb(255, 255, 255);
            font-weight: 700;
            font-size: 17px;
            transition: color 0.5s ease;
        }
</code>```

How can I achieve this? Thank you.

答:
Give the line items display: flex. I just added this:

```<code>.input-list li {
  display: flex;
}
</code>```

label {
  color: #cfcfcf;
}

.input-list {
  list-style-type: none;
  width: 100%;
  padding: 0;
  margin: 0;
}

.input-list li {
  display: flex;
  align-items: center;
  padding: 3px 0;
}

.input-list li input {
  margin-right: 22px;
}

.input-list li input:checked+label {
  color: rgb(255, 255, 255);
  font-weight: 700;
  font-size: 17px;
  transition: color 0.5s ease;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="input-list">
  <li>
    <input id="1" name="config-prod" value="1" type="radio">
    <label class="sub-label" for="1">One</label>
  </li>
  <li>
    <input id="2" name="config-prod" value="2" type="radio">
    <label class="sub-label" for="2">Two</label>
  </li>
  <li>
    <input id="3" name="config-prod" value="3" type="radio">
    <label class="sub-label" for="3">Three, a really long one... Really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really long...</label>
  </li>
  <li>
    <input id="4" name="config-prod" value="4" type="radio">
    <label class="sub-label" for="4">Fourth</label>
  </li>
</ul></code>```

Body:
The label for each radio button is aligned until the label text is not displayed on a single line. I would like the alignment to look like this. However, it currently looks like this when viewed on a small screen.

This outputs data from a MySQL database into radiobuttons.

<?php
$stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
$stmt->execute();
$stmt->bind_result($case_id, $case_name, $case_price);
while($stmt->fetch()) {
echo '

<input id="'.$case_id.'" name="config-prod" value="'.$case_id.'" type="radio">
'.$case_name.'         [£'.$case_price.']

';
}
$stmt->close();
?>

CSS:

label {
    margin-top: 5px;
    color: #cfcfcf;
}

.input-list {
    list-style-type: none;
    width: 100%;
    padding: 0;
    margin: 0;
}
    .input-list li input {
        margin-right: 22px;
    }
        .input-list li input:checked + label {
            color: rgb(255, 255, 255);
            font-weight: 700;
            font-size: 17px;
            transition: color 0.5s ease;
        }

How can I achieve this? Thank you.

Body:
Give the line items display: flex. I just added this:

.input-list li {
  display: flex;
}

label {
  color: #cfcfcf;
}

.input-list {
  list-style-type: none;
  width: 100%;
  padding: 0;
  margin: 0;
}

.input-list li {
  display: flex;
  align-items: center;
  padding: 3px 0;
}

.input-list li input {
  margin-right: 22px;
}

.input-list li input:checked+label {
  color: rgb(255, 255, 255);
  font-weight: 700;
  font-size: 17px;
  transition: color 0.5s ease;
}

<ul class="input-list">
  <li>
    <input id="1" name="config-prod" value="1" type="radio">
    <label class="sub-label" for="1">One</label>
  </li>
  <li>
    <input id="2" name="config-prod" value="2" type="radio">
    <label class="sub-label" for="2">Two</label>
  </li>
  <li>
    <input id="3" name="config-prod" value="3" type="radio">
    <label class="sub-label" for="3">Three, a really long one... Really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really long...</label>
  </li>
  <li>
    <input id="4" name="config-prod" value="4" type="radio">
    <label class="sub-label" for="4">Fourth</label>
  </li>
</ul>


问:
React FilePond Preview [ File Poster ] Not Working
My FilePond Poster preview code not working, please help me find what i'm doing wrong.

i tried different variations of the code seen below but with no luck.

-i tried to enable instant Upload (didn't work)

```<code>import React, { Component, Fragment } from 'react';
import { FilePond, File, registerPlugin } from 'react-filepond';
import FilePondPluginImagePreview from 'filepond-plugin-image-preview';
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css';
import FilePondPluginFilePoster from 'filepond-plugin-file-poster';
import 'filepond-plugin-file-poster/dist/filepond-plugin-file-poster.css';
import 'filepond/dist/filepond.min.css';
registerPlugin(FilePondPluginImagePreview, FilePondPluginFilePoster);

export default class MyFilePond extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
        };
    }
    handleInit() {
        console.log('FilePond instance has initialised', this.pond);
    }
    render() {
        return (
            <Fragment>
                <FilePond
                    ref={ref => (this.pond = ref)}
                    allowFilePoster={true}
                    instantUpload={false}
                    server={{}}
                    name="image"
                    acceptedFileTypes={['image/*']}
                    oninit={() => this.handleInit()}
                >
                    <File
                        file={{
                            name: 'my-file.png',
                            size: 3001025,
                            type: 'image/png'
                        }}
                        metadata={{poster : 'https://www.pngarts.com/files/3/Spongebob-Squarepants-Transparent.png'}}
                        source="https://www.pngarts.com/files/3/Spongebob-Squarepants-Transparent.png"
            />
                </FilePond>
            </Fragment>
        );
    }
}
</code>```

答:
If you keep getting CORS error like my case, you can try this hack:
+ Clone the poster plugin and make it your own plugin.
+ In the source code of poster plugin find and remove this line: img.crossOrigin = 'Anonymous';

Body:
My FilePond Poster preview code not working, please help me find what i'm doing wrong.

i tried different variations of the code seen below but with no luck.

-i tried to enable instant Upload (didn't work)

import React, { Component, Fragment } from 'react';
import { FilePond, File, registerPlugin } from 'react-filepond';
import FilePondPluginImagePreview from 'filepond-plugin-image-preview';
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css';
import FilePondPluginFilePoster from 'filepond-plugin-file-poster';
import 'filepond-plugin-file-poster/dist/filepond-plugin-file-poster.css';
import 'filepond/dist/filepond.min.css';
registerPlugin(FilePondPluginImagePreview, FilePondPluginFilePoster);

export default class MyFilePond extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
        };
    }
    handleInit() {
        console.log('FilePond instance has initialised', this.pond);
    }
    render() {
        return (
            <Fragment>
                <FilePond
                    ref={ref => (this.pond = ref)}
                    allowFilePoster={true}
                    instantUpload={false}
                    server={{}}
                    name="image"
                    acceptedFileTypes={['image/*']}
                    oninit={() => this.handleInit()}
                >
                    <File
                        file={{
                            name: 'my-file.png',
                            size: 3001025,
                            type: 'image/png'
                        }}
                        metadata={{poster : 'https://www.pngarts.com/files/3/Spongebob-Squarepants-Transparent.png'}}
                        source="https://www.pngarts.com/files/3/Spongebob-Squarepants-Transparent.png"
            />
                </FilePond>
            </Fragment>
        );
    }
}


问:
TimeoutException on sending messages to kafka topic
I've got the problem with producing messages to Kafka topic.

When producing a few messages to Kafka topic, intermittently it fails with an exception:

org.apache.kafka.common.errors.TimeoutException: Expiring 6 record(s) for some-topic-1: 30056 ms has passed since batch creation plus linger time

The problem seems to be different than others I already found here. It happens with really low load. I'm pretty sure that I not exceed buffer size (default value). linger.ms setting is set to 0 (default). request.timeout.ms is also set to default which is 30000.

Actually my question is: is there anything that could hold sending kafka message process for 30 seconds between calling send() method and actually sending it? I'm looking for anything that could make ProducerBatch living time longer than 30 seconds in very low load (or without any load).

I use Kafka managed service from external provider so I asked him about broker status and he said everything is ok. Btw, it happens on three different Kafka instances. Kafka Client version doesn't matter too - it's happening for both 0.11.0.0 and 2.0.1.

答:
I've just looked at the Kafka documentation for version 2.0.X and I would say that you're facing this error because of the default settings and the low message ingestion load.

Let's try and dissect your error message:

org.apache.kafka.common.errors.TimeoutException: Expiring 6 record(s)
  for some-topic-1: 30056 ms has passed since batch creation plus linger
  time

First clue in the error is 30056 ms has passed - The configuration request.timeout.ms is playing out here. The default value for this config is 30000 i.e. 30 seconds. This 30 seconds wait is for filling up the buffer on the Producer's side - I've explained this in the next point.

Second clue in the error message is since batch creation - When you invoke send() method - the message gets buffered at the Producer's side and it will wait for 30 seconds (as directed by the first config property)  to fill the batch. Now, the batch.size has a default value of 16384 bytes i.e. 16 KB so if the message ingestion load is low (as it is in your case) and the buffer doesn't fill up with more messages to the size of 16 KB in 30 seconds - you would expect this error message. So, in your case it seems that the Expiring 6 record(s) don't really make up the 16 KB required to fill the batch.

Lastly, the error also makes a mention of plus linger time - This is the linger.ms configuration that finds it's use in situations where the ingestion load is high and the producer wants to limit the send() calls to the Kafka broker(s). This is the duration the Producer will wait for before sending the messages to the broker after the batch is ready (i.e. buffer is filled up to batch.size). The default value for this is 0 so in your case, the producer will wait for 0 milliseconds after the batch is ready. But your buffer doesn't actually fill up in the given time.

Now, to answer your question: You could increase linger.ms to be able to hold the messages longer after the batch is ready. If you need more time to fill the batch then you'll need to increase request.timeout.ms. You might as well try a combination of both.

On similar lines, to fix this error you could increase request.timeout.ms or reduce batch.sizeor maybe both.

Hope this helps!


问:
Alternate ways to sendKeys in Selenium java
Below is the HTML for a text field:

```<code><input class=" input" maxlength="255" type="text" aria-describedby="" placeholder="" id="4769:0" data-aura-rendered-by="4773:0" data-interactive-lib-uid="53">
</code>```

I have written below code to type the 'text' in the field

```<code>driver.findElement(By.xpath(".//div/input[starts-with(@id,'4') and @class=' input' and @type='text' and @placeholder='']")).sendKeys("text");
</code>```

It is identifying the field but not typing the text?

答:
Seems like your locator strategy is a problem:

```<code>.//div/input[starts-with(@id,'4') and @class=' input' and @type='text' and @placeholder='']
</code>```

. -> are we finding any child element?
starts-with(@id,'4') -> can return multiple elements

and same is for other 'and' conditions in your xpath.

Try some other xpath taking following-sibling/preceding.

Body:
Below is the HTML for a text field:

<input class=" input" maxlength="255" type="text" aria-describedby="" placeholder="" id="4769:0" data-aura-rendered-by="4773:0" data-interactive-lib-uid="53">

I have written below code to type the 'text' in the field

driver.findElement(By.xpath(".//div/input[starts-with(@id,'4') and @class=' input' and @type='text' and @placeholder='']")).sendKeys("text");

It is identifying the field but not typing the text?

Body:
Seems like your locator strategy is a problem:

.//div/input[starts-with(@id,'4') and @class=' input' and @type='text' and @placeholder='']

. -> are we finding any child element?
starts-with(@id,'4') -> can return multiple elements

and same is for other 'and' conditions in your xpath.

Try some other xpath taking following-sibling/preceding.


问:
Looking for javascript event equivalent to 'onRender'
I'd like to add to my  element JS event listener that will be triggered when the page is rendered (or loaded) to the DOM and the TD contains its innerHTML value.
something like:

```<code><script>
function manipulate(field){
field.value = field.value+'_done';
}
</script>
<td onRender=manipulate(this)>Hello World</td>
</code>```

I can't use onLoad because it can be used in  only to my understanding
Is there any way to do it?

答:
You can still use the body's onload, it will fire when the complete page is ready and loaded. You can set an attribute for every TD element you'd like to manipulate, and then traverse the page to find those elements and call your function.

Why do you want to manipulate something after the DOM is loaded?

Body:
I'd like to add to my  element JS event listener that will be triggered when the page is rendered (or loaded) to the DOM and the TD contains its innerHTML value.
something like:

Hello World

I can't use onLoad because it can be used in  only to my understanding
Is there any way to do it?


问:
How to get instagram Stories Highlights using c#?
I'm writing app using c#, I use InstaSharper library. I want to get user "Stories Highlights", but there are only method GetUserStoryFeedAsync() to get current user stories. How can I get user "Stories Highlights"?

答:
```<code>var user = await InstaApi.UserProcessor.GetUserAsync("giorgos.xou");
var userId = user.Value.Pk.ToString();
var Highlights = await InstaApi.StoryProcessor.GetHighlightFeedsAsync(userId);

foreach (InstaHighlightFeed Highlight in Highlights.Value.Items)
{
    //sb2.AppendLine(Highlight.Title);
}
</code>```


问:
How to group by one column and divide the numbers in second column depending from the third
I have frequency (column 1) for SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING (column 3) mutations for a list of genes in the second column.

I need to calculate dN/dS ratio (NON_SYNONYMOUS_CODING / SYNONYMOUS_CODING) for each gene.

Not all genes may have both SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING frequency

```<code>0.00491398 A1BG SYNONYMOUS_CODING
0.923601 A1BG NON_SYNONYMOUS_CODING
0.051361 A1CF NON_SYNONYMOUS_CODING
0.153161 A1CF SYNONYMOUS_CODING
0.0977385 A2M SYNONYMOUS_CODING
1.36114 A2M NON_SYNONYMOUS_CODING
2.19662 A2ML1 SYNONYMOUS_CODING
3.43866 A2ML1 NON_SYNONYMOUS_CODING
</code>```

Expected result is smth like this:

```<code>187.95 A1BG
0.3353 A1CF
13.926 A2M
1.565 A2ML1
</code>```

答:
Using GNU awk and indirect function calls (use the value of $3 as the name of the function to call):

```<code>$ awk '
function NON_SYNONYMOUS_CODING(n,s) {          # notice the parameter order here...
    return n/s
}
function SYNONYMOUS_CODING(s,n) {              # and here
    return n/s
}
{
    fun=$3                                     # get the function name from $3
    if($2 in a) {                              # if other $2 has already been seen
        print $2,@fun($1,a[$2])                # divide in the function and output
        delete a[$2]                           # saving memory
    } else                                     # if this $2 is the first
        a[$2]=$1                               # hash it
}' file
</code>```

Output:

```<code>A1BG 187.954
A1CF 0.33534
A2M 13.9263
A2ML1 1.56543
</code>```

Body:
I have frequency (column 1) for SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING (column 3) mutations for a list of genes in the second column.

I need to calculate dN/dS ratio (NON_SYNONYMOUS_CODING / SYNONYMOUS_CODING) for each gene.

Not all genes may have both SYNONYMOUS_CODING and NON_SYNONYMOUS_CODING frequency

0.00491398 A1BG SYNONYMOUS_CODING
0.923601 A1BG NON_SYNONYMOUS_CODING
0.051361 A1CF NON_SYNONYMOUS_CODING
0.153161 A1CF SYNONYMOUS_CODING
0.0977385 A2M SYNONYMOUS_CODING
1.36114 A2M NON_SYNONYMOUS_CODING
2.19662 A2ML1 SYNONYMOUS_CODING
3.43866 A2ML1 NON_SYNONYMOUS_CODING

Expected result is smth like this:

187.95 A1BG
0.3353 A1CF
13.926 A2M
1.565 A2ML1

Body:
Using GNU awk and indirect function calls (use the value of $3 as the name of the function to call):

$ awk '
function NON_SYNONYMOUS_CODING(n,s) {          # notice the parameter order here...
    return n/s
}
function SYNONYMOUS_CODING(s,n) {              # and here
    return n/s
}
{
    fun=$3                                     # get the function name from $3
    if($2 in a) {                              # if other $2 has already been seen
        print $2,@fun($1,a[$2])                # divide in the function and output
        delete a[$2]                           # saving memory
    } else                                     # if this $2 is the first
        a[$2]=$1                               # hash it
}' file

Output:

A1BG 187.954
A1CF 0.33534
A2M 13.9263
A2ML1 1.56543


问:
FFT polynomial multiplication in Python using inbuilt Numpy.fft
I want to multiply two polynomials fast in python. As my polynomials are rather large (> 100000) elements and I have to multiply lots of them. Below, you will find my approach,

```<code>from numpy.random import seed, randint
from numpy import polymul, pad
from numpy.fft import fft, ifft
from timeit import default_timer as timer

length=100

def test_mul(arr_a,arr_b):  #inbuilt python multiplication

    c=polymul(arr_a,arr_b)

    return c

def sb_mul(arr_a,arr_b):    #my schoolbook multiplication

    c=[0]*(len(arr_a) + len(arr_b) - 1 )
    for i in range( len(arr_a) ):
        for j in range( len(arr_b) ):
            k=i+j
            c[k]=c[k]+arr_a[i]*arr_b[j]
    return c

def fft_test(arr_a,arr_b):  #fft based polynomial multuplication

    arr_a1=pad(arr_a,(0,length),'constant')
    arr_b1=pad(arr_b,(0,length),'constant')
    a_f=fft(arr_a1)
    b_f=fft(arr_b1)

    c_f=[0]*(2*length)

    for i in range( len(a_f) ):
        c_f[i]=a_f[i]*b_f[i]

    return c_f

if __name__ == '__main__':

    seed(int(timer()))
    random=1
    if(random==1):
        x=randint(1,1000,length)
        y=randint(1,1000,length)
    else:
        x=[1]*length
        y=[1]*length

    start=timer()
    res=test_mul(x,y)
    end=timer()
    print("time for built in pol_mul", end-start)

    start=timer()
    res1=sb_mul(x,y)
    end=timer()
    print("time for schoolbook mult", end-start)

    res2=fft_test(x,y)

    print(res2)

    #########check############
    if( len(res)!=len(res1) ):
        print("ERROR");

    for i in range( len(res) ):
        if( res[i]!=res1[i] ):
            print("ERROR at pos ",i,"res[i]:",res[i],"res1[i]:",res1[i])
</code>```

Now, here are my approach in detail,
1. First, I tried myself with a naive implementation of Schoolbook with complexity O(n^2). But as you may expect it turned out to be very slow.

Second, I came to know polymul in the Numpy library. This function is a lot faster than the previous one. But I realized this is also a O(n^2) complexity. You can see, if you increase the length k the time increases by k^2 times.

My third approach is to try a FFT based multiplication using the inbuilt FFT functions. I followed the the well known approach  also described here but Iam not able to get it work.

Now my questions are,

Where am I going wrong in my FFT based approach? Can you please tell me how can I fix it?

Is my observation that polymul function has O(n^2) complexity correct?

Please, let me know if you have any question.
Thanks in advance.

答:
Where am I going wrong in my FFT based approach? Can you please tell me how can I fix it?

The main problem is that in the FFT based approach, you should be taking the inverse transform after the multiplication, but that step is missing from your code. With this missing step your code should look like the following:

```<code>def fft_test(arr_a,arr_b):  #fft based polynomial multiplication

    arr_a1=pad(arr_a,(0,length),'constant')
    arr_b1=pad(arr_b,(0,length),'constant')
    a_f=fft(arr_a1)
    b_f=fft(arr_b1)

    c_f=[0]*(2*length)

    for i in range( len(a_f) ):
        c_f[i]=a_f[i]*b_f[i]

    return ifft(c_f)
</code>```

Note that there may also a few opportunities for improvements:

The zero padding can be handled directly by passing the required FFT length as the second argument (e.g. a_f = fft(arr_a, length))

The coefficient multiplication in your for loop may be directly handled by numpy.multiply.

If the polynomial coefficients are real-valued, then you can use numpy.fft.rfft and numpy.fft.irfft (instead of numpy.fft.fft and numpy.fft.ifft) for some extra performance boost.

So an implementation for real-valued inputs may look like:

```<code>from numpy.fft import rfft, irfft
def fftrealpolymul(arr_a, arr_b):  #fft based real-valued polynomial multiplication
    L = len(arr_a) + len(arr_b)
    a_f = rfft(arr_a, L)
    b_f = rfft(arr_b, L)
    return irfft(a_f * b_f)
</code>```

Is my observation that polymul function has O(n2) complexity correct?

That also seem to be the performance I am observing, and matches the available code in my numpy installation (version 1.15.4, and there doesn't seem any change in that part in the more recent 1.16.1 version).

Body:
I want to multiply two polynomials fast in python. As my polynomials are rather large (> 100000) elements and I have to multiply lots of them. Below, you will find my approach,

from numpy.random import seed, randint
from numpy import polymul, pad
from numpy.fft import fft, ifft
from timeit import default_timer as timer

length=100

def test_mul(arr_a,arr_b):  #inbuilt python multiplication

    c=polymul(arr_a,arr_b)

    return c

def sb_mul(arr_a,arr_b):    #my schoolbook multiplication

    c=[0]*(len(arr_a) + len(arr_b) - 1 )
    for i in range( len(arr_a) ):
        for j in range( len(arr_b) ):
            k=i+j
            c[k]=c[k]+arr_a[i]*arr_b[j]
    return c

def fft_test(arr_a,arr_b):  #fft based polynomial multuplication

    arr_a1=pad(arr_a,(0,length),'constant')
    arr_b1=pad(arr_b,(0,length),'constant')
    a_f=fft(arr_a1)
    b_f=fft(arr_b1)

    c_f=[0]*(2*length)

    for i in range( len(a_f) ):
        c_f[i]=a_f[i]*b_f[i]

    return c_f

if __name__ == '__main__':

    seed(int(timer()))
    random=1
    if(random==1):
        x=randint(1,1000,length)
        y=randint(1,1000,length)
    else:
        x=[1]*length
        y=[1]*length

    start=timer()
    res=test_mul(x,y)
    end=timer()
    print("time for built in pol_mul", end-start)

    start=timer()
    res1=sb_mul(x,y)
    end=timer()
    print("time for schoolbook mult", end-start)

    res2=fft_test(x,y)

    print(res2)

    #########check############
    if( len(res)!=len(res1) ):
        print("ERROR");

    for i in range( len(res) ):
        if( res[i]!=res1[i] ):
            print("ERROR at pos ",i,"res[i]:",res[i],"res1[i]:",res1[i])

Now, here are my approach in detail,
1. First, I tried myself with a naive implementation of Schoolbook with complexity O(n^2). But as you may expect it turned out to be very slow.

Second, I came to know polymul in the Numpy library. This function is a lot faster than the previous one. But I realized this is also a O(n^2) complexity. You can see, if you increase the length k the time increases by k^2 times.

My third approach is to try a FFT based multiplication using the inbuilt FFT functions. I followed the the well known approach  also described here but Iam not able to get it work.

Now my questions are,

Where am I going wrong in my FFT based approach? Can you please tell me how can I fix it?

Is my observation that polymul function has O(n^2) complexity correct?

Please, let me know if you have any question.
Thanks in advance.

Body:
Where am I going wrong in my FFT based approach? Can you please tell me how can I fix it?

The main problem is that in the FFT based approach, you should be taking the inverse transform after the multiplication, but that step is missing from your code. With this missing step your code should look like the following:

def fft_test(arr_a,arr_b):  #fft based polynomial multiplication

    arr_a1=pad(arr_a,(0,length),'constant')
    arr_b1=pad(arr_b,(0,length),'constant')
    a_f=fft(arr_a1)
    b_f=fft(arr_b1)

    c_f=[0]*(2*length)

    for i in range( len(a_f) ):
        c_f[i]=a_f[i]*b_f[i]

    return ifft(c_f)

Note that there may also a few opportunities for improvements:

The zero padding can be handled directly by passing the required FFT length as the second argument (e.g. a_f = fft(arr_a, length))

The coefficient multiplication in your for loop may be directly handled by numpy.multiply.

If the polynomial coefficients are real-valued, then you can use numpy.fft.rfft and numpy.fft.irfft (instead of numpy.fft.fft and numpy.fft.ifft) for some extra performance boost.

So an implementation for real-valued inputs may look like:

from numpy.fft import rfft, irfft
def fftrealpolymul(arr_a, arr_b):  #fft based real-valued polynomial multiplication
    L = len(arr_a) + len(arr_b)
    a_f = rfft(arr_a, L)
    b_f = rfft(arr_b, L)
    return irfft(a_f * b_f)

Is my observation that polymul function has O(n2) complexity correct?

That also seem to be the performance I am observing, and matches the available code in my numpy installation (version 1.15.4, and there doesn't seem any change in that part in the more recent 1.16.1 version).


问:
Is there a way to break the long text without defining width or max-width in EDGE / IE11?
I am facing an issue where in text is overflowing the parent in IE11 & EDGE and working fine  in Chrome, firefox and Opera.

I have tried multiple approaches
Approach 1 -> Using break-all instead of break-word:
  With this approach, text is getting truncated in between the words. So, I can't use this approach

Approach 2 -> Using max-width or width property set for child
  With this approach, width should be hardcoded for all the child controls or should be given as some % like 95%

Approach 3 -> Using display type as inline
  With this approach, there will be no margins, padding as inline will ignore all these properties.

I have tried the above approaches and added the issue in the below jsfiddle link

"https://jsfiddle.net/gc4yknax/"

This code works fine in Chrome and breaks in Edge / IE11.

Expected output: Long Text should get wrapped into next line and should not go beyond the container.

Actual output: Long text is not getting wrapped and going beyond the parent container.

答: You can add overflow: hidden in css .break-word. It will fix the problem.


问:
How to change page heading in activeadmin
I want to change the titles of page as shown in diagram below.

How can I change that?

答:
Use translations to override labels and page titles for actions. You can read more in docs</p>

```<code>en:
  active_admin:
    resources:
      experience: # Registered resource
        new_model: 'Get new experience'
</code>```

Body:
Use translations to override labels and page titles for actions. You can read more in docs

en:
  active_admin:
    resources:
      experience: # Registered resource
        new_model: 'Get new experience'


问:
Is there a simpler method to get slice of a tensors as shown in the following example?
I want to do slicing of tensors like the following slicing in numpy. How can I do that?

```<code># numpy array
a = np.reshape(np.arange(60), (3,2,2,5))
idx = np.array([0, 1, 0])
N = np.shape(a)[0]
mask = a[np.arange(N),:,:,idx]

# I have tried several solutions, but only the following success.
# tensors
import tensorflow as tf
import numpy as np

a = tf.cast(tf.constant(np.reshape(np.arange(60), (3,2,2,5))), tf.int32)
idx2 = tf.constant([0, 1, 0])

fn = lambda i: a[i][:,:,idx2[i]]
idx = tf.range(tf.shape(a)[0])
masks = tf.map_fn(fn, idx)
with tf.Session() as sess:
    print(sess.run(a))
    print(sess.run(tf.shape(masks)))
    print(sess.run(masks))
</code>```

Is there a simpler method to achieve this ?

Can I use function tf.gather or tf.gather_nd to achieve this ?
Many thanks!

答:
Another method use tf.gather_nd:

```<code>import tensorflow as tf
import numpy as np

a = tf.cast(tf.constant(np.reshape(np.arange(60), (3,2,2,5))), tf.int32)
idx = tf.range(tf.shape(a)[0])
idx2 = tf.constant([0,1,0])
indices = tf.stack([idx, idx2], axis=1)
a = tf.transpose(a, [0,3,1,2])
masks = tf.gather_nd(a, indices)

with tf.Session() as sess:
    print(sess.run(a))
    print(sess.run(tf.shape(masks)))
    print(sess.run(masks))
</code>```

Body:
I want to do slicing of tensors like the following slicing in numpy. How can I do that?

# numpy array
a = np.reshape(np.arange(60), (3,2,2,5))
idx = np.array([0, 1, 0])
N = np.shape(a)[0]
mask = a[np.arange(N),:,:,idx]

# I have tried several solutions, but only the following success.
# tensors
import tensorflow as tf
import numpy as np

a = tf.cast(tf.constant(np.reshape(np.arange(60), (3,2,2,5))), tf.int32)
idx2 = tf.constant([0, 1, 0])

fn = lambda i: a[i][:,:,idx2[i]]
idx = tf.range(tf.shape(a)[0])
masks = tf.map_fn(fn, idx)
with tf.Session() as sess:
    print(sess.run(a))
    print(sess.run(tf.shape(masks)))
    print(sess.run(masks))

Is there a simpler method to achieve this ?

Can I use function tf.gather or tf.gather_nd to achieve this ?
Many thanks!

Body:
Another method use tf.gather_nd:

import tensorflow as tf
import numpy as np

a = tf.cast(tf.constant(np.reshape(np.arange(60), (3,2,2,5))), tf.int32)
idx = tf.range(tf.shape(a)[0])
idx2 = tf.constant([0,1,0])
indices = tf.stack([idx, idx2], axis=1)
a = tf.transpose(a, [0,3,1,2])
masks = tf.gather_nd(a, indices)

with tf.Session() as sess:
    print(sess.run(a))
    print(sess.run(tf.shape(masks)))
    print(sess.run(masks))


问:
PDO bindParam not working in IN binding for sql query
I'm trying to get some videos according to some attributes (age, year, countries). For some reason, even though I'm binding parameters to the query properly and have specified the query properly (u.country NOT IN ($countries_count)), I still get results for the country = U.S.A. Is there something work with my bindParam. Please Help.

```<code><?php
    $parameters = json_decode(file_get_contents('php://input'), true);
    $age = $parameters["age"];
    $year = $parameters["year"];
    $countries = sizeof($parameters["countries"]) == 0 ? array("0") : $parameters["countries"];
    $countries_count = implode(",", array_fill(0, sizeof($countries), "?"));

    $sql = "SELECT
                v.title, u.name
            FROM
                video AS v JOIN user AS u ON v.id_user = u.id
            WHERE
                u.age <= ? AND YEAR(v.upload_date) >= ? AND
                u.country NOT IN ($countries_count);";

    $connection = new PDO("mysql:host=localhost;dbname=data_base", "root", "");
    $statement = $connection->prepare($sql);
    $statement->bindParam(1, $age, PDO::PARAM_INT);
    $statement->bindParam(2, $year, PDO::PARAM_INT);
    foreach ($countries as $k => $x) {
        $statement->bindParam($k+3, $x, PDO::PARAM_STR);
    }
    $statement->execute();
    echo json_encode($statement->fetchAll());
?>
</code>```

答:
Change bindParam to bindValue

If you want to use bindParam, change your sql to

```<code>u.age <= :age and
YEAR(v.upload_date) >= :year
...
</code>```

Then bind param:

```<code>->bindParam(':age', $age)
->bindParam(':year', $year)
</code>```

Body:
I'm trying to get some videos according to some attributes (age, year, countries). For some reason, even though I'm binding parameters to the query properly and have specified the query properly (u.country NOT IN ($countries_count)), I still get results for the country = U.S.A. Is there something work with my bindParam. Please Help.

<?php
    $parameters = json_decode(file_get_contents('php://input'), true);
    $age = $parameters["age"];
    $year = $parameters["year"];
    $countries = sizeof($parameters["countries"]) == 0 ? array("0") : $parameters["countries"];
    $countries_count = implode(",", array_fill(0, sizeof($countries), "?"));

    $sql = "SELECT
                v.title, u.name
            FROM
                video AS v JOIN user AS u ON v.id_user = u.id
            WHERE
                u.age <= ? AND YEAR(v.upload_date) >= ? AND
                u.country NOT IN ($countries_count);";

    $connection = new PDO("mysql:host=localhost;dbname=data_base", "root", "");
    $statement = $connection->prepare($sql);
    $statement->bindParam(1, $age, PDO::PARAM_INT);
    $statement->bindParam(2, $year, PDO::PARAM_INT);
    foreach ($countries as $k => $x) {
        $statement->bindParam($k+3, $x, PDO::PARAM_STR);
    }
    $statement->execute();
    echo json_encode($statement->fetchAll());
?>

Body:
Change bindParam to bindValue

If you want to use bindParam, change your sql to

u.age <= :age and
YEAR(v.upload_date) >= :year
...

Then bind param:

->bindParam(':age', $age)
->bindParam(':year', $year)


问:
Ingress vs Load Balancer
I am quite confused about the roles of Ingress and Load Balancer in Kubernetes.

As far as I understand Ingress is used to map incoming traffic from the internet to the services running in the cluster.

The role of load balancer is to forward traffic to a host. In that regard how does ingress differ from load balancer? Also what is the concept of load balancer inside kubernetes as compared to Amazon ELB and ALB?

答: In simple words, load balancer distributes the requests among multiple backend services (of same type) whereas ingress is more like an API gateway (reverse proxy) which routes the request to a specific backend service based on, for instance, the URL.</p>

Title: Ingress vs Load Balancer