问:
Databinding a ObservableCollection<T> in MVVM
I have a ListView with a Datatemplate that holds a list of Movies. It is databinded to a ObservableColection but whenever I edit the Movie.Name it does not update the ListView even though "Name" is called in my PropertyChangedEventHandler is called with "Name".

I add 2 "Movie"s to my collection in my initializer and these are shown correct (Klovn the Movie, Taken)

So when I click Edit it should change the text of the selected movie and change the Name of it to "Test" and is is changed but the change is not shown in the ListView but if I output Collection with a foreach then Name is Test.

View.xaml

<Window x:Class="MovieDB3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="File">
                <MenuItem Header="Edit" Click="MenuEditClick"/>
            </MenuItem>
        </Menu>
        <Grid DockPanel.Dock="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <ListView VerticalAlignment="Stretch" Name="ListViewMovies" ItemsSource="{Binding Path=Collection}" IsSynchronizedWithCurrentItem="True" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <WrapPanel>
                            <TextBlock Text="{Binding Path=Name}"/>
                        </WrapPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </DockPanel>
</Window>
```

<p>View.cs</p>

```using System;
using System.Windows;
using MovieDB3.Models;
using MovieDB3.ViewModels;

namespace MovieDB3
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        private MainViewModel MVM;
        public MainWindow()
        {
            InitializeComponent();
            MVM = new MainViewModel();
            DataContext = MVM;
        }

        private void MenuEditClick(object sender, RoutedEventArgs e)
        {
            MVM.setMovieName((Movie)ListViewMovies.SelectedItem, "test");
        }
    }
}
```

<p>The ViewModel</p>

```using System;
using System.ComponentModel;
using MovieDB3.Models;
using System.Collections.ObjectModel;

namespace MovieDB3.ViewModels
{
    class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Movie> Collection {get; set;}

        public MainViewModel()
        {
            Collection = new ObservableCollection<Movie>();

            //Test kode
            Movie movie = new Movie();
            movie.Name = "Klovn The Movie";
            Collection.Add(movie);
            movie = new Movie();
            movie.Name = "Taken";
            Collection.Add(movie);
        }

        public void setMovieName(Movie movie, string newName)
        {
            //movie.Name = newName;
            Console.WriteLine("CurrentName: " + movie.Name);
            int i = Collection.IndexOf(movie);
            Collection[i].Name = newName;
            Console.WriteLine("NewName: " + movie.Name);
            NotifyPropertyChanged("Name");
        }

        public void setMovieName(string currentName, string newName)
        {
            foreach (Movie movie in Collection)
            {
                if (movie.Name.Equals(currentName))
                {
                    movie.Name = newName;
                    NotifyPropertyChanged("Name");
                    return;
                }
            }
        }

        //public string MovieName
        //{
        //    set
        //    {

        //        NotifyPropertyChanged("MovieName");
        //    }
        //}

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}
```

<p>Movie.cs</p>

```using System;

namespace MovieDB3.Models
{
    class Movie
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public double Rating { get; set; }
        public DateTime Release { get; set; }
        public TimeSpan Runtime { get; set; }
        public String Trailer { get; set; }
    }
}
```

答: I think the Movie itself needs to implement INotifyPropertyChanged.  You are notifying via the wrong object (the viewmodel).</p>

Body:
I have a ListView with a Datatemplate that holds a list of Movies. It is databinded to a ObservableColection but whenever I edit the Movie.Name it does not update the ListView even though "Name" is called in my PropertyChangedEventHandler is called with "Name".

I add 2 "Movie"s to my collection in my initializer and these are shown correct (Klovn the Movie, Taken)

So when I click Edit it should change the text of the selected movie and change the Name of it to "Test" and is is changed but the change is not shown in the ListView but if I output Collection with a foreach then Name is Test.

View.xaml

<Window x:Class="MovieDB3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="File">
                <MenuItem Header="Edit" Click="MenuEditClick"/>
            </MenuItem>
        </Menu>
        <Grid DockPanel.Dock="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <ListView VerticalAlignment="Stretch" Name="ListViewMovies" ItemsSource="{Binding Path=Collection}" IsSynchronizedWithCurrentItem="True" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <WrapPanel>
                            <TextBlock Text="{Binding Path=Name}"/>
                        </WrapPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </DockPanel>
</Window>

View.cs

using System;
using System.Windows;
using MovieDB3.Models;
using MovieDB3.ViewModels;

namespace MovieDB3
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        private MainViewModel MVM;
        public MainWindow()
        {
            InitializeComponent();
            MVM = new MainViewModel();
            DataContext = MVM;
        }

        private void MenuEditClick(object sender, RoutedEventArgs e)
        {
            MVM.setMovieName((Movie)ListViewMovies.SelectedItem, "test");
        }
    }
}

The ViewModel

using System;
using System.ComponentModel;
using MovieDB3.Models;
using System.Collections.ObjectModel;

namespace MovieDB3.ViewModels
{
    class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Movie> Collection {get; set;}

        public MainViewModel()
        {
            Collection = new ObservableCollection<Movie>();

            //Test kode
            Movie movie = new Movie();
            movie.Name = "Klovn The Movie";
            Collection.Add(movie);
            movie = new Movie();
            movie.Name = "Taken";
            Collection.Add(movie);
        }

        public void setMovieName(Movie movie, string newName)
        {
            //movie.Name = newName;
            Console.WriteLine("CurrentName: " + movie.Name);
            int i = Collection.IndexOf(movie);
            Collection[i].Name = newName;
            Console.WriteLine("NewName: " + movie.Name);
            NotifyPropertyChanged("Name");
        }

        public void setMovieName(string currentName, string newName)
        {
            foreach (Movie movie in Collection)
            {
                if (movie.Name.Equals(currentName))
                {
                    movie.Name = newName;
                    NotifyPropertyChanged("Name");
                    return;
                }
            }
        }

        //public string MovieName
        //{
        //    set
        //    {

        //        NotifyPropertyChanged("MovieName");
        //    }
        //}

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}

Movie.cs

using System;

namespace MovieDB3.Models
{
    class Movie
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public double Rating { get; set; }
        public DateTime Release { get; set; }
        public TimeSpan Runtime { get; set; }
        public String Trailer { get; set; }
    }
}


来源: stackexchange

问:
Listview not holding drawable on scroll in choice mode "CHOICE_MODE_MULTIPLE"
I am trying to multi-select list-view by setting drawable in OnItemClickListener,but when I scroll the list-view selected items loses drawable which I have changed on listview.OnitemClickListener in ItemChecked method.

What all I have tried :

1.Using xml selector in drawable

2.Tried changing drawable of selecteditems in custom adapter.

None of the above is working neither any of solution on stackoverflow.

Here is my adapter:

```<code>public class QuestionsOptionsAdapterMultipleSelectionLV extends BaseAdapter {
    Context context;
    ArrayList<QuestionOptionsModel> items;
    String which;
    CollegepondSandbox cs;
    ArrayList<String> arr;
    boolean isTouch = false;
    int positionselected;
    QuestionsOptionsAdapterMultipleSelectionLV adapter1;

 public QuestionsOptionsAdapterMultipleSelectionLV(Context context,
        ArrayList<QuestionOptionsModel> items) {
        this.context = context;
        this.items = items;
        this.which = which;
        this.arr = arr;
        cs = new CollegepondSandbox();

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
       // positionselected =items.indexOf(items.get(position));
        return items.indexOf(items.get(position));
    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup
    parent) {
            if(convertView==null){
        LayoutInflater inflater = (LayoutInflater)
    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        convertView = inflater.inflate(R.layout.custom_options_multiple,
     null);

        WebView tvOptiontext;
        ImageView ivOption;

        LinearLayout llOptionsMultiple;

        ivOption = (ImageView) convertView.findViewById(R.id.cbOption);
        tvOptiontext = (WebView) convertView.findViewById(R.id.tvOptiontext);
        llOptionsMultiple = (LinearLayout) convertView.findViewById(R.id.llOptionsMultiple);
        tvOptiontext.loadData(items.get(position).QOption, "text/html", "utf-8");

        return convertView;
        }
       }
</code>```

here is my OnItemClickListener:

```<code>  lvOption.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            lvOption.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(final AdapterView<?> parent, View view, int position, long id) {

                    ivOption = (ImageView) view.findViewById(R.id.cbOption);

                       if (lvOption.isItemChecked(position)) {
                            ivOption.setImageResource(R.drawable.tick_2);
       multipleSelectedIDs.add(answersal.get(position).QIsCorrect);
                        } else {
                            ivOption.setImageResource(R.drawable.tick_1);
      multipleSelectedIDs.remove(answersal.get(position).QIsCorrect);
                        }
                });
</code>```

答:
Found a similar issue on stackoverflow @Shaiful and modified as per my needs.

Steps:

1.Store the positions as string in Arraylist

2.pass the arraylist to adapter.

3.Change drawable in adapter and not in activity as show in code below:

Changes in listview.OnItemClick in activity :

```<code>  if (lvOption.isItemChecked(position)) {
                        multipleSelectedIDs.add(answersal.get(position).QIsCorrect);
                        selected.add(String.valueOf(position));
                    } else {
                        multipleSelectedIDs.remove(answersal.get(position).QIsCorrect);
                        selected.remove(String.valueOf(position));
                    }
                    adapterMultipleListview.setSelectedDrawable(selected);
</code>```

Now changes in adapter :

```<code>//add this method in adapter
 public void setSelectedDrawable(ArrayList<String> ind) {
    selectedIndex = ind;
    notifyDataSetChanged();
}
//change drawable in getview() method
 if (selectedIndex.contains(String.valueOf(position))) {
        ivOption.setBackgroundResource(R.drawable.tick_2);
    } else {
        ivOption.setBackgroundResource(R.drawable.tick_1);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to multi-select list-view by setting drawable in OnItemClickListener,but when I scroll the list-view selected items loses drawable which I have changed on listview.OnitemClickListener in ItemChecked method.

What all I have tried :

1.Using xml selector in drawable

2.Tried changing drawable of selecteditems in custom adapter.

None of the above is working neither any of solution on stackoverflow.

Here is my adapter:

public class QuestionsOptionsAdapterMultipleSelectionLV extends BaseAdapter {
    Context context;
    ArrayList<QuestionOptionsModel> items;
    String which;
    CollegepondSandbox cs;
    ArrayList<String> arr;
    boolean isTouch = false;
    int positionselected;
    QuestionsOptionsAdapterMultipleSelectionLV adapter1;

 public QuestionsOptionsAdapterMultipleSelectionLV(Context context,
        ArrayList<QuestionOptionsModel> items) {
        this.context = context;
        this.items = items;
        this.which = which;
        this.arr = arr;
        cs = new CollegepondSandbox();

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
       // positionselected =items.indexOf(items.get(position));
        return items.indexOf(items.get(position));
    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup
    parent) {
            if(convertView==null){
        LayoutInflater inflater = (LayoutInflater)
    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        convertView = inflater.inflate(R.layout.custom_options_multiple,
     null);

        WebView tvOptiontext;
        ImageView ivOption;

        LinearLayout llOptionsMultiple;

        ivOption = (ImageView) convertView.findViewById(R.id.cbOption);
        tvOptiontext = (WebView) convertView.findViewById(R.id.tvOptiontext);
        llOptionsMultiple = (LinearLayout) convertView.findViewById(R.id.llOptionsMultiple);
        tvOptiontext.loadData(items.get(position).QOption, "text/html", "utf-8");

        return convertView;
        }
       }

here is my OnItemClickListener:

  lvOption.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            lvOption.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(final AdapterView<?> parent, View view, int position, long id) {

                    ivOption = (ImageView) view.findViewById(R.id.cbOption);

                       if (lvOption.isItemChecked(position)) {
                            ivOption.setImageResource(R.drawable.tick_2);
       multipleSelectedIDs.add(answersal.get(position).QIsCorrect);
                        } else {
                            ivOption.setImageResource(R.drawable.tick_1);
      multipleSelectedIDs.remove(answersal.get(position).QIsCorrect);
                        }
                });

Body:
Found a similar issue on stackoverflow @Shaiful and modified as per my needs.

Steps:

1.Store the positions as string in Arraylist

2.pass the arraylist to adapter.

3.Change drawable in adapter and not in activity as show in code below:

Changes in listview.OnItemClick in activity :

  if (lvOption.isItemChecked(position)) {
                        multipleSelectedIDs.add(answersal.get(position).QIsCorrect);
                        selected.add(String.valueOf(position));
                    } else {
                        multipleSelectedIDs.remove(answersal.get(position).QIsCorrect);
                        selected.remove(String.valueOf(position));
                    }
                    adapterMultipleListview.setSelectedDrawable(selected);

Now changes in adapter :

//add this method in adapter
 public void setSelectedDrawable(ArrayList<String> ind) {
    selectedIndex = ind;
    notifyDataSetChanged();
}
//change drawable in getview() method
 if (selectedIndex.contains(String.valueOf(position))) {
        ivOption.setBackgroundResource(R.drawable.tick_2);
    } else {
        ivOption.setBackgroundResource(R.drawable.tick_1);
    }


问:
Bash-shell Replace separator between specific column
```<code>input file:
cat file1.txt
^AirIfLoadProfile=1$ trafficModelPrb bitRatePerQci=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$ trafficModelPrb bufferStatus=1
^AirIfLoadProfile=1$ trafficModelPrb noOfArtificialUsers=0
^AirIfLoadProfile=1$ trafficModelPrb qciDistSinrHigh=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$ trafficModelPrb qciDistSinrLow=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$ trafficModelPrb qciDistSinrMedium=100 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$ trafficModelPrb ulDlRatioPerQci=0 0 0 0 0 0 0 0 0

output file:
cat file2.txt
^AirIfLoadProfile=1$;trafficModelPrb;bitRatePerQci=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$;trafficModelPrb;bufferStatus=1
^AirIfLoadProfile=1$;trafficModelPrb;noOfArtificialUsers=0
^AirIfLoadProfile=1$;trafficModelPrb;qciDistSinrHigh=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$;trafficModelPrb;qciDistSinrLow=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$;trafficModelPrb;qciDistSinrMedium=100 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$;trafficModelPrb;ulDlRatioPerQci=0 0 0 0 0 0 0 0 0
</code>```

Replace the space separator in column 1 between column 2 , and column 2 between column 3 with semicolon. The file2 is the output .

答:
Following sed may help you in same.

```<code>sed 's/ /;/1;s/ /;/1'   Input_file
</code>```

Where I am substituting the very first space in a line with ;(semi colon) and then again changing the very first space with ;(semi colon) because after first change of space in a line the 2nd space becomes 1st space now so we need to put 1st space only by doing /1 in sed command.

Body:
input file:
cat file1.txt
^AirIfLoadProfile=1$ trafficModelPrb bitRatePerQci=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$ trafficModelPrb bufferStatus=1
^AirIfLoadProfile=1$ trafficModelPrb noOfArtificialUsers=0
^AirIfLoadProfile=1$ trafficModelPrb qciDistSinrHigh=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$ trafficModelPrb qciDistSinrLow=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$ trafficModelPrb qciDistSinrMedium=100 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$ trafficModelPrb ulDlRatioPerQci=0 0 0 0 0 0 0 0 0

output file:
cat file2.txt
^AirIfLoadProfile=1$;trafficModelPrb;bitRatePerQci=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$;trafficModelPrb;bufferStatus=1
^AirIfLoadProfile=1$;trafficModelPrb;noOfArtificialUsers=0
^AirIfLoadProfile=1$;trafficModelPrb;qciDistSinrHigh=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$;trafficModelPrb;qciDistSinrLow=0 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$;trafficModelPrb;qciDistSinrMedium=100 0 0 0 0 0 0 0 0
^AirIfLoadProfile=1$;trafficModelPrb;ulDlRatioPerQci=0 0 0 0 0 0 0 0 0

Replace the space separator in column 1 between column 2 , and column 2 between column 3 with semicolon. The file2 is the output .

Body:
Following sed may help you in same.

sed 's/ /;/1;s/ /;/1'   Input_file

Where I am substituting the very first space in a line with ;(semi colon) and then again changing the very first space with ;(semi colon) because after first change of space in a line the 2nd space becomes 1st space now so we need to put 1st space only by doing /1 in sed command.


问:
How can I convert a number to text in the excel "datatables.js" download
I'm trying to convert a number as text in datatables.js while downloading excel file. If I normally put a single quote ' manually in the excel file before a number it works.. but when I do that programmatically it doesn't.. where I'm doing wrong? The following are my columns declaration;

```<code>"columns": [
{ "data": "ID", "visible": false, "searchable": false },
{
    "data": "ProductCode", "title": 'Product Code', "visible": true, responsivePriority: 1, render: function (data, type, row) {

        if (type === 'export') {

            return "'" + data;
        }
        else {

            return data;
        }
    }
},
...
]
</code>```

This is my button declaration;

```<code>// Initialize Download Button
new $.fn.dataTable.Buttons(table, {

    buttons: [{
        extend: 'excel', text: 'Download Excel', className: 'btn-sm btn-success downloadButton', exportOptions: {
            columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
            orthogonal: 'export'
        }
    }]
});
</code>```

It shows like this '12345 in the downloaded excel file but if I just press F2 (Edit) and press enter excel converts it to the text :(. Any help will be highly appreciable.

答:
I solved this issue by commenting out below code in addrow function in datatable.js file.

// Detect numbers - don't match numbers with leading zeros or a negative

```<code>// anywhere but the start
                //if ( typeof row[i] === 'number' || (
                //      row[i].match &&
                //      $.trim(row[i]).match(/^-?\d+(\.\d+)?$/) &&
                //      ! $.trim(row[i]).match(/^0\d+/) )
                //) {
                //  cell = _createNode( rels, 'c', {
                //      attr: {
                //          t: 'n',
                //          r: cellId
                //      },
                //      children: [
                //          _createNode( rels, 'v', { text: row[i] } )
                //      ]
                //  } );
                //}
                //else {
</code>```

below is the function

```<code> var addRow = function ( row ) {
            currentRow = rowPos+1;
            rowNode = _createNode( rels, "row", { attr: {r:currentRow} } );

            for ( var i=0, ien=row.length ; i<ien ; i++ ) {
                // Concat both the Cell Columns as a letter and the Row of the cell.
                var cellId = createCellPos(i) + '' + currentRow;
                var cell;

                if ( row[i] === null || row[i] === undefined ) {
                    row[i] = '';
                }

                // Detect numbers - don't match numbers with leading zeros or a negative
                // anywhere but the start
                //if ( typeof row[i] === 'number' || (
                //      row[i].match &&
                //      $.trim(row[i]).match(/^-?\d+(\.\d+)?$/) &&
                //      ! $.trim(row[i]).match(/^0\d+/) )
                //) {
                //  cell = _createNode( rels, 'c', {
                //      attr: {
                //          t: 'n',
                //          r: cellId
                //      },
                //      children: [
                //          _createNode( rels, 'v', { text: row[i] } )
                //      ]
                //  } );
                //}
                //else {
                    // Replace non standard characters for text output
                    var text = ! row[i].replace ?
                        row[i] :
                        row[i].replace(/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, '');

                    cell = _createNode( rels, 'c', {
                        attr: {
                            t: 'inlineStr',
                            r: cellId
                        },
                        children:{
                            row: _createNode( rels, 'is', {
                                children: {
                                    row: _createNode( rels, 't', {
                                        text: text
                                    } )
                                }
                            } )
                        }
                    } );
                //}

                rowNode.appendChild( cell );
            }
            relsGet.appendChild(rowNode);
            rowPos++;
        };
</code>```

Body:
I'm trying to convert a number as text in datatables.js while downloading excel file. If I normally put a single quote ' manually in the excel file before a number it works.. but when I do that programmatically it doesn't.. where I'm doing wrong? The following are my columns declaration;

"columns": [
{ "data": "ID", "visible": false, "searchable": false },
{
    "data": "ProductCode", "title": 'Product Code', "visible": true, responsivePriority: 1, render: function (data, type, row) {

        if (type === 'export') {

            return "'" + data;
        }
        else {

            return data;
        }
    }
},
...
]

This is my button declaration;

// Initialize Download Button
new $.fn.dataTable.Buttons(table, {

    buttons: [{
        extend: 'excel', text: 'Download Excel', className: 'btn-sm btn-success downloadButton', exportOptions: {
            columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
            orthogonal: 'export'
        }
    }]
});

It shows like this '12345 in the downloaded excel file but if I just press F2 (Edit) and press enter excel converts it to the text :(. Any help will be highly appreciable.

Body:
I solved this issue by commenting out below code in addrow function in datatable.js file.

// Detect numbers - don't match numbers with leading zeros or a negative

// anywhere but the start
                //if ( typeof row[i] === 'number' || (
                //      row[i].match &&
                //      $.trim(row[i]).match(/^-?\d+(\.\d+)?$/) &&
                //      ! $.trim(row[i]).match(/^0\d+/) )
                //) {
                //  cell = _createNode( rels, 'c', {
                //      attr: {
                //          t: 'n',
                //          r: cellId
                //      },
                //      children: [
                //          _createNode( rels, 'v', { text: row[i] } )
                //      ]
                //  } );
                //}
                //else {

below is the function

 var addRow = function ( row ) {
            currentRow = rowPos+1;
            rowNode = _createNode( rels, "row", { attr: {r:currentRow} } );

            for ( var i=0, ien=row.length ; i<ien ; i++ ) {
                // Concat both the Cell Columns as a letter and the Row of the cell.
                var cellId = createCellPos(i) + '' + currentRow;
                var cell;

                if ( row[i] === null || row[i] === undefined ) {
                    row[i] = '';
                }

                // Detect numbers - don't match numbers with leading zeros or a negative
                // anywhere but the start
                //if ( typeof row[i] === 'number' || (
                //      row[i].match &&
                //      $.trim(row[i]).match(/^-?\d+(\.\d+)?$/) &&
                //      ! $.trim(row[i]).match(/^0\d+/) )
                //) {
                //  cell = _createNode( rels, 'c', {
                //      attr: {
                //          t: 'n',
                //          r: cellId
                //      },
                //      children: [
                //          _createNode( rels, 'v', { text: row[i] } )
                //      ]
                //  } );
                //}
                //else {
                    // Replace non standard characters for text output
                    var text = ! row[i].replace ?
                        row[i] :
                        row[i].replace(/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, '');

                    cell = _createNode( rels, 'c', {
                        attr: {
                            t: 'inlineStr',
                            r: cellId
                        },
                        children:{
                            row: _createNode( rels, 'is', {
                                children: {
                                    row: _createNode( rels, 't', {
                                        text: text
                                    } )
                                }
                            } )
                        }
                    } );
                //}

                rowNode.appendChild( cell );
            }
            relsGet.appendChild(rowNode);
            rowPos++;
        };


问:
Find similar items and order by common tags count
I searched through similar questions but the solutions were for different situations with different tables structures :(

I need to get the list of design_id with similar tags, ordered by entries having the most common tags count first

Tables structures:

```<code>shop_tags (tag_id, tag_name)
shop_tags_link (tag_id, design)
shop_tshirts (design_id, article_id)
</code>```

Let's say I have 4 designs

```<code>design_id 1 tags = red, blue
design_id 2 tags = black, grey
design_id 3 tags = yellow, green
design_id 4 tags = white, red, black
design_id 5 tags = red
</code>```

The input is an array of designs ID :

```<code>$input = array("1", "2");
</code>```

I need to find designs with similar tags and sort them by the common tags count (desc), so if the input is designs 1 and 2 we're looking for designs with tags "red, blue, black, grey" which would give the following result in this order :

design 4, design 5  (excluding the original input designs of course)

Finally, instead of returning the designs ID, I need to find the corresponding article_id from table shop_tshirts with the matching design. What is the best way to do this? Should I do a separate query or another INNER JOIN?

答:
Restating what we have to work with, so that the solution is more obvious:

```<code>+-----------+    +-----------------+    +--------------+
| shop_tags |    | shop_tags_links |    | shop_tshirts |
+-----------+    +-----------------+    +--------------+
| tag_id    |----| tag_id          |  /-| design_id    |
| tag_name  |    | design_id       |-/  | article_id   |
+-----------+    +-----------------+    +--------------+

design_id 1 tags = red, blue
design_id 2 tags = black, grey
design_id 3 tags = yellow, green
design_id 4 tags = white, red, black
design_id 5 tags = red

+-----------+   +-----------------+   +--------------+
| shop_tags |   | shop_tags_links |   | shop_tshirts |
+-----------+   +-----------------+   +--------------+
| 1 red     |   |   1  1          |   | 1  ?         |
| 2 blue    |   |   2  1          |   | 2  ?         |
| 3 black   |   |   3  2          |   | 3  ?         |
| 4 grey    |   |   4  2          |   | 4  ?         |
| 5 yellow  |   |   5  3          |   | 5  ?         |
| 6 green   |   |   6  3          |
| 7 white   |   |   7  4          |
|           |   |   1  4          |
                |   3  4          |
                |   1  5          |
</code>```

"find designs with similar tags and sort them by the common tags count (desc)",
  so if the input is designs 1 and 2 we're looking for designs with tags "red, blue, black, grey" which would give the following result in this order :

design 4, design 5 (excluding the original input designs of course)"

This should get you pointed in the right direction.  This is off the top of my head and untested, so it probably needs a little tweaking, but it should cover the main concepts.

```<code>select count(b.tag_id) as mysort, b.design_id, c.article_id
from shop_tags_links as a, shop_tags_links as b inner join shop_tshirts as c on b.design_id=c.design_id
where
    a.design_id IN (?,?) AND
    a.tag_id=b.tag_id AND
    b.design_id NOT IN(?,?)
group by b.design_id
order by mysort desc
</code>```

Body:
I searched through similar questions but the solutions were for different situations with different tables structures :(

I need to get the list of design_id with similar tags, ordered by entries having the most common tags count first

Tables structures:

shop_tags (tag_id, tag_name)
shop_tags_link (tag_id, design)
shop_tshirts (design_id, article_id)

Let's say I have 4 designs

design_id 1 tags = red, blue
design_id 2 tags = black, grey
design_id 3 tags = yellow, green
design_id 4 tags = white, red, black
design_id 5 tags = red

The input is an array of designs ID :

$input = array("1", "2");

I need to find designs with similar tags and sort them by the common tags count (desc), so if the input is designs 1 and 2 we're looking for designs with tags "red, blue, black, grey" which would give the following result in this order :

design 4, design 5  (excluding the original input designs of course)

Finally, instead of returning the designs ID, I need to find the corresponding article_id from table shop_tshirts with the matching design. What is the best way to do this? Should I do a separate query or another INNER JOIN?

Body:
Restating what we have to work with, so that the solution is more obvious:

+-----------+    +-----------------+    +--------------+
| shop_tags |    | shop_tags_links |    | shop_tshirts |
+-----------+    +-----------------+    +--------------+
| tag_id    |----| tag_id          |  /-| design_id    |
| tag_name  |    | design_id       |-/  | article_id   |
+-----------+    +-----------------+    +--------------+

design_id 1 tags = red, blue
design_id 2 tags = black, grey
design_id 3 tags = yellow, green
design_id 4 tags = white, red, black
design_id 5 tags = red

+-----------+   +-----------------+   +--------------+
| shop_tags |   | shop_tags_links |   | shop_tshirts |
+-----------+   +-----------------+   +--------------+
| 1 red     |   |   1  1          |   | 1  ?         |
| 2 blue    |   |   2  1          |   | 2  ?         |
| 3 black   |   |   3  2          |   | 3  ?         |
| 4 grey    |   |   4  2          |   | 4  ?         |
| 5 yellow  |   |   5  3          |   | 5  ?         |
| 6 green   |   |   6  3          |
| 7 white   |   |   7  4          |
|           |   |   1  4          |
                |   3  4          |
                |   1  5          |

"find designs with similar tags and sort them by the common tags count (desc)",
  so if the input is designs 1 and 2 we're looking for designs with tags "red, blue, black, grey" which would give the following result in this order :

design 4, design 5 (excluding the original input designs of course)"

This should get you pointed in the right direction.  This is off the top of my head and untested, so it probably needs a little tweaking, but it should cover the main concepts.

select count(b.tag_id) as mysort, b.design_id, c.article_id
from shop_tags_links as a, shop_tags_links as b inner join shop_tshirts as c on b.design_id=c.design_id
where
    a.design_id IN (?,?) AND
    a.tag_id=b.tag_id AND
    b.design_id NOT IN(?,?)
group by b.design_id
order by mysort desc


问:
Animate application icon in windows phone
I have tried googling for this and came up empty. What I want is a tutorial or example code of how to change my icon on the windows phone like the people application or SMS. For example when you get a new SMS message it puts a number next to the face in the icon. Is there any way for me to do that in my app?</p>

答:
You can update your application's Tile using Push Notifications from a web service registered with a Microsoft Push Notification Service. However, this isn't absolutely necessary. You can even update your tiles without push notifications, by setting a ShellTileSchedule. The minimum update interval is 1 hour, however.
See here.</p>

ContentLicense: CC BY-SA 2.5


问:
How can I change array key for specific array value
I have an multidimensional array like this:

```<code>Position 0: {id=5, name=john}
Position 1: {id=7, name=frank}
Position 2: {id=9, name=tina}
</code>```

What I'm trying to do is:
Change the Position Key (0,1,2) to id value for each one!

```<code>Position 5: {id=5, name=john}
Position 7: {id=7, name=frank}
Position 9: {id=9, name=tina}
</code>```

I tried to use "array_flip" according to PHP Doc. But I did not succeed! But I just found reference for unidimensional arrays. Like this:

```<code><?php
$input = array("oranges", "apples", "pears");
$flipped = array_flip($input);
print_r($flipped);
?>
</code>```

Any idea? Thanks.

答:
A simple oneliner:</p>

```<code>$new_array = array_combine(
    array_column($your_array, 'id'),    // these are keys
    $your_array                         // these are values
);
</code>```

Body:
I have an multidimensional array like this:

Position 0: {id=5, name=john}
Position 1: {id=7, name=frank}
Position 2: {id=9, name=tina}

What I'm trying to do is:
Change the Position Key (0,1,2) to id value for each one!

Position 5: {id=5, name=john}
Position 7: {id=7, name=frank}
Position 9: {id=9, name=tina}

I tried to use "array_flip" according to PHP Doc. But I did not succeed! But I just found reference for unidimensional arrays. Like this:

<?php
$input = array("oranges", "apples", "pears");
$flipped = array_flip($input);
print_r($flipped);
?>

Any idea? Thanks.

Body:
A simple oneliner:

$new_array = array_combine(
    array_column($your_array, 'id'),    // these are keys
    $your_array                         // these are values
);


问:
Java remote debugging - how can I keep debugger listening?
I'm using IntelliJ IDEA to remote debug a Java CLI program with the debugger listening for connections.

This works fine for the first invocation, but the debugger stops listening after the CLI program disconnects. I want the debugger to keep listening since multiple CLI invocations will be made (in sequence, not in parallel) and only one of these will trigger the breakpoint I've set.

Here's my client debug config:

```<code>-agentlib:jdwp=transport=dt_socket,server=n,address=5005,suspend=y
</code>```

Is it possible to keep the debugger listening?

答:
Well since your CLI program terminates, debugger also stops. If you still want to continue debugger session for multiple runs of CLI program, then you can try as below,

Write a wrapper program from which you invoke your CLI program multiple times and debug the wrapper program instead of your CLI program.

Something like this,

```<code>public class Wrapper {
    public static void main(String[] args) {
        YourCLIProgram yp = new YourCLIProgram();
        // First Invocation
        String[] arg1 = { }; // Arguments required for your CLI program
        yp.main(arg1);
        // Second Invocation
        String[] arg2 = { }; // Arguments required for your CLI program
        yp.main(arg2);
        // Third Invocation
        String[] arg3 = { }; // Arguments required for your CLI program
        yp.main(arg3);
        // Fourth Invocation
        String[] arg4 = { }; // Arguments required for your CLI program
        yp.main(arg4);

    }
}
</code>```

I hope it works.

Body:
I'm using IntelliJ IDEA to remote debug a Java CLI program with the debugger listening for connections.

This works fine for the first invocation, but the debugger stops listening after the CLI program disconnects. I want the debugger to keep listening since multiple CLI invocations will be made (in sequence, not in parallel) and only one of these will trigger the breakpoint I've set.

Here's my client debug config:

-agentlib:jdwp=transport=dt_socket,server=n,address=5005,suspend=y

Is it possible to keep the debugger listening?

Body:
Well since your CLI program terminates, debugger also stops. If you still want to continue debugger session for multiple runs of CLI program, then you can try as below,

Write a wrapper program from which you invoke your CLI program multiple times and debug the wrapper program instead of your CLI program.

Something like this,

public class Wrapper {
    public static void main(String[] args) {
        YourCLIProgram yp = new YourCLIProgram();
        // First Invocation
        String[] arg1 = { }; // Arguments required for your CLI program
        yp.main(arg1);
        // Second Invocation
        String[] arg2 = { }; // Arguments required for your CLI program
        yp.main(arg2);
        // Third Invocation
        String[] arg3 = { }; // Arguments required for your CLI program
        yp.main(arg3);
        // Fourth Invocation
        String[] arg4 = { }; // Arguments required for your CLI program
        yp.main(arg4);

    }
}

I hope it works.


问:
Can crawlers update imported tables in AWS Glue?
I'm familiarizing myself with crawlers in AWS Glue. I imported a database catalog from Athena, and would like to crawl the data locations of these tables daily to automatically update their partitions when data is added.

However, my crawlers only seem to create new tables, separate from the ones imported from Athena. They don't seem to update my existing tables. Is there any way to do this? Not seeing any mention of it in their docs.

答:
You may need to add a custom classifier whose job is to classify the data into separate tables in the data catalogue. You are probably using the default classifiers which do not know how to uniquely identify your schema.

What are classifiers: http://docs.aws.amazon.com/glue/latest/dg/add-classifier.html


问:
Site's gone down…cant figure it out :/
Im struggling to find out why my site has gone down. Went to login in after a couple of weeks and my site is showing the following error:

```<code>Fatal error: Uncaught Error: Class 'wpdb' not found in /customers/6/a/c/superhuggable.com/httpd.www/wp-includes/load.php:404 Stack trace: #0 /customers/6/a/c/superhuggable.com/httpd.www/wp-settings.php(106): require_wp_db() #1 /customers/6/a/c/superhuggable.com/httpd.www/wp-config.php(98): require_once('/customers/6/a/...') #2 /customers/6/a/c/superhuggable.com/httpd.www/wp-load.php(37): require_once('/customers/6/a/...') #3 /customers/6/a/c/superhuggable.com/httpd.www/wp-blog-header.php(13): require_once('/customers/6/a/...') #4 /customers/6/a/c/superhuggable.com/httpd.www/index.php(17): require('/customers/6/a/...') #5 {main} thrown in /customers/6/a/c/superhuggable.com/httpd.www/wp-includes/load.php on line 404
</code>```

The domain is superhuggable.com. Im not a professional dev, but can normally get my head round most things, was wondering if you guys could help?

Thank you.

答:
Pretty sure something is wrong with your WordPress core files. Try re-installing the WordPress. Here's how you can do it without losing your existing site data.

Keep the wp-content folder and wp-config.php file in a safe place. And delete everything else from your wordpress installation directory.

Download Wordpress From https://wordpress.org/download/

Extract all files. And Replace wp-content folder and wp-config.php file.

If still doesn't work You may try deactivating all of your plugins and themes via the database. (Here's help)

And also you may try searching guide to fix common wordpress fatal errors.

Happy debugging!

Title: Site's gone down…cant figure it out :/

Body:
Im struggling to find out why my site has gone down. Went to login in after a couple of weeks and my site is showing the following error:

Fatal error: Uncaught Error: Class 'wpdb' not found in /customers/6/a/c/superhuggable.com/httpd.www/wp-includes/load.php:404 Stack trace: #0 /customers/6/a/c/superhuggable.com/httpd.www/wp-settings.php(106): require_wp_db() #1 /customers/6/a/c/superhuggable.com/httpd.www/wp-config.php(98): require_once('/customers/6/a/...') #2 /customers/6/a/c/superhuggable.com/httpd.www/wp-load.php(37): require_once('/customers/6/a/...') #3 /customers/6/a/c/superhuggable.com/httpd.www/wp-blog-header.php(13): require_once('/customers/6/a/...') #4 /customers/6/a/c/superhuggable.com/httpd.www/index.php(17): require('/customers/6/a/...') #5 {main} thrown in /customers/6/a/c/superhuggable.com/httpd.www/wp-includes/load.php on line 404

The domain is superhuggable.com. Im not a professional dev, but can normally get my head round most things, was wondering if you guys could help?

Thank you.


问:
Is there a way to build and run .xcodeproj file from zipped project?
I have an old project that already published on the Appstore a while ago, which is not compatible with the recent iOS 11. Now I want to submit an update to make my App available on the Appstore again, but for some reason I can not find the Xcode project on my computer. The only thing I found on my computer is the zipped project, which I can browse its contents, but there is no "xcodeproj" file within it, and the nib files are not openable as I'm getting "Interface Builder cannot open compiled nibs." error every time I double click on them. Is there a way to rebuild and run my project? instead of starting my project from scratch. Any help will be appreciated. Thanks in advance.

Update: I have this black icon with "exec" within the zipped file, which has no extension, but when I open it with Xcode I get a window with this black image in it, is it the .xcodeproj file?

答: Nib file is just a UI design file. You can use it to design a layout and work with cocoa class. You can't use this project simply with Nib file.</p>


问:
Javascript, Click eventlistener doing the same thing with multiple classes
I'm very new to learning JavaScript, and I've tried to read, and look for similar answers, but everything is pointing at jQuery, which I want to avoid using for this problem. I can't quite work out what is jQuery and what still works in JS...

I have set up a function that can grab the innerHTML but I can't seem to assign it to the same classes, else it'll only work on the first instance, and I tried creating multiple classes but essentially they're all the same button with different values...

```<code>document.querySelector(".b1").addEventListener("click", writeDisp);
document.querySelector(".b2").addEventListener("click", writeDisp);
document.querySelector(".b3").addEventListener("click", writeDisp);
document.querySelector(".b4").addEventListener("click", writeDisp);

function writeDisp() {
  if(dispNum.length < 9){
    if(dispNum === "0") {
      dispNum = this.innerHTML
    } else {
      dispNum = dispNum + this.innerHTML};
      document.querySelector(".display").textContent = dispNum;
    }
  }
}
</code>```

How can I make this more simple. As there are way more .b* classes to add, and I'd rather not have a massive list if possible.

Thanks,

答:
```<code>var class_elem = document.querySelectorAll("button[class^='b']");

function writeDisp(){
  if(dispNum.length < 9){
    if(dispNum === "0"){dispNum = this.innerHTML}else{dispNum = dispNum + this.innerHTML};
    document.querySelector(".display").textContent = dispNum;
  }
}

for (var i = 0; i < class_elem.length; i++) {
    class_elem[i].addEventListener('click', writeDisp, false);
}

//Here your code in javascript only.
</code>```

Body:
I'm very new to learning JavaScript, and I've tried to read, and look for similar answers, but everything is pointing at jQuery, which I want to avoid using for this problem. I can't quite work out what is jQuery and what still works in JS...

I have set up a function that can grab the innerHTML but I can't seem to assign it to the same classes, else it'll only work on the first instance, and I tried creating multiple classes but essentially they're all the same button with different values...

document.querySelector(".b1").addEventListener("click", writeDisp);
document.querySelector(".b2").addEventListener("click", writeDisp);
document.querySelector(".b3").addEventListener("click", writeDisp);
document.querySelector(".b4").addEventListener("click", writeDisp);

function writeDisp() {
  if(dispNum.length < 9){
    if(dispNum === "0") {
      dispNum = this.innerHTML
    } else {
      dispNum = dispNum + this.innerHTML};
      document.querySelector(".display").textContent = dispNum;
    }
  }
}

How can I make this more simple. As there are way more .b* classes to add, and I'd rather not have a massive list if possible.

Thanks,


问:
TS - assign value from a callback function using return
Im getting data of class People array with each person having attendance list as Observable<any[]>.

```<code>// Class person
class Person {
   id: number;
   name: string;
   attendance: Observable<any[]>; // An Observable array
}

// People array (I only use array for simplicity sake)
// NOTE: Every person has a list of attendance
people = Person[] = this.someService.getPeople();
</code>```

Now I'm validating if some of the people may had 0 length of attendance assuming that attendance: Observable<any[]> is always an empty array [] if nothing is found, return false otherwise true to validateAttendance().

```<code>validateAttendance(): boolean {

    // Loop to each person and get attendance list.
    people.forEach(p => {
       // Get the list using a callback function.
       const func = (callback: (data) => void) => {
            // Get attendance using subscribe() method
            p.attendance.subscribe(list => {
                callback(list);
            });
        }

       // An attempt to get the list from a callback function
       // Failed because return is undefined.
       const result = func(res => {
           console.log(res); // Got list of attendance of a given person.
           return res;
       });

       if (result.length <= 0) {
           alert(`${p.name} has no attendance, must be a lazy one please check.`);
           return false;
       }
    });

    return true;
}
</code>```

In order to do that i attempted to create a callback function inside the validateAttendance() method and return the attendance list from it. HOWEVER the result variable is undefined!

It is possible to return a value from a callback function this way?

答:
There are several things wrong with your code:

It is asynchronous, so the function needs to be async too (using Promise)

func() does not return a value, so the result will always be undefined.

You have alert() deep in your code. Are you going to pop up for each person with no attendance? It is better to separate logic and UI.

I have modified your code to the following:

```<code>function validateAttendance(people): Promise<boolean> {
  return getPeopleWithNoAttendance(people)
    .then(peopleWithNoAttendance => {
      if (peopleWithNoAttendance.length > 0) {
        // or loop though them
        alert(`${peopleWithNoAttendance[0].name} has no attendance, must be a lazy one please check.`);
        return false
      }
      return true
    })
}

function getPeopleWithNoAttendance(people) {
  return Promise.all(people.map(person => {
    return new Promise(r => {
      person.attendance.subscribe(r)
    }).then(attendance => {
      return attendance.length <= 0 ? person : undefined
    })
  })).then(listOfPeopleOrUndefined => {
    const listOfPeople = listOfPeopeleOrUndefined.filter(p => p)
    return listOfPeople
  })
}
</code>```

Also changed is having the people variable passed in. If this is a method in a class, feel free to change that.

Body:
Im getting data of class People array with each person having attendance list as Observable<any[]>.

// Class person
class Person {
   id: number;
   name: string;
   attendance: Observable<any[]>; // An Observable array
}

// People array (I only use array for simplicity sake)
// NOTE: Every person has a list of attendance
people = Person[] = this.someService.getPeople();

Now I'm validating if some of the people may had 0 length of attendance assuming that attendance: Observable<any[]> is always an empty array [] if nothing is found, return false otherwise true to validateAttendance().

validateAttendance(): boolean {

    // Loop to each person and get attendance list.
    people.forEach(p => {
       // Get the list using a callback function.
       const func = (callback: (data) => void) => {
            // Get attendance using subscribe() method
            p.attendance.subscribe(list => {
                callback(list);
            });
        }

       // An attempt to get the list from a callback function
       // Failed because return is undefined.
       const result = func(res => {
           console.log(res); // Got list of attendance of a given person.
           return res;
       });

       if (result.length <= 0) {
           alert(`${p.name} has no attendance, must be a lazy one please check.`);
           return false;
       }
    });

    return true;
}

In order to do that i attempted to create a callback function inside the validateAttendance() method and return the attendance list from it. HOWEVER the result variable is undefined!

It is possible to return a value from a callback function this way?

Body:
There are several things wrong with your code:

It is asynchronous, so the function needs to be async too (using Promise)

func() does not return a value, so the result will always be undefined.

You have alert() deep in your code. Are you going to pop up for each person with no attendance? It is better to separate logic and UI.

I have modified your code to the following:

function validateAttendance(people): Promise<boolean> {
  return getPeopleWithNoAttendance(people)
    .then(peopleWithNoAttendance => {
      if (peopleWithNoAttendance.length > 0) {
        // or loop though them
        alert(`${peopleWithNoAttendance[0].name} has no attendance, must be a lazy one please check.`);
        return false
      }
      return true
    })
}

function getPeopleWithNoAttendance(people) {
  return Promise.all(people.map(person => {
    return new Promise(r => {
      person.attendance.subscribe(r)
    }).then(attendance => {
      return attendance.length <= 0 ? person : undefined
    })
  })).then(listOfPeopleOrUndefined => {
    const listOfPeople = listOfPeopeleOrUndefined.filter(p => p)
    return listOfPeople
  })
}

Also changed is having the people variable passed in. If this is a method in a class, feel free to change that.


问:
Converting await in infinite for loop into raw promise.then
As far as I know, async/await is just syntactic sugar over promise.then. Consider this code snippet:

```<code>function sleep(n){
    return new Promise(res => setTimeout(res, n));
}

function* range(n){
    var i = 0;
    while(i < n)    yield i++;
}
</code>```

```<code>async function doStuff(){
    for(let n of range(10)){
        console.log(n);          // print the number
        await sleep(1000);       // wait for 1 second
    }
}
</code>```

async/await makes the code very linear, efficient and easy to understand. One thing to keep in mind is that range does not have to have an actual end for this to work.

The problem now is how this can be rewritten using pre-ES7 era's promise.then. Here's a possible implementation of the same loop:

```<code>function doStuff(){
    return Array.from(range(10)).reduce((acc, ele) => {
        return acc
            .then(() => console.log(ele))
            .then(() => sleep(1000))
    }, Promise.resolve());
}
</code>```

Ignoring the fact that the code isn't quite elegant, the use of Array.from(range(10))

creates an extra array that isn't needed, and

assumes range(10) will end some point in the future.

Doesn't look like a good conversion.

We can also completely reinvent the wheel by using yield as await, but that would make the syntax non ES5-compliant. The goal here is to:

Rewrite using ES5-compliant syntax

Use the promise-returning sleep function

Dynamically chain the sleep promise while allowing the iterator to not have an end

doStuff can be chained:

```<code>doStuff().finally(cleanUp);  // clean up if something failed
</code>```

(Optional) Code should not be overly complex

Any idea?

答:
I've always said that if you need an asynchronous design pattern first look at the async library. In this case, since you're using promises, take a look at the promisified async-q library. The translation is straight forward:</p>

```<code>var n = 0;
async.whilst(() => n < 10, () => {
    n++;
    console.log(n);
    return sleep(1000);
})
</code>```

Body:
As far as I know, async/await is just syntactic sugar over promise.then. Consider this code snippet:

function sleep(n){
    return new Promise(res => setTimeout(res, n));
}

function* range(n){
    var i = 0;
    while(i < n)    yield i++;
}

async function doStuff(){
    for(let n of range(10)){
        console.log(n);          // print the number
        await sleep(1000);       // wait for 1 second
    }
}

async/await makes the code very linear, efficient and easy to understand. One thing to keep in mind is that range does not have to have an actual end for this to work.

The problem now is how this can be rewritten using pre-ES7 era's promise.then. Here's a possible implementation of the same loop:

function doStuff(){
    return Array.from(range(10)).reduce((acc, ele) => {
        return acc
            .then(() => console.log(ele))
            .then(() => sleep(1000))
    }, Promise.resolve());
}

Ignoring the fact that the code isn't quite elegant, the use of Array.from(range(10))

creates an extra array that isn't needed, and

assumes range(10) will end some point in the future.

Doesn't look like a good conversion.

We can also completely reinvent the wheel by using yield as await, but that would make the syntax non ES5-compliant. The goal here is to:

Rewrite using ES5-compliant syntax

Use the promise-returning sleep function

Dynamically chain the sleep promise while allowing the iterator to not have an end

doStuff can be chained:

doStuff().finally(cleanUp);  // clean up if something failed

(Optional) Code should not be overly complex

Any idea?

Body:
I've always said that if you need an asynchronous design pattern first look at the async library. In this case, since you're using promises, take a look at the promisified async-q library. The translation is straight forward:

var n = 0;
async.whilst(() => n < 10, () => {
    n++;
    console.log(n);
    return sleep(1000);
})


问:
How to automatically authenticate windows integrate without login popup?
I wrote an asp.net application with default.aspx. When I hit this page It is asking me windows login popup window. My application should me windows authentication required but it should "Integrated Windows authentication". If I enter login password I am able to see my page.

How can I automatically integrate this windows authentication?

I added below code in web.config. still doesn't work.

```<code><authentication mode="Windows"/>
    <identity impersonate="false"/>
    <authorization>
        <deny users="?"/>
    </authorization>
</code>```

答: I would turn off enable anonymous access and just use the "Integrated Windows authentication".  Also, if you are using FireFox the domain token for the logged in user is not available without some workarounds.  So I would try to stick to using IE if you can too, to make it easier (no pop-ups).</p>

Body:
I wrote an asp.net application with default.aspx. When I hit this page It is asking me windows login popup window. My application should me windows authentication required but it should "Integrated Windows authentication". If I enter login password I am able to see my page.

How can I automatically integrate this windows authentication?

I added below code in web.config. still doesn't work.

<authentication mode="Windows"/>
    <identity impersonate="false"/>
    <authorization>
        <deny users="?"/>
    </authorization>


问:
Hide navigation bar when scrolling web view without navigation controller in iOS
I want the same behaviour as this

How do you hide navigation bar when scrolling in web view if the main view has a navigation bar without a navigationController? Navigation bars don't have the alternative via storyboard to check 'hide bars on swipe'.

This will not work either

```<code>self.navigationController.hidesBarsOnSwipe = true
</code>```

This is what my SB looks like:

Regards

答:
you might try the following solution:

Swift

```<code>import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {
  @IBOutlet var webView:UIWebView!
  @IBOutlet var navigationBar:UINavigationBar!
  @IBOutlet var navigationBarTop:NSLayoutConstraint!
  var lastContentOffset:CGFloat = 0.0

  override func viewDidLoad() {
    super.viewDidLoad()
    self.webView.scrollView.delegate = self
    self.webView.loadRequest(URLRequest(url: URL(string: "https://www.apple.com")!))
  }

  public func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let threshold:CGFloat = 20.0
    let delta = abs(self.lastContentOffset - scrollView.contentOffset.y)
    if delta > threshold || scrollView.contentOffset.y <= 0 {
      if self.lastContentOffset > scrollView.contentOffset.y && self.navigationBarTop.constant < 0 && (self.lastContentOffset < (scrollView.contentSize.height - scrollView.frame.height)) {
        self.showNavBar(true)
      } else if (self.lastContentOffset < scrollView.contentOffset.y && self.navigationBarTop.constant == 0 && (self.lastContentOffset > 0)) {
        self.showNavBar(false)
      }
    }
    self.lastContentOffset = scrollView.contentOffset.y;
  }

  func showNavBar(_ isVisible:Bool) {
    UIView.animate(withDuration: 0.25, animations: {
      self.navigationBarTop.constant = isVisible ? 0 : -(self.navigationBar.frame.height + UIApplication.shared.statusBarFrame.height)
      self.view.setNeedsLayout()
      self.view.layoutIfNeeded()
    })
  }
}
</code>```

full source code here: https://github.com/mugx/AnimatedNavigationBar

Objective-C

```<code>#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIScrollViewDelegate>
@property IBOutlet UIWebView *webView;
@property IBOutlet UINavigationBar *navigationBar;
@property IBOutlet NSLayoutConstraint *navigationBarTop;
@property (nonatomic,assign) CGFloat lastContentOffset;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.scrollView.delegate = self;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]]];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat threshold = 20.0;
    CGFloat delta = fabs(self.lastContentOffset - scrollView.contentOffset.y);
    if (delta > threshold || scrollView.contentOffset.y <= 0) {
        if (self.lastContentOffset > scrollView.contentOffset.y && self.navigationBarTop.constant < 0 && (self.lastContentOffset < (scrollView.contentSize.height - scrollView.frame.size.height))) {
            [self showNavBar:true];
        } else if (self.lastContentOffset < scrollView.contentOffset.y && self.navigationBarTop.constant == 0 && (self.lastContentOffset > 0)) {
            [self showNavBar:false];
        }
    }
    self.lastContentOffset = scrollView.contentOffset.y;
}

- (void)showNavBar:(Boolean)isVisible {
    [UIView animateWithDuration:0.25 animations:^{
        self.navigationBarTop.constant = isVisible ? 0 : -(self.navigationBar.frame.size.height + UIApplication.sharedApplication.statusBarFrame.size.height);
        [self.view setNeedsLayout];
        [self.view layoutIfNeeded];
    }];
}

@end
</code>```

This is the first solution I thought, of course is not drag and drop, you have to link the respective IBOutlet. Anyway the mechanism I think is clear, leverage on scrollView delegate embedded in the webview, then calculate the delta offset in order to show/hide (with a smooth animation) your custom navigation bar. If something is not clear, I'll modify the answer.

Body:
I want the same behaviour as this

How do you hide navigation bar when scrolling in web view if the main view has a navigation bar without a navigationController? Navigation bars don't have the alternative via storyboard to check 'hide bars on swipe'.

This will not work either

self.navigationController.hidesBarsOnSwipe = true

This is what my SB looks like:

Regards

Body:
you might try the following solution:

Swift

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {
  @IBOutlet var webView:UIWebView!
  @IBOutlet var navigationBar:UINavigationBar!
  @IBOutlet var navigationBarTop:NSLayoutConstraint!
  var lastContentOffset:CGFloat = 0.0

  override func viewDidLoad() {
    super.viewDidLoad()
    self.webView.scrollView.delegate = self
    self.webView.loadRequest(URLRequest(url: URL(string: "https://www.apple.com")!))
  }

  public func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let threshold:CGFloat = 20.0
    let delta = abs(self.lastContentOffset - scrollView.contentOffset.y)
    if delta > threshold || scrollView.contentOffset.y <= 0 {
      if self.lastContentOffset > scrollView.contentOffset.y && self.navigationBarTop.constant < 0 && (self.lastContentOffset < (scrollView.contentSize.height - scrollView.frame.height)) {
        self.showNavBar(true)
      } else if (self.lastContentOffset < scrollView.contentOffset.y && self.navigationBarTop.constant == 0 && (self.lastContentOffset > 0)) {
        self.showNavBar(false)
      }
    }
    self.lastContentOffset = scrollView.contentOffset.y;
  }

  func showNavBar(_ isVisible:Bool) {
    UIView.animate(withDuration: 0.25, animations: {
      self.navigationBarTop.constant = isVisible ? 0 : -(self.navigationBar.frame.height + UIApplication.shared.statusBarFrame.height)
      self.view.setNeedsLayout()
      self.view.layoutIfNeeded()
    })
  }
}

full source code here: https://github.com/mugx/AnimatedNavigationBar

Objective-C

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIScrollViewDelegate>
@property IBOutlet UIWebView *webView;
@property IBOutlet UINavigationBar *navigationBar;
@property IBOutlet NSLayoutConstraint *navigationBarTop;
@property (nonatomic,assign) CGFloat lastContentOffset;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.scrollView.delegate = self;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]]];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat threshold = 20.0;
    CGFloat delta = fabs(self.lastContentOffset - scrollView.contentOffset.y);
    if (delta > threshold || scrollView.contentOffset.y <= 0) {
        if (self.lastContentOffset > scrollView.contentOffset.y && self.navigationBarTop.constant < 0 && (self.lastContentOffset < (scrollView.contentSize.height - scrollView.frame.size.height))) {
            [self showNavBar:true];
        } else if (self.lastContentOffset < scrollView.contentOffset.y && self.navigationBarTop.constant == 0 && (self.lastContentOffset > 0)) {
            [self showNavBar:false];
        }
    }
    self.lastContentOffset = scrollView.contentOffset.y;
}

- (void)showNavBar:(Boolean)isVisible {
    [UIView animateWithDuration:0.25 animations:^{
        self.navigationBarTop.constant = isVisible ? 0 : -(self.navigationBar.frame.size.height + UIApplication.sharedApplication.statusBarFrame.size.height);
        [self.view setNeedsLayout];
        [self.view layoutIfNeeded];
    }];
}

@end

This is the first solution I thought, of course is not drag and drop, you have to link the respective IBOutlet. Anyway the mechanism I think is clear, leverage on scrollView delegate embedded in the webview, then calculate the delta offset in order to show/hide (with a smooth animation) your custom navigation bar. If something is not clear, I'll modify the answer.


问:
Excel VBA "else" statement counting wrongly
I have created an "If ElseIf Else" statement that will count the strings in a strings. It does count the keywords/strings that I want to be counted but it is counting the "others"/ Else items wrongly. As shown below highlighted in red, I should only have 6 strings that should be labelled as "others" but it counted as 8. It is a total of 18 rows but on the total results it counted it as 20.
I am newby in VBA and needing experts advise. Thank you.

```<code>Option Compare Text

Public Sub Keywords()

Dim row_number As Long
Dim count_of_corp_or_windows As Long
Dim count_of_mcafee As Long
Dim count_of_token As Long
Dim count_of_host_or_ipass As Long
Dim count_of_others As Long
Dim count_of_X As Long
Dim count_of_all As Long
Dim items As Variant

row_number = 0
count_of_corp_or_windows = 0
count_of_mcafee = 0
count_of_token = 0
count_of_host_or_ipass = 0
count_of_X = 0
count_of_others = 0
count_of_all = 0
Do

row_number = row_number + 1
items = Sheets("LoginPassword").Range("N" & row_number)
    If InStr(items, "corp") Or InStr(items, "windows") Then
        count_of_corp_or_windows = count_of_corp_or_windows + 1
    ElseIf InStr(items, "mcafee") Then
        count_of_mcafee = count_of_mcafee + 1
    ElseIf InStr(items, "token") Then
        count_of_token = count_of_token + 1
    ElseIf InStr(items, "host") Or InStr(items, "ipass") Then
        count_of_host_or_ipass = count_of_host_or_ipass + 1
    ElseIf InStr(items, "X A") Then
        count_of_X = count_of_X + 1
    Else:
        count_of_others = count_of_others + 1

    End If

Loop Until items = ""

count_of_all = count_of_corp_or_windows + count_of_mcafee + count_of_token + count_of_host_or_ipass + count_of_X + count_of_others

Range("N2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(3, 0).Value = "Count"
ActiveCell.Offset(4, 0).Value = count_of_corp_or_windows
ActiveCell.Offset(5, 0).Value = count_of_mcafee
ActiveCell.Offset(6, 0).Value = count_of_token
ActiveCell.Offset(7, 0).Value = count_of_host_or_ipass
ActiveCell.Offset(8, 0).Value = count_of_X
ActiveCell.Offset(9, 0).Value = count_of_others
ActiveCell.Offset(11, 0).Value = count_of_all
ActiveCell.Offset(3, 1).Value = "Keywords"
ActiveCell.Offset(4, 1).Value = "Corp or Windows"
ActiveCell.Offset(5, 1).Value = "Mcafee"
ActiveCell.Offset(6, 1).Value = "Token"
ActiveCell.Offset(7, 1).Value = "Host or ipass"
ActiveCell.Offset(8, 1).Value = "X accounts"
ActiveCell.Offset(9, 1).Value = "Others"
ActiveCell.Offset(11, 1).Value = "Total"
ActiveCell.Offset(3, -1).Value = "Percent"
ActiveCell.Offset(4, -1).Value = count_of_corp_or_windows / count_of_all
ActiveCell.Offset(5, -1).Value = count_of_mcafee / count_of_all
ActiveCell.Offset(6, -1).Value = count_of_token / count_of_all
ActiveCell.Offset(7, -1).Value = count_of_host_or_ipass / count_of_all
ActiveCell.Offset(8, -1).Value = count_of_X / count_of_all
ActiveCell.Offset(9, -1).Value = count_of_others / count_of_all
End Sub
</code>```

答:
You should start row_number at 2 instead of 1 because cell N1 contains "Short Description" which you probably do not want to match to anything?

Also you are looping Until a blank cell but the blank cell has already been counted as an "other" cell so this plus the "Short Description" cell probably accounts for the 2 unexpected other cells that are counted. So probably just change row_number = 0 to row_number = 1 and Else: to ElseIf items <> "" then

Body:
I have created an "If ElseIf Else" statement that will count the strings in a strings. It does count the keywords/strings that I want to be counted but it is counting the "others"/ Else items wrongly. As shown below highlighted in red, I should only have 6 strings that should be labelled as "others" but it counted as 8. It is a total of 18 rows but on the total results it counted it as 20.
I am newby in VBA and needing experts advise. Thank you.

Option Compare Text

Public Sub Keywords()

Dim row_number As Long
Dim count_of_corp_or_windows As Long
Dim count_of_mcafee As Long
Dim count_of_token As Long
Dim count_of_host_or_ipass As Long
Dim count_of_others As Long
Dim count_of_X As Long
Dim count_of_all As Long
Dim items As Variant

row_number = 0
count_of_corp_or_windows = 0
count_of_mcafee = 0
count_of_token = 0
count_of_host_or_ipass = 0
count_of_X = 0
count_of_others = 0
count_of_all = 0
Do

row_number = row_number + 1
items = Sheets("LoginPassword").Range("N" & row_number)
    If InStr(items, "corp") Or InStr(items, "windows") Then
        count_of_corp_or_windows = count_of_corp_or_windows + 1
    ElseIf InStr(items, "mcafee") Then
        count_of_mcafee = count_of_mcafee + 1
    ElseIf InStr(items, "token") Then
        count_of_token = count_of_token + 1
    ElseIf InStr(items, "host") Or InStr(items, "ipass") Then
        count_of_host_or_ipass = count_of_host_or_ipass + 1
    ElseIf InStr(items, "X A") Then
        count_of_X = count_of_X + 1
    Else:
        count_of_others = count_of_others + 1

    End If

Loop Until items = ""

count_of_all = count_of_corp_or_windows + count_of_mcafee + count_of_token + count_of_host_or_ipass + count_of_X + count_of_others

Range("N2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(3, 0).Value = "Count"
ActiveCell.Offset(4, 0).Value = count_of_corp_or_windows
ActiveCell.Offset(5, 0).Value = count_of_mcafee
ActiveCell.Offset(6, 0).Value = count_of_token
ActiveCell.Offset(7, 0).Value = count_of_host_or_ipass
ActiveCell.Offset(8, 0).Value = count_of_X
ActiveCell.Offset(9, 0).Value = count_of_others
ActiveCell.Offset(11, 0).Value = count_of_all
ActiveCell.Offset(3, 1).Value = "Keywords"
ActiveCell.Offset(4, 1).Value = "Corp or Windows"
ActiveCell.Offset(5, 1).Value = "Mcafee"
ActiveCell.Offset(6, 1).Value = "Token"
ActiveCell.Offset(7, 1).Value = "Host or ipass"
ActiveCell.Offset(8, 1).Value = "X accounts"
ActiveCell.Offset(9, 1).Value = "Others"
ActiveCell.Offset(11, 1).Value = "Total"
ActiveCell.Offset(3, -1).Value = "Percent"
ActiveCell.Offset(4, -1).Value = count_of_corp_or_windows / count_of_all
ActiveCell.Offset(5, -1).Value = count_of_mcafee / count_of_all
ActiveCell.Offset(6, -1).Value = count_of_token / count_of_all
ActiveCell.Offset(7, -1).Value = count_of_host_or_ipass / count_of_all
ActiveCell.Offset(8, -1).Value = count_of_X / count_of_all
ActiveCell.Offset(9, -1).Value = count_of_others / count_of_all
End Sub


问:
Check overflow with Z3
I'm new to Z3 and I was checking the online python tutorial.

Then I thought I could check overflow behavior in BitVecs.

I wrote this code:

```<code>x = BitVec('x', 3)
y = Int('y')

solve(BV2Int(x) == y, Not(BV2Int(x + 1) == (y + 1)))
</code>```

and I was expecting [y = 7, x = 7] (i.e. when values are equal but successors are not because x + 1 will be 0 and y + 1 will be 8)

But Z3 answers [y = 0, x = 0].

What am I doing wrong?

答: For others who are concerned by this, this appears to have been solved at some point. I just re-ran this example with the latest version of z3 (a few years after initial post), and it does return 7,7.</p>

Title: Check overflow with Z3

Body:
I'm new to Z3 and I was checking the online python tutorial.

Then I thought I could check overflow behavior in BitVecs.

I wrote this code:

x = BitVec('x', 3)
y = Int('y')

solve(BV2Int(x) == y, Not(BV2Int(x + 1) == (y + 1)))

and I was expecting [y = 7, x = 7] (i.e. when values are equal but successors are not because x + 1 will be 0 and y + 1 will be 8)

But Z3 answers [y = 0, x = 0].

What am I doing wrong?


问:
Please explain the output of below program
Just run this program and explain me output of last line why it prints "g" instead of "f". Here my intention is to know why it is showing previous functions return value? </p>

```<code>#include <iostream>
#include <string>

std::string f() {
  return "f";
}

std::string g() {
  return "g";
}

int main() {
  const char * s = f().c_str();
  std::cout << "s = " << s << std::endl;
  std::cout << "g() = " << g() << std::endl;
  std::cout << "s = " << s << std::endl;
}
</code>```

答:
That is because you are relying on a temporary value generated by "f().c_str()".The value set is not extended in the future calls to your char array i.e. s rather contains garbage since it has become dangling.
Moreover it doesnt necessarily print 'g' always.</p>

Body:
Just run this program and explain me output of last line why it prints "g" instead of "f". Here my intention is to know why it is showing previous functions return value?

#include <iostream>
#include <string>

std::string f() {
  return "f";
}

std::string g() {
  return "g";
}

int main() {
  const char * s = f().c_str();
  std::cout << "s = " << s << std::endl;
  std::cout << "g() = " << g() << std::endl;
  std::cout << "s = " << s << std::endl;
}


问:
caching - RAM access times
Consider two loops over an array:

```<code>int *arr = new int[1024 * 1024];
// Loop1
for (int i = 0; i < n; i++) arr[i] *= 3;
// Loop2
for (int i = 0; i < n; i += 16) arr[i] *= 3;
</code>```

As they both are O(n) in big O notation, however, they have the same number of RAM access. i.e. same number of cache misses.

Why would they have the same number of RAM access? Wouldn't loop 2 has less RAM access according to after each visit i is incremented by 16?

答: Cache is always accessed / managed with the granularity of a line. There will be more than one element in a cache line. I think your cache line can hold 16 elements or more and hence one RAM access will load all the adjacent elements to cache and further RAM access is not required for the next 16 bytes.</p>

Title: caching - RAM access times

Body:
Consider two loops over an array:

int *arr = new int[1024 * 1024];
// Loop1
for (int i = 0; i < n; i++) arr[i] *= 3;
// Loop2
for (int i = 0; i < n; i += 16) arr[i] *= 3;

As they both are O(n) in big O notation, however, they have the same number of RAM access. i.e. same number of cache misses.

Why would they have the same number of RAM access? Wouldn't loop 2 has less RAM access according to after each visit i is incremented by 16?


问:
Scenarios where automated testing is unhelpful
What are some situations where unit testing and TDD and the like are more trouble than they're worth?

Some things I've come up with are:

When generating test data is tricky: Sometimes, being able to come up with valid, non trivial test data is a challenge in itself.

When the only practical way of verifying correctness of the code is to run it.

When you're testing visual elements of the design.

What are some other cases?

答:
I'm not sure that it's ever unhelpful.  In some cases, it may be more difficult and you may choose not to use it -- in the case of the visual layout of your UI, for instance.  There may also be times when it is wasted effort -- for example, unit testing designer-generated code or frameworks not written by you.  Generating data shouldn't be an impediment to unit testing. Your tests should be small enough and well-focused enough that you don't typically need to generate an entire dataset for any single test, so mocking is a very useful technique in these situations.  If I find myself mocking the same things over and over I will sometimes coalesce it into a fake database class that all of the tests can rely on.

Neither unit testing nor running your code will verify its correctness.  Unit testing can help eliminate bugs, especially with TDD, and make sure that bugs that are found are fixed.  If you need to make sure that your code is correct, you'll need to apply different, logic-based techniques to prove correctness.  These are outside the scope of unit testing.

OwnerDisplayName: Shalmanese

OwnerDisplayName: tvanfosson


问:
How to add onload event to a div element
How do you add an onload event to an element?

Can I use:

```<code><div onload="oQuickReply.swap();" ></div>
</code>```

for this?

答:
I had the same question and was trying to get a Div to load a scroll script, using onload or load. The problem I found was that it would always work before the Div could open, not during or after, so it wouldn't really work.

Then I came up with this as a work around.

```<code><body>

<span onmouseover="window.scrollTo(0, document.body.scrollHeight);"
onmouseout="window.scrollTo(0, document.body.scrollHeight);">

<div id="">
</div>

<a href="" onclick="window.scrollTo(0, document.body.scrollHeight);">Link to open Div</a>

</span>
</body>
</code>```

I placed the Div inside a Span and gave the Span two events, a mouseover and a mouseout. Then below that Div, I placed a link to open the Div, and gave that link an event for onclick. All events the exact same, to make the page scroll down to bottom of page. Now when the button to open the Div is clicked, the page will jump down part way, and the Div will open above the button, causing the mouseover and mouseout events to help push the scroll down script. Then any movement of the mouse at that point will push the script one last time.

ContentLicense: CC BY-SA 4.0

Body:
How do you add an onload event to an element?

Can I use:

for this?

Body:
I had the same question and was trying to get a Div to load a scroll script, using onload or load. The problem I found was that it would always work before the Div could open, not during or after, so it wouldn't really work.

Then I came up with this as a work around.

<body>

<span onmouseover="window.scrollTo(0, document.body.scrollHeight);"
onmouseout="window.scrollTo(0, document.body.scrollHeight);">

<div id="">
</div>

<a href="" onclick="window.scrollTo(0, document.body.scrollHeight);">Link to open Div</a>

</span>
</body>

I placed the Div inside a Span and gave the Span two events, a mouseover and a mouseout. Then below that Div, I placed a link to open the Div, and gave that link an event for onclick. All events the exact same, to make the page scroll down to bottom of page. Now when the button to open the Div is clicked, the page will jump down part way, and the Div will open above the button, causing the mouseover and mouseout events to help push the scroll down script. Then any movement of the mouse at that point will push the script one last time.


答:
If you don't want to use jquery, you can use native document.querySelectorAll API like this

```<code>function writeDisp(){
  if(dispNum.length < 9){
    if(dispNum === "0"){
        dispNum = this.innerHTML
    } else {
        dispNum = dispNum + this.innerHTML
    }
    document.querySelector(".display").textContent = dispNum;
  }
}

// this line will select all html tags that contains a class
// name starting with 'b'
var doms = document.querySelectorAll("[class^=b]");

doms.forEach(function(dom) {
  dom.addEventListener('click', writeDisp);
})
</code>```

Note

querySelectorAll will fetch only those DOM instance in which b* is defined as first class, so in case of multiple class defintion, it will not fetch those DOMs which don't have the desired classname at first. That means if you have a DOM defintion like

, this will be ignored, as here, classname starting with b sits after a class.

Title: Javascript, Click eventlistener doing the same thing with multiple classes

Body:
If you don't want to use jquery, you can use native document.querySelectorAll API like this

function writeDisp(){
  if(dispNum.length < 9){
    if(dispNum === "0"){
        dispNum = this.innerHTML
    } else {
        dispNum = dispNum + this.innerHTML
    }
    document.querySelector(".display").textContent = dispNum;
  }
}

// this line will select all html tags that contains a class
// name starting with 'b'
var doms = document.querySelectorAll("[class^=b]");

doms.forEach(function(dom) {
  dom.addEventListener('click', writeDisp);
})

Note

querySelectorAll will fetch only those DOM instance in which b* is defined as first class, so in case of multiple class defintion, it will not fetch those DOMs which don't have the desired classname at first. That means if you have a DOM defintion like <div class="a box"></div>, this will be ignored, as here, classname starting with b sits after a class.


问:
How to Store Log Data in Json format in android?
I am logging events in the android application.

Now I need to store the Log data that is generated by the application in JSON format.How can I do this... any suggestion for this?

this is the code for logging various events of the Android application using AppEventLogger class

```<code>public  class AppEventLogger {

private static final String TAG = AppEventsLogger.class.getCanonicalName();

public void Loginlog(Long id,  boolean result, int failedattempts, int attempts,long eventTime, long mLastInteractionTime) {
    final long eventTime = System.currentTimeMillis();

    logLogin(
        id,
        result,
        failedattempts,
        attempts,
        eventTime,
        mLastInteractionTime);

}

public void Logoutlog(long eventTime ,boolean isLoggedOut,){
    final long eventTime = System.currentTimeMillis();

    logLogout(
        eventTime,
        isLoggedOut);
}
</code>```

答:
```<code>    private void log(Context context,String data) {
        try {
            Log.i("info",data);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("log.txt", Context.MODE_PRIVATE));
            outputStreamWriter.append(data);
            outputStreamWriter.close();
        }
        catch (IOException e) {
            Log.e("Exception", "File write failed: " + e.toString());
        }
    }
</code>```

Body:
I am logging events in the android application.

Now I need to store the Log data that is generated by the application in JSON format.How can I do this... any suggestion for this?

this is the code for logging various events of the Android application using AppEventLogger class

public  class AppEventLogger {

private static final String TAG = AppEventsLogger.class.getCanonicalName();

public void Loginlog(Long id,  boolean result, int failedattempts, int attempts,long eventTime, long mLastInteractionTime) {
    final long eventTime = System.currentTimeMillis();

    logLogin(
        id,
        result,
        failedattempts,
        attempts,
        eventTime,
        mLastInteractionTime);

}

public void Logoutlog(long eventTime ,boolean isLoggedOut,){
    final long eventTime = System.currentTimeMillis();

    logLogout(
        eventTime,
        isLoggedOut);
}


问:
Document Layout for Reports sent to End-Users
I'm pretty new to C# and .NET - I'm in the process of redesigning an outdated Excel/VBA-based quoting & inventory system. Most of the UI and backend is built already.

The problem is that I'm struggling to figure out how best to create and print the documents that will be sent to clients - namely the quotations themselves.

So, my question is thus: what would you recommend as something easy for a newbie to get to grips with to create documents that look something like the one I've included here? Our budget is practically zero (just to make things harder!) I've tried a few free controls floating around on the net but none of them seem to be particularly easy to use (no wysiwyg editor) or they crash (even embedding an excel sheet into the form seems to crash the IDE)

Note that these documents can sometimes spill over to 2 pages or more depending on the hire in question, and we want 'neat' page breaks (i.e. with a footer at the bottom, not looking like it's just been chopped off).

The documents will be output to either a PDF, a printer, or in rare cases HTML (although it's not the end of the world if HTML isn't possible)

Incidentally due to the aforementioned lack of budget, I'm on C# Express 2010, so anything that comes bundled with full VS is probably not going to work unless it's supported by Express.

EDIT: Can't post images as a newbie...basically it's a document with a watermark, address at top left corner, some details in the middle at the top, logo top right, then under that a full-width table of items and associated prices. Then at the bottom a bit of sales spiel, a signature, and a footer. So it's kinda like a 3 x grid with a footer, with a grid nested inside that for the prices etc. Formatted nicely (coloured text in a nice font, rounded corners for headings, nicely spaced out etc etc...)

答: I have found success using SSRS(SQL Server Reporting Services) reports, especially if the data is being stored in a database.  You can still use the reports and display/print them from the VS Report viewer in Winforms/WPF.  Although I am not sure about designer support in VS Express.  </p>