问:
Accessing UserControls in a ViewModel
The View : I have UserControl, which has a TextBox and a Label. When the "Enter" key is down, I want the Label to be updated with the value form the text box. For the sake of this example, I created a CarUserControl. I will be hosting a list of these in an ItemsControl in the MainWindow.

The Model : I have class Car, which will be the model.

The ViewModel : I do not have a ViewModel for the CarUserControl and the Car. I  have one for the MainWindow instead - lets call this the MainViewModel.

I can get the commands propogated from the individual usercontrols to the MainViewModel, but I'm unsure about getting the values from the textboxes in the MainViewModel?

Here are some of the assumptions I'm making from what I`ve read online about MVVM (there are ofcourse some sources which say the assumptions are wrong).

1] Usercontrols should not have a ViewModel.

2] Usercontrols should only expose dependency properties, and not public properties with INotifyChanged or events.

So, the question is, how do I update the label, and access the TextBox value in the MainViewModel.

Here is the test code :

-----CarUserControl.xaml----

```<code><UserControl x:Class="TestMVVM.CarUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:TestMVVM"
             mc:Ignorable="d"
             d:DesignHeight="50" d:DesignWidth="300" x:Name="thisUC">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Label Grid.Column="0">--</Label>
        <TextBox Grid.Column="1" Background="#FFE8D3D3" BorderThickness="0">
            <TextBox.InputBindings>
                <KeyBinding Key="Enter"
                                Command="{Binding KeyDownCommand, ElementName=thisUC}"
                                CommandParameter="{Binding}"/>
            </TextBox.InputBindings>
        </TextBox>
    </Grid>
</UserControl>
</code>```

-----CarUserControl.cs-----

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestMVVM
{
    /// <summary>
    /// Interaction logic for CarUserControl.xaml
    /// The Usercontrol
    /// </summary>
    public partial class CarUserControl : UserControl
    {
        private static readonly DependencyProperty StrValueProperty = DependencyProperty.Register("StrValue", typeof(float), typeof(CarUserControl), new PropertyMetadata(null));
        private static readonly DependencyProperty KeyDownCommandProperty = DependencyProperty.Register("KeyDownCommand", typeof(ICommand), typeof(CarUserControl), new PropertyMetadata(null)); //Enter key down in the text box

        public CarUserControl()
        {
            InitializeComponent();
        }

        public string StrValue
        {
            get { return (string)GetValue(StrValueProperty); }
            set { SetValue(StrValueProperty, value); }
        }

        /// <summary>
        /// "Enter" key down
        /// </summary>
        public ICommand KeyDownCommand
        {
            get { return (ICommand)GetValue(KeyDownCommandProperty); }
            set { SetValue(KeyDownCommandProperty, value); }
        }

    }
}
</code>```

//---The Model--Car.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestMVVM
{
    /// <summary>
    /// A simple model
    /// </summary>
    class Car : INotifyPropertyChanged
    {
        public Car(string name) {
            this.name = name;
        }

        private string name;
        public event PropertyChangedEventHandler PropertyChanged;

        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }
        public void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

    }
}
</code>```

-----Main View Model---

```<code>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace TestMVVM
{
    /// <summary>
    /// The Main View Model
    /// </summary>
    class MainViewModel : INotifyPropertyChanged
    {
        /// <summary>
        /// The main view model
        /// </summary>
        public MainViewModel()
        {
            //Create some test data
            cars = new ObservableCollection<Car>();
            cars.Add(new Car("Audi"));
            cars.Add(new Car("Toyota"));
            cars.Add(new Car("Subaru"));
            cars.Add(new Car("Volvo"));
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private ObservableCollection<Car> cars; //List of tensioner spools
        private ICommand enterDownCommand;

        public ObservableCollection<Car> Cars
        {
            get { return cars; }
            set
            {
                cars = value;
                OnPropertyChanged("Cars");
            }
        }

        public ICommand EnterDownCommand
        {
            get
            {
                if (enterDownCommand == null)
                {
                    enterDownCommand = new RelayMCommand<Car>(OnEnterDownCommand);
                }
                return enterDownCommand;
            }
        }

        /// <summary>
        /// Called when "Enter" key is down.
        /// </summary>
        /// <param name="obj"></param>
        private void OnEnterDownCommand(Car obj)
        {
            //How do I get the text box value here?
            Console.Write(">>"+obj.Name);
        }

        public void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}
</code>```

-----MainWindow---

```<code>  <Window x:Class="TestMVVM.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:TestMVVM"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MainViewModel x:Name ="MainVM"/>
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">
            <Viewbox>
                <ItemsControl ItemsSource="{Binding Cars}" Margin="5" Width="200">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <local:CarUserControl Margin="5"
                                                  KeyDownCommand="{Binding Path=DataContext.EnterDownCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Vertical" IsItemsHost="True" />
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                </ItemsControl>
            </Viewbox>
        </Grid>
    </Grid>

</Window>
</code>```

---Relay Command---

```<code>   using System;
using System.Threading;
using System.Windows.Input;

namespace TestMVVM
{
    /// <summary>
    /// Same as the Relay Command, except this handles an array of generic type <T>
    /// </summary>
    /// <typeparam name="T">Generic type parameter</typeparam>
    public class RelayMCommand<T> : ICommand
    {
        private Predicate<T> _canExecute;
        private Action<T> _execute;

        public RelayMCommand(Action<T> execute, Predicate<T> canExecute = null)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        private void Execute(T parameter)
        {
            _execute(parameter);
        }

        private bool CanExecute(T parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        public bool CanExecute(object parameter)
        {
            return parameter == null ? false : CanExecute((T)parameter);
        }

        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }

        public event EventHandler CanExecuteChanged;

        public void RaiseCanExecuteChanged()
        {
            var temp = Volatile.Read(ref CanExecuteChanged);
            if (temp != null)
            {
                temp(this, new EventArgs());
            }
        }
    }
}
</code>```

答:
A UserControl may inherit its DataContext from a parent window or the current item in an ItemsControl.

So if you bind your ItemsControl to an IEnumerable<Car>, each instance of the CarUserControl can bind directly to the Name property of the corresponding Car object:

```<code><TextBox Text="{Binding Name}"
            Grid.Column="1" Background="#FFE8D3D3" BorderThickness="0">
    <TextBox.InputBindings>
        <KeyBinding Key="Enter"
                    Command="{Binding KeyDownCommand, ElementName=thisUC}"
                    CommandParameter="{Binding}"/>
    </TextBox.InputBindings>
</TextBox>
</code>```

This is because the UserControl automatically inherits the DataContext from its parent element which is the corresponding Car object in the ItemsControl in this case.

Title: Accessing UserControls in a ViewModel

Body:
The View : I have UserControl, which has a TextBox and a Label. When the "Enter" key is down, I want the Label to be updated with the value form the text box. For the sake of this example, I created a CarUserControl. I will be hosting a list of these in an ItemsControl in the MainWindow.

The Model : I have class Car, which will be the model.

The ViewModel : I do not have a ViewModel for the CarUserControl and the Car. I  have one for the MainWindow instead - lets call this the MainViewModel.

I can get the commands propogated from the individual usercontrols to the MainViewModel, but I'm unsure about getting the values from the textboxes in the MainViewModel?

Here are some of the assumptions I'm making from what I`ve read online about MVVM (there are ofcourse some sources which say the assumptions are wrong).

1] Usercontrols should not have a ViewModel.

2] Usercontrols should only expose dependency properties, and not public properties with INotifyChanged or events.

So, the question is, how do I update the label, and access the TextBox value in the MainViewModel.

Here is the test code :

-----CarUserControl.xaml----

<UserControl x:Class="TestMVVM.CarUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:TestMVVM"
             mc:Ignorable="d"
             d:DesignHeight="50" d:DesignWidth="300" x:Name="thisUC">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        --
        <TextBox Grid.Column="1" Background="#FFE8D3D3" BorderThickness="0">
            <TextBox.InputBindings>
                <KeyBinding Key="Enter"
                                Command="{Binding KeyDownCommand, ElementName=thisUC}"
                                CommandParameter="{Binding}"/>
            </TextBox.InputBindings>
        </TextBox>
    </Grid>
</UserControl>

-----CarUserControl.cs-----

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestMVVM
{
    ///
    /// Interaction logic for CarUserControl.xaml
    /// The Usercontrol
    ///
    public partial class CarUserControl : UserControl
    {
        private static readonly DependencyProperty StrValueProperty = DependencyProperty.Register("StrValue", typeof(float), typeof(CarUserControl), new PropertyMetadata(null));
        private static readonly DependencyProperty KeyDownCommandProperty = DependencyProperty.Register("KeyDownCommand", typeof(ICommand), typeof(CarUserControl), new PropertyMetadata(null)); //Enter key down in the text box

        public CarUserControl()
        {
            InitializeComponent();
        }

        public string StrValue
        {
            get { return (string)GetValue(StrValueProperty); }
            set { SetValue(StrValueProperty, value); }
        }

        ///
        /// "Enter" key down
        ///
        public ICommand KeyDownCommand
        {
            get { return (ICommand)GetValue(KeyDownCommandProperty); }
            set { SetValue(KeyDownCommandProperty, value); }
        }

    }
}

//---The Model--Car.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestMVVM
{
    ///
    /// A simple model
    ///
    class Car : INotifyPropertyChanged
    {
        public Car(string name) {
            this.name = name;
        }

        private string name;
        public event PropertyChangedEventHandler PropertyChanged;

        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }
        public void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

    }
}

-----Main View Model---

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace TestMVVM
{
    ///
    /// The Main View Model
    ///
    class MainViewModel : INotifyPropertyChanged
    {
        ///
        /// The main view model
        ///
        public MainViewModel()
        {
            //Create some test data
            cars = new ObservableCollection<Car>();
            cars.Add(new Car("Audi"));
            cars.Add(new Car("Toyota"));
            cars.Add(new Car("Subaru"));
            cars.Add(new Car("Volvo"));
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private ObservableCollection<Car> cars; //List of tensioner spools
        private ICommand enterDownCommand;

        public ObservableCollection<Car> Cars
        {
            get { return cars; }
            set
            {
                cars = value;
                OnPropertyChanged("Cars");
            }
        }

        public ICommand EnterDownCommand
        {
            get
            {
                if (enterDownCommand == null)
                {
                    enterDownCommand = new RelayMCommand<Car>(OnEnterDownCommand);
                }
                return enterDownCommand;
            }
        }

        ///
        /// Called when "Enter" key is down.
        ///
        /// <param name="obj"></param>
        private void OnEnterDownCommand(Car obj)
        {
            //How do I get the text box value here?
            Console.Write(">>"+obj.Name);
        }

        public void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}

-----MainWindow---

  <Window x:Class="TestMVVM.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:TestMVVM"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MainViewModel x:Name ="MainVM"/>
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">
            <Viewbox>
                <ItemsControl ItemsSource="{Binding Cars}" Margin="5" Width="200">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <local:CarUserControl Margin="5"
                                                  KeyDownCommand="{Binding Path=DataContext.EnterDownCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Vertical" IsItemsHost="True" />
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                </ItemsControl>
            </Viewbox>
        </Grid>
    </Grid>

</Window>

---Relay Command---

   using System;
using System.Threading;
using System.Windows.Input;

namespace TestMVVM
{
    ///
    /// Same as the Relay Command, except this handles an array of generic type <T>
    ///
    /// <typeparam name="T">Generic type parameter</typeparam>
    public class RelayMCommand<T> : ICommand
    {
        private Predicate<T> _canExecute;
        private Action<T> _execute;

        public RelayMCommand(Action<T> execute, Predicate<T> canExecute = null)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        private void Execute(T parameter)
        {
            _execute(parameter);
        }

        private bool CanExecute(T parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        public bool CanExecute(object parameter)
        {
            return parameter == null ? false : CanExecute((T)parameter);
        }

        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }

        public event EventHandler CanExecuteChanged;

        public void RaiseCanExecuteChanged()
        {
            var temp = Volatile.Read(ref CanExecuteChanged);
            if (temp != null)
            {
                temp(this, new EventArgs());
            }
        }
    }
}

Body:
A UserControl may inherit its DataContext from a parent window or the current item in an ItemsControl.

So if you bind your ItemsControl to an IEnumerable<Car>, each instance of the CarUserControl can bind directly to the Name property of the corresponding Car object:

<TextBox Text="{Binding Name}"
            Grid.Column="1" Background="#FFE8D3D3" BorderThickness="0">
    <TextBox.InputBindings>
        <KeyBinding Key="Enter"
                    Command="{Binding KeyDownCommand, ElementName=thisUC}"
                    CommandParameter="{Binding}"/>
    </TextBox.InputBindings>
</TextBox>

This is because the UserControl automatically inherits the DataContext from its parent element which is the corresponding Car object in the ItemsControl in this case.


来源: stackexchange

问:
ASP.NET MVC 2: Emulating eBay Postback
Below is an image of the sections I'm talking about:

What I'm doing is very similar to eBay:

1) a form at the top for "search terms" and then a category.

2) filters on the left that a user can click to refine the search even further.

3) sorting those results.

I played with eBay a bit and it looks to me like they are posting back every time a filter (box on the left) is clicked, or when they sort the results. Do they then store a copy of all the "settings" used to display the page in the form and use that to post back on a submit click?

How can I emulate this functionality? I don't like the idea of wrapping an entire page in a form element... it seems dirty. Should I use jQuery to collect all of the user input and then somehow pass it along?

答:
I'm not sure how eBay does it, but if it were me, I'd have some javascript object that keeps track of all the search options on the page. Each of the elements you've highlighted would fire an event that would cause my javascript object to update this information, send it via AJAX to a controller action, and update the results area with the changes.

That's a somewhat simplified version of events, but hopefully it can put you on the right track.

ContentLicense: CC BY-SA 2.5

Title: ASP.NET MVC 2: Emulating eBay Postback


问:
Accessing Django Admin with requests library
I'm trying to access to my Django Admin through requests library.

r1 = requests.get('page.com/admin/')

r_token = r.cookies['csrftoken']

req_cookies = {'csrftoken': '{}'.format(r_token)} # Cookie for the request

req_data = {'csrfmiddlewaretoken': '{}'.format(r_token),'username':'my_username','password':'my_password'} # Data for request

res = requests.post('page.com/admin/', cookies=req_cookies, data=req_data)

At this point, I should have accessed to my admin page but it keeps asking for my credentials. Any idea?

答: The admin login page is /admin/login/. If you post to /admin/ you'll get redirected to /admin/login/.

ContentLicense: CC BY-SA 3.0


问:
Where is Web.config during development?
When I publish my ASP .Net Core 1.1 MVC web app, I see the Publish folder contain a Web.config file, where I can set stdoutLogEnabled, etc. However, while developing I don't see this file at all - it looks like it's being generated when publishing... How can I therefore set the variables in this file without having to manually edit the file after each publish?

答:
Web.config only makes sense if you host the app on Windows with IIS. You have to manually add it to the project to edit the file's contents or it will be auto-generated:

Documentation:

If you don't have a web.config file in the project when you publish with dotnet publish or with Visual Studio publish, the file is created for you in published output. If you have the file in your project, it's transformed with the correct processPath and arguments to configure the ASP.NET Core Module and moved to published output. The transformation doesn't touch IIS configuration settings that you've included in the file.

Title: Where is Web.config during development?


问:
Unable to center Bootstrap carousel inside iPhone mockup
I'm unable to center my Bootstrap carousel inside an iPhone mockup. It's positioned to the left inside the mockup. I have tried different approaches with no success so far.

Webpage with the problem.

Thanks for all help.

HTML code:

header.masthead {
  position: relative;
  overflow-y: hidden;
  width: 100%;
  min-height: auto;
  color: white;
  background: url("../img/bg-pattern.png"), #00879b;
  background: url("../img/bg-pattern.png"), -webkit-linear-gradient(to right, #185a9d, #43cea2);
  background: url("../img/bg-pattern.png"), linear-gradient(to right, #185a9d, #43cea2); }

  header.masthead .header-content {
    position: relative;
    padding: 150px 0 50px;
    text-align: center; }
    header.masthead .header-content .header-content-inner {
      position: relative;
      max-width: 500px;
      margin: 0 auto; }
      header.masthead .header-content .header-content-inner h1 {
        font-size: 30px;
        margin-top: 0;
        margin-bottom: 30px; }
      header.masthead .header-content .header-content-inner .list-badges {
        margin-bottom: 25px; }
        header.masthead .header-content .header-content-inner .list-badges img {
          height: 50px;
          margin-bottom: 25px; }
  header.masthead .device-container {
    max-width: 300px;
    margin: 0 auto 100px; }
    header.masthead .device-container .screen img {
      border-radius: 3px;}
  @media (min-width: 768px) {
    header.masthead {
      min-height: 100%; }
      header.masthead .header-content {
        height: 100vh;
        min-height: 600px;
        padding: 0;
        text-align: left; }
        header.masthead .header-content .header-content-inner {
          position: absolute;
          top: 50%;
          max-width: none;
          margin: 0;
          transform: translateY(-50%); }
          header.masthead .header-content .header-content-inner h1 {
            font-size: 35px; }
      header.masthead .device-container {
        max-width: none;
        max-height: calc(100vh - 100px);
        margin: 100px auto 0; } }
  @media (min-width: 992px) {
    header.masthead .header-content .header-content-inner h1 {
      font-size: 50px; } }

section.download {
  position: relative;
  padding: 150px 0; }
  section.download h2 {
    font-size: 50px;
    margin-top: 0; }
  section.download .badges .badge-link {
    display: block;
    margin-bottom: 25px; }
    section.download .badges .badge-link:last-child {
      margin-bottom: 0; }
    section.download .badges .badge-link img {
      height: 60px; }
    @media (min-width: 768px) {
      section.download .badges .badge-link {
        display: inline-block;
        margin-bottom: 0; } }
  @media (min-width: 768px) {
    section.download h2 {
      font-size: 70px; } }

section.features .section-heading {
  margin-bottom: 100px; }
  section.features .section-heading h2 {
    margin-top: 0; }
  section.features .section-heading p {
    margin-bottom: 0; }

section.features .device-container,
section.features .feature-item {
  max-width: 300px;
  margin: 0 auto; }

section.features .device-container {
  margin-bottom: 100px; }
  @media (min-width: 992px) {
    section.features .device-container {
      margin-bottom: 0; } }

section.features .feature-item {
  margin-bottom: 100px;
  text-align: center; }
  section.features .feature-item h3 {
    font-size: 30px; }
  section.features .feature-item i {
    font-size: 80px;
    background: #43cea2;  /* fallback for old browsers */
    background: -webkit-linear-gradient(to left, #185a9d, #43cea2);  /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(to left, #185a9d, #43cea2); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-sm-5">
                    <div class="device-container">
                        <div class="device-mockup iphone6 portrait white">
                            <div class="device">
                                <div class="screen">
                                    <!-- Demo image for screen mockup, you can put an image here, some HTML, an animation, video, or anything else! -->
                                    <div id="carousel-device-mockup" class="carousel slide" data-ride="carousel">
                                        <!-- Wrapper for slides -->
                                        <div class="carousel-inner" role="listbox">
                                            <div class="carousel-item active">
                                              <div class="screen">
                                              <img src="img/menu.png" alt="1" class="img-fluid">
                                              </div>
                                            </div>
                                            <div class="carousel-item">
                                              <div class="screen">
                                              <img src="img/order.png" alt="2" class="img-fluid">
                                              </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- <img src="img/Order_Details.png" class="img-fluid" alt=""> -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div></code>```

答: For the .carousel-item.active, change it to display:block instead of flex, and for the .img-fluid, max-width:none; width:100%;  This will solve the issue.</p>


问:
powershell log - new file every day
I log network status (nslookup, ping, tracert) into a log file. The log file size grows and is quite difficult to work with after a while.

I am looking for a way to have a new log file created for every day. I am sure it's easy but I did not find a way.

When I set log file name to $log_file = ".\network_" + (Get-Date -f yyyy-MM-dd) + ".log" hoping it will create a new file when date changes, it does not work. Instead I get Non-authoritative answer:.

Sorry for newbie question but I really did not find any answer. Thx!

edit:

it's really simple script (shortened example below):

```<code>$log_file = ".\network_" + (Get-Date -f yyyy-MM-dd_HH-mm) + ".log"
$server = "server.com"
$gateway = (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway
& ipconfig /all >> $log_file

while($true) {
$timestamp = "rnrn[" + (Get-Date -f yyyy-MM-dd) + " " +(Get-Date -f HH:mm:ss) + "]"
$timestamp >> $log_file
"rnrn" >> $log_file
"ping to $server)" >> $log_file
& ping $server >> $log_file
}
</code>```

答:
You might consider the Log-Entry framework (also on GitHub) I published awhile ago:

It has basically all the features were you ask for:

File is automatically truncated if it grows over ~100Kb (default)

Time stamps

Inline logging

Proper type casting (e.g. notice that the $gateway has also a $Null property in my case)

```<code>Function Main {
    Log -File ".\Network.log"
    $server = Log "Server:" "192.168.1.1" ?
    $gateway = Log "Gateway:" (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway ?
    Log "IP Config:" ((& ipconfig /all) -Join "`r`n")
    Log "Ping to $Server" ((& ping $server) -Join "`r`n")
}
</code>```

The log will look like this:

2017-06-08  Test (version: 01.00.02, PowerShell version: 5.X.X5063.296)
09:13:14.01 C:\Users\User\Network.ps1
15:28:14.67 Server: 192.168.X.X
15:28:14.75 Gateway: @($Null, "192.168.X.X")
15:28:14.78 IP Config: Windows IP Configuration
            Host Name . . . . . . . . . . . . : Computer
            Primary Dns Suffix  . . . . . . . :
            Node Type . . . . . . . . . . . . : Hybrid
            IP Routing Enabled. . . . . . . . : No
            WINS Proxy Enabled. . . . . . . . : No
            DNS Suffix Search List. . . . . . : lan
            Ethernet adapter Ethernet:
            Connection-specific DNS Suffix  . : lan
            Description . . . . . . . . . . . : Intel(R) 82579LM Gigabit Network Connection
            Physical Address. . . . . . . . . : XX-XX-XX-XX-XX-XX
            DHCP Enabled. . . . . . . . . . . : Yes
            Autoconfiguration Enabled . . . . : Yes
            Link-local IPv6 Address . . . . . : XXXX::XXXX:XXXX:XXXX:XXXX%8(Preferred)
            IPv4 Address. . . . . . . . . . . : 192.168.X.X(Preferred)
            Subnet Mask . . . . . . . . . . . : 255.255.255.0
            Lease Obtained. . . . . . . . . . : Thursday, June 8, 2017 9:08:58 AM
            Lease Expires . . . . . . . . . . : Friday, June 9, 2017 9:08:57 AM
            Default Gateway . . . . . . . . . : 192.168.X.X
            DHCP Server . . . . . . . . . . . : 192.168.X.X
            DHCPv6 IAID . . . . . . . . . . . : 9808.X.X
            DHCPv6 Client DUID. . . . . . . . : XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX
            DNS Servers . . . . . . . . . . . : 192.168.X.X
            NetBIOS over Tcpip. . . . . . . . : Enabled
            Ethernet adapter VirtualBox Host-Only Network:
            Connection-specific DNS Suffix  . :
            Description . . . . . . . . . . . : VirtualBox Host-Only Ethernet Adapter
            Physical Address. . . . . . . . . : XX-XX-XX-XX-XX-XX
            DHCP Enabled. . . . . . . . . . . : No
            Autoconfiguration Enabled . . . . : Yes
            Link-local IPv6 Address . . . . . : XXXX::XXXX:XXXX:XXXX:XXXX%5(Preferred)
            IPv4 Address. . . . . . . . . . . : 192.168.X.X(Preferred)
            Subnet Mask . . . . . . . . . . . : 255.255.255.0
            Default Gateway . . . . . . . . . :
            DHCPv6 IAID . . . . . . . . . . . : 420085799
            DHCPv6 Client DUID. . . . . . . . : XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX
            DNS Servers . . . . . . . . . . . : XXXX:0:0:XXXX:.X.X
            XXXX:0:0:XXXX::2%1
            XXXX:0:0:XXXX::3%1
            NetBIOS over Tcpip. . . . . . . . : Enabled
            Wireless LAN adapter Wi-Fi:
            Media State . . . . . . . . . . . : Media disconnected
            Connection-specific DNS Suffix  . : lan
            Description . . . . . . . . . . . : Intel(R) Centrino(R) AdvancXX-N 6235
            Physical Address. . . . . . . . . : XX-XX-XX-XX-XX-XX
            DHCP Enabled. . . . . . . . . . . : Yes
            Autoconfiguration Enabled . . . . : Yes
            Wireless LAN adapter Local Area Connection* 2:
            Media State . . . . . . . . . . . : Media disconnected
            Connection-specific DNS Suffix  . :
            Description . . . . . . . . . . . : Microsoft Wi-Fi Direct Virtual Adapter
            Physical Address. . . . . . . . . : XX-XX-XX-XX-XX-XX
            DHCP Enabled. . . . . . . . . . . : Yes
            Autoconfiguration Enabled . . . . : Yes
            Ethernet adapter Bluetooth Network Connection:
            Media State . . . . . . . . . . . : Media disconnected
            Connection-specific DNS Suffix  . :
            Description . . . . . . . . . . . : Bluetooth Device (Personal Area Network)
            Physical Address. . . . . . . . . : XX-XX-XX-XX-XX-XX
            DHCP Enabled. . . . . . . . . . . : Yes
            Autoconfiguration Enabled . . . . : Yes
15:28:17.82 Ping to 192.168.X.X Pinging 192.168.X.X with 32 bytes of data:
            Reply from 192.168.X.X: bytes=32 time<1ms TTL=64
            Reply from 192.168.X.X: bytes=32 time=1ms TTL=64
            Reply from 192.168.X.X: bytes=32 time<1ms TTL=64
            Reply from 192.168.X.X: bytes=32 time<1ms TTL=64
            Ping statistics for 192.168.X.X:
            Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
            Approximate round trip times in milli-seconds:
            Minimum = 0ms, Maximum = 1ms, Average = 0ms
15:28:17.84 End
```

Title: powershell log - new file every day

Body:
I log network status (nslookup, ping, tracert) into a log file. The log file size grows and is quite difficult to work with after a while.

I am looking for a way to have a new log file created for every day. I am sure it's easy but I did not find a way.

When I set log file name to $log_file = ".\network_" + (Get-Date -f yyyy-MM-dd) + ".log" hoping it will create a new file when date changes, it does not work. Instead I get Non-authoritative answer:.

Sorry for newbie question but I really did not find any answer. Thx!

edit:

it's really simple script (shortened example below):

$log_file = ".\network_" + (Get-Date -f yyyy-MM-dd_HH-mm) + ".log"
$server = "server.com"
$gateway = (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway
& ipconfig /all >> $log_file

while($true) {
$timestamp = "rnrn[" + (Get-Date -f yyyy-MM-dd) + " " +(Get-Date -f HH:mm:ss) + "]"
$timestamp >> $log_file
"rnrn" >> $log_file
"ping to $server)" >> $log_file
& ping $server >> $log_file
}

Body:
You might consider the Log-Entry framework (also on GitHub) I published awhile ago:

It has basically all the features were you ask for:

File is automatically truncated if it grows over ~100Kb (default)

Time stamps

Inline logging

Proper type casting (e.g. notice that the $gateway has also a $Null property in my case)

Function Main {
    Log -File ".\Network.log"
    $server = Log "Server:" "192.168.1.1" ?
    $gateway = Log "Gateway:" (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway ?
    Log "IP Config:" ((& ipconfig /all) -Join "`r`n")
    Log "Ping to $Server" ((& ping $server) -Join "`r`n")
}

The log will look like this:

2017-06-08  Test (version: 01.00.02, PowerShell version: 5.X.X5063.296)
09:13:14.01 C:\Users\User\Network.ps1
15:28:14.67 Server: 192.168.X.X
15:28:14.75 Gateway: @($Null, "192.168.X.X")
15:28:14.78 IP Config: Windows IP Configuration
            Host Name . . . . . . . . . . . . : Computer
            Primary Dns Suffix  . . . . . . . :
            Node Type . . . . . . . . . . . . : Hybrid
            IP Routing Enabled. . . . . . . . : No
            WINS Proxy Enabled. . . . . . . . : No
            DNS Suffix Search List. . . . . . : lan
            Ethernet adapter Ethernet:
            Connection-specific DNS Suffix  . : lan
            Description . . . . . . . . . . . : Intel(R) 82579LM Gigabit Network Connection
            Physical Address. . . . . . . . . : XX-XX-XX-XX-XX-XX
            DHCP Enabled. . . . . . . . . . . : Yes
            Autoconfiguration Enabled . . . . : Yes
            Link-local IPv6 Address . . . . . : XXXX::XXXX:XXXX:XXXX:XXXX%8(Preferred)
            IPv4 Address. . . . . . . . . . . : 192.168.X.X(Preferred)
            Subnet Mask . . . . . . . . . . . : 255.255.255.0
            Lease Obtained. . . . . . . . . . : Thursday, June 8, 2017 9:08:58 AM
            Lease Expires . . . . . . . . . . : Friday, June 9, 2017 9:08:57 AM
            Default Gateway . . . . . . . . . : 192.168.X.X
            DHCP Server . . . . . . . . . . . : 192.168.X.X
            DHCPv6 IAID . . . . . . . . . . . : 9808.X.X
            DHCPv6 Client DUID. . . . . . . . : XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX
            DNS Servers . . . . . . . . . . . : 192.168.X.X
            NetBIOS over Tcpip. . . . . . . . : Enabled
            Ethernet adapter VirtualBox Host-Only Network:
            Connection-specific DNS Suffix  . :
            Description . . . . . . . . . . . : VirtualBox Host-Only Ethernet Adapter
            Physical Address. . . . . . . . . : XX-XX-XX-XX-XX-XX
            DHCP Enabled. . . . . . . . . . . : No
            Autoconfiguration Enabled . . . . : Yes
            Link-local IPv6 Address . . . . . : XXXX::XXXX:XXXX:XXXX:XXXX%5(Preferred)
            IPv4 Address. . . . . . . . . . . : 192.168.X.X(Preferred)
            Subnet Mask . . . . . . . . . . . : 255.255.255.0
            Default Gateway . . . . . . . . . :
            DHCPv6 IAID . . . . . . . . . . . : 420085799
            DHCPv6 Client DUID. . . . . . . . : XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX-XX
            DNS Servers . . . . . . . . . . . : XXXX:0:0:XXXX:.X.X
            XXXX:0:0:XXXX::2%1
            XXXX:0:0:XXXX::3%1
            NetBIOS over Tcpip. . . . . . . . : Enabled
            Wireless LAN adapter Wi-Fi:
            Media State . . . . . . . . . . . : Media disconnected
            Connection-specific DNS Suffix  . : lan
            Description . . . . . . . . . . . : Intel(R) Centrino(R) AdvancXX-N 6235
            Physical Address. . . . . . . . . : XX-XX-XX-XX-XX-XX
            DHCP Enabled. . . . . . . . . . . : Yes
            Autoconfiguration Enabled . . . . : Yes
            Wireless LAN adapter Local Area Connection* 2:
            Media State . . . . . . . . . . . : Media disconnected
            Connection-specific DNS Suffix  . :
            Description . . . . . . . . . . . : Microsoft Wi-Fi Direct Virtual Adapter
            Physical Address. . . . . . . . . : XX-XX-XX-XX-XX-XX
            DHCP Enabled. . . . . . . . . . . : Yes
            Autoconfiguration Enabled . . . . : Yes
            Ethernet adapter Bluetooth Network Connection:
            Media State . . . . . . . . . . . : Media disconnected
            Connection-specific DNS Suffix  . :
            Description . . . . . . . . . . . : Bluetooth Device (Personal Area Network)
            Physical Address. . . . . . . . . : XX-XX-XX-XX-XX-XX
            DHCP Enabled. . . . . . . . . . . : Yes
            Autoconfiguration Enabled . . . . : Yes
15:28:17.82 Ping to 192.168.X.X Pinging 192.168.X.X with 32 bytes of data:
            Reply from 192.168.X.X: bytes=32 time<1ms TTL=64
            Reply from 192.168.X.X: bytes=32 time=1ms TTL=64
            Reply from 192.168.X.X: bytes=32 time<1ms TTL=64
            Reply from 192.168.X.X: bytes=32 time<1ms TTL=64
            Ping statistics for 192.168.X.X:
            Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
            Approximate round trip times in milli-seconds:
            Minimum = 0ms, Maximum = 1ms, Average = 0ms
15:28:17.84 End


问:
How to bind XML to a TreeView without code behind for (MVVM, dataContext from XAML)
I have a window with a tree view control inside and a XML file. I want to bind the tree view to the XML file entirely from the XAML, without any C# code behind.

This is how I'm doing it now:

XAML

```<code><Window.Resources>
    <HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="TreeViewItemData">
        <TreeViewItem Header="{Binding Path=Attribute[text].Value}" IsExpanded="True"/>
    </HierarchicalDataTemplate>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40" />
        <RowDefinition Height="370*" />
    </Grid.RowDefinitions>
    <TextBlock Text="RD Admin Tool" Grid.Row="0" FontSize="22" FontWeight="Bold" Padding="50,5"></TextBlock>
    <StackPanel Orientation="Horizontal" Grid.Row ="1">
        <Border BorderBrush="#FF7C7B7B" BorderThickness="1" Name="tBorder" Width="200" CornerRadius="5" Background="#FFF5F2F2">
            <TreeView Name="OptionsTree"
                      ItemsSource="{Binding Path=Root.Elements}"
                      ItemTemplate="{StaticResource TreeViewItemData}"
                      HorizontalAlignment="Left" VerticalAlignment="Top"
                      Margin="5,0,0,0" FontSize="18" Background="#FFF5F2F2">
            </TreeView>
        </Border>
        <Canvas Name="OptionContent" Width="445">
        </Canvas>
    </StackPanel>
</Grid>
</code>```

Constructor in code behind:

```<code> public MyWindow()
    {
        InitializeComponent();

        XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\Tree.xml"));
        this.MyTreeView.DataContext = doc;
    }
</code>```

But I'd really like to write it from the XAML and have no code behind.

Any suggestion?

答:
You can make use of the XmlDataProvider within XAML to define your external XML as a resource. This can then be referenced and bound to within your various elements in XAML.

Walk through can be found here...in addition an MSDN sample makes use of the XmlDataProvider in conjunction with a TreeView here

Body:
I have a window with a tree view control inside and a XML file. I want to bind the tree view to the XML file entirely from the XAML, without any C# code behind.

This is how I'm doing it now:

XAML

<Window.Resources>
    <HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="TreeViewItemData">
        <TreeViewItem Header="{Binding Path=Attribute[text].Value}" IsExpanded="True"/>
    </HierarchicalDataTemplate>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40" />
        <RowDefinition Height="370*" />
    </Grid.RowDefinitions>
    <TextBlock Text="RD Admin Tool" Grid.Row="0" FontSize="22" FontWeight="Bold" Padding="50,5"></TextBlock>
    <StackPanel Orientation="Horizontal" Grid.Row ="1">
        <Border BorderBrush="#FF7C7B7B" BorderThickness="1" Name="tBorder" Width="200" CornerRadius="5" Background="#FFF5F2F2">
            <TreeView Name="OptionsTree"
                      ItemsSource="{Binding Path=Root.Elements}"
                      ItemTemplate="{StaticResource TreeViewItemData}"
                      HorizontalAlignment="Left" VerticalAlignment="Top"
                      Margin="5,0,0,0" FontSize="18" Background="#FFF5F2F2">
            </TreeView>
        </Border>
        <Canvas Name="OptionContent" Width="445">
        </Canvas>
    </StackPanel>
</Grid>

Constructor in code behind:

 public MyWindow()
    {
        InitializeComponent();

        XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\Tree.xml"));
        this.MyTreeView.DataContext = doc;
    }

But I'd really like to write it from the XAML and have no code behind.

Any suggestion?


问:
asterisk is not displayed correctly next to input on click event
can someone please tell me why when I click Edit in this Fiddle, asterisk is not lined up with input field but is shown on the bottom.

CSS

```<code>.required-field::after {
    display: none;
    content: "*";
    color: red;
    font-size: 23px;
    margin-left: 5px;
}
</code>```

JS

```<code> $("p").on('click', function(){
              var $style = $('<style>');
                $style.appendTo('head');
                var base = ".required-field::after{display:block;}";
                $style.html(base);
                });
</code>```

Thanks

Body:
can someone please tell me why when I click Edit in this Fiddle, asterisk is not lined up with input field but is shown on the bottom.

CSS

.required-field::after {
    display: none;
    content: "*";
    color: red;
    font-size: 23px;
    margin-left: 5px;
}

JS

 $("p").on('click', function(){
              var $style = $('

Body:
You have to use display:inline instead of block

 $("p").on('click', function(){
              var $style = $('<style>');
                $style.appendTo('head');
                var base = ".required-field::after{display:inline;}";
                $style.html(base);
                });

.required-field::after {
    display: none;
    content: "*";
    color: red;
    font-size: 23px;
    margin-left: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='mvnDefinitionInput required-field'>
<input type='text' class='mvnDefinitionFieldExtraInput'/>
</div>
<p class='editDefMVN"'><span>Edit</span></p>


问:
Unit testing: Call @PostConstruct after defining mocked behaviour
I have two classes:

```<code>public MyService {
    @Autowired
    private MyDao myDao;
    private List<Items> list;

    @PostConstruct
    private void init(){
         list = myDao.getItems();
    }
}
</code>```

Now I'm wanting to involve MyService in a unit test, and so I'll mock the behaviour MyDao.

XML:

```<code><bean class = "com.package.MyService">
<bean  class="org.mockito.Mockito" factory-method="mock">
     <constructor-arg value="com.package.MyDao"/>
</bean>

<util:list id="responseItems" value-type="com.package.Item">
    <ref bean="item1"/>
    <ref bean="item2"/>
</util:list>
</code>```

Unit Test:

```<code>@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class MyServiceTest {

    @Autowired
    MyService myService

    @Autowired
    MyDao myDao;

    @Resource
    @Qualifier("responseItems")
    private List<Item> responseItems;

    @Before
    public void setupTests() {
        reset(myDao);
        when(myDao.getItems()).thenReturn(responseItems);
    }
}
</code>```

The problem with this is that the MyService bean is created, and its @PostConstruct bean called before the mocked behaviour is defined.

How can I either define the mocked behaviour in the XML or delay @PostConstruct until after the unit test setup?

答:
I have same kind of requirement in my project. where i need to set a string using @PostConstructor and I did not want to ran spring context or in other words I want simple mock. My requirement was follow:

```<code>public class MyService {

@Autowired
private SomeBean bean;

private String status;

@PostConstruct
private void init() {
    status = someBean.getStatus();
}
</code>```

}

Solution:

```<code>public class MyServiceTest(){

@InjectMocks
private MyService target;

@Mock
private SomeBean mockBean;

@Before
public void setUp() throws NoSuchMethodException,  InvocationTargetException, IllegalAccessException {

    MockitoAnnotations.initMocks(this);

    when(mockBean.getStatus()).thenReturn("http://test");

    //call post-constructor
    Method postConstruct =  MyService.class.getDeclaredMethod("init",null); // methodName,parameters
    postConstruct.setAccessible(true);
    postConstruct.invoke(target);
  }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two classes:

public MyService {
    @Autowired
    private MyDao myDao;
    private List<Items> list;

    @PostConstruct
    private void init(){
         list = myDao.getItems();
    }
}

Now I'm wanting to involve MyService in a unit test, and so I'll mock the behaviour MyDao.

XML:

<bean class = "com.package.MyService">
<bean  class="org.mockito.Mockito" factory-method="mock">
     <constructor-arg value="com.package.MyDao"/>
</bean>

<util:list id="responseItems" value-type="com.package.Item">
    <ref bean="item1"/>
    <ref bean="item2"/>
</util:list>

Unit Test:

@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class MyServiceTest {

    @Autowired
    MyService myService

    @Autowired
    MyDao myDao;

    @Resource
    @Qualifier("responseItems")
    private List<Item> responseItems;

    @Before
    public void setupTests() {
        reset(myDao);
        when(myDao.getItems()).thenReturn(responseItems);
    }
}

The problem with this is that the MyService bean is created, and its @PostConstruct bean called before the mocked behaviour is defined.

How can I either define the mocked behaviour in the XML or delay @PostConstruct until after the unit test setup?

Body:
I have same kind of requirement in my project. where i need to set a string using @PostConstructor and I did not want to ran spring context or in other words I want simple mock. My requirement was follow:

public class MyService {

@Autowired
private SomeBean bean;

private String status;

@PostConstruct
private void init() {
    status = someBean.getStatus();
}

}

Solution:

public class MyServiceTest(){

@InjectMocks
private MyService target;

@Mock
private SomeBean mockBean;

@Before
public void setUp() throws NoSuchMethodException,  InvocationTargetException, IllegalAccessException {

    MockitoAnnotations.initMocks(this);

    when(mockBean.getStatus()).thenReturn("http://test");

    //call post-constructor
    Method postConstruct =  MyService.class.getDeclaredMethod("init",null); // methodName,parameters
    postConstruct.setAccessible(true);
    postConstruct.invoke(target);
  }

}


问:
Loop through a string and wrap each word in a div - PHP
Im getting a websites "keywords" for my web ranker. Its returning the result I need, but I want to wrap each keyword its returning into a span tag.

This is how im  getting the keywords:

```<code>$websiteTags = get_meta_tags('http://www.'.$website.'/');

dd($websiteTags);
</code>```

Which gives me this:

Them I just call the $websiteTags['keywords']; to get this result:

I need to wrap each word in that string in a span tag so it will look nicer in the frontend, because right now its just putting out that long string.

My question is, how would I  loop through that string and wrap each keyword in a span tag.

I have tried doing foreach loops, str_replace() and looked online, but could not find the solution I need.

答:
```<code>new_list = ['<span style="....">"%s"</span>' % x
            for x in $websiteTags['keywords'];)
</code>```

nb. $websiteTags['keywords'] is some string as defined in your question

Body:
Im getting a websites "keywords" for my web ranker. Its returning the result I need, but I want to wrap each keyword its returning into a span tag.

This is how im  getting the keywords:

$websiteTags = get_meta_tags('http://www.'.$website.'/');

dd($websiteTags);

Which gives me this:

Them I just call the $websiteTags['keywords']; to get this result:

I need to wrap each word in that string in a span tag so it will look nicer in the frontend, because right now its just putting out that long string.

My question is, how would I  loop through that string and wrap each keyword in a span tag.

I have tried doing foreach loops, str_replace() and looked online, but could not find the solution I need.

Body:
new_list = ['<span style="....">"%s"</span>' % x
            for x in $websiteTags['keywords'];)

nb. $websiteTags['keywords'] is some string as defined in your question


问:
associate a specific index to a vector
Can I associate an index to a vector that is maintained and that I can retrieve by a second vector?

```<code>V1<-c("a", "b", "c", "d", "e", "f")
</code>```

I want to associate an index something similar to:

```<code>"a" "b" "c" "d" "e" "f"
 1   2   3   4   5   6
</code>```

Then by a second vector

```<code>V2<-c("b", "c", "f")
</code>```

I should get integers 2, 3, 6

I know I can create a data frame with two columns ID=V1 and ixd= 1:length(V1)and subset by V2

I am wondering if there is a faster way

答:
You can do a named vector, i.e.

```<code>v1 <- setNames(seq(6), letters[1:6])

#then,

v1[names(v1) %in% c('b', 'c', 'f') ]
#b c f
#2 3 6
</code>```

Note that while a named vector also has names for its values, it is still numeric

Or as @jogo suggests, simply

```<code>v1[c('b', 'c', 'f')]
#b c f
#2 3 6
</code>```

Title: associate a specific index to a vector

Body:
Can I associate an index to a vector that is maintained and that I can retrieve by a second vector?

V1<-c("a", "b", "c", "d", "e", "f")

I want to associate an index something similar to:

"a" "b" "c" "d" "e" "f"
 1   2   3   4   5   6

Then by a second vector

V2<-c("b", "c", "f")

I should get integers 2, 3, 6

I know I can create a data frame with two columns ID=V1 and ixd= 1:length(V1)and subset by V2

I am wondering if there is a faster way

Body:
You can do a named vector, i.e.

v1 <- setNames(seq(6), letters[1:6])

#then,

v1[names(v1) %in% c('b', 'c', 'f') ]
#b c f
#2 3 6

Note that while a named vector also has names for its values, it is still numeric

Or as @jogo suggests, simply

v1[c('b', 'c', 'f')]
#b c f
#2 3 6


问:
compilation Error CS0176 (static member cannot be accessed) on non static method
my problem is the following :

when I try to compile my c# apps it run into this exception :

Static member 'ResponseManager.manage(Response)' cannot be accessed
  with an instance reference; qualify it with a type name instead

on this

```<code>ResponseManager responseManager = new ResponseManager();
responseManager.manage(response);
</code>```

As you can see I'm using a new instance of the ResponseManager.

here is his "manage" method's declaration :

public void manage(Response response)

I checked in project and it's the only method with this name, she's not static and ResponseManager don't have any static fields/methods and yet it won't compile.

When i try to rename my method everywhere in my code (declaration and usage) I get the following error :

ResponseManager does not contain a definition for 'sometest' and no
  extension method 'sometest' accepting a first argument of type
  'ResponseManager ' could be found (are you missing a using
  directive or an assembly reference?)

I hope I provided enought information to help me resolve this.
Many thanks !

Edit :

```<code>public class ResponseManager
{

    TransactionDAO transactionDAO = new TransactionDAO();
    LignesDAO ligneDAO = new LignesDAO();
    SimDAO simDAO = new SimDAO();
    MailSender mailSender = new MailSender();
    HttpClient httpClient = new HttpClient();
    ApplicationDAO appDAO = new ApplicationDAO();

    //RENAME !!!!!!!!
    public void manage(Response response)
    {

        if (response.responseStatus.status == "SUCCESS")
        {
            transactionDAO.updateTransactionById(response.header.transactionId, response.responseStatus.status);

            string type = transactionDAO.getTransactionTypeById(response.header.transactionId);

            if(type != null) {

                switch (type) {
                    case "activate":
                        ligneDAO.setActivatedSim(response.simIdendity.simSerial);
                        //simDAO.setActivatedSim(response.simIdendity.simSerial);

                        break;
                    case "suspend":
                        ligneDAO.setSuspendedSim(response.simIdendity.simSerial);
                        //simDAO.setSuspendedSim(response.simIdendity.simSerial);

                        break;
                    case "reactivate":
                        ligneDAO.setActivatedSim(response.simIdendity.simSerial);
                        //simDAO.setActivatedSim(response.simIdendity.simSerial);

                        break;
                    case "detail-subscription":

                        break;
                    case "detail-sim":
                        //Mapping between Response and Sim classes

                        break;
                    case "bar" :

                        break;
                    case "unbar" :

                        break;
                }
            }

            int appId = transactionDAO.getIdAppFromTransactionId(response.header.transactionId);

            string url = appDAO.getUrlFromAppId(appId);

            httpClient.send(null, url);

        }
        else
        {
            transactionDAO.updateTransactionById(response.header.transactionId, response.responseStatus.status, response.responseStatus.errorCode);

            string type = transactionDAO.getTransactionTypeById(response.header.transactionId);

            mailSender.createTransatelProvisionningErrorMail(response.header.transactionId, response.simIdendity.simSerial, response.simIdendity.msisdn, type, response.responseStatus.errorCode, response.responseStatus.reason);
        }

    }

}
</code>```

答: If you are sure that the problem is not with your code than try Unloading and Reloading the project or restarting VS2017. It solves the problem sometimes. And please provide RespnseManager's Code.</p>

Body:
my problem is the following :

when I try to compile my c# apps it run into this exception :

Static member 'ResponseManager.manage(Response)' cannot be accessed
  with an instance reference; qualify it with a type name instead

on this

ResponseManager responseManager = new ResponseManager();
responseManager.manage(response);

As you can see I'm using a new instance of the ResponseManager.

here is his "manage" method's declaration :

public void manage(Response response)

I checked in project and it's the only method with this name, she's not static and ResponseManager don't have any static fields/methods and yet it won't compile.

When i try to rename my method everywhere in my code (declaration and usage) I get the following error :

ResponseManager does not contain a definition for 'sometest' and no
  extension method 'sometest' accepting a first argument of type
  'ResponseManager ' could be found (are you missing a using
  directive or an assembly reference?)

I hope I provided enought information to help me resolve this.
Many thanks !

Edit :

public class ResponseManager
{

    TransactionDAO transactionDAO = new TransactionDAO();
    LignesDAO ligneDAO = new LignesDAO();
    SimDAO simDAO = new SimDAO();
    MailSender mailSender = new MailSender();
    HttpClient httpClient = new HttpClient();
    ApplicationDAO appDAO = new ApplicationDAO();

    //RENAME !!!!!!!!
    public void manage(Response response)
    {

        if (response.responseStatus.status == "SUCCESS")
        {
            transactionDAO.updateTransactionById(response.header.transactionId, response.responseStatus.status);

            string type = transactionDAO.getTransactionTypeById(response.header.transactionId);

            if(type != null) {

                switch (type) {
                    case "activate":
                        ligneDAO.setActivatedSim(response.simIdendity.simSerial);
                        //simDAO.setActivatedSim(response.simIdendity.simSerial);

                        break;
                    case "suspend":
                        ligneDAO.setSuspendedSim(response.simIdendity.simSerial);
                        //simDAO.setSuspendedSim(response.simIdendity.simSerial);

                        break;
                    case "reactivate":
                        ligneDAO.setActivatedSim(response.simIdendity.simSerial);
                        //simDAO.setActivatedSim(response.simIdendity.simSerial);

                        break;
                    case "detail-subscription":

                        break;
                    case "detail-sim":
                        //Mapping between Response and Sim classes

                        break;
                    case "bar" :

                        break;
                    case "unbar" :

                        break;
                }
            }

            int appId = transactionDAO.getIdAppFromTransactionId(response.header.transactionId);

            string url = appDAO.getUrlFromAppId(appId);

            httpClient.send(null, url);

        }
        else
        {
            transactionDAO.updateTransactionById(response.header.transactionId, response.responseStatus.status, response.responseStatus.errorCode);

            string type = transactionDAO.getTransactionTypeById(response.header.transactionId);

            mailSender.createTransatelProvisionningErrorMail(response.header.transactionId, response.simIdendity.simSerial, response.simIdendity.msisdn, type, response.responseStatus.errorCode, response.responseStatus.reason);
        }

    }

}


问:
Application redirects to login.aspx page
I am working on a application where unauthenticated users will be directed to my /Account/login.cshtml page, where they will be required to log in with a name and password stored in my database. (Individual Authentication).

What Have I done

So far, I have set up authentication and connection to my database and login works fine. However, when I try to set my login page I am redirected to login.aspx.
I have added the following to my webconfig and something strange occurs.

```<code><authentication mode="Forms">
  <forms loginUrl="~/Account/Login"  />
</authentication>
</code>```

With the above,when I run my program this is what i am redirected to.

```<code>http://localhost:64998/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/
</code>```

however if i change the link to /Account/test (a page that doesnt exist) I get an error of the page doesnt exist as i expect. So im wondering if there's something wrong with my Account/Login?

I dont believe anything is wrong with my login.cshtml page, because if I call it explicitly I can log in fine. The problem occurs when I am trying to redirect to this page when I am not authenticated.

Any help as to where to watch would be appeciated.

UPDATE
Login in account Controller

```<code>   public UserManager<ApplicationUser> UserManager { get; private set; }

        //
        // GET: /Account/Login
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
</code>```

App Settings part of Web Config

```<code>  <appSettings>
    <add key="PreserveLoginUrl" value="true" />
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

 <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</code>```

Further Testing

After more testing I realize that, commenting out the following code causes the application work to fine. But I still that dont think that is a solution as absent it my session doesnt expire.

code is question is in my FilterConfig and called in RegisterGlobalFilters

```<code>  public class SessionExpireFilterAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;
            // check if session is supported
            if (ctx.Session != null)
            {

                // check if a new session id was generated
                if (ctx.Session.IsNewSession)
                {

                    // If it says it is a new session, but an existing cookie exists, then it must
                    // have timed out
                    string sessionCookie = ctx.Request.Headers["Cookie"];
                    if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        string redirectOnSuccess = filterContext.HttpContext.Request.Url.PathAndQuery;
                        string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
                        string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
                        if (ctx.Request.IsAuthenticated)
                        {
                            FormsAuthentication.SignOut();
                            HttpContext.Current.Session.Abandon();

                            // clear authentication cookie
                            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
                            cookie1.Expires = DateTime.Now.AddYears(-1);
                            HttpContext.Current.Response.Cookies.Add(cookie1);

                            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
                            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
                            cookie2.Expires = DateTime.Now.AddYears(-1);
                            HttpContext.Current.Response.Cookies.Add(cookie2);
                        }
                        RedirectResult rr = new RedirectResult(loginUrl);
                        filterContext.Result = rr;
                        //ctx.Response.Redirect("~/Home/Logon");
                    }
                }
            }

            base.OnActionExecuting(filterContext);
        }

    }
</code>```

答:
You need to allow anonymous access to your login page. Right now, if a user that's not logged in yet hits any page, including the login page, they are redirected to the login page, where they are still not logged in and so are redirected again, and again, and again, etc.

You can do this by replacing the [Authorize] attribute on the page and actions in the controller with [AllowAnonymous].

Body:
I am working on a application where unauthenticated users will be directed to my /Account/login.cshtml page, where they will be required to log in with a name and password stored in my database. (Individual Authentication).

What Have I done

So far, I have set up authentication and connection to my database and login works fine. However, when I try to set my login page I am redirected to login.aspx.
I have added the following to my webconfig and something strange occurs.

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login"  />
</authentication>

With the above,when I run my program this is what i am redirected to.

http://localhost:64998/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/Account/Login?ReturnUrl=/

however if i change the link to /Account/test (a page that doesnt exist) I get an error of the page doesnt exist as i expect. So im wondering if there's something wrong with my Account/Login?

I dont believe anything is wrong with my login.cshtml page, because if I call it explicitly I can log in fine. The problem occurs when I am trying to redirect to this page when I am not authenticated.

Any help as to where to watch would be appeciated.

UPDATE
Login in account Controller

   public UserManager<ApplicationUser> UserManager { get; private set; }

        //
        // GET: /Account/Login
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {

App Settings part of Web Config

  <appSettings>
    <add key="PreserveLoginUrl" value="true" />
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

 <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

Further Testing

After more testing I realize that, commenting out the following code causes the application work to fine. But I still that dont think that is a solution as absent it my session doesnt expire.

code is question is in my FilterConfig and called in RegisterGlobalFilters

  public class SessionExpireFilterAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;
            // check if session is supported
            if (ctx.Session != null)
            {

                // check if a new session id was generated
                if (ctx.Session.IsNewSession)
                {

                    // If it says it is a new session, but an existing cookie exists, then it must
                    // have timed out
                    string sessionCookie = ctx.Request.Headers["Cookie"];
                    if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        string redirectOnSuccess = filterContext.HttpContext.Request.Url.PathAndQuery;
                        string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
                        string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
                        if (ctx.Request.IsAuthenticated)
                        {
                            FormsAuthentication.SignOut();
                            HttpContext.Current.Session.Abandon();

                            // clear authentication cookie
                            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
                            cookie1.Expires = DateTime.Now.AddYears(-1);
                            HttpContext.Current.Response.Cookies.Add(cookie1);

                            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
                            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
                            cookie2.Expires = DateTime.Now.AddYears(-1);
                            HttpContext.Current.Response.Cookies.Add(cookie2);
                        }
                        RedirectResult rr = new RedirectResult(loginUrl);
                        filterContext.Result = rr;
                        //ctx.Response.Redirect("~/Home/Logon");
                    }
                }
            }

            base.OnActionExecuting(filterContext);
        }

    }


问:
Toolkit for DSL / custom types in C#?
So, I've got a C# application with a custom types hierarchy that's ~4 layers deep.

This layering exists to provide a clean implementation of data validation and change event propagation.

An example would be:
DocumentNameValue -> NameValue - > StringValue -> BaseDataValue.

The system works fine, but given all the layers of indirection, performance surfers.  In absolute terms, it's not a huge hit, but it does add up.

To clarify, the performance issue seems to be as a result of the nested calls that happen on data access.

For instance, calling DocumentNameValue.setValue("test.doc") will result in each layer of hierarchy running certain validation tests on the input.  These start at the base and move up.  Various events are also fired along the way.  The value is actually "stored" at the base of the hierarchy, if that makes any sense.

Since all I've really done is define a strict hierarchy of types, does there exist a recommended method to do either of:

Transform this C# code in to a "flat" high performance equivalent? (Run-time or Compile-time)

Or, perhaps better, construct a DSL that would just spit out the equivalent list of types/objects?

The overall goal is twofold:  Have strong types that are specific to my application problem domain, provide a clean place to put my validation rules.

Can anyone provide some tips / suggestions?  Am I doing this all wrong?

Thank you

答:
The system works fine, but given all
  the layers of indirection, performance
  surfers. In absolute terms, it's not a
  huge hit, but it does add up.

Probably not.  You most likely need to reexamine this assumption.

Is this sort of thing frequently done?

No.  Because there is no need.  Creating an inheritance hierarchy (versus classes that do not inherit another) does not meaningfully affect performance in the vast, vast, huge, overwhelming, vast majority of applications.  Furthermore, if your project is one that is meaningfully affected by the use of inheritance, you've probably already made the wrong decision going with a managed language.

Title: Toolkit for DSL / custom types in C#?


问:
why does ejs and jquery(jquery-advanced-news-ticker) collide in this code?
I have a node application I am using with ejs as my views driver, and i am trying to use this great plugin.

the code by itself works great, but when I load a dynamic code using ejs it stops. (if i try that with static html it works perffectly).

my ejs:

```<code><% if(jobs !== undefined){ %>
<div class="container">
    <div class="well well-sm newswell">
        <ul class="newsticker"><strong>
            <% jobs.forEach(function(item){ %>
                <li><%= item.message %></li>
            <% }); %>
        </strong></ul>
    </div>
</div>
<% } %>
</code>```

and the script:

```<code>jQuery(document).ready(function() {
      setTimeout(function() {
         $('.newsticker').newsTicker({
            max_rows: 1,
            speed: 600,
            direction: 'down',
            duration: 4000,
            pauseOnHover: 1
            });
      }, 2000);
   });
</code>```

why do they collide?

答: i ended up using the plugin's method for stopping and then starting and it worked.</p>

Body:
I have a node application I am using with ejs as my views driver, and i am trying to use this great plugin.

the code by itself works great, but when I load a dynamic code using ejs it stops. (if i try that with static html it works perffectly).

my ejs:

<% if(jobs !== undefined){ %>

            <% jobs.forEach(function(item){ %>

<%= item.message %>

            <% }); %>

<% } %>

and the script:

jQuery(document).ready(function() {
      setTimeout(function() {
         $('.newsticker').newsTicker({
            max_rows: 1,
            speed: 600,
            direction: 'down',
            duration: 4000,
            pauseOnHover: 1
            });
      }, 2000);
   });

why do they collide?


问:
Android M + Retrofit + JSON : Can't make field constructor accessible
I am currently checking my app for M support. I get this error when I am making API calls with retrofit. This seems to be a json error that I getting. Has anybody else run into it yet? Here is my JSON helper class.

```<code>public class JsonHelper {

    private static final String JSON_PARSE_ERROR = "Unable to parse JSON: ";
    private static Gson sGson;
    private static Gson sExposeGson;

    static {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapterFactory(new EnumTypeAdapterFactory());
        builder.registerTypeAdapter(BlogCategoryDto.class, new BlogCategorySerializer());
        ...

        sGson = builder.create();

        builder.excludeFieldsWithoutExposeAnnotation();
        sExposeGson = builder.create();
    }

    public static Gson getGson() {
        return sGson;
    }

    public static Gson getsExposeGsonGson() {
        return sExposeGson;
    }

    public static String toJson(@NonNull Object object) {
        return sGson.toJson(object);
    }

    public static String toJson(@NonNull Object object, @NonNull Type type) {
        return sGson.toJson(object, type);
    }

    public static String toExposeJson(@NonNull Object object) {
        return sExposeGson.toJson(object);
    }

    public static String toExposeJson(@NonNull Object object, @NonNull Type type) {
        return sExposeGson.toJson(object, type);
    }

    public static <T> T fromJson(@NonNull String content, @NonNull Class<T> clazz)
            throws IllegalStateException {
        try {
            return sGson.fromJson(content, clazz);
        } catch (JsonSyntaxException e) {
            throw new IllegalStateException(JSON_PARSE_ERROR + content, e);
        }
    }

    public static <T> T fromJson(@NonNull String content, @NonNull Type type)
            throws IllegalStateException {
        try {
            return sGson.fromJson(content, type);
        } catch (JsonSyntaxException e) {
            throw new IllegalStateException(JSON_PARSE_ERROR + content, e);
        }
    }
}
</code>```

This is the error that is thrown

```<code>D/Retrofit﹕java.lang.SecurityException: Can't make field constructor accessible
        at java.lang.reflect.Constructor.setAccessible(Constructor.java:334)
        at com.google.gson.internal.ConstructorConstructor.newDefaultConstructor(ConstructorConstructor.java:97)
        at com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:79)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:82)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:52)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:92)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:92)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:52)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:92)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.Gson.fromJson(Gson.java:809)
        at com.google.gson.Gson.fromJson(Gson.java:775)
        at retrofit.converter.GsonConverter.fromBody(GsonConverter.java:63)
        at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:367)
        at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
        at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)
        at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at retrofit.Platform$Android$2$1.run(Platform.java:142)
        at java.lang.Thread.run(Thread.java:818)
</code>```

答:
Best way!</p>

```<code>  GsonBuilder builder = new GsonBuilder().excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC);
  Gson gson = builder.create();
  Retrofit retrofit = new Retrofit.Builder().baseUrl(URL)
      .addConverterFactory(GsonConverterFactory.create(gson))
      .build();
</code>```

Body:
I am currently checking my app for M support. I get this error when I am making API calls with retrofit. This seems to be a json error that I getting. Has anybody else run into it yet? Here is my JSON helper class.

public class JsonHelper {

    private static final String JSON_PARSE_ERROR = "Unable to parse JSON: ";
    private static Gson sGson;
    private static Gson sExposeGson;

    static {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapterFactory(new EnumTypeAdapterFactory());
        builder.registerTypeAdapter(BlogCategoryDto.class, new BlogCategorySerializer());
        ...

        sGson = builder.create();

        builder.excludeFieldsWithoutExposeAnnotation();
        sExposeGson = builder.create();
    }

    public static Gson getGson() {
        return sGson;
    }

    public static Gson getsExposeGsonGson() {
        return sExposeGson;
    }

    public static String toJson(@NonNull Object object) {
        return sGson.toJson(object);
    }

    public static String toJson(@NonNull Object object, @NonNull Type type) {
        return sGson.toJson(object, type);
    }

    public static String toExposeJson(@NonNull Object object) {
        return sExposeGson.toJson(object);
    }

    public static String toExposeJson(@NonNull Object object, @NonNull Type type) {
        return sExposeGson.toJson(object, type);
    }

    public static <T> T fromJson(@NonNull String content, @NonNull Class<T> clazz)
            throws IllegalStateException {
        try {
            return sGson.fromJson(content, clazz);
        } catch (JsonSyntaxException e) {
            throw new IllegalStateException(JSON_PARSE_ERROR + content, e);
        }
    }

    public static <T> T fromJson(@NonNull String content, @NonNull Type type)
            throws IllegalStateException {
        try {
            return sGson.fromJson(content, type);
        } catch (JsonSyntaxException e) {
            throw new IllegalStateException(JSON_PARSE_ERROR + content, e);
        }
    }
}

This is the error that is thrown

D/Retrofit﹕java.lang.SecurityException: Can't make field constructor accessible
        at java.lang.reflect.Constructor.setAccessible(Constructor.java:334)
        at com.google.gson.internal.ConstructorConstructor.newDefaultConstructor(ConstructorConstructor.java:97)
        at com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:79)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:82)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:52)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:92)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:92)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:52)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:92)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83)
        at com.google.gson.Gson.getAdapter(Gson.java:359)
        at com.google.gson.Gson.fromJson(Gson.java:809)
        at com.google.gson.Gson.fromJson(Gson.java:775)
        at retrofit.converter.GsonConverter.fromBody(GsonConverter.java:63)
        at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:367)
        at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
        at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)
        at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at retrofit.Platform$Android$2$1.run(Platform.java:142)
        at java.lang.Thread.run(Thread.java:818)

Body:
Best way!

  GsonBuilder builder = new GsonBuilder().excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC);
  Gson gson = builder.create();
  Retrofit retrofit = new Retrofit.Builder().baseUrl(URL)
      .addConverterFactory(GsonConverterFactory.create(gson))
      .build();


问:
I need to know how many times temperatures;20 & 30 are crossed in the given data set 'Tair' using R
This is what I have done

```<code>maxT<-c(20,30)
Tair<-c(28.8,0,0,28.8,29.1,28.5,28.7,28.2,28.3,28.8,30.1,31.3,30.7,31.9,31.5,30.7,32,33,33,33.6,33.7,32.4,32.7,30.5,27.4,27.1,25.9,26.2,28.3,29.8,30.8,31.4,32)
dmx<-c(0)
 for (i in maxT)
 {
   for (j in Tair)
   {
     if(j>i){dmx=dmx+1}
   }
   dmx
 }
}
</code>```

When I run the above given script, It returns a single value for 'dmax' which is a sum of times temperatures crosses 20 and 30.
Thanks in advance.

答:
If you want to calculate the number of observations between 20 and 30 (it's not obvious) here is a solution:</p>

```<code>dmx <- sum(Tair>maxT[1] & Tair<maxT[2])
</code>```

Body:
This is what I have done

maxT<-c(20,30)
Tair<-c(28.8,0,0,28.8,29.1,28.5,28.7,28.2,28.3,28.8,30.1,31.3,30.7,31.9,31.5,30.7,32,33,33,33.6,33.7,32.4,32.7,30.5,27.4,27.1,25.9,26.2,28.3,29.8,30.8,31.4,32)
dmx<-c(0)
 for (i in maxT)
 {
   for (j in Tair)
   {
     if(j>i){dmx=dmx+1}
   }
   dmx
 }
}

When I run the above given script, It returns a single value for 'dmax' which is a sum of times temperatures crosses 20 and 30.
Thanks in advance.

Body:
If you want to calculate the number of observations between 20 and 30 (it's not obvious) here is a solution:

dmx <- sum(Tair>maxT[1] & Tair<maxT[2])


问:
Lining up cards in a row dynamically (based on available space)
I stumbled on this site: http://deweyapp.io/. If you play around with the size of the browser window, you'll see that the cards either drop to the next line or are pushed up to the previous one (depending on the resize action).

How is this accomplished using bootstrap or material design? I can't figure it out, for the life of me.

Thanks,
Vladimir

答:
The cards are in a container
 which has a fixed width and display:inline-block;

Body: The cards are in a container <li> which has a fixed width and display:inline-block;


问:
pick item from list at random, each has different chance
I wanted to write a simple function that allows to roll random item from list, i did it with this code:

```<code>this.resources = [false, 'nitrogen', 'silicon', 'cobalt', 'magnesium'];

this.assign_resource = function() {
    var index = tools.rnd(0, this.resources.length - 1);
    return this.resources[index];
};
</code>```

But it doesn't play well, so i wanted to change it to different system that allows a list of items (including empty one) and it picks one at random but each one has different chance (for example this one has 10%, this one has 20%). Maybe someone could help me with this kind of function.

Edited -----

for example this could be new list:

```<code>this.resources = [
    { type: 'empty', chance: 30 },
    { type: 'nitrogen', chance: 10 },
    { type: 'silicon', chance: 20 },
    { type: 'cobalt', chance: 30 },
    { type: 'magnesium', chance: 10 }
];
</code>```

How to use it now to make it happen properly?

Edited 2 -----

I am trying to figure out well done programming solution using math rather then simply duplicating items in array, answers presented in this topic are just work arounds to a problem.

答:
I would set it up so that only the actual resources are in your array and "empty" happens if the random roll falls outside of those.</p>

```<code>this.resources = [
    { type: 'nitrogen', chance: 10 },
    { type: 'silicon', chance: 20 },
    { type: 'cobalt', chance: 30 },
    { type: 'magnesium', chance: 10 }
];

this.assign_resource = function() {
  var rnd = Math.random();
  var acc = 0;
  for (var i=0, r; r = this.resources[i]; i++) {
    acc += r.chance / 100;
    if (rnd < acc) return r.type;
  }
  // rnd wasn't less than acc, so no resource was found
  return 'empty';
}
</code>```

Body:
I wanted to write a simple function that allows to roll random item from list, i did it with this code:

this.resources = [false, 'nitrogen', 'silicon', 'cobalt', 'magnesium'];

this.assign_resource = function() {
    var index = tools.rnd(0, this.resources.length - 1);
    return this.resources[index];
};

But it doesn't play well, so i wanted to change it to different system that allows a list of items (including empty one) and it picks one at random but each one has different chance (for example this one has 10%, this one has 20%). Maybe someone could help me with this kind of function.

Edited -----

for example this could be new list:

this.resources = [
    { type: 'empty', chance: 30 },
    { type: 'nitrogen', chance: 10 },
    { type: 'silicon', chance: 20 },
    { type: 'cobalt', chance: 30 },
    { type: 'magnesium', chance: 10 }
];

How to use it now to make it happen properly?

Edited 2 -----

I am trying to figure out well done programming solution using math rather then simply duplicating items in array, answers presented in this topic are just work arounds to a problem.

Body:
I would set it up so that only the actual resources are in your array and "empty" happens if the random roll falls outside of those.

this.resources = [
    { type: 'nitrogen', chance: 10 },
    { type: 'silicon', chance: 20 },
    { type: 'cobalt', chance: 30 },
    { type: 'magnesium', chance: 10 }
];

this.assign_resource = function() {
  var rnd = Math.random();
  var acc = 0;
  for (var i=0, r; r = this.resources[i]; i++) {
    acc += r.chance / 100;
    if (rnd < acc) return r.type;
  }
  // rnd wasn't less than acc, so no resource was found
  return 'empty';
}


问:
How can I convert an int number from decimal to binary
how to convert an int array of length 8 to  an int array of length 32 each 4 indexes are the binary representation of an index of the first array is there such a method that do all overhead.

Edit, PST: I updated the title. However, this doesn't quite reflect with the notion of "binary", it's just decomposing integers into bytes. Correct and/or add examples if this is not accurate.

ok programers the main thing that i want is >> How can I convert an int number from decimal to binary

答:
I'm not sure, but maybe this is what you're looking for?

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#toBinaryString(int)