问:
How to Call Javascript method from a javascript file in the Iframe of aspx page?
I have an aspx page where I have a parent page xyz.aspx page where one js file(abc.js) mentioned in the  tag. I need to call a method written in abc.js in child aspx page on load based on some condition. I would like to know how to call this function in child aspx page under document.ready()/window.onload.

I tried using parent.methodname() under script tag but it didnt work.
Here is the code how it looks like:

```<code><script type="text/javascript">
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" :         decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    $(window).load(function () {
        var flgInsidePresentation = getParameterByName("flgInsidePresentation");
        if (flgInsidePresentation) { parent.updateButtons(null, 2, 1); }
    });

</script>
</code>```

If I write only Parent in my console i get the parent page(xyz.aspx) where the js file is mentioned under  tag.

PS: I have to call updateButtons method from deck.navigation.js file from my child.aspx page

```<code>(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  var updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);
</code>```

Please let me know if there is any other way. Thanks for the help in advance.

答:
This is because of Scope issues.

```<code>(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  var updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);
</code>```

In the above, you are declaring the function with var keyword. It's scope is inside the function only and you can access it only via the $.

Read more about Scope of var here

To change it,

Do the following

```<code>(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  window.updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);
</code>```

Now the function is declared as global.

You can access it using parent.updateButtons(null, 2, 1);

Body:
I have an aspx page where I have a parent page xyz.aspx page where one js file(abc.js) mentioned in the  tag. I need to call a method written in abc.js in child aspx page on load based on some condition. I would like to know how to call this function in child aspx page under document.ready()/window.onload.

I tried using parent.methodname() under script tag but it didnt work.
Here is the code how it looks like:

If I write only Parent in my console i get the parent page(xyz.aspx) where the js file is mentioned under  tag.

PS: I have to call updateButtons method from deck.navigation.js file from my child.aspx page

(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  var updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);

Please let me know if there is any other way. Thanks for the help in advance.

Body:
This is because of Scope issues.

(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  var updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);

In the above, you are declaring the function with var keyword. It's scope is inside the function only and you can access it only via the $.

Read more about Scope of var here

To change it,

Do the following

(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  window.updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);

Now the function is declared as global.

You can access it using parent.updateButtons(null, 2, 1);


来源: stackexchange

问:
Update User Using Laravel 5.4
need your help at my laravel user update...

here's my coding:

```<code><form class="form-horizontal" role="form" method="POST" action="{{ route('editregister.post') }}">
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                            <label for="name" class="col-md-4 control-label">Name</label>

                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control" name="name" value="{{ $users->name }}" required autofocus>
                                @if ($errors->has('name'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group{{ $errors->has('username') ? ' has-error' : '' }}">
                            <label for="username" class="col-md-4 control-label">Username</label>
                            <div class="col-md-6">
                                <input id="username" type="username" class="form-control" name="username" value="{{ $users->username }}" required>
                                @if ($errors->has('username'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('username') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        @if ($users->position == "Super Admin")

                        @else
                            <div class="form-group{{ $errors->has('position') ? ' has-error' : '' }}">
                                <label for="user-position" class="col-md-4 control-label">Position</label>
                                <div class="col-md-6">
                                    <select id="position" class="form-control" name="position" required autofocus>
                                        <option value=""> -- Select Position -- </option>
                                        <option value="Admin" {{ $users->position == 'Admin' ? 'selected' : '' }}>Admin</option>
                                        <option value="User" {{ $users->position == 'User' ? 'selected' : '' }}>User</option>
                                    </select>
                                    @if ($errors->has('position'))
                                        <span class="help-block">
                                            <strong>{{ $errors->first('position') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>
                        @endif
                        @if(session()->has('message'))
                            <div class="alert alert-success">
                                {{ session()->get('message') }}
                            </div>
                        @endif
                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>
                                <a href='{{ url('/userlist') }}' class="btn btn-primary">
                                    Cancel
                                </a>
                            </div>
                        </div>
                    </form>
</code>```

and here's my controller:

```<code>public function editregister(Request $request, $iduser)
{

    $this->validate(request(), [
        'name' => 'required|max:255',
        'username' => 'required|max:255|unique:users',
        'position' => 'required',
        ]
    );

    $name = $request->input('name');
    $username = $request->input('username');
    $position = $request->input('position');
    $updated_at = date("Y-m-d H:i:s");

    DB::table('users')->where('id', $iduser)->update([
        ['name' => $name, 'username' => $username, 'position' => $position, 'updated_at' => $updated_at, ]
    ]);

    return redirect()->back()->with('message', 'User is successfully Updated!');
}
</code>```

and here my web routes coding:

```<code>Route::get('edituser/{iduser}',['as' => 'edituser', 'uses' => 'UserRegController@editregisterform']);
Route::post('editregister', ['as' => 'editregister.post', 'uses' => 'UserRegController@editregister']);
</code>```

I don't know how to it works when updating a data... Im a new user of laravel 5.4...

please help me about this one thanks..

答:
Hi thanks guys for your response...

I just found the problem...

I remove the Request $request

```<code>public function editregister(Request $request, $iduser)
</code>```

and make like this:

```<code>public function editregister($iduser)
</code>```

then it fixed...

ContentLicense: CC BY-SA 3.0

Title: Update User Using Laravel 5.4

Body:
need your help at my laravel user update...

here's my coding:

<form class="form-horizontal" role="form" method="POST" action="{{ route('editregister.post') }}">
                        {{ csrf_field() }}

has('name') ? ' has-error' : '' }}">
                            Name

                                <input id="name" type="text" class="form-control" name="name" value="{{ $users->name }}" required autofocus>
                                @if ($errors->has('name'))

                                        {{ $errors->first('name') }}

                                @endif

has('username') ? ' has-error' : '' }}">
                            Username

                                <input id="username" type="username" class="form-control" name="username" value="{{ $users->username }}" required>
                                @if ($errors->has('username'))

                                        {{ $errors->first('username') }}

                                @endif

                        @if ($users->position == "Super Admin")

                        @else

has('position') ? ' has-error' : '' }}">
                                Position

                                    <select id="position" class="form-control" name="position" required autofocus>
                                        <option value=""> -- Select Position -- </option>
                                        <option value="Admin" {{ $users->position == 'Admin' ? 'selected' : '' }}>Admin</option>
                                        <option value="User" {{ $users->position == 'User' ? 'selected' : '' }}>User</option>
                                    </select>
                                    @if ($errors->has('position'))

                                            {{ $errors->first('position') }}

                                    @endif

                        @endif
                        @if(session()->has('message'))

                                {{ session()->get('message') }}

                        @endif

                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>

                                    Cancel

                    </form>

and here's my controller:

public function editregister(Request $request, $iduser)
{

    $this->validate(request(), [
        'name' => 'required|max:255',
        'username' => 'required|max:255|unique:users',
        'position' => 'required',
        ]
    );

    $name = $request->input('name');
    $username = $request->input('username');
    $position = $request->input('position');
    $updated_at = date("Y-m-d H:i:s");

    DB::table('users')->where('id', $iduser)->update([
        ['name' => $name, 'username' => $username, 'position' => $position, 'updated_at' => $updated_at, ]
    ]);

    return redirect()->back()->with('message', 'User is successfully Updated!');
}

and here my web routes coding:

Route::get('edituser/{iduser}',['as' => 'edituser', 'uses' => 'UserRegController@editregisterform']);
Route::post('editregister', ['as' => 'editregister.post', 'uses' => 'UserRegController@editregister']);

I don't know how to it works when updating a data... Im a new user of laravel 5.4...

please help me about this one thanks..

Body:
Hi thanks guys for your response...

I just found the problem...

I remove the Request $request

public function editregister(Request $request, $iduser)

and make like this:

public function editregister($iduser)

then it fixed...


问:
Is there a more agile way to re-factor the following string formating code
I need to format a string as bellow :

```<code>print "%8s%-32s%-32s%-32s" % (' ', 'CAT A', 'CAT B', 'CAT C')
</code>```

Since the number of cat is a variable, here is what I code.

```<code>values = [' ', ]
format = "%8s"
# width is a variable
width = house.get_width()

for cat in range(house.get_cat_count()):
    format = format + '%-' + str(width) + 's'
    values.append('CAT ' + chr(ord('A') + operator))

# format is "%8s%-32s%-32s%-32s"
# values is [' ', 'CAT A', 'CAT B', 'CAT C']
${format % tuple(values)}
</code>```

The code doesn't seem short and agile. Is there any other way to code it in python style?

答:
Why not:

```<code>" "*8 + "%-32s"*len(values) % tuple(values)
</code>```

then:

```<code>values=["CAT "+chr(65+i) for i in house.get_cat_count()]
" "*8 + ("%%-%ds" % house.get_width()) * len(values) % tuple(values)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to format a string as bellow :

print "%8s%-32s%-32s%-32s" % (' ', 'CAT A', 'CAT B', 'CAT C')

Since the number of cat is a variable, here is what I code.

values = [' ', ]
format = "%8s"
# width is a variable
width = house.get_width()

for cat in range(house.get_cat_count()):
    format = format + '%-' + str(width) + 's'
    values.append('CAT ' + chr(ord('A') + operator))

# format is "%8s%-32s%-32s%-32s"
# values is [' ', 'CAT A', 'CAT B', 'CAT C']
${format % tuple(values)}

The code doesn't seem short and agile. Is there any other way to code it in python style?

Body:
Why not:

" "*8 + "%-32s"*len(values) % tuple(values)

then:

values=["CAT "+chr(65+i) for i in house.get_cat_count()]
" "*8 + ("%%-%ds" % house.get_width()) * len(values) % tuple(values)


问:
Ansible: Use of Diff command using Ansible
I am trying to one simple task which is find out the difference between the two files and store it in notepad. I am not able to do it with command as well as shell. Please suggest where i am going wrong-

```<code>---
- hosts: myserver
  tasks:
   - name: get the difference
     command: diff hosts.new hosts.mod
     register: diff
   - debug: var=diff.cmd
</code>```

Error -

```<code>fatal: [zlp12037]: FAILED! => {"changed": true, "cmd": ["diff", "hosts.new", "hosts.mod"], "delta": "0:00:00.003102", "end": "2017-03-29 10:17:34.448063", "failed": true, "rc": 1, "start": "2017-03-29 10:17:34.444961", "stderr": "", "stdout":
</code>```

答:
I'm not quite sure what your input play looks like with your formatting. But the following should be a solution:

```<code>- name: "Get difference from two files"
  command: diff filea fileb
  args:
    chdir: "/home/user/"
  failed_when: "diff.rc > 1"
  register: diff
- name: debug output
  debug: msg="{{ diff.stdout }}"
</code>```

Some explanation:

If something fails with the diff command, the return code is > 1. We evaluate this by the "failed_when".

To get the output of the command, we print the ".stdout" element.

To make sure we're in the folder where the files are, we use "chdir".

ContentLicense: CC BY-SA 4.0

Body:
I am trying to one simple task which is find out the difference between the two files and store it in notepad. I am not able to do it with command as well as shell. Please suggest where i am going wrong-

---
- hosts: myserver
  tasks:
   - name: get the difference
     command: diff hosts.new hosts.mod
     register: diff
   - debug: var=diff.cmd

Error -

fatal: [zlp12037]: FAILED! => {"changed": true, "cmd": ["diff", "hosts.new", "hosts.mod"], "delta": "0:00:00.003102", "end": "2017-03-29 10:17:34.448063", "failed": true, "rc": 1, "start": "2017-03-29 10:17:34.444961", "stderr": "", "stdout":

Body:
I'm not quite sure what your input play looks like with your formatting. But the following should be a solution:

- name: "Get difference from two files"
  command: diff filea fileb
  args:
    chdir: "/home/user/"
  failed_when: "diff.rc > 1"
  register: diff
- name: debug output
  debug: msg="{{ diff.stdout }}"

Some explanation:

If something fails with the diff command, the return code is > 1. We evaluate this by the "failed_when".

To get the output of the command, we print the ".stdout" element.

To make sure we're in the folder where the files are, we use "chdir".


问:
Regex search by dictionary in Java
I have a large dictionary (about 10 million words and expressions). I would like to build a very fast system allowing to search the whole dictionary using * and ? masks. E.g.:

*est*:

forest

estimate

nest

k??g*:

king

kaggle

kingdom

I know it could be easily solved using trie data structure, if I program it manually. Is there production-ready (or almost ready) for such a task in Java?

答:
One way to do it would be to create a single string that contains those 10 million words and phrases. Build the string so that there's one entry per line. That is, if "foo", "bar", and "bas" are all words, the string would be:

```<code>"foo\nbar\nbas\n"
</code>```

You can then use the standard regular expression library to find all of the matches. Just make sure that your regex is anchored so that it doesn't extend beyond a newline. So if you look for the regex "ba*", it will find "bar" and "bas", rather than finding "bar\nbas\n".

I think the default in Java regular expressions is to stop at newlines, so you might not have to do anything special. Otherwise, there are regex options that will let you specify how to handle embedded newlines in your string.

One thing to point out: when the regex engine reports that it found a match, it'll report the starting position. You'll need to back up to the start of the word (previous \n), and copy to the end (next \n).

Obviously, you'd want to build this giant dictionary string just once at startup, or whenever the dictionary changes. Whatever, you really don't want to be building it for every single search.

It's not the fastest possible solution, but it's quite likely fast enough for your purposes. It's easy to implement and easy to prove correct. It'd be a good way to get started.

Title: Regex search by dictionary in Java

Body:
One way to do it would be to create a single string that contains those 10 million words and phrases. Build the string so that there's one entry per line. That is, if "foo", "bar", and "bas" are all words, the string would be:

"foo\nbar\nbas\n"

You can then use the standard regular expression library to find all of the matches. Just make sure that your regex is anchored so that it doesn't extend beyond a newline. So if you look for the regex "ba*", it will find "bar" and "bas", rather than finding "bar\nbas\n".

I think the default in Java regular expressions is to stop at newlines, so you might not have to do anything special. Otherwise, there are regex options that will let you specify how to handle embedded newlines in your string.

One thing to point out: when the regex engine reports that it found a match, it'll report the starting position. You'll need to back up to the start of the word (previous \n), and copy to the end (next \n).

Obviously, you'd want to build this giant dictionary string just once at startup, or whenever the dictionary changes. Whatever, you really don't want to be building it for every single search.

It's not the fastest possible solution, but it's quite likely fast enough for your purposes. It's easy to implement and easy to prove correct. It'd be a good way to get started.


Title: Operation on Pandas Dataframe columns using its Index

Body:
This should be relatively easy.  I have a pandas dataframe (Dates):

    A   B   C
1/8/2017    1/11/2017   1/20/2017   1/25/2017
1/9/2017    1/11/2017   1/20/2017   1/25/2017
1/10/2017   1/11/2017   1/20/2017   1/25/2017
1/11/2017   1/20/2017   1/25/2017   1/31/2017
1/12/2017   1/20/2017   1/25/2017   1/31/2017
1/13/2017   1/20/2017   1/25/2017   1/31/2017

I would like to take the difference between Dates.index and Dates.  The output would be like so:

    A   B   C
1/8/2017     3   12      17
1/9/2017     2   11      16
1/10/2017    1   10      15
1/11/2017    9   14      20
1/12/2017    8   13      19
1/13/2017    7   12      18

Naturally, I tried this:

Dates - Dates.index

But I receive this lovely TypeError:

TypeError: Could not operate DatetimeIndex...with block values ufunc subtract cannot use operands with types dtype('<M8[ns]') and dtype('O')

Instead, I've written a loop to go column by column, but that just seems silly. Can anyone suggest a pythonic way to do this?

EDIT

In [1]: import pandas as pd
import numpy as np
import datetime
dates = pd.date_range('20170108',periods=6)
df = pd.DataFrame(np.empty([len(dates),3]),index=dates,columns=list('ABC'))
df['A'].loc[0:3] = datetime.date(2017, 1, 11)
df['B'].loc[0:3] = datetime.date(2017, 1, 20)
df['C'].loc[0:3] = datetime.date(2017, 1, 25)
df['A'].loc[3:6] = datetime.date(2017, 1, 20)
df['B'].loc[3:6] = datetime.date(2017, 1, 25)
df['C'].loc[3:6] = datetime.date(2017, 1, 31)

In [2]: print(df)
                     A           B           C
2017-01-08  2017-01-11  2017-01-20  2017-01-25
2017-01-09  2017-01-11  2017-01-20  2017-01-25
2017-01-10  2017-01-11  2017-01-20  2017-01-25
2017-01-11  2017-01-20  2017-01-25  2017-01-31
2017-01-12  2017-01-20  2017-01-25  2017-01-31
2017-01-13  2017-01-20  2017-01-25  2017-01-31

In [3]: df = df.sub(df.index.to_series(),axis=0)

ValueError: operands could not be broadcast together with shapes (18,) (6,)

Body:
You need first convert all columns to_datetime and then use sub:

#if dtypes of all columns are datetime, omit it
date_cols = list('ABC')
for col in df.columns:
    df[col] = pd.to_datetime(df[col])

df = df.sub(df.index.to_series(),axis=0)
print (df)
                A       B       C
2017-01-08 3 days 12 days 17 days
2017-01-09 2 days 11 days 16 days
2017-01-10 1 days 10 days 15 days
2017-01-11 9 days 14 days 20 days
2017-01-12 8 days 13 days 19 days
2017-01-13 7 days 12 days 18 days

You need dtypes datetime64:

dates = pd.date_range('20170108',periods=6)
df = pd.DataFrame(index=dates)
df.loc[0:3, 'A'] = pd.Timestamp(2017, 1, 11)
df.loc[0:3, 'B'] = pd.Timestamp(2017, 1, 20)
df.loc[0:3, 'C'] = pd.Timestamp(2017, 1, 25)
df.loc[3:6, 'A'] = pd.Timestamp(2017, 1, 20)
df.loc[3:6, 'B'] = pd.Timestamp(2017, 1, 25)
df.loc[3:6, 'C'] = pd.Timestamp(2017, 1, 31)
print (df)
                    A          B          C
2017-01-08 2017-01-11 2017-01-20 2017-01-25
2017-01-09 2017-01-11 2017-01-20 2017-01-25
2017-01-10 2017-01-11 2017-01-20 2017-01-25
2017-01-11 2017-01-20 2017-01-25 2017-01-31
2017-01-12 2017-01-20 2017-01-25 2017-01-31
2017-01-13 2017-01-20 2017-01-25 2017-01-31

print (df.dtypes)
A    datetime64[ns]
B    datetime64[ns]
C    datetime64[ns]
dtype: object

df = df.sub(df.index.to_series(),axis=0)
print (df)
                A       B       C
2017-01-08 3 days 12 days 17 days
2017-01-09 2 days 11 days 16 days
2017-01-10 1 days 10 days 15 days
2017-01-11 9 days 14 days 20 days
2017-01-12 8 days 13 days 19 days
2017-01-13 7 days 12 days 18 days


问:
This error keeps showing up on my desktop
This Javascript error keeps showing up on my desktop, and when i delete it another one will pop up.

Can anybody with knowledge about this please help me?

Oh the image is on Danish so yeah. Translated it says that there was a script-error with the script, and asks if i still want to play the script on this site.

答:
Solution Found

Go to Control Panel

Go to Programs and Functions

See if there is any program that refers to the url-error-message you got, and if there is, delete it.

Note If the program is a program that you need to have for running your system or just an important program, don't delete it, there could be other ways to fix it.

Other ways to fix it

 1. Start up the installer that you used to install the program, if there is a button that says "Repair software/program" or something like that; tap the button.

If there isn't a button that says "Repair software/program" (or something like that); try to install the program again.


问:
Split a string with unknown number of spaces as separator in Python
I need a function similar to str.split(' ') but there might be more than one space, and different number of them between the meaningful characters. Something like this:

```<code>s = ' 1234    Q-24 2010-11-29         563   abc  a6G47er15        '
ss = s.magic_split()
print(ss)  # ['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']
</code>```

Can I somehow use regular expressions to catch those spaces in between?

答:
If you don't pass any arguments to str.split(), it will treat runs of whitespace as a single separator:

```<code>>>> ' 1234    Q-24 2010-11-29         563   abc  a6G47er15'.split()
['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']
</code>```

Body:
I need a function similar to str.split(' ') but there might be more than one space, and different number of them between the meaningful characters. Something like this:

s = ' 1234    Q-24 2010-11-29         563   abc  a6G47er15        '
ss = s.magic_split()
print(ss)  # ['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']

Can I somehow use regular expressions to catch those spaces in between?

Body:
If you don't pass any arguments to str.split(), it will treat runs of whitespace as a single separator:

>>> ' 1234    Q-24 2010-11-29         563   abc  a6G47er15'.split()
['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']


问:
PyOpenCL: gl sharing context creation failed (overflow error)
I want to create an application that uses OpenCL to caluculate the color value of every pixel in a texture and OpenGL to display that texture. The problem is that when I try to create a context with GL sharing properties the program freezes. Using the function get_gl_sharing_context_properties() I get a list [(8200, 65538), (8203, 18446744072971422270)]. The last number in the list is too big to convert to a 64 bit int and I get an overflow error.
The code I use to create the CL context:

```<code>def cl_init():
    platform = cl.get_platforms()[1]
    device = platform.get_devices(cl.device_type.GPU)

    from pyopencl.tools import get_gl_sharing_context_properties

    print(cl.have_gl())
    print(get_gl_sharing_context_properties())
    print(sys.platform)
    context = cl.Context(properties=[
                (cl.context_properties.PLATFORM, platform)] +
                get_gl_sharing_context_properties())

    print("Context creation done")

    queue = cl.CommandQueue(context)
</code>```

The code never reaches print("Context creation done"). I use QtPy4 and the QGLWidget to create the OpenGL context and display the texture.

答:
Ok ran into a similar issue myself and here is my fix for it. If you look exactly at what get_gl_sharing_context_properties() is doing according to PyOpenCL's source code on github under the tools module, you will find the following platform-specific code:

```<code>def get_gl_sharing_context_properties():
    ctx_props = cl.context_properties

    from OpenGL import platform as gl_platform

    props = []

    import sys
    if sys.platform in ["linux", "linux2"]:
        from OpenGL import GLX
        props.append(
            (ctx_props.GL_CONTEXT_KHR, gl_platform.GetCurrentContext()))
        props.append(
                (ctx_props.GLX_DISPLAY_KHR,
                    GLX.glXGetCurrentDisplay()))
    elif sys.platform == "win32":
        from OpenGL import WGL
        props.append(
            (ctx_props.GL_CONTEXT_KHR, gl_platform.GetCurrentContext()))
        props.append(
                (ctx_props.WGL_HDC_KHR,
                    WGL.wglGetCurrentDC()))
    elif sys.platform == "darwin":
        props.append(
            (ctx_props.CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
                cl.get_apple_cgl_share_group()))
    else:
        raise NotImplementedError("platform '%s' not yet supported"
                % sys.platform)

    return props
</code>```

Now, since I am on Windows, I took a look at the WGL code (which comes from PyOpenGL) and found that WGL.wglGetCurrentDC() (like get_gl_sharing_context_properties() of course) was returning incorrect handle values sometimes that caused the integer overflow. It turns out the DC (device context) is really supposed to be a 32 bit signed integer. However, in the PyOpenGL wrapper function, it is being converted wrongly to a 64 bit unsigned integer. As a result, whenever a negative DC handle value is passed into PyOpenGL, it is being converted to become 2^64 + annoying_negative_dc_number instead!

The solution: convert it back! Here is what I now do to reliably get a working gl interop context:

```<code>platform = cl.get_platforms()[0]
ctx_props = cl.context_properties
gl_props = get_gl_sharing_context_properties()
device_context = gl_props[-1][-1]
if device_context >= 2 ** 32:
    device_context -= (2 ** 64)
fixed_gl_props = [gl_props[0], (gl_props[-1][0], device_context)]
ctx = cl.Context(properties=[(ctx_props.PLATFORM, platform)] + fixed_gl_props)
</code>```

Body:
I want to create an application that uses OpenCL to caluculate the color value of every pixel in a texture and OpenGL to display that texture. The problem is that when I try to create a context with GL sharing properties the program freezes. Using the function get_gl_sharing_context_properties() I get a list [(8200, 65538), (8203, 18446744072971422270)]. The last number in the list is too big to convert to a 64 bit int and I get an overflow error.
The code I use to create the CL context:

def cl_init():
    platform = cl.get_platforms()[1]
    device = platform.get_devices(cl.device_type.GPU)

    from pyopencl.tools import get_gl_sharing_context_properties

    print(cl.have_gl())
    print(get_gl_sharing_context_properties())
    print(sys.platform)
    context = cl.Context(properties=[
                (cl.context_properties.PLATFORM, platform)] +
                get_gl_sharing_context_properties())

    print("Context creation done")

    queue = cl.CommandQueue(context)

The code never reaches print("Context creation done"). I use QtPy4 and the QGLWidget to create the OpenGL context and display the texture.

Body:
Ok ran into a similar issue myself and here is my fix for it. If you look exactly at what get_gl_sharing_context_properties() is doing according to PyOpenCL's source code on github under the tools module, you will find the following platform-specific code:

def get_gl_sharing_context_properties():
    ctx_props = cl.context_properties

    from OpenGL import platform as gl_platform

    props = []

    import sys
    if sys.platform in ["linux", "linux2"]:
        from OpenGL import GLX
        props.append(
            (ctx_props.GL_CONTEXT_KHR, gl_platform.GetCurrentContext()))
        props.append(
                (ctx_props.GLX_DISPLAY_KHR,
                    GLX.glXGetCurrentDisplay()))
    elif sys.platform == "win32":
        from OpenGL import WGL
        props.append(
            (ctx_props.GL_CONTEXT_KHR, gl_platform.GetCurrentContext()))
        props.append(
                (ctx_props.WGL_HDC_KHR,
                    WGL.wglGetCurrentDC()))
    elif sys.platform == "darwin":
        props.append(
            (ctx_props.CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
                cl.get_apple_cgl_share_group()))
    else:
        raise NotImplementedError("platform '%s' not yet supported"
                % sys.platform)

    return props

Now, since I am on Windows, I took a look at the WGL code (which comes from PyOpenGL) and found that WGL.wglGetCurrentDC() (like get_gl_sharing_context_properties() of course) was returning incorrect handle values sometimes that caused the integer overflow. It turns out the DC (device context) is really supposed to be a 32 bit signed integer. However, in the PyOpenGL wrapper function, it is being converted wrongly to a 64 bit unsigned integer. As a result, whenever a negative DC handle value is passed into PyOpenGL, it is being converted to become 2^64 + annoying_negative_dc_number instead!

The solution: convert it back! Here is what I now do to reliably get a working gl interop context:

platform = cl.get_platforms()[0]
ctx_props = cl.context_properties
gl_props = get_gl_sharing_context_properties()
device_context = gl_props[-1][-1]
if device_context >= 2 ** 32:
    device_context -= (2 ** 64)
fixed_gl_props = [gl_props[0], (gl_props[-1][0], device_context)]
ctx = cl.Context(properties=[(ctx_props.PLATFORM, platform)] + fixed_gl_props)


问:
Checking if a key exists in a JavaScript object?
How do I check if a particular key exists in a JavaScript object or array?

If a key doesn't exist, and I try to access it, will it return false? Or throw an error?

答:
Optional chaining operator:

const invoice = {customer: {address: {city: "foo"}}}

console.log( invoice?.customer?.address?.city )
console.log( invoice?.customer?.address?.street )
console.log( invoice?.xyz?.address?.city )```
</div>
</div>
</p>
<p><em>See supported browsers list</em></p>
<hr />
<h3>For those which have <code>lodash</code> included in their project:<br>There is a lodash _.get method  which tries to get "deep" keys:</h3>
<blockquote>
<p>Gets the value at path of object. If the resolved value is undefined,
the defaultValue is returned in its place.</p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var object = { 'a': [{ 'b': { 'c': 3 } }] };

console.log(
  _.get(object, 'a[0].b.c'),           // => 3
  _.get(object, ['a', '0', 'b', 'c']), // => 3
  _.get(object, 'a.b.c'),              // => undefined
  _.get(object, 'a.b.c', 'default')    // => 'default'
)</code>```

```

This will effectively check if that key, however deep, is defined and will not throw an error which might harm the flow of your program if that key is not defined.

Body:
Optional chaining operator:

const invoice = {customer: {address: {city: "foo"}}}

console.log( invoice?.customer?.address?.city )
console.log( invoice?.customer?.address?.street )
console.log( invoice?.xyz?.address?.city )

See supported browsers list

For those which have lodash included in their project:
There is a lodash _.get method  which tries to get "deep" keys:

Gets the value at path of object. If the resolved value is undefined,
the defaultValue is returned in its place.

var object = { 'a': [{ 'b': { 'c': 3 } }] };

console.log(
  _.get(object, 'a[0].b.c'),           // => 3
  _.get(object, ['a', '0', 'b', 'c']), // => 3
  _.get(object, 'a.b.c'),              // => undefined
  _.get(object, 'a.b.c', 'default')    // => 'default'
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

This will effectively check if that key, however deep, is defined and will not throw an error which might harm the flow of your program if that key is not defined.


问:
How can I Create a Tableview Under Custom Tableview cell
I am just thinking. Suppose, i have a tableview which have custom cell. It's simple. But My idea is that, when i click a tableview cell then another tableview is appear under that tableview cell, and again i click that cell then that sub tableview disappear. Similarly when i click second cell than work same. Is it possible? Please Provide me any idea or reference.</p>

答:
Create a custom table view cell classCustomTableViewCell by subclassingUITableViewCell class. And system will generate CustomTableViewCell.h, CustomTableViewCell.m, CustomTableViewCell.xib files for you.

Add protocols UITableViewDataSource and UITableViewDelegate in your CustomTableViewCell.h and implement the required methods in CustomTableViewCell.m files

Add a method for setting datasource and use the datasource for updating the table.

NOTE:

Handle table-dequeue mechanism properly, otherwise you will end up
with weird issues that may take time to investigate and resolve.

If you use this custom cell for all the cells in your parent table then the gestures will only listened by the child table. So plan for that too.

Please visit my blog for the sample code. https://myioslearnings.blogspot.in/2017/03/nested-table-view-in-ios-objective-c.html


问:
Foreach not working when partial view is being called
After reading this i went to my code and changed my view to partial making all the returns that would return views to be returning partial views instead.
Then I called my partial view in a page, surprisingly enough when i call my partial view it outputs an error: "Object reference not set to an instance of an object." See this for details
Thing is my partial view works just fine when I test it it just doesn't load when it is used in another page. What is the problem here?

Partial view code:

```<code>@model IEnumerable<MvcMovieClean.Models.MovieClean>

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<div class="album">
    <div class="container">
        <div class="row">

            @foreach (var item in Model)
            {
                <div class="card">
                    <img alt="100%x280" src="@Html.DisplayFor(modelItem => item.ImgURL)"/>
                    <p class="card-text">@Html.DisplayFor(modelItem => item.Plot)</p>
                </div>

            }

        </div>
    </div>
</div>
</code>```

How I am calling the partial view in the page:

```<code><div class="row">
    @Html.Partial("~/Views/Movies/Index.cshtml")
</div>
</code>```

答:
It is because you have not passed model object to it and it will ofcourse fail as it will be null, if you have action in controller for this partial view, i would suggest to call it using Html.Action or Html.RenderAction like:

Possible Solution 1:

```<code><div class="row">
    @Html.Action("Index","Movies")
</div>
</code>```

If you already have MoviesController class and in that you will see an action method named Index, Html.Action("Index","Movies") will call the Index method of MoviesController class and will render the returned html of the partial view as response in browser.

and your action would contain the code to get the movies from database and return in the partial view like:

```<code>public ActionResult Index()
{

   var movies = ...// call to db to get them

  return PartialView("~/Views/Movies/Index.cshtml",movies);
}
</code>```

Possible Solution 2:

of if you have the movies collection in the model of you parent view, then you need to pass it to the partial view like:

```<code><div class="row">
    @Html.Partial("~/Views/Movies/Index.cshtml",Model.Movies)
</div>
</code>```

Body:
After reading this i went to my code and changed my view to partial making all the returns that would return views to be returning partial views instead.
Then I called my partial view in a page, surprisingly enough when i call my partial view it outputs an error: "Object reference not set to an instance of an object." See this for details
Thing is my partial view works just fine when I test it it just doesn't load when it is used in another page. What is the problem here?

Partial view code:

@model IEnumerable<MvcMovieClean.Models.MovieClean>

Index

    @Html.ActionLink("Create New", "Create")

            @foreach (var item in Model)
            {

                     item.ImgURL)"/>

@Html.DisplayFor(modelItem => item.Plot)

            }

How I am calling the partial view in the page:

    @Html.Partial("~/Views/Movies/Index.cshtml")

Body:
It is because you have not passed model object to it and it will ofcourse fail as it will be null, if you have action in controller for this partial view, i would suggest to call it using Html.Action or Html.RenderAction like:

Possible Solution 1:

<div class="row">
    @Html.Action("Index","Movies")
</div>

If you already have MoviesController class and in that you will see an action method named Index, Html.Action("Index","Movies") will call the Index method of MoviesController class and will render the returned html of the partial view as response in browser.

and your action would contain the code to get the movies from database and return in the partial view like:

public ActionResult Index()
{

   var movies = ...// call to db to get them

  return PartialView("~/Views/Movies/Index.cshtml",movies);
}

Possible Solution 2:

of if you have the movies collection in the model of you parent view, then you need to pass it to the partial view like:

<div class="row">
    @Html.Partial("~/Views/Movies/Index.cshtml",Model.Movies)
</div>


问:
No module named 'virtualenvwrapper'
I am working to set up a Django project on Amazon EC2 with an Ubuntu 14.04 LTS instance. I want to write my code using Python 3. I've been advised that the best way to do this is to use virtualenvwrapper. I've installed virtualenvwrapper successfully and put

```<code>export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3.4
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh
</code>```

into my .bashrc file. Now I see:

```<code> /usr/bin/python3.4: Error while finding spec for 'virtualenvwrapper.hook_loader' (<class 'ImportErro
 r'>: No module named 'virtualenvwrapper')
 virtualenvwrapper.sh: There was a problem running the initialization hooks.

 If Python could not import the module virtualenvwrapper.hook_loader,
 check that virtualenvwrapper has been installed for
 VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3.4 and that PATH is
 set properly.
</code>```

How can I fix this?

答:
If you use brew to install python, you will want to ensure that you set this environment variable:

```<code>export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python
</code>```

in your bash_profile (or whatever shell you are using).

Title: No module named 'virtualenvwrapper'

Body:
I am working to set up a Django project on Amazon EC2 with an Ubuntu 14.04 LTS instance. I want to write my code using Python 3. I've been advised that the best way to do this is to use virtualenvwrapper. I've installed virtualenvwrapper successfully and put

export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3.4
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh

into my .bashrc file. Now I see:

 /usr/bin/python3.4: Error while finding spec for 'virtualenvwrapper.hook_loader' (<class 'ImportErro
 r'>: No module named 'virtualenvwrapper')
 virtualenvwrapper.sh: There was a problem running the initialization hooks.

 If Python could not import the module virtualenvwrapper.hook_loader,
 check that virtualenvwrapper has been installed for
 VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3.4 and that PATH is
 set properly.

How can I fix this?

Body:
If you use brew to install python, you will want to ensure that you set this environment variable:

export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python

in your bash_profile (or whatever shell you are using).


答:
Looking at that you are not passing the model into your partial view.

you should be passing in something like:

```<code><div class="row">
    @Html.Partial("~/Views/Movies/Index.cshtml", model)
</div>
</code>```

where model is an instance of

```<code>IEnumerable<MvcMovieClean.Models.MovieClean>
</code>```

Title: Foreach not working when partial view is being called

Body:
Looking at that you are not passing the model into your partial view.

you should be passing in something like:

<div class="row">
    @Html.Partial("~/Views/Movies/Index.cshtml", model)
</div>

where model is an instance of

IEnumerable<MvcMovieClean.Models.MovieClean>


问:
Where's the HXML docs?
I've looked all over the Haxe Flash Command-line compiler website but was unable to find any detailed documentation of the HXML files (scroll down to the "Changing SWF properties" section) which describe the compile.

Anybody know of a reference source?

Found HXML:

-swf MyApp.swf .... Compile to SWF

-main MyAppClass .... Entry-point Class (.AS file)

-swf-header 200:300:25:FFFFFF .... Width:Height:FPS:BackColor (of SWF)

Edit:  Scroll down for my answer with the complete list of commands.

答:
Got it! Here's the complete list of HXML / command line Options for the Haxe compiler

—cp  : add a directory to find source files

—js  : compile code to JavaScript file

—as3  : generate AS3 code into target directory

—swf  : compile code to Flash SWF file

—swf9  : compile code to Flash9 SWF file

—swf—version  : change the SWF version (6 to 10)

—swf—header  : define SWF header (width:height:fps:color)

—swf—lib  : add the SWF library to the compiled SWF

—neko  : compile code to Neko Binary

—php  : generate PHP code into target directory

—x  : shortcut for compiling and executing a neko file

—xml  : generate XML types description

—main  : select startup class

—lib  : use an haxelib library

—D  : define a conditional compilation flag

—resource [@name] : add a named resource file

—exclude  : don’t generate code for classes listed in this file

—v : turn on verbose node

—debug : add debug informations to the compiled code

—prompt : prompt on error

—cmd : run the specified command after successful compilation

——flash—strict : more type strict flash API

——no—traces : don’t compile trace calls in the program

——flash—use—stage : place objects found on the stage of the SWF lib

——neko—source : keep generated neko source

——gen—hx—classes  : generate hx headers from SWF9 file

——next : separate several haxe compilations

——display : display code tips

——no—output : compiles but does not generate any file

——times : measure compilation times

—-no—inline : disable inlining

——php—front  : select the name for the PHP front file

——remap  : remap a package to another one

—help : Display this list of options

——help : Display this list of options

OwnerDisplayName: Jeremy Rudd

Title: Where's the HXML docs?

LastEditorDisplayName: Jeremy Rudd


问:
Using dates in oracle prepared statements from .net4
Given this table:

```<code>myTable
EMPID           NOT NULL CHAR(10)
DEFFECTIVE      NOT NULL DATE
SSCHEME                  CHAR(10)
</code>```

and this prepared statement:

```<code>update myTable set sScheme = :sScheme
where empID = :sEmpID
and dEffective= :dStart
</code>```

with these parameters:

```<code>OCmd.Parameters.Add("sEmpID", OracleDbType.Char).Value = sEmp_No        'string
OCmd.Parameters.Add("dStart", OracleDbType.Date).Value = dtStart        'System.DateTime
OCmd.Parameters.Add("sScheme", OracleDbType.Char).Value = sScheme       'string
</code>```

Why do I keep getting Oracle.DataAccess.Client.OracleException ORA-01858: a non-numeric character was found where a numeric was expected

I see lots of people suggesting to pass the date in as formatted string and then do a to_date in the query - but that just seems a horribly backward step.

Have tried using SetSessionInfo (from OracleGlobalization) to match the DateFormat as specified by Culture but to no avail.

Initially this app was running a .net2 using the MS oracle provider with no issues, but moving to .net4 and Oracle.DataAccess causes me this headache.

Using System.DateTime as the .net type for the date as per instructions here: http://docs.oracle.com/html/E15167_01/featTypes.htm

.net framework 4
Oracle.DataAccess (v4.112.3.0)

答:
I suppose that, in the background, the date is passed as a string. And you need to have the good format so that Oracle can reconvert the date to its intended format.

Two solutions:
the first one is to use the to_date...
the second is to change the date format of the client. For this, you have two ways:
  - at the OS level:
    export NLS_DATE_FORMAT='DD/MM/YYYY HH24:MI:SS' (export for linux, set for windows)
  - in the software:
    sql 'alter session set NLS_DATE_FORMAT='DD/MM/YYYY HH24:MI:SS';

In both cases, you have to find the 'good' format.

You can also change the format by changing the country code of the client. usually, the Oracle side is intended to your with US formats. So an
export LANG=C (or en_US.UTF-8)
Will do the trick.

But, as much Oracle is clear on how it works, I found that others are not always. so you have to experiment...

First thing, print a date to know which default format is used...

Or just use to_date... Which, even if it is ugly, will always do the job...

regards

Body:
Given this table:

myTable
EMPID           NOT NULL CHAR(10)
DEFFECTIVE      NOT NULL DATE
SSCHEME                  CHAR(10)

and this prepared statement:

update myTable set sScheme = :sScheme
where empID = :sEmpID
and dEffective= :dStart

with these parameters:

OCmd.Parameters.Add("sEmpID", OracleDbType.Char).Value = sEmp_No        'string
OCmd.Parameters.Add("dStart", OracleDbType.Date).Value = dtStart        'System.DateTime
OCmd.Parameters.Add("sScheme", OracleDbType.Char).Value = sScheme       'string

Why do I keep getting Oracle.DataAccess.Client.OracleException ORA-01858: a non-numeric character was found where a numeric was expected

I see lots of people suggesting to pass the date in as formatted string and then do a to_date in the query - but that just seems a horribly backward step.

Have tried using SetSessionInfo (from OracleGlobalization) to match the DateFormat as specified by Culture but to no avail.

Initially this app was running a .net2 using the MS oracle provider with no issues, but moving to .net4 and Oracle.DataAccess causes me this headache.

Using System.DateTime as the .net type for the date as per instructions here: http://docs.oracle.com/html/E15167_01/featTypes.htm

.net framework 4
Oracle.DataAccess (v4.112.3.0)


问:
Unity 3D : Simple model make lag on mobile
I have checked Google or the Unity Community but no answers to my specific question.

Description of the problem

I am creating a simple game for Android in Low Poly Style and I want to optimize it for this platform.  All of my models are made with Blender and there working fine.

I also created a simple house, made of cube with Blender but when the player is near the house, the game lag ! So I decided to make this house with some cube in Unity 3D, to see if it is lagging:

Blue = the player, Red AND yellow = the direction where the player looks

And surprise, the game lag too! And really. I don't know why. As you can see, this is a very simple house. When the player is front of the door and can see the inside house (yellow arrow), the game lag but when the player rotate the camera to see other part of the environment (red arrow), no lag.

Attempt of resolution

I decreased the number of vertices, faces and edges for all of my Blender models including my house but this house is already lagging.

I decrease the side view of the camera player.

I checked the occlusion culling but there is nothing to do.

I recreated a new Blender file for my house but the problem is always here

I also exported my mesh in .obj/.fbx but the lag is always here

My question

What is wrong with Blender/Unity ? What can I do ?

EDIT

Here is a video of my problem. As you can see, when the player see the house, it is lagging but when the house is not visible in the camera player, pfuit, no lag: Link

Profiler

Here is the profile when I play the game on mobile:

Red part -> Player see the environnement, Yellow part -> Player look at the house. I can see in the overview screen the "Graphics.PresentAndSync" increase of 10-15% when the player sees the house. I will check that in detail.

答: To find the real cause of the lag, you should profile your app on Android. See Android part of Profiler window for more details.


问:
Using codeigniter Confirm and delete record. Having issue in javascript confirm to delete records and redirect to the same controller/index method
I am new to codeigniter. After deleting my table record i want to redirect to same controller index method.Record deleted successfully but alert message was showing repeatedly. Instead redirect() method i am using javascript confirm method to delete it will showing alert box again and again. If i try redirect() method its not showing confirm alert box. If i try exact base_url() method to redirect it will move to URL: http://localhost/codeigniter/category/remove_category/25 and the page was empty. I tried many ways. I don't know why the confirm alert box showing repeatedly. Please advise me. Thanks in advance.

View Codes

```<code><table border="1">
<tbody>
    <tr>
        <td>Category Id</td>
        <td>Category Name</td>
        <td>Click Edit Link</td>
        <td>Click Delete Link</td>
    </tr>
    <?php

    foreach ($category->result() as $row)
    {
        ?><tr>
            <td><?php echo $row->category_id;?></td>
            <td><?php echo $row->category_name;?></td>
            <td><a href="<?=base_url()?>category/edit_category/<?=$row->category_id?>">Edit</a></td>
            <td><a href="<?=base_url()?>category/remove_category/<?=$row->category_id?>">Delete</a></td>
        </tr>
        <?php
    }
    ?>
</tbody>
</table>
</code>```

Controller Codes

```<code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Category extends CI_Controller {

function __construct() {
    parent::__construct();
    $this->load->model('category_model');

}

function index(){

    $data['category']=$this->category_model->show_category();
    //return the data in view
    $this->load->view('categories_view', $data);

}

function remove_category($category_id){

    if($this->category_model->delete_category($category_id))
    {
    /*echo "<script type='text/javascript'> confirm('Are you sure to delete permanently?');
    window.location.href='index'";*/
   //redirect(base_url().'category');

    echo "<script>
                    confirm('Are you sure to delete permanently?!');
                    window.location.href = '" . base_url() . "category';
                </script>";
    }
}

}
</code>```

Model Codes

```<code>class Category_model extends CI_Model {

function show_category(){

    $query = $this->db->get('tbl_category');
    return $query;

}

function insert_category($data){

    $this->db->insert('tbl_category', $data);
    return $this->db->insert_id();
}

function delete_category($category_id){
    $this->db->where('category_id', $category_id);
    $this->db->delete('tbl_category');
}
</code>```

}

答:
The proper way to do this is redirect(); Something like this:

```<code>    $this->session->set_flashdata('message', 'Category was deleted');
    redirect('category', 'refresh');
</code>```

Then on Category controller:

```<code>   if ($this->session->flashdata('message')) {
      //show the message to confirm
   }
</code>```

Finally, if you want javascript confirm: so when the user clicks, it asks to confirm and then goes to delete if the user clicks okay. You're asking confirmation when the row has already been deleted.

```<code>  <td><a onclick="return confirm('are you sure?')" href="<?=base_url()?>category/remove_category/<?=$row->category_id?>">Delete</a></td>
</code>```

Body:
I am new to codeigniter. After deleting my table record i want to redirect to same controller index method.Record deleted successfully but alert message was showing repeatedly. Instead redirect() method i am using javascript confirm method to delete it will showing alert box again and again. If i try redirect() method its not showing confirm alert box. If i try exact base_url() method to redirect it will move to URL: http://localhost/codeigniter/category/remove_category/25 and the page was empty. I tried many ways. I don't know why the confirm alert box showing repeatedly. Please advise me. Thanks in advance.

View Codes

        Category Id
        Category Name
        Click Edit Link
        Click Delete Link

    <?php

    foreach ($category->result() as $row)
    {
        ?>

            <?php echo $row->category_id;?>
            <?php echo $row->category_name;?>
            <a href="<?=base_url()?>category/edit_category/<?=$row->category_id?>">Edit
            <a href="<?=base_url()?>category/remove_category/<?=$row->category_id?>">Delete

        <?php
    }
    ?>

Controller Codes

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Category extends CI_Controller {

function __construct() {
    parent::__construct();
    $this->load->model('category_model');

}

function index(){

    $data['category']=$this->category_model->show_category();
    //return the data in view
    $this->load->view('categories_view', $data);

}

function remove_category($category_id){

    if($this->category_model->delete_category($category_id))
    {
    /*echo "";
    }
}

}

Model Codes

class Category_model extends CI_Model {

function show_category(){

    $query = $this->db->get('tbl_category');
    return $query;

}

function insert_category($data){

    $this->db->insert('tbl_category', $data);
    return $this->db->insert_id();
}

function delete_category($category_id){
    $this->db->where('category_id', $category_id);
    $this->db->delete('tbl_category');
}

}

Body:
The proper way to do this is redirect(); Something like this:

    $this->session->set_flashdata('message', 'Category was deleted');
    redirect('category', 'refresh');

Then on Category controller:

   if ($this->session->flashdata('message')) {
      //show the message to confirm
   }

Finally, if you want javascript confirm: so when the user clicks, it asks to confirm and then goes to delete if the user clicks okay. You're asking confirmation when the row has already been deleted.

  <td><a onclick="return confirm('are you sure?')" href="<?=base_url()?>category/remove_category/<?=$row->category_id?>">Delete</a></td>


问:
c# Richtext box can not load rtf file while Microsoft word using that file
i used a read stream to read an rtf file however it failed when this rtf file is opened by  Microsoft word.

is there anyone know how to solve this problem?

答:
The proper way to read a RTF file for a rich text box (has to be of type System.Windows.Forms.RichTextBox) is like this:

```<code>myRichTextBox.LoadFile(myFilename);
</code>```

But, because you have a lock on the file, you have to do it this way (credit to @slaks):

```<code>myRichTextBox.LoadFile(new FileStream(myFilename, FileAccess.Read, FileSharing.ReadWrite));
</code>```

And to save it, simply call this function:

```<code>myRichTextBox.SaveFile(myFilename);
</code>```

Body:
The proper way to read a RTF file for a rich text box (has to be of type System.Windows.Forms.RichTextBox) is like this:

myRichTextBox.LoadFile(myFilename);

But, because you have a lock on the file, you have to do it this way (credit to @slaks):

myRichTextBox.LoadFile(new FileStream(myFilename, FileAccess.Read, FileSharing.ReadWrite));

And to save it, simply call this function:

myRichTextBox.SaveFile(myFilename);


问:
docker on OSX slow volumes
I'm trying to use docker beta on OSX, mainly for Symfony development but the mounted volumes are incredible slow. Even for a vanilla Symfony project I get 6s page load time. That's unbearable! Has anyone found a solution to this issue? Trying to move away from vagrant but I just can't find any reasonable way to work with docker instead.</p>

答:
For people reading this now, maybe it's better to wait for Docker to fix this issue. A pull request has already been accepted to improve performance(https://github.com/docker/docker/pull/31047).
This will be release somewhere in April 2017 and should be a big improvement.

I've tried some workarounds for Docker for Mac, but all of them had some pretty big disadvantages, mostly in usability. A good source for alternatives of the OSXFS can be found at: https://github.com/EugenMayer/docker-sync/wiki/Alternatives-to-docker-sync. Credits for Eugen Mayer for setting this up.

EDIT:
First improvement is implemented in the edge release. https://github.com/docker/for-mac/issues/77 has more info on this.

Title: docker on OSX slow volumes


问:
Elasticsearch- get all values for a given field?
Is it possible to query for all of the values a specific field? Say I have "articles" and each  article has an author, is there a query I can perform to find a list of all authors? </p>

答:
How to get all possible values for field author?

```<code>curl -XGET  http://localhost:9200/articles/_search?pretty -d '
{
    "aggs" : {
        "whatever_you_like_here" : {
            "terms" : { "field" : "author", "size":10000 }
        }
    },
    "size" : 0
}'
</code>```

Note

"size":10000 Get at most 10000 unique values. Default is 10.

"size":0 By default, "hits" contains 10 documents. We don't need them.

By default, the buckets are ordered by the doc_count in decreasing order.

Reference: bucket terms aggregation

Also note, according to this page, facets have been replaced by aggregations in Elasticsearch 1.0, which are a superset of facets.

Body:
How to get all possible values for field author?

curl -XGET  http://localhost:9200/articles/_search?pretty -d '
{
    "aggs" : {
        "whatever_you_like_here" : {
            "terms" : { "field" : "author", "size":10000 }
        }
    },
    "size" : 0
}'

Note

"size":10000 Get at most 10000 unique values. Default is 10.

"size":0 By default, "hits" contains 10 documents. We don't need them.

By default, the buckets are ordered by the doc_count in decreasing order.

Reference: bucket terms aggregation

Also note, according to this page, facets have been replaced by aggregations in Elasticsearch 1.0, which are a superset of facets.


问:
SQLITE3 increase Max Columns
I am thinking about using SQLlite3 so I started some performance tests.

Because I've got an table with many Columns I want to increase the MAX Column Limit from SQLite3.
As I read on the SQLite website the limit was set to 2000 columns and now I want to increase it.

I wanted to use sqlite3_limit() but, because I use SQLAPI, I cannot use this function.

I've read on some website I need to change something "inside" SQLite and then have to recompile it but I haven't really understood this part and so I wanted to ask:

Is there was another way to increase Max columns?

My programm is running on Win10 in c++

答:
There is no other way but by setting the number of columns you want at compile time.

Luckily, it is not hard.

Download amalgamation source code here. It is named sqlite-amalgamation-*.zip

Unzip and change directory inside the unzippped folder. You will see sqlite3.c and sqlite3.h among other files.

Issue this statement to create an object file and setting the desired number of columns: gcc -I. -O3 -DSQLITE_MAX_COLUMN=5000 -c sqlite3.c -o sqlite3.o Change 5000 to the number you desire. Note that, according to the comments in sqlite3.c, you shouldn't use a number greater than 32676.

create a static library to link against: ar crsf libsqlite3.a sqlite3.o

Now you can link against the library when compiling your program using -lsqlite3, after having placed the library in a location that your linker is aware of (or use -L/path/to/library).

Alternative to steps 3) and 4).

If you don't want to actually create the static library but you just want to drop the sqlite3.h and sqlite3.c in your source code (something that SQLite itself suggests doing with their amalgamation files), then open sqlite3.c with your favourite editor, look for SQLITE_MAX_COLUMN and modify the value in there.

I used gcc via MinGW to do this. The same steps apply to the tools offered by MSVC, just changing the commands for compilation and library creation as appropriate.

Title: SQLITE3 increase Max Columns


问:
can't declare array in C# POST request
```<code>var resultHttpPost = ZennoPoster.HttpPost("http://box.chomikuj.pl/services/ChomikBoxService.svc",
"<?xml version='1.0' encoding='UTF-8'?><s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><Auth xmlns='http://chomikuj.pl/'><name>topbarlogin</name><passHash>e10adc3949ba59abbe56e057f20f883e</passHash><ver>4</ver></Auth></s:Body></s:Envelope>",
"text/xml;charset=utf-8", "", "UTF-8", ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.HeaderAndBody, 30000, "", "Mozilla/5.0", true, 1, string[] headers = new String[3]{ "a", "b", "c" }, "", false);
</code>```

I have problem with this:

```<code>string[] headers = new String[3]{ "a", "b", "c" }
</code>```

I still get the error and I don't know how to declare it.

答:
You have to write just:

```<code>new String[3]{ "a", "b", "c" }
</code>```

and not:

```<code>string[] headers = new String[3]{ "a", "b", "c" }
</code>```

Title: can't declare array in C# POST request

Body:
var resultHttpPost = ZennoPoster.HttpPost("http://box.chomikuj.pl/services/ChomikBoxService.svc",
"<?xml version='1.0' encoding='UTF-8'?><s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><Auth xmlns='http://chomikuj.pl/'><name>topbarlogin</name><passHash>e10adc3949ba59abbe56e057f20f883e</passHash><ver>4</ver></Auth></s:Body></s:Envelope>",
"text/xml;charset=utf-8", "", "UTF-8", ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.HeaderAndBody, 30000, "", "Mozilla/5.0", true, 1, string[] headers = new String[3]{ "a", "b", "c" }, "", false);

I have problem with this:

string[] headers = new String[3]{ "a", "b", "c" }

I still get the error and I don't know how to declare it.

Body:
You have to write just:

new String[3]{ "a", "b", "c" }

and not:

string[] headers = new String[3]{ "a", "b", "c" }


Title: Split a string with unknown number of spaces as separator in Python

Body:
I need a function similar to str.split(' ') but there might be more than one space, and different number of them between the meaningful characters. Something like this:

s = ' 1234    Q-24 2010-11-29         563   abc  a6G47er15        '
ss = s.magic_split()
print(ss)  # ['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']

Can I somehow use regular expressions to catch those spaces in between?

Body:
s = ' 1234    Q-24 2010-11-29         563   abc  a6G47er15        '
ss = s.split()
print(ss)  # ['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']


问:
Javascript - check the position on screen after the scroll has finished
I have a script where I scroll down to an element on click or page load, but I need trigger scrolling down, when the image is loaded, because I have problem with scrolling until the page is loaded. Now I need to solve the problem that when the page is loaded already and if it is on the position that it is supposed to be, that it doesn't scroll again. How can I check if the page has already scrolled to that position:

```<code>$('html,body').animate({
  scrollTop: magazineDetailOffset
});

$('#cover-image').load(function() {
  console.log($(".magazine-detail").offset().top - 80);
  console.log($(window).scrollTop());
  $('html,body').animate({
     scrollTop: magazineDetailOffset
  });
});
</code>```

So, basically I need to make a check if the element is already scrolled to the top and only if it is not then do the scroll animation again.

```<code>$('#cover-image').load(function() {
  if (theElementIsNotScrolledToTop) {
    $('html,body').animate({
       scrollTop: magazineDetailOffset
    });
  }
});
</code>```

But not sure how to do that?
I have tried with with checking $(document).scrollTop() but that always gives me 0.

答:
If you want to check if the image is exactly at the top (not below or above), you can set theElementIsNotScrolledToTop as so:

```<code>theElementIsNotScrolledToTop = $('#cover-image').offset().top !== $(window).scrollTop()
</code>```

but if you are even a pixel off, it will still fire, so you may want to add some logic to find the threshold you are looking for, hope that helps!

Body:
I have a script where I scroll down to an element on click or page load, but I need trigger scrolling down, when the image is loaded, because I have problem with scrolling until the page is loaded. Now I need to solve the problem that when the page is loaded already and if it is on the position that it is supposed to be, that it doesn't scroll again. How can I check if the page has already scrolled to that position:

$('html,body').animate({
  scrollTop: magazineDetailOffset
});

$('#cover-image').load(function() {
  console.log($(".magazine-detail").offset().top - 80);
  console.log($(window).scrollTop());
  $('html,body').animate({
     scrollTop: magazineDetailOffset
  });
});

So, basically I need to make a check if the element is already scrolled to the top and only if it is not then do the scroll animation again.

$('#cover-image').load(function() {
  if (theElementIsNotScrolledToTop) {
    $('html,body').animate({
       scrollTop: magazineDetailOffset
    });
  }
});

But not sure how to do that?
I have tried with with checking $(document).scrollTop() but that always gives me 0.

Body:
If you want to check if the image is exactly at the top (not below or above), you can set theElementIsNotScrolledToTop as so:

theElementIsNotScrolledToTop = $('#cover-image').offset().top !== $(window).scrollTop()

but if you are even a pixel off, it will still fire, so you may want to add some logic to find the threshold you are looking for, hope that helps!


问:
URL for cloudant on docker compose
Using the docker compose, I'm trying to get my app to call the cloudant URL with the following values, but always get connection refused:

http://admin:pass@0.0.0.0:8080

http://admin:pass@cloudant:8080

But if I go to http://0.0.0.0:8080/dashboard.html, I can access the cloudant web console.

Here is my compose file (referencing the sample in  Running Cloudant as docker container with docker compose)

```<code>version: '2.1'

services:
  app:
    build: app/
    links:
    - cloudant
  cloudant:
    image: ibmcom/cloudant-developer:latest
    container_name: cloudant-testdb
    ports:
      - "8080:80"
    expose:
      - "80"
    volumes:
      - cloudant:/srv
    mem_limit: 256M
    restart: always
    privileged: true
    network_mode: bridge
volumes:
    cloudant:
</code>```

答:
Here is how I got this to work:

Specify the hostname for the cloudant container in your docker-compose file like so:

```<code>restart: always
hostname: cloudant
privileged: true
</code>```

When communicating between containers you use the ports exposed by the services in the container, not the ports that are defined in the mapping. In this case you use the port exposed by Cloudant which is 80. So, your URL should look like this:

http://admin:pass@cloudant

Set the network_mode value to bridge in the app container.

Here is a working example: https://github.com/markwatsonatx/tutorial-cloudant-nodejs-intro

Also, be sure to accept the license in Cloudant and initialize the database. You may need to restart docker-compose after doing so.

Title: URL for cloudant on docker compose

Body:
Using the docker compose, I'm trying to get my app to call the cloudant URL with the following values, but always get connection refused:

http://admin:pass@0.0.0.0:8080

http://admin:pass@cloudant:8080

But if I go to http://0.0.0.0:8080/dashboard.html, I can access the cloudant web console.

Here is my compose file (referencing the sample in  Running Cloudant as docker container with docker compose)

version: '2.1'

services:
  app:
    build: app/
    links:
    - cloudant
  cloudant:
    image: ibmcom/cloudant-developer:latest
    container_name: cloudant-testdb
    ports:
      - "8080:80"
    expose:
      - "80"
    volumes:
      - cloudant:/srv
    mem_limit: 256M
    restart: always
    privileged: true
    network_mode: bridge
volumes:
    cloudant:

Body:
Here is how I got this to work:

Specify the hostname for the cloudant container in your docker-compose file like so:

restart: always
hostname: cloudant
privileged: true

When communicating between containers you use the ports exposed by the services in the container, not the ports that are defined in the mapping. In this case you use the port exposed by Cloudant which is 80. So, your URL should look like this:

http://admin:pass@cloudant

Set the network_mode value to bridge in the app container.

Here is a working example: https://github.com/markwatsonatx/tutorial-cloudant-nodejs-intro

Also, be sure to accept the license in Cloudant and initialize the database. You may need to restart docker-compose after doing so.


问:
Xamarin.Forms+Prism Navigation target control
I have a Xamarin app made up of several page types. I'm using Prism.

I'd like the navigation target of the app to be a nested view in the app within the main page, not the main page itself, so that the MainPage is used as an outer frame that's always there, and a nested page hosts the app's navigation service.

In this way I can have some controls (i.e. back/forward/home) always present.
How do I configure the NavigationService's 'MainPage' to be a nested page within the actual MainPage?

I'm pretty new to XF, and haven't used the NavigationPage before, but could it be of any use here?

答: You don't. Prism's navigation service will not support what you are trying to do because the INavigationService is Page based.  It sounds like your approach is very unorthodox.  Why not just use a NavigationPage and provide your options in a custom renderer or as toolbar items?


问:
JSF throws argument type mismatch when binding
I'm trying to do the following: When the user enters a value in the rich:calendar component, then the h:inputText should have its required attributed set to true. I'm following the instructions in this post: Reference JSF control's attributes via JavaScript

Sorry for creating another post, but I couldn't figure out how to post the code into the comments area and make it readable. The page throws this error:

javax.el.ELException: /pages/overtime/overtime-n.xhtml @121,65 binding="#{oc.overtimeDate}": java.lang.IllegalArgumentException: argument type mismatch

The problem is that the binding is inside a c:forEach loop, and I'm trying to use the loop variable to bind to. The overtime.overtimeItems is defined as an ArrayList<OvertimeComponent> with each OvertimeComponent object having various properties (overtimeDate, overtimeDateId, id, overtimeHours, etc.).

```<code><c:forEach items="#{overtime.overtimeItems}" var="oc">
  <rich:calendar value="#{oc.overtimeDate}"
    requiredMessage="Date 1 is required."
    id="#{oc.overtimeDateId}"
    binding="#{oc.overtimeDate}"
    required="#{oc.id == 1 ? true : false}">
  </rich:calendar>
  <h:inputText value="#{oc.overtimeHours}"
    id="#{oc.overtimeHoursId}"
    requiredMessage="Hours is required."
    required="#{not empty oc.overtimeDate.value}" >
  </h:inputText>
  .....
</c:forEach>
</code>```

How do I make the h:inputText required if the rich:calendar object has a value? There's a way to do this using the binding property of the calendar, but I'm not sure how to do it inside a c:forEach. I can't use AJAX for this project. Thanks.

答:
The binding attribute should point to an UIComponent, not to a value object like Date. The answer in your previous question would have worked if you wasn't using c:forEach.

```<code><rich:calendar value="#{oc.overtimeDate}"
    requiredMessage="Date 1 is required."
    id="#{oc.overtimeDateId}"
    binding="#{calendarComponent}"
    required="#{oc.id == 1 ? true : false}">
</rich:calendar>
<h:inputText value="#{oc.overtimeHours}"
    id="#{oc.overtimeHoursId}"
    requiredMessage="Hours is required."
    required="#{not empty calendarComponent.value}" >
</h:inputText>
</code>```

The above example binds the component to the "page scope", not to a particular bean since you're usually not interested in the component from inside the bean. You can name #{calendarComponent} whatever you want. You can access it anywhere in the same page by the same name.

However, in your particular case you're using c:forEach and not ui:repeat, so components are actually repeated in the component tree (the ui:repeat only repeats in the HTML renderer). This means that you cannot use the suggested approach. All components would then share the same binding which is wrong. Best would be to add an UIComponent (more precise, UIInput) property to the object behind oc and bind to it instead, so that every component has its own unique binding. E.g.

```<code>public class OvertimeComponent {
    private UIInput calendarComponent;
    // ...
</code>```

with

```<code><rich:calendar value="#{oc.overtimeDate}"
    requiredMessage="Date 1 is required."
    id="#{oc.overtimeDateId}"
    binding="#{oc.calendarComponent}"
    required="#{oc.id == 1}">
</rich:calendar>
<h:inputText value="#{oc.overtimeHours}"
    id="#{oc.overtimeHoursId}"
    requiredMessage="Hours is required."
    required="#{not empty oc.calendarComponent.value}" >
</h:inputText>
</code>```

(note that I simplified the EL of the required attribute of rich:calendar since it already returns a boolean anyway)

Body:
I'm trying to do the following: When the user enters a value in the rich:calendar component, then the h:inputText should have its required attributed set to true. I'm following the instructions in this post: Reference JSF control's attributes via JavaScript

Sorry for creating another post, but I couldn't figure out how to post the code into the comments area and make it readable. The page throws this error:

javax.el.ELException: /pages/overtime/overtime-n.xhtml @121,65 binding="#{oc.overtimeDate}": java.lang.IllegalArgumentException: argument type mismatch

The problem is that the binding is inside a c:forEach loop, and I'm trying to use the loop variable to bind to. The overtime.overtimeItems is defined as an ArrayList<OvertimeComponent> with each OvertimeComponent object having various properties (overtimeDate, overtimeDateId, id, overtimeHours, etc.).

<c:forEach items="#{overtime.overtimeItems}" var="oc">
  <rich:calendar value="#{oc.overtimeDate}"
    requiredMessage="Date 1 is required."
    id="#{oc.overtimeDateId}"
    binding="#{oc.overtimeDate}"
    required="#{oc.id == 1 ? true : false}">
  </rich:calendar>
  <h:inputText value="#{oc.overtimeHours}"
    id="#{oc.overtimeHoursId}"
    requiredMessage="Hours is required."
    required="#{not empty oc.overtimeDate.value}" >
  </h:inputText>
  .....
</c:forEach>

How do I make the h:inputText required if the rich:calendar object has a value? There's a way to do this using the binding property of the calendar, but I'm not sure how to do it inside a c:forEach. I can't use AJAX for this project. Thanks.

Body:
The binding attribute should point to an UIComponent, not to a value object like Date. The answer in your previous question would have worked if you wasn't using c:forEach.

<rich:calendar value="#{oc.overtimeDate}"
    requiredMessage="Date 1 is required."
    id="#{oc.overtimeDateId}"
    binding="#{calendarComponent}"
    required="#{oc.id == 1 ? true : false}">
</rich:calendar>
<h:inputText value="#{oc.overtimeHours}"
    id="#{oc.overtimeHoursId}"
    requiredMessage="Hours is required."
    required="#{not empty calendarComponent.value}" >
</h:inputText>

The above example binds the component to the "page scope", not to a particular bean since you're usually not interested in the component from inside the bean. You can name #{calendarComponent} whatever you want. You can access it anywhere in the same page by the same name.

However, in your particular case you're using c:forEach and not ui:repeat, so components are actually repeated in the component tree (the ui:repeat only repeats in the HTML renderer). This means that you cannot use the suggested approach. All components would then share the same binding which is wrong. Best would be to add an UIComponent (more precise, UIInput) property to the object behind oc and bind to it instead, so that every component has its own unique binding. E.g.

public class OvertimeComponent {
    private UIInput calendarComponent;
    // ...

with

<rich:calendar value="#{oc.overtimeDate}"
    requiredMessage="Date 1 is required."
    id="#{oc.overtimeDateId}"
    binding="#{oc.calendarComponent}"
    required="#{oc.id == 1}">
</rich:calendar>
<h:inputText value="#{oc.overtimeHours}"
    id="#{oc.overtimeHoursId}"
    requiredMessage="Hours is required."
    required="#{not empty oc.calendarComponent.value}" >
</h:inputText>

(note that I simplified the EL of the required attribute of rich:calendar since it already returns a boolean anyway)


问:
PRISM RequestNavigate is not working
I am working PRISM and have 2 regions in XAML MainWindowView:

```<code><IG6:SplitPane IG6:XamDockManager.InitialLocation="DockedTop">
<IG6:TabGroupPane x:Name="MessageGroupPane" prism:RegionManager.RegionName="{x:Static inf:RegionNames.MessageGroupPane}">

<IG6:SplitPane IG6:XamDockManager.InitialLocation="DockedBottom"
<IG6:TabGroupPane x:Name="MainContentGroupPane"  prism:RegionManager.RegionName="{x:Static inf:RegionNames.MainContentGroupPane}">

public class InfrastructureModule : IModule
{
    container.RegisterType<IMessageViewVM, MessageViewVM>();
    container.RegisterType<object, MessageView>("MessageView");
    regionManager.RegisterViewWithRegion(RegionNames.MessageGroupPane, typeof(MessageView));
}
</code>```

When the code executes, ALL views are placed in the last tabGroupPane identified in the XAML --in this case the MainContentGroupPane-- not in the requested region MessageGroupPane.

I am using TabGroupPaneRegionActiveAwareBehavior from the examples provided by Brian Lagunas.  Views are shown correctly but I am unable to place them in a specific region.  Can someone point me in the right direction?

答:
you should register in the module the target view TargetView for navigation:

```<code>    container.RegisterTypeForNavigation<TargetView>();
</code>```

Title: PRISM RequestNavigate is not working

Body:
I am working PRISM and have 2 regions in XAML MainWindowView:

<IG6:SplitPane IG6:XamDockManager.InitialLocation="DockedTop">
<IG6:TabGroupPane x:Name="MessageGroupPane" prism:RegionManager.RegionName="{x:Static inf:RegionNames.MessageGroupPane}">

<IG6:SplitPane IG6:XamDockManager.InitialLocation="DockedBottom"
<IG6:TabGroupPane x:Name="MainContentGroupPane"  prism:RegionManager.RegionName="{x:Static inf:RegionNames.MainContentGroupPane}">

public class InfrastructureModule : IModule
{
    container.RegisterType<IMessageViewVM, MessageViewVM>();
    container.RegisterType<object, MessageView>("MessageView");
    regionManager.RegisterViewWithRegion(RegionNames.MessageGroupPane, typeof(MessageView));
}

When the code executes, ALL views are placed in the last tabGroupPane identified in the XAML --in this case the MainContentGroupPane-- not in the requested region MessageGroupPane.

I am using TabGroupPaneRegionActiveAwareBehavior from the examples provided by Brian Lagunas.  Views are shown correctly but I am unable to place them in a specific region.  Can someone point me in the right direction?

Body:
you should register in the module the target view TargetView for navigation:

    container.RegisterTypeForNavigation<TargetView>();