问:
How to do a partial look up in excel and get the data in next column till four rows in VBA
I have  sheet 1 with Column name: Main task

MainTask

And, I have Sheet 2 where the Sub-tasks are given based on the characters between 1st and 2nd hyphen(-) of the Data in Main Task for eg: Under the main task column there is "Pyramid - IoT Forecast - Latin America - Argentina - 2017". So, based on the string " IoT Forecast" the sub tasks are given as in the below image.

Out Put:

Now In sheet 3  I need every title from the main task should be copied and pasted from the Sheet 1 and look for relevant sub tasks and pasted in the next column like the below image.

I have used, Wild cards, partial V-look up with Mid Function but only single sub task is populating. Please help me provide code in VBA.

答:
You will need to do an array formula, something similar to the below where the sub category is in C1

=INDEX($A$2:$A$6,SMALL(IF(NOT(ISERROR(SEARCH("-" & $C$1 & "-",$A$2:$A$6))),ROW($A$2:$A$6)-1),ROWS($D$1:D1)))


来源: stackexchange

问:
WPF Data binding: Changing items in the binded collection does not update binding source?
I have two classes:

```<code>public class Person
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }
    public ObservableCollection<AccountDetail> Phones
    {
        get
        {
            ObservableCollection<AccountDetail> phones;
            phones = new ObservableCollection<AccountDetail>();
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    phones.Add(detail);
                }
            }
            return phones;
        }
        set
        {
            ObservableCollection<AccountDetail> phones;
            phones = value;
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    Details.Remove(detail);
                }
            }
            foreach (AccountDetail detail in phones)
            {
                if (!string.IsNullOrEmpty(detail.Value))
                {
                    Details.Add(detail);
                }
            }
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;
}
</code>```

and

```<code>public class AccountDetail
{
    public DetailType Type
    {
        get { return type; }
        set { type = value; }
    }
    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    private DetailType type;
    private string value;
}
</code>```

In my XAML file I have a ListBox named PhonesListBox which is data bound to the phones list (a property of the Person object):

```<code><Window.Resources>

    <!-- Window controller -->
    <contollers:PersonWindowController
        x:Key="WindowController" />

</Window.Resources>

...

<ListBox
    Name="PhonesListBox"
    Margin="0,25,0,0"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Top"
    ItemsSource="{Binding Path=SelectedPerson.Phones,
                  Source={StaticResource ResourceKey=WindowController}}"
    HorizontalContentAlignment="Stretch" />

...
</code>```

In its code behind class, there's a handler for a button which adds a new item to that PhonesListBox:

```<code>private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    ObservableCollection<AccountDetail> phones;

    phones = (ObservableCollection<AccountDetail>)PhonesListBox.ItemsSource;
    phones.Add(new AccountDetail(DetailType.Phone));
}
</code>```

The problem is, the newly added list box item is not added in the person's details observable collection, i.e. the Phones property is not updated (set is never called). Why? Where am I making a mistake?

Thanks for all the help.

UPDATE: I changed the AddPhoneButton_Click method to:

```<code>private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    PersonWindowController windowController;
    ObservableCollection<AccountDetail> details;

    windowController = (PersonWindowController)this.FindResource("WindowController");
    details = windowController.SelectedPerson.Details;
    details.Add(new AccountDetail(DetailType.Phone));
}
</code>```

This updates the appropriate collection, which is details not Phones (as phones is just a view or a getter of a subset of detail items). Also, I realized I don't even need the Phones setter. The problem I am facing now is that my UI is not updated with the changes made to the details collection (and subsequently phones). I don't know how or where to call for the property changed as neither details nor phones are changing; their collection members are. Help. Please.

答:
Changing you Person class to something like following should work :

```<code>public class Person
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }

    public ObservableCollection<AccountDetail> Phones
    {
        get
        {
            if (phones == null)
            {
                phones = new ObservableCollection<AccountDetail>();
            }

            phones.Clear();
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    phones.Add(detail);
                }
            }
            return phones;
        }
        set
        {
            phones.Clear();

            foreach (var item in value)
            {
                phones.Add(item);
            }

            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    Details.Remove(detail);
                }
            }

            foreach (AccountDetail detail in phones)
            {
                if (!string.IsNullOrEmpty(detail.Value))
                {
                    Details.Add(detail);
                }
            }
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;
    public ObservableCollection<AccountDetail> phones;
}
</code>```

The code is not tested and it may require a few changes from you to actually work.

ContentLicense: CC BY-SA 2.5

Body:
I have two classes:

public class Person
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }
    public ObservableCollection<AccountDetail> Phones
    {
        get
        {
            ObservableCollection<AccountDetail> phones;
            phones = new ObservableCollection<AccountDetail>();
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    phones.Add(detail);
                }
            }
            return phones;
        }
        set
        {
            ObservableCollection<AccountDetail> phones;
            phones = value;
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    Details.Remove(detail);
                }
            }
            foreach (AccountDetail detail in phones)
            {
                if (!string.IsNullOrEmpty(detail.Value))
                {
                    Details.Add(detail);
                }
            }
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;
}

and

public class AccountDetail
{
    public DetailType Type
    {
        get { return type; }
        set { type = value; }
    }
    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    private DetailType type;
    private string value;
}

In my XAML file I have a ListBox named PhonesListBox which is data bound to the phones list (a property of the Person object):

<Window.Resources>

    <contollers:PersonWindowController
        x:Key="WindowController" />

</Window.Resources>

...

<ListBox
    Name="PhonesListBox"
    Margin="0,25,0,0"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Top"
    ItemsSource="{Binding Path=SelectedPerson.Phones,
                  Source={StaticResource ResourceKey=WindowController}}"
    HorizontalContentAlignment="Stretch" />

...

In its code behind class, there's a handler for a button which adds a new item to that PhonesListBox:

private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    ObservableCollection<AccountDetail> phones;

    phones = (ObservableCollection<AccountDetail>)PhonesListBox.ItemsSource;
    phones.Add(new AccountDetail(DetailType.Phone));
}

The problem is, the newly added list box item is not added in the person's details observable collection, i.e. the Phones property is not updated (set is never called). Why? Where am I making a mistake?

Thanks for all the help.

UPDATE: I changed the AddPhoneButton_Click method to:

private void AddPhoneButton_Click(object sender, RoutedEventArgs e)
{
    PersonWindowController windowController;
    ObservableCollection<AccountDetail> details;

    windowController = (PersonWindowController)this.FindResource("WindowController");
    details = windowController.SelectedPerson.Details;
    details.Add(new AccountDetail(DetailType.Phone));
}

This updates the appropriate collection, which is details not Phones (as phones is just a view or a getter of a subset of detail items). Also, I realized I don't even need the Phones setter. The problem I am facing now is that my UI is not updated with the changes made to the details collection (and subsequently phones). I don't know how or where to call for the property changed as neither details nor phones are changing; their collection members are. Help. Please.

Body:
Changing you Person class to something like following should work :

public class Person
{
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
    public ObservableCollection<AccountDetail> Details
    {
        get { return details; }
        set { details = value; }
    }

    public ObservableCollection<AccountDetail> Phones
    {
        get
        {
            if (phones == null)
            {
                phones = new ObservableCollection<AccountDetail>();
            }

            phones.Clear();
            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    phones.Add(detail);
                }
            }
            return phones;
        }
        set
        {
            phones.Clear();

            foreach (var item in value)
            {
                phones.Add(item);
            }

            foreach (AccountDetail detail in Details)
            {
                if (detail.Type == DetailType.Phone)
                {
                    Details.Remove(detail);
                }
            }

            foreach (AccountDetail detail in phones)
            {
                if (!string.IsNullOrEmpty(detail.Value))
                {
                    Details.Add(detail);
                }
            }
        }
    }

    private string firstName;
    private string lastName;
    private ObservableCollection<AccountDetail> details;
    public ObservableCollection<AccountDetail> phones;
}

The code is not tested and it may require a few changes from you to actually work.


问:
Angular 2 show popup and redirect
I need show popup showing some message and then redirect to another component.But the thing is it doesn't show popup but redirecting to another component.i have tried the following code which redirects to another component.Since i'm newbie to angular 2 kindly help me.

Note : popwindow is showing if i dnt redirect to another component

```<code>import { Component,OnInit, ViewEncapsulation,ViewContainerRef } from '@angular/core';
    import { NgForm } from '@angular/forms';
    import { HttpService } from 'app/http.service';
    import { Router } from '@angular/router';
    import { Overlay } from 'angular2-modal';
    import { Modal } from 'angular2-modal/plugins/bootstrap';

    @Component({
      selector: 'app-registration',
      templateUrl: './registration.component.html',
      styleUrls: ['./registration.component.css'],
      encapsulation: ViewEncapsulation.None
    })
    export class RegistrationComponent implements OnInit {

      constructor(private httpService : HttpService,private router: Router,overlay: Overlay, vcRef: ViewContainerRef, public modal: Modal) {
        overlay.defaultViewContainer = vcRef;
       }

      ngOnInit() {
      }

      onsubmit(form: NgForm){
        this.httpService.sendData(form.value).subscribe(data =>{
          if(data.data == 1 ){this.modal.alert().title('Message').body('Successfully registered').open();
           this.router.navigate(['/login']);}

      },error => {
        if(error)
        {
          this.modal.alert().title('Message').body('Server is not reachable').open();
        }
      });

      }

    }
</code>```

答:
It's because you don't wait between your instructions.

You can add before this.router.navigate(['/login']); a timer instruction may be 2 seconds.

ContentLicense: CC BY-SA 3.0

Title: Angular 2 show popup and redirect

Body:
I need show popup showing some message and then redirect to another component.But the thing is it doesn't show popup but redirecting to another component.i have tried the following code which redirects to another component.Since i'm newbie to angular 2 kindly help me.

Note : popwindow is showing if i dnt redirect to another component

import { Component,OnInit, ViewEncapsulation,ViewContainerRef } from '@angular/core';
    import { NgForm } from '@angular/forms';
    import { HttpService } from 'app/http.service';
    import { Router } from '@angular/router';
    import { Overlay } from 'angular2-modal';
    import { Modal } from 'angular2-modal/plugins/bootstrap';

    @Component({
      selector: 'app-registration',
      templateUrl: './registration.component.html',
      styleUrls: ['./registration.component.css'],
      encapsulation: ViewEncapsulation.None
    })
    export class RegistrationComponent implements OnInit {

      constructor(private httpService : HttpService,private router: Router,overlay: Overlay, vcRef: ViewContainerRef, public modal: Modal) {
        overlay.defaultViewContainer = vcRef;
       }

      ngOnInit() {
      }

      onsubmit(form: NgForm){
        this.httpService.sendData(form.value).subscribe(data =>{
          if(data.data == 1 ){this.modal.alert().title('Message').body('Successfully registered').open();
           this.router.navigate(['/login']);}

      },error => {
        if(error)
        {
          this.modal.alert().title('Message').body('Server is not reachable').open();
        }
      });

      }

    }


问:
add pages to sidemenu of side menu project template
I created a project using the sidemenu template.

```<code>ionic start projectName sidemenu --v2
</code>```

after that i generated another page using: ionic g page pageName

what I want to do is to add this generated page to the side menu.

can you please help me, I'm newbie to ionic.

Thanks in advance

答:
You have to add your new page to the pages array as shown below.

Git repo: Sample Side menu

app.component.ts

```<code>import { PageNamePage } from "../pages/page-name/page-name";

    export class MyApp {

        this.pages = [
          { title: 'Page One', component: Page1 },
          { title: 'Page Two', component: Page2 },
          { title: 'Page Three', component: PageNamePage }//your new page
        ];
    }
</code>```

You have to add new page as shown below inside the app.module.ts.I have removed default code for clarity.

app.module.ts :

```<code>import { PageNamePage } from "../pages/page-name/page-name";//your new page

@NgModule({
  declarations: [
    PageNamePage,//new page
  ],
  entryComponents: [
    PageNamePage,//new page
  ],
 })
export class AppModule { }
</code>```

Side Menu Now :

Body:
I created a project using the sidemenu template.

ionic start projectName sidemenu --v2

after that i generated another page using: ionic g page pageName

what I want to do is to add this generated page to the side menu.

can you please help me, I'm newbie to ionic.

Thanks in advance

Body:
You have to add your new page to the pages array as shown below.

Git repo: Sample Side menu

app.component.ts

import { PageNamePage } from "../pages/page-name/page-name";

    export class MyApp {

        this.pages = [
          { title: 'Page One', component: Page1 },
          { title: 'Page Two', component: Page2 },
          { title: 'Page Three', component: PageNamePage }//your new page
        ];
    }

You have to add new page as shown below inside the app.module.ts.I have removed default code for clarity.

app.module.ts :

import { PageNamePage } from "../pages/page-name/page-name";//your new page

@NgModule({
  declarations: [
    PageNamePage,//new page
  ],
  entryComponents: [
    PageNamePage,//new page
  ],
 })
export class AppModule { }

Side Menu Now :


问:
touchListener not working in Fragment elements
I have done an implementation in which I have to use fragments with activity all set but when I am trying to implement touchListener on fragments any view it's not working.

Here is my code:

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        _view = inflater.inflate(R.layout.slide_listfragment, container, false);

        /**
         * Set touch listener for implementing right to left swipe on slide menu
         */
        _view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                //***************** Multi touch events ************************
                int action = (event.getAction() & event.getActionMasked());
                //int action = MotionEventCompat.getActionMasked(event);
                //Get the index of the pointer associated with the action.
                int index = MotionEventCompat.getActionIndex(event);
                int xPos = -1;
                int yPos = -1;

                //***************** Single touch events ************************

                switch (action) {

                    case MotionEvent.ACTION_DOWN: {
                        downX = event.getX();
                        downY = event.getY();
                        return true;
                    }
                    case MotionEvent.ACTION_UP: {
                        upX = event.getX();
                        upY = event.getY();
                        float deltaX = downX - upX;
                        float deltaY = downY - upY;

                        // swipe horizontal?
                        if (Math.abs(deltaX) > MIN_DISTANCE) {
                            // left or right
                            if (deltaX < 0) {
                                //this.onLeftToRightSwipe();
                                //((MenuActivity) getActivity()).getSlideoutHelper().close();
                                return true;
                            }
                            if (deltaX > 0) {
                                //this.onRightToLeftSwipe();
                                ((MenuActivity) getActivity()).getSlideoutHelper().close();
                                return true;
                            }
                        } else if (Math.abs(deltaX) == 0) {
                            Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long horizontally, need at least " + MIN_DISTANCE);
                            // return false; // We don't consume the event

                            //Single tap implementation
                        }
                        return true; // no swipe horizontally and no swipe vertically
                    }// case MotionEvent.ACTION_UP:
                }
                return true;
            }
        });

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

        mOutputRecyclerView = (RecyclerView) _view.findViewById(R.id.outputRecyclerView);
        DisplayMetrics displayMetrics = getActivity().getResources().getDisplayMetrics();
        int screenWidth = displayMetrics.widthPixels;
        int screenHeight = displayMetrics.heightPixels;

        ViewGroup.LayoutParams params = mOutputRecyclerView.getLayoutParams();
        params.width = (screenWidth - screenWidth / 3);
        mOutputRecyclerView.setLayoutParams(params);

        RelativeLayout settingRl = null;
        ///////////////change screen background based on selected theme//////////////
        mainRl = (RelativeLayout) _view.findViewById(R.id.sliderlinearlayout);
        if (SharedPref.getSharedPrefData(getActivity(), SharedPref.SELECTED_THEME).
                equalsIgnoreCase(Util.THEME_LIGHT)) {
            mOutputRecyclerView.setBackgroundColor(getActivity().getResources().getColor(R.color.light_theme_horizontal_strip_color));
            mainRl.setBackgroundColor(getActivity().getResources().getColor(R.color.light_theme_horizontal_strip_color));
            settingRl = (RelativeLayout) _view.findViewById(R.id.settingLightRl);
        } else {
            mOutputRecyclerView.setBackgroundColor(getActivity().getResources().getColor(R.color.background_color));
            mainRl.setBackgroundColor(getActivity().getResources().getColor(R.color.background_color));
            settingRl = (RelativeLayout) _view.findViewById(R.id.settingRl);
        }
        //////////////////////////////////////////////////////////////////////////////

        Util.overrideFonts(getActivity(), _view.findViewById(R.id.handyTitleTv), 1);

        RelativeLayout.LayoutParams layoutParam = new RelativeLayout.LayoutParams(
                (screenWidth - (screenWidth / 3) - 20),
                (int) getActivity().getResources().getDimension(R.dimen.footer_height));
        layoutParam.setMargins(20,
                10, 20,
                20);
        layoutParam.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        settingRl.setLayoutParams(layoutParam);
        settingRl.setVisibility(View.VISIBLE);

        //Set clicklistener for setting option
        settingRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Util.pressButtonEffect(view);
                Util.isSliderCliked = true;
                ((MenuActivity) getActivity()).getSlideoutHelper().close();
                Intent intent = new Intent(getActivity(), MhubProFirstSettingActivity.class);
                startActivity(intent);
            }
        });

        //Get list of available IR packs for output devices
        if (mIrPackResponsePojo != null) {
            irPackOutputListTable = mIrPackResponsePojo.getIrPackOutputListTable();
        }

        //Sets vertical output device list
        setOutputList();

        //Override fonts for all text view
        Util.overrideFonts(getActivity(), _view.findViewById(R.id.settingLightTv), 1);
        Util.overrideFonts(getActivity(), _view.findViewById(R.id.settingTv), 1);

        return _view;
    }
</code>```

For a solution I implemented dispacthTouchEvent() method in my fragment's parent activity so touchEvents started working but onClickListener events not working on other views.

Here is my code of activity for dispacthTouchEvent method:

```<code>@Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN: {
                downX = event.getX();
                downY = event.getY();
                return true;
            }
            case MotionEvent.ACTION_UP: {
                upX = event.getX();
                upY = event.getY();
                float deltaX = downX - upX;
                float deltaY = downY - upY;

                // swipe horizontal?
                if (Math.abs(deltaX) > MIN_DISTANCE) {
                    // left or right
                    if (deltaX < 0) {
                        //this.onLeftToRightSwipe();
                        //((MenuActivity) getActivity()).getSlideoutHelper().close();
                        return true;
                    }
                    if (deltaX > 0) {
                        //this.onRightToLeftSwipe();
                        if (mSlideoutHelper != null)
                            mSlideoutHelper.close();
                        return true;
                    }
                } else if (Math.abs(deltaX) == 0) {
                    // return false; // We don't consume the event

                    //Single tap implementation
                }
                return true; // no swipe horizontally and no swipe vertically
            }// case MotionEvent.ACTION_UP:
        }
        return super.dispatchTouchEvent(event);
    }
</code>```

答:
Dont consume your touch pass it along ;</p>

```<code>@Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN: {
                downX = event.getX();
                downY = event.getY();
                //return false;
            }
            case MotionEvent.ACTION_UP: {
                upX = event.getX();
                upY = event.getY();
                float deltaX = downX - upX;
                float deltaY = downY - upY;

                // swipe horizontal?
                if (Math.abs(deltaX) > MIN_DISTANCE) {
                    // left or right
                    if (deltaX < 0) {
                        //this.onLeftToRightSwipe();
                        //((MenuActivity) getActivity()).getSlideoutHelper().close();
                        return true;
                    }
                    if (deltaX > 0) {
                        //this.onRightToLeftSwipe();
                        if (mSlideoutHelper != null)
                            mSlideoutHelper.close();
                        return true;
                    }
                } else if (Math.abs(deltaX) == 0) {
                    // return false; // We don't consume the event

                    //Single tap implementation
                }
                //return true; // no swipe horizontally and no swipe vertically
            }// case MotionEvent.ACTION_UP:
        }
        return super.dispatchTouchEvent(event);
    }
</code>```

Body:
I have done an implementation in which I have to use fragments with activity all set but when I am trying to implement touchListener on fragments any view it's not working.

Here is my code:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        _view = inflater.inflate(R.layout.slide_listfragment, container, false);

        /**
         * Set touch listener for implementing right to left swipe on slide menu
         */
        _view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                //***************** Multi touch events ************************
                int action = (event.getAction() & event.getActionMasked());
                //int action = MotionEventCompat.getActionMasked(event);
                //Get the index of the pointer associated with the action.
                int index = MotionEventCompat.getActionIndex(event);
                int xPos = -1;
                int yPos = -1;

                //***************** Single touch events ************************

                switch (action) {

                    case MotionEvent.ACTION_DOWN: {
                        downX = event.getX();
                        downY = event.getY();
                        return true;
                    }
                    case MotionEvent.ACTION_UP: {
                        upX = event.getX();
                        upY = event.getY();
                        float deltaX = downX - upX;
                        float deltaY = downY - upY;

                        // swipe horizontal?
                        if (Math.abs(deltaX) > MIN_DISTANCE) {
                            // left or right
                            if (deltaX < 0) {
                                //this.onLeftToRightSwipe();
                                //((MenuActivity) getActivity()).getSlideoutHelper().close();
                                return true;
                            }
                            if (deltaX > 0) {
                                //this.onRightToLeftSwipe();
                                ((MenuActivity) getActivity()).getSlideoutHelper().close();
                                return true;
                            }
                        } else if (Math.abs(deltaX) == 0) {
                            Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long horizontally, need at least " + MIN_DISTANCE);
                            // return false; // We don't consume the event

                            //Single tap implementation
                        }
                        return true; // no swipe horizontally and no swipe vertically
                    }// case MotionEvent.ACTION_UP:
                }
                return true;
            }
        });

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

        mOutputRecyclerView = (RecyclerView) _view.findViewById(R.id.outputRecyclerView);
        DisplayMetrics displayMetrics = getActivity().getResources().getDisplayMetrics();
        int screenWidth = displayMetrics.widthPixels;
        int screenHeight = displayMetrics.heightPixels;

        ViewGroup.LayoutParams params = mOutputRecyclerView.getLayoutParams();
        params.width = (screenWidth - screenWidth / 3);
        mOutputRecyclerView.setLayoutParams(params);

        RelativeLayout settingRl = null;
        ///////////////change screen background based on selected theme//////////////
        mainRl = (RelativeLayout) _view.findViewById(R.id.sliderlinearlayout);
        if (SharedPref.getSharedPrefData(getActivity(), SharedPref.SELECTED_THEME).
                equalsIgnoreCase(Util.THEME_LIGHT)) {
            mOutputRecyclerView.setBackgroundColor(getActivity().getResources().getColor(R.color.light_theme_horizontal_strip_color));
            mainRl.setBackgroundColor(getActivity().getResources().getColor(R.color.light_theme_horizontal_strip_color));
            settingRl = (RelativeLayout) _view.findViewById(R.id.settingLightRl);
        } else {
            mOutputRecyclerView.setBackgroundColor(getActivity().getResources().getColor(R.color.background_color));
            mainRl.setBackgroundColor(getActivity().getResources().getColor(R.color.background_color));
            settingRl = (RelativeLayout) _view.findViewById(R.id.settingRl);
        }
        //////////////////////////////////////////////////////////////////////////////

        Util.overrideFonts(getActivity(), _view.findViewById(R.id.handyTitleTv), 1);

        RelativeLayout.LayoutParams layoutParam = new RelativeLayout.LayoutParams(
                (screenWidth - (screenWidth / 3) - 20),
                (int) getActivity().getResources().getDimension(R.dimen.footer_height));
        layoutParam.setMargins(20,
                10, 20,
                20);
        layoutParam.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        settingRl.setLayoutParams(layoutParam);
        settingRl.setVisibility(View.VISIBLE);

        //Set clicklistener for setting option
        settingRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Util.pressButtonEffect(view);
                Util.isSliderCliked = true;
                ((MenuActivity) getActivity()).getSlideoutHelper().close();
                Intent intent = new Intent(getActivity(), MhubProFirstSettingActivity.class);
                startActivity(intent);
            }
        });

        //Get list of available IR packs for output devices
        if (mIrPackResponsePojo != null) {
            irPackOutputListTable = mIrPackResponsePojo.getIrPackOutputListTable();
        }

        //Sets vertical output device list
        setOutputList();

        //Override fonts for all text view
        Util.overrideFonts(getActivity(), _view.findViewById(R.id.settingLightTv), 1);
        Util.overrideFonts(getActivity(), _view.findViewById(R.id.settingTv), 1);

        return _view;
    }

For a solution I implemented dispacthTouchEvent() method in my fragment's parent activity so touchEvents started working but onClickListener events not working on other views.

Here is my code of activity for dispacthTouchEvent method:

@Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN: {
                downX = event.getX();
                downY = event.getY();
                return true;
            }
            case MotionEvent.ACTION_UP: {
                upX = event.getX();
                upY = event.getY();
                float deltaX = downX - upX;
                float deltaY = downY - upY;

                // swipe horizontal?
                if (Math.abs(deltaX) > MIN_DISTANCE) {
                    // left or right
                    if (deltaX < 0) {
                        //this.onLeftToRightSwipe();
                        //((MenuActivity) getActivity()).getSlideoutHelper().close();
                        return true;
                    }
                    if (deltaX > 0) {
                        //this.onRightToLeftSwipe();
                        if (mSlideoutHelper != null)
                            mSlideoutHelper.close();
                        return true;
                    }
                } else if (Math.abs(deltaX) == 0) {
                    // return false; // We don't consume the event

                    //Single tap implementation
                }
                return true; // no swipe horizontally and no swipe vertically
            }// case MotionEvent.ACTION_UP:
        }
        return super.dispatchTouchEvent(event);
    }

Body:
Dont consume your touch pass it along ;

@Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN: {
                downX = event.getX();
                downY = event.getY();
                //return false;
            }
            case MotionEvent.ACTION_UP: {
                upX = event.getX();
                upY = event.getY();
                float deltaX = downX - upX;
                float deltaY = downY - upY;

                // swipe horizontal?
                if (Math.abs(deltaX) > MIN_DISTANCE) {
                    // left or right
                    if (deltaX < 0) {
                        //this.onLeftToRightSwipe();
                        //((MenuActivity) getActivity()).getSlideoutHelper().close();
                        return true;
                    }
                    if (deltaX > 0) {
                        //this.onRightToLeftSwipe();
                        if (mSlideoutHelper != null)
                            mSlideoutHelper.close();
                        return true;
                    }
                } else if (Math.abs(deltaX) == 0) {
                    // return false; // We don't consume the event

                    //Single tap implementation
                }
                //return true; // no swipe horizontally and no swipe vertically
            }// case MotionEvent.ACTION_UP:
        }
        return super.dispatchTouchEvent(event);
    }


问:
get a pid using a list of handles for a particular process
 Please refer to this.

https://pastebin.com/LTPiZUGs
This script gets a handle list of a process.

Can I use this script to get the name or pid of the process that holds the handle of a process? If possible, please give us sample code.

答:
I wrote a script a while ago which should contain all the necessary pieces to do what you want. The script as is simply lists all file handles and their processes.

The script is too long to paste it in this answer, so please refer to:

https://github.com/T-vK/WhoLockedMe


问:
How to create a 2D array using single array angular js
How can we create 2D array from single array

```<code>angular.forEach(angular.fromJson(value.resource_type_efforts), function (value1, key1) {
          $scope.data.resource_type.push(key1);
});
</code>```

when I do console.log($scope.data.resource_type) output is :-

```<code>0 :  "Senior Software Engineer"
1 :  "Software Engineer"
2 :  "QA Engineer"
3 :  "UI Developer"
4 :  "UI Designer"
5 :  "UI Developer"
6 :  "QA Engineer"
7 :  "Software Engineer"
</code>```

Now i need to split this array in 2-d array after every 4 values.

```<code>0:
  0 :  "Senior Software Engineer"
  1 :  "Software Engineer"
  2 :  "QA Engineer"
  3 :  "UI Developer"
1:
  0 :  "UI Designer"
  1 :  "UI Developer"
  2 :  "QA Engineer"
  3 :  "Software Engineer"
</code>```

Please suggest some answers

答:
Take one output array and inside loop push value in temp variable when key got %4 == 0 push temp to output array and blank temp array</p>

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope)
{
    $scope.resource_type_efforts =
    [
        'Senior Software Engineer',
        'Software Engineer',
        'QA Engineer',
        'UI Developer',
        'UI Designer',
        'UI Developer',
        'QA Engineer',
        'Software Engineer'
    ];

    $scope.output = [];
    var temp = [];
    angular.forEach(angular.fromJson($scope.resource_type_efforts), function (value1, key1)
    {

        temp.push(value1);
        if((key1+1)%4==0)
        {
            $scope.output.push(temp);
            temp = [];
        }
    });
    console.log($scope.output);
});
</script>

</body>
</html>
</code>```

Body:
How can we create 2D array from single array

angular.forEach(angular.fromJson(value.resource_type_efforts), function (value1, key1) {
          $scope.data.resource_type.push(key1);
});

when I do console.log($scope.data.resource_type) output is :-

0 :  "Senior Software Engineer"
1 :  "Software Engineer"
2 :  "QA Engineer"
3 :  "UI Developer"
4 :  "UI Designer"
5 :  "UI Developer"
6 :  "QA Engineer"
7 :  "Software Engineer"

Now i need to split this array in 2-d array after every 4 values.

0:
  0 :  "Senior Software Engineer"
  1 :  "Software Engineer"
  2 :  "QA Engineer"
  3 :  "UI Developer"
1:
  0 :  "UI Designer"
  1 :  "UI Developer"
  2 :  "QA Engineer"
  3 :  "Software Engineer"

Please suggest some answers

Body:
Take one output array and inside loop push value in temp variable when key got %4 == 0 push temp to output array and blank temp array

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope)
{
    $scope.resource_type_efforts =
    [
        'Senior Software Engineer',
        'Software Engineer',
        'QA Engineer',
        'UI Developer',
        'UI Designer',
        'UI Developer',
        'QA Engineer',
        'Software Engineer'
    ];

    $scope.output = [];
    var temp = [];
    angular.forEach(angular.fromJson($scope.resource_type_efforts), function (value1, key1)
    {

        temp.push(value1);
        if((key1+1)%4==0)
        {
            $scope.output.push(temp);
            temp = [];
        }
    });
    console.log($scope.output);
});
</script>

</body>
</html>

ContentLicense: CC BY-SA 4.0


问:
Warning : Divison by zero on woocommerce in wc-template function
```<code>function wc_get_loop_class() {
    global $woocommerce_loop;

    $woocommerce_loop['loop']    = ! empty( $woocommerce_loop['loop'] ) ? $woocommerce_loop['loop'] + 1   : 1;
    $woocommerce_loop['columns'] = ! empty( $woocommerce_loop['columns'] ) ? $woocommerce_loop['columns'] : apply_filters( 'loop_shop_columns', 4 );
    if ( 0 === ( $woocommerce_loop['loop'] - 1 ) % $woocommerce_loop['columns'] || 1 === $woocommerce_loop['columns'] ) {
        return 'first';
    } elseif ( 0 === $woocommerce_loop['loop'] % $woocommerce_loop['columns'] ) {
        return 'last';
    } else {
        return '';
    }
}
</code>```

Warning: Division by zero in
  /home/betawebs/public_html/tech/betawp/attwp/wp-content/plugins/woocommerce/includes/wc-template-functions.php
  on line 249 class="post-2606

My page is giving above error pls help

答:
This will be corrected in the next stable release.
Take a look at line 260:
https://github.com/woocommerce/woocommerce/blob/master/includes/wc-template-functions.php </p>

Body:
function wc_get_loop_class() {
    global $woocommerce_loop;

    $woocommerce_loop['loop']    = ! empty( $woocommerce_loop['loop'] ) ? $woocommerce_loop['loop'] + 1   : 1;
    $woocommerce_loop['columns'] = ! empty( $woocommerce_loop['columns'] ) ? $woocommerce_loop['columns'] : apply_filters( 'loop_shop_columns', 4 );
    if ( 0 === ( $woocommerce_loop['loop'] - 1 ) % $woocommerce_loop['columns'] || 1 === $woocommerce_loop['columns'] ) {
        return 'first';
    } elseif ( 0 === $woocommerce_loop['loop'] % $woocommerce_loop['columns'] ) {
        return 'last';
    } else {
        return '';
    }
}

Warning: Division by zero in
  /home/betawebs/public_html/tech/betawp/attwp/wp-content/plugins/woocommerce/includes/wc-template-functions.php
  on line 249 class="post-2606

My page is giving above error pls help


问:
Wpf ScrollIntoView not working first time
I have a ListView include Expander, and I assign a SelectedIndex, then call ScrollIntoView to SelectedItem position. (It can auto expand.)

lv_SelectionChanged was invoke every times.

```<code>private void lv_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        foreach (Expander exp in FindVisualChildren<Expander>(lv.lv))
        {
            var a = (exp.Header as StackPanel).Children[0] as TextBlock;
            if (a.Text.Equals((lv.lv.SelectedItem as User).group))
                exp.IsExpanded = true;
        }
        lv.ScrollIntoView(lv.SelectedItem);
    }
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }
</code>```

But, it was not working at first time. (If it's a simple ListView, it work!)

I have no idea.

Thx.

xaml

```<code><UserControl.Resources>
    <Style TargetType="{x:Type GridViewColumnHeader}">
        <Setter Property="HorizontalContentAlignment" Value="Center" />
    </Style>
    <Style x:Key="GroupHeaderStyle" TargetType="{x:Type GroupItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <!--<Expander IsExpanded="{Binding Mode=TwoWay, Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}, Mode=FindAncestor}}" MouseRightButtonDown="Expander_MouseRightButtonDown">-->
                    <Expander IsExpanded="False"  MouseRightButtonDown="Expander_MouseRightButtonDown">
                        <Expander.Header>
                            <StackPanel Orientation="Horizontal">
                                <StackPanel.ContextMenu>
                                    <ContextMenu>
                                        <MenuItem Name="mi_ExpandAll" Header="Hide Age column" Click="mi_ExpandAll_Click"/>
                                        <MenuItem Name="mi_CollapseAll" Header="None"/>
                                    </ContextMenu>
                                </StackPanel.ContextMenu>
                                <TextBlock Text="{Binding Name}" FontWeight="Bold" Foreground="Gray" FontSize="16" VerticalAlignment="Bottom"/>
                                <TextBlock Text="{Binding ItemCount}" FontSize="22" Foreground="Green" FontWeight="Bold" FontStyle="Italic" Margin="10,0,0,0" VerticalAlignment="Bottom" />
                                <TextBlock Text=" item(s)" FontSize="22" Foreground="Silver" FontStyle="Italic" VerticalAlignment="Bottom" />
                            </StackPanel>
                        </Expander.Header>
                        <ItemsPresenter>
                            <ItemsPresenter.ContextMenu>
                                <ContextMenu>
                                    <MenuItem Header="Add Item" Click="MenuItem_Click"/>
                                    <MenuItem Header="Menu Item 2">
                                        <MenuItem Header="Remove Item" Click="MenuItem_Click_1"></MenuItem>
                                        <MenuItem Header="Select last Item" Click="MenuItem_Click_2"></MenuItem>
                                    </MenuItem>
                                </ContextMenu>
                            </ItemsPresenter.ContextMenu>
                        </ItemsPresenter>
                    </Expander>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Resources>
<ListView Margin="10" Name="lv" Grid.Row="0" ItemsSource="{Binding GroupView}" SelectedIndex="{Binding Index}" SelectedItem="{Binding Item}" SelectionChanged="lv_SelectionChanged">
            <ListView.View>
                <GridView>
                    <local:GridViewColumnExt Header="Name" Width="120" DisplayMemberBinding="{Binding Name}"/>
                    <local:GridViewColumnExt x:Name="colAge" Header="Age" Width="50">
                        <local:GridViewColumnExt.CellTemplate>
                            <DataTemplate>
                                <Button Content="{Binding Age}"></Button>
                            </DataTemplate>
                        </local:GridViewColumnExt.CellTemplate>
                    </local:GridViewColumnExt>
                </GridView>
            </ListView.View>
            <ListView.GroupStyle>
                <GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle}">
                </GroupStyle>
            </ListView.GroupStyle>
        </ListView>
</code>```

I set SelectedIndex in event

```<code>private void MenuItem_Click_2(object sender, RoutedEventArgs e)
    {
        lv.SelectedIndex = 8;
    }
</code>```

Edit

I try to set IsExpanded="True", then it is work. So, if IsExpanded="False" at first, can't it scrolling?

答: I user expander.BringIntoView(), then it's work!</p>

Body:
I have a ListView include Expander, and I assign a SelectedIndex, then call ScrollIntoView to SelectedItem position. (It can auto expand.)

lv_SelectionChanged was invoke every times.

private void lv_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        foreach (Expander exp in FindVisualChildren<Expander>(lv.lv))
        {
            var a = (exp.Header as StackPanel).Children[0] as TextBlock;
            if (a.Text.Equals((lv.lv.SelectedItem as User).group))
                exp.IsExpanded = true;
        }
        lv.ScrollIntoView(lv.SelectedItem);
    }
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }

But, it was not working at first time. (If it's a simple ListView, it work!)

I have no idea.

Thx.

xaml

<UserControl.Resources>

</UserControl.Resources>
<ListView Margin="10" Name="lv" Grid.Row="0" ItemsSource="{Binding GroupView}" SelectedIndex="{Binding Index}" SelectedItem="{Binding Item}" SelectionChanged="lv_SelectionChanged">
            <ListView.View>
                <GridView>
                    <local:GridViewColumnExt Header="Name" Width="120" DisplayMemberBinding="{Binding Name}"/>
                    <local:GridViewColumnExt x:Name="colAge" Header="Age" Width="50">
                        <local:GridViewColumnExt.CellTemplate>
                            <DataTemplate>
                                <Button Content="{Binding Age}"></Button>
                            </DataTemplate>
                        </local:GridViewColumnExt.CellTemplate>
                    </local:GridViewColumnExt>
                </GridView>
            </ListView.View>
            <ListView.GroupStyle>
                <GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle}">
                </GroupStyle>
            </ListView.GroupStyle>
        </ListView>

I set SelectedIndex in event

private void MenuItem_Click_2(object sender, RoutedEventArgs e)
    {
        lv.SelectedIndex = 8;
    }

Edit

I try to set IsExpanded="True", then it is work. So, if IsExpanded="False" at first, can't it scrolling?


问:
Why is $event not working with ng-change?
This is my html tag which has ng-change event and I am passing $event as an arg to it.

```<code> <input type="text" ng-model="dynamicField.value" ng-change="myFunction(dynamicField,$event)"/>
</code>```

Below is my angularJS function-

```<code>$scope.myFunction=function(dynamicField,event){
alert(event);
}
</code>```

whenever this function is called, the alert shows event's value as 'undefined'.

Please guide me.

答:
From angular.js, ngChange directive registers an

Angular expression to be executed when input changes due to user
  interaction with the input element.

The directive just adds the evaluated expression to the list of view change listeners,

```<code>var ngChangeDirective = valueFn({
  restrict: 'A',
  require: 'ngModel',
  link: function(scope, element, attr, ctrl) {
    ctrl.$viewChangeListeners.push(function() {
      scope.$eval(attr.ngChange);
    });
  }
});
</code>```

Once $modelValue is update, these listeners get executed one at a time,

```<code>this.$$writeModelToScope = function() {
    ngModelSet($scope, ctrl.$modelValue);
    forEach(ctrl.$viewChangeListeners, function(listener) {
      try {
        listener();
      } catch (e) {
        $exceptionHandler(e);
      }
    });
  };
</code>```

As you see no events get passed around, because all ngChange does is executes the expression upon an update of the ngModel. It's a good way to make sure that your expression runs after the model value gets set.

As opposed to ngChange ngClick passes the $event into the click handling function, because it handles a DOM event,

```<code>forEach(
  'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  function(eventName) {
    var directiveName = directiveNormalize('ng-' + eventName);
    ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
      return {
        restrict: 'A',
        compile: function($element, attr) {
          // We expose the powerful $event object on the scope that provides access to the Window,
          // etc. that isn't protected by the fast paths in $parse.  We explicitly request better
          // checks at the cost of speed since event handler expressions are not executed as
          // frequently as regular change detection.
          var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
          return function ngEventHandler(scope, element) {
            element.on(eventName, function(event) {
              var callback = function() {
                fn(scope, {$event:event});
              };
              if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
                scope.$evalAsync(callback);
              } else {
                scope.$apply(callback);
              }
            });
          };
        }
      };
    }];
  }
);
</code>```

You see on occurrence of the event, the DOM event object gets passed into the handling function as $event, fn(scope, {$event:event});.

Body:
This is my html tag which has ng-change event and I am passing $event as an arg to it.

 <input type="text" ng-model="dynamicField.value" ng-change="myFunction(dynamicField,$event)"/>

Below is my angularJS function-

$scope.myFunction=function(dynamicField,event){
alert(event);
}

whenever this function is called, the alert shows event's value as 'undefined'.

Please guide me.

Body:
From angular.js, ngChange directive registers an

Angular expression to be executed when input changes due to user
  interaction with the input element.

The directive just adds the evaluated expression to the list of view change listeners,

var ngChangeDirective = valueFn({
  restrict: 'A',
  require: 'ngModel',
  link: function(scope, element, attr, ctrl) {
    ctrl.$viewChangeListeners.push(function() {
      scope.$eval(attr.ngChange);
    });
  }
});

Once $modelValue is update, these listeners get executed one at a time,

this.$$writeModelToScope = function() {
    ngModelSet($scope, ctrl.$modelValue);
    forEach(ctrl.$viewChangeListeners, function(listener) {
      try {
        listener();
      } catch (e) {
        $exceptionHandler(e);
      }
    });
  };

As you see no events get passed around, because all ngChange does is executes the expression upon an update of the ngModel. It's a good way to make sure that your expression runs after the model value gets set.

As opposed to ngChange ngClick passes the $event into the click handling function, because it handles a DOM event,

forEach(
  'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  function(eventName) {
    var directiveName = directiveNormalize('ng-' + eventName);
    ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
      return {
        restrict: 'A',
        compile: function($element, attr) {
          // We expose the powerful $event object on the scope that provides access to the Window,
          // etc. that isn't protected by the fast paths in $parse.  We explicitly request better
          // checks at the cost of speed since event handler expressions are not executed as
          // frequently as regular change detection.
          var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
          return function ngEventHandler(scope, element) {
            element.on(eventName, function(event) {
              var callback = function() {
                fn(scope, {$event:event});
              };
              if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
                scope.$evalAsync(callback);
              } else {
                scope.$apply(callback);
              }
            });
          };
        }
      };
    }];
  }
);

You see on occurrence of the event, the DOM event object gets passed into the handling function as $event, fn(scope, {$event:event});.


问:
c++ paste value and print string
I declare 2 string type strings, qhich is s, s1. I use s string with 'cin'
and I paste 3 values in s1. Then I print with 'cout' but it can't print string.

Here is my code

```<code>#include<iostream>
#include<cstdio>
using namespace std;

int main()

{

    string s,s1;
    cin>>s;
    s1[0]=s[1];
    s1[1]=s[2];
    s1[2]=s[3];
    s1[3]='\0';
    cout<<s1<<endl;
    return 0;
}
</code>```

s1 was not empty.... cout<<s1[0]<<s1[1]<<s1[2] and see.
Why s1 can't print?

答:
You can not assign as s1[0] = s[1]

Correct way is using assign function as:

```<code>string s,s1;
cin>>s;
s1.assign(s.begin()+1,s.begin()+4);
cout<<s1<<endl;
</code>```

Title: c++ paste value and print string

Body:
I declare 2 string type strings, qhich is s, s1. I use s string with 'cin'
and I paste 3 values in s1. Then I print with 'cout' but it can't print string.

Here is my code

#include<iostream>
#include<cstdio>
using namespace std;

int main()

{

    string s,s1;
    cin>>s;
    s1[0]=s[1];
    s1[1]=s[2];
    s1[2]=s[3];
    s1[3]='\0';
    cout<<s1<<endl;
    return 0;
}

s1 was not empty.... cout<<s1[0]<<s1[1]<<s1[2] and see.
Why s1 can't print?

Body:
You can not assign as s1[0] = s[1]

Correct way is using assign function as:

string s,s1;
cin>>s;
s1.assign(s.begin()+1,s.begin()+4);
cout<<s1<<endl;


问:
How to write custom Sorting in ag-grid?
I have a custom sorting function which sorts alphanumerically. I have set it to comparator as mentioned in ag-grid but, I dont find it working. Please put in some light.</p>

```<code>var naturalSort = function(valueA, valueB, nodeA, nodeB, isInverted) {

      var NUMBER_GROUPS = /(-?\d*\.?\d+)/g;

      var aa = String(valueA).split(NUMBER_GROUPS),
        bb = String(valueB).split(NUMBER_GROUPS),
        min = Math.min(aa.length, bb.length);

      for (var i = 0; i < min; i++) {
        var x = parseFloat(aa[i]) || aa[i].toLowerCase(),
          y = parseFloat(bb[i]) || bb[i].toLowerCase();
        if (x < y) return -1;
        else if (x > y) return 1;
      }

      return 0;
    };

var columnDefs = [
    {headerName: "Name", field: "name", width: 110, comparator: naturalSort}

];

var gridOptions = {
    columnDefs: columnDefs,
    rowData: null,
    enableSorting: true
};
</code>```

答:
As I tried to use the comparator function all the parameters showed as "undefined".  There is no way of providing the values to compare or even node because as far as I could see naturalSort function is executed only once when rendering the grid.

For any alteration you need to do on sorting provide the full rowData to the natural sort function. Then for each row return the value you want the sorting to be used.

```<code>var columnDefs = [{
    field: "totalIncVat",
    headerName: translations.totalIncVAT,
    template: '<div title="{{data.totalIncVat | currency:\'£\'}}"> {{data.totalIncVat | currency:\'£\'}}</div>',
    comparator: naturalSort($scope.transactionsData)
}]

//componsate/reverse template alteration to actual field for correct sorting
var naturalSort = function(gridDataArray){
    _.forEach(gridDataArray, function(transaction){
        return gridDataArray.totalIncVat;
    });
};

$scope.gridOptions = _.defaults({
    rowData: $scope.gridDataArray,
    columnDefs: columnDefs
});
</code>```

Title: How to write custom Sorting in ag-grid?

Body:
I have a custom sorting function which sorts alphanumerically. I have set it to comparator as mentioned in ag-grid but, I dont find it working. Please put in some light.

var naturalSort = function(valueA, valueB, nodeA, nodeB, isInverted) {

      var NUMBER_GROUPS = /(-?\d*\.?\d+)/g;

      var aa = String(valueA).split(NUMBER_GROUPS),
        bb = String(valueB).split(NUMBER_GROUPS),
        min = Math.min(aa.length, bb.length);

      for (var i = 0; i < min; i++) {
        var x = parseFloat(aa[i]) || aa[i].toLowerCase(),
          y = parseFloat(bb[i]) || bb[i].toLowerCase();
        if (x < y) return -1;
        else if (x > y) return 1;
      }

      return 0;
    };

var columnDefs = [
    {headerName: "Name", field: "name", width: 110, comparator: naturalSort}

];

var gridOptions = {
    columnDefs: columnDefs,
    rowData: null,
    enableSorting: true
};

Body:
As I tried to use the comparator function all the parameters showed as "undefined".  There is no way of providing the values to compare or even node because as far as I could see naturalSort function is executed only once when rendering the grid.

For any alteration you need to do on sorting provide the full rowData to the natural sort function. Then for each row return the value you want the sorting to be used.

var columnDefs = [{
    field: "totalIncVat",
    headerName: translations.totalIncVAT,
    template: '<div title="{{data.totalIncVat | currency:\'&pound;\'}}"> {{data.totalIncVat | currency:\'&pound;\'}}</div>',
    comparator: naturalSort($scope.transactionsData)
}]

//componsate/reverse template alteration to actual field for correct sorting
var naturalSort = function(gridDataArray){
    _.forEach(gridDataArray, function(transaction){
        return gridDataArray.totalIncVat;
    });
};

$scope.gridOptions = _.defaults({
    rowData: $scope.gridDataArray,
    columnDefs: columnDefs
});


问:
5 boxes not centering correctly in the center of the page
I am totally new into programming. I've aligned 5 boxed horizontally , but what I want is to center the boxes. The boxes should also be responsive what they are right now. I am searching and searching for how to center a div, but as result I get
 margin: 0 auto; width: 800px;. When I adjust my browser to 100%, the 5th box get under the other boxes.

.square {
 float:left;
 width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="outside">
  <div class="square">
   <span>2.1</span>
  </div>
  <div class="square">
   <span>2.3</span>
  </div>
  <div class="square">
   <span>2.5</span>
  </div>
  <div class="square">
   <span>2.6</span>
  </div>
  <div class="square">
   <span>2.7</span>
  </div>
 </div></code>```

答:
add text-align center for outside

```<code>.outside{
  text-align:center;
}
</code>```

Remove float & add display inline-block square

```<code>.square{
    display:inline-block;
    width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
    position: relative;
    border: 0.5px solid red;
    text-align: center;

}
</code>```

Body:
I am totally new into programming. I've aligned 5 boxed horizontally , but what I want is to center the boxes. The boxes should also be responsive what they are right now. I am searching and searching for how to center a div, but as result I get
 margin: 0 auto; width: 800px;. When I adjust my browser to 100%, the 5th box get under the other boxes.

.square {
 float:left;
 width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}

   2.1

   2.3

   2.5

   2.6

   2.7

Body:
add text-align center for outside

.outside{
  text-align:center;
}

Remove float & add display inline-block square

.square{
    display:inline-block;
    width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
    position: relative;
    border: 0.5px solid red;
    text-align: center;

}


问:
IF END IF IN SQL STORED PROCEDURE
I am trying to create a advanced search query in which user's name,status and role are filtered at the same time (one or more can be selected).
Given below is the code for the SQL Stored Procedure
I want a way to have IF and END IF, so that the where condition in all the cases are mutually exclusive
Currently if the first name is null, then the rest of the conditions fail</p>

```<code>USE [qcsl]
GO
/***** Object:  StoredProcedure [dbo].[UserAdvancedSearch]    Script Date: 3/31/2017 3:25:28 PM *****/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:        Mayank
-- Create date: 2017-03-29
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[UserAdvancedSearch]
    -- Add the parameters for the stored procedure here
  (
    @user_name varchar(50) = NULL,
    @user_last_name varchar(50) = NULL,
    @role_id varchar(50) = NULL,
    @user_status varchar(50) = NULL,
    @query varchar(2000) = NULL output
  )
  AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here

    SET @query = 'select * from user_main
    where
    'IF (@user_name is not null ) SET @query = @query + '
    (user_first_name like '''+@user_name+''' OR user_first_name IS NULL)
    'IF (@user_last_name is not null ) SET @query = @query + 'AND
    (user_last_name like '''+@user_last_name+''' OR user_last_name IS NULL)
    'IF (@user_status is not null ) SET @query = @query + 'AND
    (user_status = '+@user_status+') 'IF (@role_id is not null) SET @query = @query + '
    AND
    (user_role_id_ref = '+@role_id+')'
    EXEC(@query);
END
</code>```

答:
If MSSQL db and if I understood you question, I think you could write:

(mutually esclusive):

```<code>SET @query = 'SELECT * FROM USER_MAIN WHERE '
IF (@user_name is not null ) SET @query = @query + '(user_first_name like '''+@user_name+''' OR user_first_name IS NULL)'
ELSE IF (@user_last_name is not null ) SET @query = @query + ' (user_last_name like '''+@user_last_name+''' OR user_last_name IS NULL)'
ELSE IF (@user_status is not null ) SET @query = @query + ' (user_status = '+@user_status+') '
ELSE IF (@role_id is not null) SET @query = @query + ' (user_role_id_ref = '+@role_id+')'
</code>```

Edit: instead if you want all together:

```<code>SET @query = 'SELECT * FROM USER_MAIN WHERE 1=1 '
IF (@user_name is not null ) SET @query = @query + 'AND (user_first_name like '''+@user_name+''' OR user_first_name IS NULL)'
IF (@user_last_name is not null ) SET @query = @query + 'AND (user_last_name like '''+@user_last_name+''' OR user_last_name IS NULL)'
IF (@user_status is not null ) SET @query = @query + 'AND (user_status = '+@user_status+') '
IF (@role_id is not null) SET @query = @query + 'AND (user_role_id_ref = '+@role_id+')'
</code>```

Title: IF END IF IN SQL STORED PROCEDURE

Body:
I am trying to create a advanced search query in which user's name,status and role are filtered at the same time (one or more can be selected).
Given below is the code for the SQL Stored Procedure
I want a way to have IF and END IF, so that the where condition in all the cases are mutually exclusive
Currently if the first name is null, then the rest of the conditions fail

USE [qcsl]
GO
/***** Object:  StoredProcedure [dbo].[UserAdvancedSearch]    Script Date: 3/31/2017 3:25:28 PM *****/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:        Mayank
-- Create date: 2017-03-29
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[UserAdvancedSearch]
    -- Add the parameters for the stored procedure here
  (
    @user_name varchar(50) = NULL,
    @user_last_name varchar(50) = NULL,
    @role_id varchar(50) = NULL,
    @user_status varchar(50) = NULL,
    @query varchar(2000) = NULL output
  )
  AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here

    SET @query = 'select * from user_main
    where
    'IF (@user_name is not null ) SET @query = @query + '
    (user_first_name like '''+@user_name+''' OR user_first_name IS NULL)
    'IF (@user_last_name is not null ) SET @query = @query + 'AND
    (user_last_name like '''+@user_last_name+''' OR user_last_name IS NULL)
    'IF (@user_status is not null ) SET @query = @query + 'AND
    (user_status = '+@user_status+') 'IF (@role_id is not null) SET @query = @query + '
    AND
    (user_role_id_ref = '+@role_id+')'
    EXEC(@query);
END

Body:
If MSSQL db and if I understood you question, I think you could write:

(mutually esclusive):

SET @query = 'SELECT * FROM USER_MAIN WHERE '
IF (@user_name is not null ) SET @query = @query + '(user_first_name like '''+@user_name+''' OR user_first_name IS NULL)'
ELSE IF (@user_last_name is not null ) SET @query = @query + ' (user_last_name like '''+@user_last_name+''' OR user_last_name IS NULL)'
ELSE IF (@user_status is not null ) SET @query = @query + ' (user_status = '+@user_status+') '
ELSE IF (@role_id is not null) SET @query = @query + ' (user_role_id_ref = '+@role_id+')'

Edit: instead if you want all together:

SET @query = 'SELECT * FROM USER_MAIN WHERE 1=1 '
IF (@user_name is not null ) SET @query = @query + 'AND (user_first_name like '''+@user_name+''' OR user_first_name IS NULL)'
IF (@user_last_name is not null ) SET @query = @query + 'AND (user_last_name like '''+@user_last_name+''' OR user_last_name IS NULL)'
IF (@user_status is not null ) SET @query = @query + 'AND (user_status = '+@user_status+') '
IF (@role_id is not null) SET @query = @query + 'AND (user_role_id_ref = '+@role_id+')'


问:
C# Array.Resize Passing a Ref instead of a Value
Title might be a bit misleading

I have a string array. That I would like to pass by reference.

I know it can be accomplished simply by

```<code>public class test{
    string[] content = {"abc", "abd"};
    ViewContent vc = new ViewContent();

    public static void Main()
    {
        vc.InitView(content);
    }
}

public class ViewContent{
     string[] contentToView;

     public void InitView(ref string[] contentToShow)
     {
         contentToView = contentToShow;
         View();
     }

     public void View()
     {
         //Do whatever with contentToView
         //Example
         Array.Resize<string> (ref contentToView, someInt);
     }
}
</code>```

If I were to resize the array with

```<code>Array.Resize()
</code>```

The reference breaks and any further edits upon the resized array is not reflected on the main array from test class.

My question is:

How do I prevent the reference to the main array from breaking when the need arises for me to resize it?

Rephrase

How do I resize contentToView while also resizing content in test class?

Yes, I know it would be simpler to use Lists but I am experimenting with Arrays.

Yes, I know my problems would be solved if I pass in the test object instead of just an array. I am avoiding this method because I have other objects that have string arrays as well. You might ask that if I have other objects, that serve similar functions I could use inheritance and take in the base class to ensure that all my content can be shown. This is something I would like to avoid.

答:
How do I prevent the reference to the main array from breaking when the need arises for me to resize it?

You don't. You just don't use an array. Array objects aren't resizable, and after you've copied the value of contentToShow into contentToView, any further changes to the contentToShow variable are ignored, and likewise in reverse.

What you're asking is for contentToView to change its value (which is a reference) every time content in your test class changes, or vice versa. There's no way of achieving that. You could introduce another level of indirection with a Wrapper<T> class you'd write which basically looks like this:

```<code>public class Wrapper<T>
{
    public T Value { get; set; }
}
</code>```

If you then made test.content and ViewContent.contentToView both Wrapper<string[]> fields, then if you change test.content.Value, you'd see that change in ViewContent.contentToView.Value... but I would advise against it.

Body:
Title might be a bit misleading

I have a string array. That I would like to pass by reference.

I know it can be accomplished simply by

public class test{
    string[] content = {"abc", "abd"};
    ViewContent vc = new ViewContent();

    public static void Main()
    {
        vc.InitView(content);
    }
}

public class ViewContent{
     string[] contentToView;

     public void InitView(ref string[] contentToShow)
     {
         contentToView = contentToShow;
         View();
     }

     public void View()
     {
         //Do whatever with contentToView
         //Example
         Array.Resize<string> (ref contentToView, someInt);
     }
}

If I were to resize the array with

Array.Resize()

The reference breaks and any further edits upon the resized array is not reflected on the main array from test class.

My question is:

How do I prevent the reference to the main array from breaking when the need arises for me to resize it?

Rephrase

How do I resize contentToView while also resizing content in test class?

Yes, I know it would be simpler to use Lists but I am experimenting with Arrays.

Yes, I know my problems would be solved if I pass in the test object instead of just an array. I am avoiding this method because I have other objects that have string arrays as well. You might ask that if I have other objects, that serve similar functions I could use inheritance and take in the base class to ensure that all my content can be shown. This is something I would like to avoid.

Body:
How do I prevent the reference to the main array from breaking when the need arises for me to resize it?

You don't. You just don't use an array. Array objects aren't resizable, and after you've copied the value of contentToShow into contentToView, any further changes to the contentToShow variable are ignored, and likewise in reverse.

What you're asking is for contentToView to change its value (which is a reference) every time content in your test class changes, or vice versa. There's no way of achieving that. You could introduce another level of indirection with a Wrapper<T> class you'd write which basically looks like this:

public class Wrapper<T>
{
    public T Value { get; set; }
}

If you then made test.content and ViewContent.contentToView both Wrapper<string[]> fields, then if you change test.content.Value, you'd see that change in ViewContent.contentToView.Value... but I would advise against it.


问:
What is the purpose of a self executing function in javascript?
In javascript, when would you want to use this:

```<code>(function(){
    //Bunch of code...
})();
</code>```

over this:

```<code>//Bunch of code...
</code>```

答:
```<code>(function(){
    var foo = {
        name: 'bob'
    };
    console.log(foo.name); // bob
})();
console.log(foo.name); // Reference error
</code>```

Actually, the above function will be treated as function expression without a name.

The main purpose of wrapping a function with close and open parenthesis is to avoid polluting the global space.

The variables and functions inside the function expression became private (i.e) they will not be available outside of the function.

OwnerDisplayName: Ej

Body:
In javascript, when would you want to use this:

(function(){
    //Bunch of code...
})();

over this:

//Bunch of code...

Body:
(function(){
    var foo = {
        name: 'bob'
    };
    console.log(foo.name); // bob
})();
console.log(foo.name); // Reference error

Actually, the above function will be treated as function expression without a name.

The main purpose of wrapping a function with close and open parenthesis is to avoid polluting the global space.

The variables and functions inside the function expression became private (i.e) they will not be available outside of the function.


问:
How to determine similarity between two images using Imgproc.compareHist method of opencv in java?
I am using opencv_249 dll in java. Using below code to compare two image matrices.
The code is throwing some exception which I am not able to resolve.

```<code>static double compareImages(Mat main, Mat temp){
    main.convertTo(main, CvType.CV_32FC3);
    temp.convertTo(temp, CvType.CV_32FC3);
    Core.normalize(main, temp, 1.0, 0.0, Core.NORM_L1);
    double s=Imgproc.compareHist(main, temp, Imgproc.CV_COMP_CORREL);
    return s;
}
</code>```

The code is throwing following exception:

```<code>OpenCV Error: Assertion failed (H1.type() == H2.type() && H1.type() == CV_32F) in cv::compareHist,
file ..\..\..\..\opencv\modules\imgproc\src\histogram.cpp,
line 1985
Exception in thread "main"
CvException [org.opencv.core.CvException:
cv::Exception: ..\..\..\..\opencv\modules\imgproc\src\histogram.cpp:1985:
error: (-215) H1.type() == H2.type() && H1.type() == CV_32F
in function cv::compareHist ]
at org.opencv.imgproc.Imgproc.compareHist_0(Native Method)
at org.opencv.imgproc.Imgproc.compareHist(Imgproc.java:3051)
at ImageComparator.main(ImageComparator.java:88)
</code>```

Could anyone tell what is being missed out in the code?

答:
****OpenCV Error: Assertion failed (H1.type() == H2.type() && H1.type() == CV_32F) in...

As the error message tells you an assertion failed.
Both input image have to be of the same type and that type must be CV_32F.

Maybe you noticed that your input type is CV_32FC3?

Body:
I am using opencv_249 dll in java. Using below code to compare two image matrices.
The code is throwing some exception which I am not able to resolve.

static double compareImages(Mat main, Mat temp){
    main.convertTo(main, CvType.CV_32FC3);
    temp.convertTo(temp, CvType.CV_32FC3);
    Core.normalize(main, temp, 1.0, 0.0, Core.NORM_L1);
    double s=Imgproc.compareHist(main, temp, Imgproc.CV_COMP_CORREL);
    return s;
}

The code is throwing following exception:

OpenCV Error: Assertion failed (H1.type() == H2.type() && H1.type() == CV_32F) in cv::compareHist,
file ..\..\..\..\opencv\modules\imgproc\src\histogram.cpp,
line 1985
Exception in thread "main"
CvException [org.opencv.core.CvException:
cv::Exception: ..\..\..\..\opencv\modules\imgproc\src\histogram.cpp:1985:
error: (-215) H1.type() == H2.type() && H1.type() == CV_32F
in function cv::compareHist ]
at org.opencv.imgproc.Imgproc.compareHist_0(Native Method)
at org.opencv.imgproc.Imgproc.compareHist(Imgproc.java:3051)
at ImageComparator.main(ImageComparator.java:88)

Could anyone tell what is being missed out in the code?


问:
How to find set difference in Mysql?
What is the 'except' equivalent command in mysql?

```<code>SELECT name FROM table1 except SELECT name FROM table2
</code>```

答:
This query will work for your scenario:</p>

```<code>select A.*
from
(SELECT name FROM table1) A,
((SELECT name FROM table1) B
where
A.name != B.name;
</code>```

Title: How to find set difference in Mysql?

Body:
What is the 'except' equivalent command in mysql?

SELECT name FROM table1 except SELECT name FROM table2

Body:
This query will work for your scenario:

select A.*
from
(SELECT name FROM table1) A,
((SELECT name FROM table1) B
where
A.name != B.name;