问:
How can I perform math on last x characters of string and update text box on the fly?
I have an app where a user scans or types in a starting barcode, and the ending barcode is automatically calculated based on a quantity value.

It works fine when the starting barcode is entirely numeric, it does the math and includes leading zeroes so the end code is the correct length.

My problem is that some small percentage of the barcodes are not entirely numeric.

The barcodes are 14 characters long. The last 5 characters will always be numeric and quantities will rarely exceed a few hundred and never go high enough that we spill into the 6th digit.

I'm not a javascript expert by any means, and just getting what I have now working strained my skills -- I'm hoping the community here can help me out :)

Here's the code I'm working with:

```<code>$(document).ready(function() {
  //leading zero fill function for barcodes
  function pad(num, size) {
    var s = "00000000000000" + num;
    return s.substr(s.length - size);
  }
  //Function to do BC math: starting number + quantity -1 (since it's inclusive) = end.
  function updateCode() {
    var quantity = $(this).closest('tr').find('.quantity').val();
    var barstart = $(this).closest('tr').find('.barstart').val();
    var end = pad(parseInt(barstart, 10) + parseInt(quantity - 1, 10), 14);
    $(this).parent().next().find('.barend').val(end);
  }
  $(document).on("change, keyup", ".barstart", updateCode);
});
</code>```

Edit  Trying to insert the HTML again:

```<code><script src="//code.jquery.com/jquery-1.7.2.min.js"></script>
<table id="formtable">
<tr>
<td><input class="quantity" size="6" id="qty_1" name="qtyid_1" value="123" type="text"></td>
<td><input class="barstart" size="15" maxlength="14" id="barstartid_1" name="barstart_1" value="" placeholder="Barcode Start" type="text"></td>
<td><input class="barend" size="15" maxlength="14" id="barendid_1" name="barend_1" value="" placeholder="Barcode End" type="text"></td>
</tr>
</table>
</code>```

Here's a jsfiddle: https://jsfiddle.net/g1p2xh6y/1/

The users can live without it, but it'll save them some headaches (and help me make a good impression - this is a new gig) if I can get it working, so I greatly appreciate any help the community can offer :)

Thanks!

答:
Many thanks to @admcfajn - I didn't know the slice() function existed, and that resolved it for me. I had to move the zero padding to the suffix, and remove it from the end value, but since it's pulling the prefix instead of doing math, that's no problem.

Here's the updated function:

```<code>function updateCode() {
        var quantity = $(this).closest('tr').find('.quantity').val();
        var barstart = $(this).closest('tr').find('.barstart').val();
        var barprefix = barstart.slice(0,barstart.length-5);
      var barendsuffix = pad(parseInt(barstart.slice(-5),10)+parseInt(quantity-1,10),5);
        $(this).parent().next().find('.barend').val(barprefix+barendsuffix);
}
</code>```

Body:
I have an app where a user scans or types in a starting barcode, and the ending barcode is automatically calculated based on a quantity value.

It works fine when the starting barcode is entirely numeric, it does the math and includes leading zeroes so the end code is the correct length.

My problem is that some small percentage of the barcodes are not entirely numeric.

The barcodes are 14 characters long. The last 5 characters will always be numeric and quantities will rarely exceed a few hundred and never go high enough that we spill into the 6th digit.

I'm not a javascript expert by any means, and just getting what I have now working strained my skills -- I'm hoping the community here can help me out :)

Here's the code I'm working with:

$(document).ready(function() {
  //leading zero fill function for barcodes
  function pad(num, size) {
    var s = "00000000000000" + num;
    return s.substr(s.length - size);
  }
  //Function to do BC math: starting number + quantity -1 (since it's inclusive) = end.
  function updateCode() {
    var quantity = $(this).closest('tr').find('.quantity').val();
    var barstart = $(this).closest('tr').find('.barstart').val();
    var end = pad(parseInt(barstart, 10) + parseInt(quantity - 1, 10), 14);
    $(this).parent().next().find('.barend').val(end);
  }
  $(document).on("change, keyup", ".barstart", updateCode);
});

Edit  Trying to insert the HTML again:

<input class="quantity" size="6" id="qty_1" name="qtyid_1" value="123" type="text">
<input class="barstart" size="15" maxlength="14" id="barstartid_1" name="barstart_1" value="" placeholder="Barcode Start" type="text">
<input class="barend" size="15" maxlength="14" id="barendid_1" name="barend_1" value="" placeholder="Barcode End" type="text">

Here's a jsfiddle: https://jsfiddle.net/g1p2xh6y/1/

The users can live without it, but it'll save them some headaches (and help me make a good impression - this is a new gig) if I can get it working, so I greatly appreciate any help the community can offer :)

Thanks!

Body:
Many thanks to @admcfajn - I didn't know the slice() function existed, and that resolved it for me. I had to move the zero padding to the suffix, and remove it from the end value, but since it's pulling the prefix instead of doing math, that's no problem.

Here's the updated function:

function updateCode() {
        var quantity = $(this).closest('tr').find('.quantity').val();
        var barstart = $(this).closest('tr').find('.barstart').val();
        var barprefix = barstart.slice(0,barstart.length-5);
      var barendsuffix = pad(parseInt(barstart.slice(-5),10)+parseInt(quantity-1,10),5);
        $(this).parent().next().find('.barend').val(barprefix+barendsuffix);
}


来源: stackexchange

问:
injecting a bean as a value to a property of another bean
How would some inject a bean as a value to a property of another bean?

For example

```<code>        public class FileNameGenerator
    {
        private String name;
        private String type;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getType() {
            return type;
        }
        public void setType(String type) {
            this.type = type;
        }
    }

<bean id="FileNameGenerator" class="FileNameGenerator">
        <property name="name">
            <value>value1</value>
        </property>
        <property name="type">
            <value>value2</value>
        </property>
    </bean>
</code>```

Instead I am trying to inject a factory method bean in value1

```<code><bean id="FileNameGenerator" class="FileNameGenerator">
                <property name="name">
                    <value>
<bean class="SomeOtherClass" factory-method="staticMethodThatReturnsString">
</value>
                </property>
                <property name="type">
                    <value>value2</value>
                </property>
            </bean>
</code>```

How would I do this?

答:
Remove the value tag around your factory-bean.

Your code should look like this:

```<code><bean id="FileNameGenerator" class="FileNameGenerator">
    <property name="name">
        <bean class="SomeOtherClass" factory-method="staticMethodThatReturnsString">
    </property>
    <property name="type">
        <value>value2</value>
    </property>
</bean>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How would some inject a bean as a value to a property of another bean?

For example

        public class FileNameGenerator
    {
        private String name;
        private String type;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getType() {
            return type;
        }
        public void setType(String type) {
            this.type = type;
        }
    }

<bean id="FileNameGenerator" class="FileNameGenerator">
        <property name="name">
            <value>value1</value>
        </property>
        <property name="type">
            <value>value2</value>
        </property>
    </bean>

Instead I am trying to inject a factory method bean in value1

<bean id="FileNameGenerator" class="FileNameGenerator">
                <property name="name">
                    <value>
<bean class="SomeOtherClass" factory-method="staticMethodThatReturnsString">
</value>
                </property>
                <property name="type">
                    <value>value2</value>
                </property>
            </bean>

How would I do this?

Body:
Remove the value tag around your factory-bean.

Your code should look like this:

<bean id="FileNameGenerator" class="FileNameGenerator">
    <property name="name">
        <bean class="SomeOtherClass" factory-method="staticMethodThatReturnsString">
    </property>
    <property name="type">
        <value>value2</value>
    </property>
</bean>


问:
Traversing an Array Javascript
I'm supposed to use a while loop to traverse this array and multiply each item by 2. The page just keeps loading forever when I try to run it.... What am I missing? Thank you.</p>

```<code>var prices = [4, 5, 8, 10];

var i = 0;
while (i < prices.length){
    prices[i]++;
    i*=2;
}

console.log(prices);
</code>```

答:
You swapped the increments:

var prices = [4, 5, 8, 10];

var i = 0;
while (i < prices.length){
    prices[i] *= 2;
    i++;
}

console.log(prices);```

Title: Traversing an Array Javascript

Body:
I'm supposed to use a while loop to traverse this array and multiply each item by 2. The page just keeps loading forever when I try to run it.... What am I missing? Thank you.

var prices = [4, 5, 8, 10];

var i = 0;
while (i < prices.length){
    prices[i]++;
    i*=2;
}

console.log(prices);


问:
Adding a custom model to spree and getting error: uninitialized constant Admin
I am trying to add a custom Photo model to a spree store admin panel and when I try to go to the page I am getting an error: uninitialized constant Admin. I have a feeling it has to do with either how I am naming my files or where I am putting them. This is what I have so far:

Routes

```<code>namespace :admin do
   resources :photos
end
</code>```

My view files are all located in: app/views/spree/admin/photos

app/controllers/admin/photos_controller.rb

```<code>module Admin
    class PhotosController < Admin::BaseController
      before_action :set_photo, only: [:show, :edit, :update, :destroy]

  # GET /photos
  # GET /photos.json
  def index
    @photos = Photo.all
  end

  # GET /photos/1
  # GET /photos/1.json
  def show
  end

  # GET /photos/new
  def new
    @photo = Photo.new
  end

  # GET /photos/1/edit
  def edit
  end

  # POST /photos
  # POST /photos.json
  def create
    @photo = Photo.new(photo_params)

    respond_to do |format|
      if @photo.save
        format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
        format.json { render :show, status: :created, location: @photo }
      else
        format.html { render :new }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /photos/1
  # PATCH/PUT /photos/1.json
  def update
    respond_to do |format|
      if @photo.update(photo_params)
        format.html { redirect_to @photo, notice: 'Photo was successfully updated.' }
        format.json { render :show, status: :ok, location: @photo }
      else
        format.html { render :edit }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /photos/1
  # DELETE /photos/1.json
  def destroy
    @photo.destroy
    respond_to do |format|
      format.html { redirect_to photos_url, notice: 'Photo was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_photo
      @photo = Photo.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def photo_params
      params.require(:photo).permit(:image, :book_id)
    end

    end
  end
</code>```

Here is the full error:

```<code>Started GET "/admin/photos" for 207.93.212.56 at 2017-04-13 19:18:41 +0000
Cannot render console from 207.93.212.56! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255

ActionController::RoutingError (uninitialized constant Admin):
  activesupport (4.2.6) lib/active_support/inflector/methods.rb:261:in `const_get'
  activesupport (4.2.6) lib/active_support/inflector/methods.rb:261:in `block in constantize'
  activesupport (4.2.6) lib/active_support/inflector/methods.rb:259:in `each'
  activesupport (4.2.6) lib/active_support/inflector/methods.rb:259:in `inject'
  activesupport (4.2.6) lib/active_support/inflector/methods.rb:259:in `constantize'
  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:70:in `controller_reference'
  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:60:in `controller'
  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:39:in `serve'
  actionpack (4.2.6) lib/action_dispatch/journey/router.rb:43:in `block in serve'
  actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `each'
  actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `serve'
  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:817:in `call'
  warden (1.2.7) lib/warden/manager.rb:36:in `block in call'
  warden (1.2.7) lib/warden/manager.rb:35:in `catch'
  warden (1.2.7) lib/warden/manager.rb:35:in `call'
  rack (1.6.5) lib/rack/etag.rb:24:in `call'
  rack (1.6.5) lib/rack/conditionalget.rb:25:in `call'
  rack (1.6.5) lib/rack/head.rb:13:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/flash.rb:260:in `call'
  rack (1.6.5) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.6.5) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.2.6) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.2.6) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'
  activerecord (4.2.6) lib/active_record/migration.rb:377:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.2.6) lib/active_support/callbacks.rb:88:in `__run_callbacks__'
  activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_call_callbacks'
  activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'
  actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  web-console (2.3.0) lib/web_console/middleware.rb:20:in `block in call'
  web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch'
  web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.2.6) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.6.5) lib/rack/methodoverride.rb:22:in `call'
  rack (1.6.5) lib/rack/runtime.rb:18:in `call'
  activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  rack (1.6.5) lib/rack/lock.rb:17:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/static.rb:120:in `call'
  rack (1.6.5) lib/rack/sendfile.rb:113:in `call'
  railties (4.2.6) lib/rails/engine.rb:518:in `call'
  railties (4.2.6) lib/rails/application.rb:165:in `call'
  rack (1.6.5) lib/rack/lock.rb:17:in `call'
  rack (1.6.5) lib/rack/content_length.rb:15:in `call'
  rack (1.6.5) lib/rack/handler/webrick.rb:88:in `service'
  /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/httpserver.rb:140:in `service'
  /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/httpserver.rb:96:in `run'
  /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/server.rb:296:in `block in start_thread'
</code>```

答:
Well, you need to use proper module scoping.This code snippet will help you out.

```<code>module Spree
  module Admin
    class PhotosController < BaseController
      before_action :set_photo, only: [:show, :edit, :update, :destroy]

      # GET /photos
      # GET /photos.json
      def index
        @photos = Photo.all
      end

      # GET /photos/1
      # GET /photos/1.json
      def show
      end

      # GET /photos/new
      def new
        @photo = Photo.new
      end

      # GET /photos/1/edit
      def edit
      end

      # POST /photos
      # POST /photos.json
      def create
        @photo = Photo.new(photo_params)

        respond_to do |format|
          if @photo.save
            format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
            format.json { render :show, status: :created, location: @photo }
          else
            format.html { render :new }
            format.json { render json: @photo.errors, status: :unprocessable_entity }
          end
        end
      end

      # PATCH/PUT /photos/1
      # PATCH/PUT /photos/1.json
      def update
        respond_to do |format|
          if @photo.update(photo_params)
            format.html { redirect_to @photo, notice: 'Photo was successfully updated.' }
            format.json { render :show, status: :ok, location: @photo }
          else
            format.html { render :edit }
            format.json { render json: @photo.errors, status: :unprocessable_entity }
          end
        end
      end

      # DELETE /photos/1
      # DELETE /photos/1.json
      def destroy
        @photo.destroy
        respond_to do |format|
          format.html { redirect_to photos_url, notice: 'Photo was successfully destroyed.' }
          format.json { head :no_content }
        end
      end

      private
        # Use callbacks to share common setup or constraints between actions.
        def set_photo
          @photo = Photo.find(params[:id])
        end

        # Never trust parameters from the scary internet, only allow the white list through.
        def photo_params
          params.require(:photo).permit(:image, :book_id)
        end

        end
    end
  end
end
</code>```

Also, I would recommend you to inherit your class from ResourceController instead of BaseController. By doing so you can save some LOC and it would be really helpful.

Body:
I am trying to add a custom Photo model to a spree store admin panel and when I try to go to the page I am getting an error: uninitialized constant Admin. I have a feeling it has to do with either how I am naming my files or where I am putting them. This is what I have so far:

Routes

namespace :admin do
   resources :photos
end

My view files are all located in: app/views/spree/admin/photos

app/controllers/admin/photos_controller.rb

module Admin
    class PhotosController < Admin::BaseController
      before_action :set_photo, only: [:show, :edit, :update, :destroy]

  # GET /photos
  # GET /photos.json
  def index
    @photos = Photo.all
  end

  # GET /photos/1
  # GET /photos/1.json
  def show
  end

  # GET /photos/new
  def new
    @photo = Photo.new
  end

  # GET /photos/1/edit
  def edit
  end

  # POST /photos
  # POST /photos.json
  def create
    @photo = Photo.new(photo_params)

    respond_to do |format|
      if @photo.save
        format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
        format.json { render :show, status: :created, location: @photo }
      else
        format.html { render :new }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /photos/1
  # PATCH/PUT /photos/1.json
  def update
    respond_to do |format|
      if @photo.update(photo_params)
        format.html { redirect_to @photo, notice: 'Photo was successfully updated.' }
        format.json { render :show, status: :ok, location: @photo }
      else
        format.html { render :edit }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /photos/1
  # DELETE /photos/1.json
  def destroy
    @photo.destroy
    respond_to do |format|
      format.html { redirect_to photos_url, notice: 'Photo was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_photo
      @photo = Photo.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def photo_params
      params.require(:photo).permit(:image, :book_id)
    end

    end
  end

Here is the full error:

Started GET "/admin/photos" for 207.93.212.56 at 2017-04-13 19:18:41 +0000
Cannot render console from 207.93.212.56! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255

ActionController::RoutingError (uninitialized constant Admin):
  activesupport (4.2.6) lib/active_support/inflector/methods.rb:261:in `const_get'
  activesupport (4.2.6) lib/active_support/inflector/methods.rb:261:in `block in constantize'
  activesupport (4.2.6) lib/active_support/inflector/methods.rb:259:in `each'
  activesupport (4.2.6) lib/active_support/inflector/methods.rb:259:in `inject'
  activesupport (4.2.6) lib/active_support/inflector/methods.rb:259:in `constantize'
  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:70:in `controller_reference'
  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:60:in `controller'
  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:39:in `serve'
  actionpack (4.2.6) lib/action_dispatch/journey/router.rb:43:in `block in serve'
  actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `each'
  actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `serve'
  actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:817:in `call'
  warden (1.2.7) lib/warden/manager.rb:36:in `block in call'
  warden (1.2.7) lib/warden/manager.rb:35:in `catch'
  warden (1.2.7) lib/warden/manager.rb:35:in `call'
  rack (1.6.5) lib/rack/etag.rb:24:in `call'
  rack (1.6.5) lib/rack/conditionalget.rb:25:in `call'
  rack (1.6.5) lib/rack/head.rb:13:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/flash.rb:260:in `call'
  rack (1.6.5) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.6.5) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.2.6) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.2.6) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'
  activerecord (4.2.6) lib/active_record/migration.rb:377:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.2.6) lib/active_support/callbacks.rb:88:in `__run_callbacks__'
  activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_call_callbacks'
  activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'
  actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  web-console (2.3.0) lib/web_console/middleware.rb:20:in `block in call'
  web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch'
  web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.2.6) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.6.5) lib/rack/methodoverride.rb:22:in `call'
  rack (1.6.5) lib/rack/runtime.rb:18:in `call'
  activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  rack (1.6.5) lib/rack/lock.rb:17:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/static.rb:120:in `call'
  rack (1.6.5) lib/rack/sendfile.rb:113:in `call'
  railties (4.2.6) lib/rails/engine.rb:518:in `call'
  railties (4.2.6) lib/rails/application.rb:165:in `call'
  rack (1.6.5) lib/rack/lock.rb:17:in `call'
  rack (1.6.5) lib/rack/content_length.rb:15:in `call'
  rack (1.6.5) lib/rack/handler/webrick.rb:88:in `service'
  /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/httpserver.rb:140:in `service'
  /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/httpserver.rb:96:in `run'
  /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/server.rb:296:in `block in start_thread'

Body:
Well, you need to use proper module scoping.This code snippet will help you out.

module Spree
  module Admin
    class PhotosController < BaseController
      before_action :set_photo, only: [:show, :edit, :update, :destroy]

      # GET /photos
      # GET /photos.json
      def index
        @photos = Photo.all
      end

      # GET /photos/1
      # GET /photos/1.json
      def show
      end

      # GET /photos/new
      def new
        @photo = Photo.new
      end

      # GET /photos/1/edit
      def edit
      end

      # POST /photos
      # POST /photos.json
      def create
        @photo = Photo.new(photo_params)

        respond_to do |format|
          if @photo.save
            format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
            format.json { render :show, status: :created, location: @photo }
          else
            format.html { render :new }
            format.json { render json: @photo.errors, status: :unprocessable_entity }
          end
        end
      end

      # PATCH/PUT /photos/1
      # PATCH/PUT /photos/1.json
      def update
        respond_to do |format|
          if @photo.update(photo_params)
            format.html { redirect_to @photo, notice: 'Photo was successfully updated.' }
            format.json { render :show, status: :ok, location: @photo }
          else
            format.html { render :edit }
            format.json { render json: @photo.errors, status: :unprocessable_entity }
          end
        end
      end

      # DELETE /photos/1
      # DELETE /photos/1.json
      def destroy
        @photo.destroy
        respond_to do |format|
          format.html { redirect_to photos_url, notice: 'Photo was successfully destroyed.' }
          format.json { head :no_content }
        end
      end

      private
        # Use callbacks to share common setup or constraints between actions.
        def set_photo
          @photo = Photo.find(params[:id])
        end

        # Never trust parameters from the scary internet, only allow the white list through.
        def photo_params
          params.require(:photo).permit(:image, :book_id)
        end

        end
    end
  end
end

Also, I would recommend you to inherit your class from ResourceController instead of BaseController. By doing so you can save some LOC and it would be really helpful.


问:
Capybara test failing because element can not be found
I am writing a RSpec Capybara test for a Rails 5 application. My application is for students learning how to write HTML and CSS. The application creates "test" objects, and then allows the user to take a test. Each time the user answers a question correctly, the app adds to the test object's "score" attribute. At the end, the application gives the user a final score and then records the test result.

I am having my Capybara tests fail because they can not locate a button. The way my app works, the user answers a question and then clicks the "Submit" button. ONLY after they submit an answer, a SECOND button appears that says "Next Question."

My test can not find that second button. I'm not an expert at testing and could use some help. I tried "sleep 5" but it didn't work.

Here is the error:

1) taking test with incorrect answers
     Failure/Error: click_button 'Next Question'

```<code> Capybara::ElementNotFound:
   Unable to find button "Next Question"
 # ./spec/features/taking_test_spec.rb:12:in `block (2 levels) in <top (required)>'
</code>```

Here is my test:

```<code>require 'rails_helper'

feature "taking test" do

    scenario "with incorrect answers" do
        visit '/'
        click_link "HTML Test"
        click_button "Start"
        fill_in "answer", with: '<p>'
        click_button 'Submit'
        sleep 5
        click_button 'Next Question'
        expect(page).to have_content('CSS helps you control the appearance of HTML elements.')
    end

end
</code>```

Here is the relevant portion of the controller for tests:

```<code>class TestsController < ApplicationController
before_action :authenticate_user!, only: [:destroy]

def index
    @test = Test.new
    @tests = Test.all.order(created_at: :desc).paginate(:page => params[:page], :per_page => 4)
end

def question1
    @test = Test.find(params[:id])
    correct_answer = "<p>"
    user_answer = params[:answer]
    if user_answer == correct_answer
        flash.now[:success] = "That is correct!"
        new_score = @test.score += 1
        @test.update(score: new_score)
    elsif params[:answer].present? && params[:answer] != correct_answer
        flash.now[:danger] = "Wrong answer."
    end
end
</code>```

Here is the view for question1, including the button that Capybara can not find:

```<code><div class="container-fluid">

    <div class="row background-white">
        <div class="col-md-8 col-md-push-2 score_container">
            <h5 class="text-center">Current Score: <%= @test.score %></h5>
        </div>

        <div class="col-sm-6 col-sm-push-3 col-xs-10 col-xs-push-1 question_container">
            <div class="form_group">
            <%= form_tag question1_path(@test), method: :get do %>
                <h5>1. How do you write an opening paragraph tag in HTML?</h5>
                <div class="form-group">
                    <%= text_area_tag :answer, params[:answer], class: 'form-control', id: 'answer' %>
                </div>
                <% if !flash[:success] && !flash[:danger] %>
                <div class="form-group">
                    <%= submit_tag "Submit", class: "btn btn-primary" %>
                </div>
                <% end %>
            <% end %>
            </div>

            <% if flash[:success] || flash[:danger] %>
                <%= link_to "Next Question", question2_path(@test), class:"btn btn-success pull-right" %>
            <% end %>
        </div>
    </div>
</div>
</code>```

答:
Your Next Question is not a button, it's a link (  element with href attribute - that happens to be styled to look like a button, but it's not a button).  Capybara defines a button as input [of type submit, reset, image, button] or button element. You need to use click_link to click a link, or click_link_or_button if you don't care which it is.

```<code>visit '/'
click_link "HTML Test"
click_button "Start"
fill_in "answer", with: '<p>'
click_button 'Submit'
click_link 'Next Question'
expect(page).to have_content('CSS helps you control the ap
</code>```

Body:
I am writing a RSpec Capybara test for a Rails 5 application. My application is for students learning how to write HTML and CSS. The application creates "test" objects, and then allows the user to take a test. Each time the user answers a question correctly, the app adds to the test object's "score" attribute. At the end, the application gives the user a final score and then records the test result.

I am having my Capybara tests fail because they can not locate a button. The way my app works, the user answers a question and then clicks the "Submit" button. ONLY after they submit an answer, a SECOND button appears that says "Next Question."

My test can not find that second button. I'm not an expert at testing and could use some help. I tried "sleep 5" but it didn't work.

Here is the error:

1) taking test with incorrect answers
     Failure/Error: click_button 'Next Question'

 Capybara::ElementNotFound:
   Unable to find button "Next Question"
 # ./spec/features/taking_test_spec.rb:12:in `block (2 levels) in <top (required)>'

Here is my test:

require 'rails_helper'

feature "taking test" do

    scenario "with incorrect answers" do
        visit '/'
        click_link "HTML Test"
        click_button "Start"
        fill_in "answer", with: '
'
        click_button 'Submit'
        sleep 5
        click_button 'Next Question'
        expect(page).to have_content('CSS helps you control the appearance of HTML elements.')
    end

end

Here is the relevant portion of the controller for tests:

class TestsController < ApplicationController
before_action :authenticate_user!, only: [:destroy]

def index
    @test = Test.new
    @tests = Test.all.order(created_at: :desc).paginate(:page => params[:page], :per_page => 4)
end

def question1
    @test = Test.find(params[:id])
    correct_answer = "
"
    user_answer = params[:answer]
    if user_answer == correct_answer
        flash.now[:success] = "That is correct!"
        new_score = @test.score += 1
        @test.update(score: new_score)
    elsif params[:answer].present? && params[:answer] != correct_answer
        flash.now[:danger] = "Wrong answer."
    end
end

Here is the view for question1, including the button that Capybara can not find:

Current Score: <%= @test.score %>

            <%= form_tag question1_path(@test), method: :get do %>

1. How do you write an opening paragraph tag in HTML?

                    <%= text_area_tag :answer, params[:answer], class: 'form-control', id: 'answer' %>

                <% if !flash[:success] && !flash[:danger] %>

                    <%= submit_tag "Submit", class: "btn btn-primary" %>

                <% end %>
            <% end %>

            <% if flash[:success] || flash[:danger] %>
                <%= link_to "Next Question", question2_path(@test), class:"btn btn-success pull-right" %>
            <% end %>

Body:
Your Next Question is not a button, it's a link ( <a> element with href attribute - that happens to be styled to look like a button, but it's not a button).  Capybara defines a button as input [of type submit, reset, image, button] or button element. You need to use click_link to click a link, or click_link_or_button if you don't care which it is.

visit '/'
click_link "HTML Test"
click_button "Start"
fill_in "answer", with: '<p>'
click_button 'Submit'
click_link 'Next Question'
expect(page).to have_content('CSS helps you control the ap


问:
How to make an application compatible in all Android phones?
Pls help me to solve my issue.. In most of my application the Ui design is not compatible for all Android devices.. ie..all the widgets are not aligning in proper order in all phones.. i want to develop an application which should fit all phone size and resolution ( large phones, normal ones and in small ones) ..pls resolve this issue...

Thanks in advance...

答:
That may not be possible. However you can look at these links and learn how to provide different images(pixels and density), layouts and further on. It may not be possible to make a userinterface on a low level density screen the same way as a high density screen and then you can target different layouts to different phones e.g.

Providing Resources

Application Resources

ContentLicense: CC BY-SA 2.5


问:
Collapsing Toolbar only for one Fragment in Navigation View

The Problem

I have a navigation drawer with different fragments. There is a default toolbar every Fragment should use, except of one Fragment which needs a collapsing Toolbar.

My Question

How can I switch between the toolbars for the fragments ?

答:
It seems you want to achieve something like this.

I have made an activity with common toolbar. when switching to the collapsing toolbar fragment I've made the toolbar transparent and fragment's toolbar takes over. The toolbar's color remains the same on switching to other fragments.

This allows you to manage complete collapsing toolbar's layout structure in xml and logic remains in Fragment.

Hope this will help. Refer the gif linked.

Gist for gif


问:
What is the significance of Parent-Child relationship in self referencing tables in sql?
I do understand the parent-child relationship of tables using keys but what is its significance in self-reference?</p>

答:
Self-reference lets you construct table structures for storing hierarchies.

For example, a table of employees that has a self-referencing manager ID lets you store an organizational structure of a company in a single table:

```<code>CREATE TABLE Employee (
    EmployeeId int
,   Name varchar(max)
,   DepartmentId int
,   ...
,   ManagerId int null
)
</code>```

Body:
Self-reference lets you construct table structures for storing hierarchies.

For example, a table of employees that has a self-referencing manager ID lets you store an organizational structure of a company in a single table:

CREATE TABLE Employee (
    EmployeeId int
,   Name varchar(max)
,   DepartmentId int
,   ...
,   ManagerId int null
)


问:
Preserve empty Excel cells when reading data from clipboard into DataTable
I am using the following code to read Excel data from the clipboard into a C# data table. The code is relatively unchanged as found from this answer to this question. I then add the data table as a data source to a DataGridView control for manipulation.

However, in my Excel data, I have blank/empty cells that I need to preserve, which this code does not do (blank cells are skipped over, effectively compressing each row leaving no empty space; the empty cells are missing from the Excel XML). How could I preserve empty cells when transferring to the data table?

Method:

```<code>private DataTable ParseClipboardData(bool blnFirstRowHasHeader)
    {
        var clipboard = Clipboard.GetDataObject();
        if (!clipboard.GetDataPresent("XML Spreadsheet")) return null;
        StreamReader streamReader = new StreamReader((MemoryStream)clipboard.GetData("XML Spreadsheet"));
        streamReader.BaseStream.SetLength(streamReader.BaseStream.Length - 1);

        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(streamReader.ReadToEnd());
        XNamespace ssNs = "urn:schemas-microsoft-com:office:spreadsheet";
        DataTable dt = new DataTable();

        var linqRows = xmlDocument.fwToXDocument().Descendants(ssNs + "Row").ToList<XElement>();
        for (int x = 0; x < linqRows.Max(a => a.Descendants(ssNs + "Cell").Count()); x++)
            dt.Columns.Add("Column " + x.ToString());

        int intCol = 0;
        DataRow currentRow;

        linqRows.ForEach(rowElement =>
        {
            intCol = 0;
            currentRow = dt.Rows.Add();
            rowElement.Descendants(ssNs + "Cell")
                .ToList<XElement>()
                .ForEach(cell => currentRow[intCol++] = cell.Value);
        });

        if (blnFirstRowHasHeader)
        {
            int x = 0;
            foreach (DataColumn dcCurrent in dt.Columns)
                dcCurrent.ColumnName = dt.Rows[0][x++].ToString();

            dt.Rows.RemoveAt(0);
        }

        return dt;
    }
</code>```

Extension method:

```<code>public static XDocument fwToXDocument(this XmlDocument xmlDocument)
{
    using (XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlDocument))
    {
        xmlNodeReader.MoveToContent();
        var doc = XDocument.Load(xmlNodeReader);
        return doc;
    }
}
</code>```

Contrived example to illustrate: (Excel 2015)

Range in Excel, copied to clipboard

DataGridView on Winform, with data table as data source

答:
The cell's xml will have an Index attribute if the previous cell was missing (had an empty value). You can update your code to check if the column index has changed before copying it to your data table row.</p>

```<code>linqRows.ForEach(rowElement =>
{
    intCol = 0;
    currentRow = dt.Rows.Add();
    rowElement.Descendants(ssNs + "Cell")
        .ToList<XElement>()
        .ForEach(cell =>
        {
            int cellIndex = 0;
            XAttribute indexAttribute = cell.Attribute(ssNs + "Index");

            if (indexAttribute != null)
            {
                Int32.TryParse(indexAttribute.Value, out cellIndex);
                intCol = cellIndex - 1;
            }

            currentRow[intCol] = cell.Value;
            intCol++;
        });
});
</code>```

Body:
I am using the following code to read Excel data from the clipboard into a C# data table. The code is relatively unchanged as found from this answer to this question. I then add the data table as a data source to a DataGridView control for manipulation.

However, in my Excel data, I have blank/empty cells that I need to preserve, which this code does not do (blank cells are skipped over, effectively compressing each row leaving no empty space; the empty cells are missing from the Excel XML). How could I preserve empty cells when transferring to the data table?

Method:

private DataTable ParseClipboardData(bool blnFirstRowHasHeader)
    {
        var clipboard = Clipboard.GetDataObject();
        if (!clipboard.GetDataPresent("XML Spreadsheet")) return null;
        StreamReader streamReader = new StreamReader((MemoryStream)clipboard.GetData("XML Spreadsheet"));
        streamReader.BaseStream.SetLength(streamReader.BaseStream.Length - 1);

        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(streamReader.ReadToEnd());
        XNamespace ssNs = "urn:schemas-microsoft-com:office:spreadsheet";
        DataTable dt = new DataTable();

        var linqRows = xmlDocument.fwToXDocument().Descendants(ssNs + "Row").ToList<XElement>();
        for (int x = 0; x < linqRows.Max(a => a.Descendants(ssNs + "Cell").Count()); x++)
            dt.Columns.Add("Column " + x.ToString());

        int intCol = 0;
        DataRow currentRow;

        linqRows.ForEach(rowElement =>
        {
            intCol = 0;
            currentRow = dt.Rows.Add();
            rowElement.Descendants(ssNs + "Cell")
                .ToList<XElement>()
                .ForEach(cell => currentRow[intCol++] = cell.Value);
        });

        if (blnFirstRowHasHeader)
        {
            int x = 0;
            foreach (DataColumn dcCurrent in dt.Columns)
                dcCurrent.ColumnName = dt.Rows[0][x++].ToString();

            dt.Rows.RemoveAt(0);
        }

        return dt;
    }

Extension method:

public static XDocument fwToXDocument(this XmlDocument xmlDocument)
{
    using (XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlDocument))
    {
        xmlNodeReader.MoveToContent();
        var doc = XDocument.Load(xmlNodeReader);
        return doc;
    }
}

Contrived example to illustrate: (Excel 2015)

Range in Excel, copied to clipboard

DataGridView on Winform, with data table as data source

Body:
The cell's xml will have an Index attribute if the previous cell was missing (had an empty value). You can update your code to check if the column index has changed before copying it to your data table row.

linqRows.ForEach(rowElement =>
{
    intCol = 0;
    currentRow = dt.Rows.Add();
    rowElement.Descendants(ssNs + "Cell")
        .ToList<XElement>()
        .ForEach(cell =>
        {
            int cellIndex = 0;
            XAttribute indexAttribute = cell.Attribute(ssNs + "Index");

            if (indexAttribute != null)
            {
                Int32.TryParse(indexAttribute.Value, out cellIndex);
                intCol = cellIndex - 1;
            }

            currentRow[intCol] = cell.Value;
            intCol++;
        });
});


问:
iOS - UIScrollView inside UICollectionViewCell - animation is not correct (delayed) for inner view
I have this hierarchy:

UICollectionView - UICollectionViewCell - UIScrollView - UIView: DetailedView

Inside UIView, I have detailed content (buttons, images views etc). UICollectionView has height constraint.

Inside button click, I have an animation to smoothly change height with this:

```<code>UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveLinear, animations: {
           self.heightConstraint.constant = newHeight
           self.collectionViewLayout.invalidateLayout()

           self.superview?.layoutIfNeeded()
}, completion: { finished in })
</code>```

Animation of UICollectionView is correct, but DetailedView animation is weird. It is looking like items are stretched and their size is corrected with a delay.

I have 4 cells in UICollectionView, if I scroll to sides.

If I dont call self.collectionViewLayout.invalidateLayout(), content (DetailedView) is repeated inside UICollectionView and there is no animation for the content at all. It just "sits" at its place and repeats.

(now those are 2 of my 4 cells inside one view, but they should be each on its own "page")

But it should be

My scene has these constraints (I have removed button that starts animation, it had no constraint and was put in top left corner):

Height Constraint is changed inside animation.

答:
You need to provide more code. But two things first to start with which you should take into account:

Animations and .layoutIfNeeded() are intensive methods to call, anywhere in an app. They usually completetely re-calculates constraints, sizing, positionning etc. You also need to bear in mind, the more subviews present in the view you are calling it on, the heavier the task. In your case, you are calling it on the lowest views in the hierarchy, then moving up to their superViews to call it again, and then you call it a third time on the highest view of the hierarchy..

So You're doing the work three times for each sub-subview (in this case DetailedView), twice for your middle subviews (your scrollView), and once for your view which contains your UICollectionView.
So just by assumption, you're doing too much layout-resizing here, all the while trying to animating it all, which might explain why your collectionView's animation is fine (calculated only once), but that it's cell's subviews are not (they are being re-calculated more than once, and not at the same time as the collectionView's)

You need to figure out which view is needed for re-sizing and Usually, you should only have to call .layoutIfNeeded() on a particular view to animate whatever it is you need. By this definition, you need to test your hierarchy for the right place to call .layoutIfNeeded() when you're re-sizing many of it's subviews which themselves are getting constraint changes. While animating a higher-level view in the hierarchy does means you re-calculate all of the subviews too, the animation methods for UIView should take care of ironing out the transitions for them as well if you change their constraints prior to calling the .layoutIfNeeded().

Unfortunately, as your hierarchy grows in complexity, it does become more and more challenging, so trial and error is sometimes the safe route to go.

Second, it's nearly impossible to judge how appropriate your approach is to your use case without more code. This is especially the case if you're adding a scrollview inside of a collectionView which is itself a UIScrollView subclass. So there might also be some touch interaction/animation conflicting against your desired animation. I won't correct your code otherwise, because i don't know what you're trying to do, but start by figuring out which view should perform .layoutIfNeeded().

For now, check out these videos by google, they go into this hierarchy .layoutIfNeeded() issue really well:

Animating Constraints Part 1

Animating Constraints Part 2

Body:
I have this hierarchy:

UICollectionView - UICollectionViewCell - UIScrollView - UIView: DetailedView

Inside UIView, I have detailed content (buttons, images views etc). UICollectionView has height constraint.

Inside button click, I have an animation to smoothly change height with this:

UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveLinear, animations: {
           self.heightConstraint.constant = newHeight
           self.collectionViewLayout.invalidateLayout()

           self.superview?.layoutIfNeeded()
}, completion: { finished in })

Animation of UICollectionView is correct, but DetailedView animation is weird. It is looking like items are stretched and their size is corrected with a delay.

I have 4 cells in UICollectionView, if I scroll to sides.

If I dont call self.collectionViewLayout.invalidateLayout(), content (DetailedView) is repeated inside UICollectionView and there is no animation for the content at all. It just "sits" at its place and repeats.

(now those are 2 of my 4 cells inside one view, but they should be each on its own "page")

But it should be

My scene has these constraints (I have removed button that starts animation, it had no constraint and was put in top left corner):

Height Constraint is changed inside animation.


问:
Performance issue joining system tables & DMVs on DB with many partitioned tables?
I'm running the below query on each database in my environment, twice a day, for tracking. I have a relatively busy server with a database that has a count of 95k rows for this query (this DB contains many about 20 tables that can have many partitions, some upwards of 300). On all my other servers it runs fine, but for this one database I've started having problems, where it used to finish within a couple of minutes but now will run over 18 minutes.

If I just do a COUNT, it comes back with 93462 in about 1 second.

SELECT i.name takes 2 seconds (returns 93462 rows)

SELECT p.rows takes at least 18 minutes

sp_whoisactive shows no WAIT_INFO.  I tried using SQL Sentry Plan Explorer's WAIT STATS feature, but since the query never finishes (longest I've let it run is 18 minutes) I don't get any results.

This is on SQL Server 2016 SP1-CU2, Enterprise, 64-bit

All help greatly appreciated!

```<code>SELECT distinct 'mydbname' AS database_name,
        SCHEMA_NAME(o.schema_id) AS table_schema,
        o.name AS table_name,
        i.name AS index_name,
        o.type_desc as type_desc_full,
        CASE i.type
                WHEN 0 THEN 'HP'
                WHEN 1 THEN 'C'
                WHEN 2 THEN 'NC'
                WHEN 3 THEN 'XM'
                WHEN 4 THEN 'Sp'
                WHEN 5 THEN 'CS' --clustered columnstore, which doesn't exist (yet)
                WHEN 6 THEN 'cs' --nonclustered columnstore, available in 2012.
        ELSE 'UK' END AS type_desc_brief,
        MAX(a.type) as allocation_type,
        MAX(p.rows) AS rows_in_table,
        SUM(a.total_pages * 8/1024) AS Total_MB,
        avg(u.user_seeks) AS user_seeks,
        MAX(last_user_seek) AS last_user_seek,
        avg(u.user_lookups) AS user_lookups,
        MAX(last_user_lookup) AS last_user_lookup,
        avg(u.user_scans) AS  user_scans,
        MAX(last_user_scan) AS last_user_scan,
        avg(u.user_updates) AS  user_updates,
        MAX(last_user_update) AS last_user_update
FROM    sys.indexes i
JOIN    sys.objects o
        ON i.object_id = o.object_id
LEFT JOIN sys.dm_db_index_usage_stats u
        ON i.object_id = u.object_id
           AND i.index_id = u.index_id
           AND u.database_id = DB_ID()
inner JOIN sys.partitions as p
        on i.object_id = p.object_id
        and i.index_id = p.index_id
INNER JOIN sys.allocation_units AS a
        on (a.type = 2 AND p.partition_id = a.container_id)
        OR ((a.type = 1 OR a.type = 3) AND p.hobt_id = a.container_id)
--WHERE   o.type_desc NOT IN ('SYSTEM_TABLE', 'INTERNAL_TABLE','SQL_TABLE_VALUED_FUNCTION')           -- No system tables!
GROUP BY SCHEMA_NAME(o.schema_id),
        o.name,
        i.name,
        o.type_desc,
        CASE i.type
                WHEN 0 THEN 'HP'
                WHEN 1 THEN 'C'
                WHEN 2 THEN 'NC'
                WHEN 3 THEN 'XM'
                WHEN 4 THEN 'Sp'
                WHEN 5 THEN 'CS' --clustered columnstore
                WHEN 6 THEN 'cs' --nonclustered columnstore, available in 2012.
        ELSE 'UK' END
</code>```

答:
i've seen blocking due to access of sys.partitions.  i believe sys.partitions.rows comes from stats object.  May be collecting from lots and lots of individual objects, and any one stats object may be locus of blocking.

Does sys.dm_session_wait_stats shed any light?

Body:
I'm running the below query on each database in my environment, twice a day, for tracking. I have a relatively busy server with a database that has a count of 95k rows for this query (this DB contains many about 20 tables that can have many partitions, some upwards of 300). On all my other servers it runs fine, but for this one database I've started having problems, where it used to finish within a couple of minutes but now will run over 18 minutes.

If I just do a COUNT, it comes back with 93462 in about 1 second.

SELECT i.name takes 2 seconds (returns 93462 rows)

SELECT p.rows takes at least 18 minutes

sp_whoisactive shows no WAIT_INFO.  I tried using SQL Sentry Plan Explorer's WAIT STATS feature, but since the query never finishes (longest I've let it run is 18 minutes) I don't get any results.

This is on SQL Server 2016 SP1-CU2, Enterprise, 64-bit

All help greatly appreciated!

SELECT distinct 'mydbname' AS database_name,
        SCHEMA_NAME(o.schema_id) AS table_schema,
        o.name AS table_name,
        i.name AS index_name,
        o.type_desc as type_desc_full,
        CASE i.type
                WHEN 0 THEN 'HP'
                WHEN 1 THEN 'C'
                WHEN 2 THEN 'NC'
                WHEN 3 THEN 'XM'
                WHEN 4 THEN 'Sp'
                WHEN 5 THEN 'CS' --clustered columnstore, which doesn't exist (yet)
                WHEN 6 THEN 'cs' --nonclustered columnstore, available in 2012.
        ELSE 'UK' END AS type_desc_brief,
        MAX(a.type) as allocation_type,
        MAX(p.rows) AS rows_in_table,
        SUM(a.total_pages * 8/1024) AS Total_MB,
        avg(u.user_seeks) AS user_seeks,
        MAX(last_user_seek) AS last_user_seek,
        avg(u.user_lookups) AS user_lookups,
        MAX(last_user_lookup) AS last_user_lookup,
        avg(u.user_scans) AS  user_scans,
        MAX(last_user_scan) AS last_user_scan,
        avg(u.user_updates) AS  user_updates,
        MAX(last_user_update) AS last_user_update
FROM    sys.indexes i
JOIN    sys.objects o
        ON i.object_id = o.object_id
LEFT JOIN sys.dm_db_index_usage_stats u
        ON i.object_id = u.object_id
           AND i.index_id = u.index_id
           AND u.database_id = DB_ID()
inner JOIN sys.partitions as p
        on i.object_id = p.object_id
        and i.index_id = p.index_id
INNER JOIN sys.allocation_units AS a
        on (a.type = 2 AND p.partition_id = a.container_id)
        OR ((a.type = 1 OR a.type = 3) AND p.hobt_id = a.container_id)
--WHERE   o.type_desc NOT IN ('SYSTEM_TABLE', 'INTERNAL_TABLE','SQL_TABLE_VALUED_FUNCTION')           -- No system tables!
GROUP BY SCHEMA_NAME(o.schema_id),
        o.name,
        i.name,
        o.type_desc,
        CASE i.type
                WHEN 0 THEN 'HP'
                WHEN 1 THEN 'C'
                WHEN 2 THEN 'NC'
                WHEN 3 THEN 'XM'
                WHEN 4 THEN 'Sp'
                WHEN 5 THEN 'CS' --clustered columnstore
                WHEN 6 THEN 'cs' --nonclustered columnstore, available in 2012.
        ELSE 'UK' END


问:
Codeigniter - matching user entered password to hashed password stored in DB always returns false. Please help
I have my controller Setup
my join_model
and my login_model

A user registers and after they have passed all validation and captcha etc and have clicked submit they are set to setup.

My setup controller loads the join_model and the create() method, takes all the post data and gets ready to send it to db. This is when the password they entered in the signup form get's hashed, salted etc.

After this I have an if statement that checks whether user passed the checkLogin method in the login_model with TRUE. This method is in the setup controller and I called it loginValidated.

If that is TRUE then user is re-directed to member area (dash).

When I test I keep getting sent to the failed page. I also changed the if state to (!this->loginValidated()) and then I get de-directed to the account area meaning the passwords must not match.

I was wondering if anyone could have a quick look through my code to see if they spot where I'm going wrong?

```<code><?php

class Setup extends Controller {

    public function index() {

        $this->load->model('join_model');
        $this->join_model->create();
        if ($this->loginValidated()) { //if user credentials passed validation

        redirect('dash'); //forward to dashboard
        }
        else {
            redirect('failed');
        }
    }
    public function loginValidated() {
        $this->load->model('login_model'); //load login_model model
        $this->login_model->checkLogin(); //load checkLogin method

    }
 }

<?php
//MY CONTROLLER

class Login_Model extends CI_Model {

    public function checkLogin() {
            return Join_Model::$u;

            $this->db->where('email', $this->input->post('email')); //compare db email to email entered in form
            $this->db->where('password', $u->password); //compare db password to password entered by user after hashing
            $query = $this->db->get('user'); // get the above info from 'user' table

            if ($query->num_rows == 1) { //if number of rows returned is 1

            $this->load->library('session');
            $this->session->set_userdata('user_id',$u->id);
            $this->session->set_userdata('username',$u->username);
            $this->session->set_userdata('first_name',$u->first_name);
            $this->session->set_userdata('last_name',$u->last_name);
            $this->session->set_userdata('logged_in', 'TRUE');

            return TRUE;
      }
   }
}

<?php
// MY JOIN MODEL

class Join_Model extends CI_Model {
    public static $u;
    public function create() {
                $this->load->helper('date');
                $this->load->library('encrypt');

  $u->first_name = $this->input->post('first_name');
                $u->last_name = $this->input->post('last_name');
                $u->email = $this->input->post('email');

                // sha1 and salt password
                $salt = $this->config->item('encryption_key');
  $password = $this->encrypt->sha1($this->input->post('password'));
                $start_hash = sha1($salt . $password);
                $end_hash = sha1($password . $salt);
                $hashed = sha1($start_hash . $password . $end_hash);
                $u->password = sha1($hashed);

                $u->birthday = $this->input->post('year') . '-' . $this->input->post('month') . '-' . $this->input->post('day');
                $u->sex = $this->input->post('sex');

                $u->created_at = date('Y-m-d H:i:s', now()); // date and time user joined the website

                $this->db->insert('user', $u);

    }
}
</code>```

答:
My CI is a bit rusty, but it looks like you are returning something on the first line of your checkLogin() function, it would seem to me that the code below that is not getting executed then.

Also, you need to hash the password again before you send it to the database, otherwise you are comparing the clear text password to the hash.

Also, it seems to me like you'd need a User controller and model, not a model for user registration and login. Furthermore you should refrain from loading libraries inside your model, this is considered ugly when working with an MVC framework.

Body:
I have my controller Setup
my join_model
and my login_model

A user registers and after they have passed all validation and captcha etc and have clicked submit they are set to setup.

My setup controller loads the join_model and the create() method, takes all the post data and gets ready to send it to db. This is when the password they entered in the signup form get's hashed, salted etc.

After this I have an if statement that checks whether user passed the checkLogin method in the login_model with TRUE. This method is in the setup controller and I called it loginValidated.

If that is TRUE then user is re-directed to member area (dash).

When I test I keep getting sent to the failed page. I also changed the if state to (!this->loginValidated()) and then I get de-directed to the account area meaning the passwords must not match.

I was wondering if anyone could have a quick look through my code to see if they spot where I'm going wrong?

<?php

class Setup extends Controller {

    public function index() {

        $this->load->model('join_model');
        $this->join_model->create();
        if ($this->loginValidated()) { //if user credentials passed validation

        redirect('dash'); //forward to dashboard
        }
        else {
            redirect('failed');
        }
    }
    public function loginValidated() {
        $this->load->model('login_model'); //load login_model model
        $this->login_model->checkLogin(); //load checkLogin method

    }
 }

<?php
//MY CONTROLLER

class Login_Model extends CI_Model {

    public function checkLogin() {
            return Join_Model::$u;

            $this->db->where('email', $this->input->post('email')); //compare db email to email entered in form
            $this->db->where('password', $u->password); //compare db password to password entered by user after hashing
            $query = $this->db->get('user'); // get the above info from 'user' table

            if ($query->num_rows == 1) { //if number of rows returned is 1

            $this->load->library('session');
            $this->session->set_userdata('user_id',$u->id);
            $this->session->set_userdata('username',$u->username);
            $this->session->set_userdata('first_name',$u->first_name);
            $this->session->set_userdata('last_name',$u->last_name);
            $this->session->set_userdata('logged_in', 'TRUE');

            return TRUE;
      }
   }
}

<?php
// MY JOIN MODEL

class Join_Model extends CI_Model {
    public static $u;
    public function create() {
                $this->load->helper('date');
                $this->load->library('encrypt');

  $u->first_name = $this->input->post('first_name');
                $u->last_name = $this->input->post('last_name');
                $u->email = $this->input->post('email');

                // sha1 and salt password
                $salt = $this->config->item('encryption_key');
  $password = $this->encrypt->sha1($this->input->post('password'));
                $start_hash = sha1($salt . $password);
                $end_hash = sha1($password . $salt);
                $hashed = sha1($start_hash . $password . $end_hash);
                $u->password = sha1($hashed);

                $u->birthday = $this->input->post('year') . '-' . $this->input->post('month') . '-' . $this->input->post('day');
                $u->sex = $this->input->post('sex');

                $u->created_at = date('Y-m-d H:i:s', now()); // date and time user joined the website

                $this->db->insert('user', $u);

    }
}


问:
No python terminal in jupyter notebook

Attached a screenshot of the error. I have tried creating python 3 and python2 virtualEnv but nothing is working. Any help would be highly appreciated.

答:
I solved the problem by updating the ipython kernel. I could not run any notebook because it was showing 0 active kernel message in the command prompt and hence I couldn't run any python kernel in the browser. Following steps solved the problem:

sudo apt-get -y install ipython ipython-notebook

sudo -H pip install jupyter

Following this link solved the problem.

Title: No python terminal in jupyter notebook


问:
Extracting strings from a pandas dataframe
I'm here again hoping to find a solution to my coding nightmare. I have a dictionary term_dict with list of terms as keys and term category as values. And a dataframe data with ID and Notes columns. The task is to find matching terms in the data.Notes using the term_dict for every data.ID record.

```<code>  term_dict{
  Ibuprofen 800mg     :     Drug
  Hip Replacement Surgery : Treatment
  Tylenol   AM          :   Drug
  Mild Dislocation      :   Treatment
  Advil                  :  Drug
  Fractured Tibia       :   Treatment
  Quinone               :   Drug
  Fever                 :   Treatment
  Penicillin 250mg      :   Drug
  Histerectomy          :   Treatment
  Surgical removal of bunion :  Treatment
  Therapy               :   Treatment
  Bunion                :   Treatment
  Hospita X             :   Location
  mg                    :   Dosage
  stop                  :   Exclusion
}

data:
ID      Notes
604     Take 2 tablets of advil & 3 caps of pen
        250mg twice daily
602     Stop pen but cont. with advil
        as needed for the fracture
210     2 tabs of Tyl 3x daily for 5 days
607     nan
700     surgery scheduled for 01/01/2017
515     nan
019     Call my office if bunion pain persist
        after 3 days
604     f/up appt. @Hospital X
</code>```

So far, this is my code:

```<code>lists = []
for s in data['Notes']:
    cleanNotes = " " + " ".join(re.split(r'[^a-z 0-9]|[w/]',s.lower())) + " "
    for k, v in term_dict.items():
        k = " %s "%k
        if k in cleanNotes and v != exclusion:
            if k in cleanNotes and v == 'drug':
                lists.append(k)
                data['Drug'] = ':'.join(str(lists))
            elif k in cleanNotes and v == 'location':
                lists.append(k)
                data['Location'] = ' '.join(str(lists))
            elif k in cleanNotes and v == 'treatment':
                lists.append(k)
                data['Treatment'] = ':'.join(str(lists))
            elif k in cleanNotes and v == 'dosage':
                lists.append(k)
                data['Dosage'] = ':'.join(str(lists))
        else:
            for s in data.Notes:
            matches = list(datefinder.find_dates(s.lower()))
            data['Date'] = ', '.join([str(dates) for dates in matches])
</code>```

....and my output is not what's expected because the code just populates the new columns of the dataframe with matches from he last record of the dataframe:

```<code>data:
ID      Notes                                       Drug                Dosage      Location        Treatment   Date
604     Take 2 tablets of advil & 3 caps of pen     advil                           Hospital X
        250mg twice daily
602     Stop pen but cont. with advil               advil                           Hospital X
        as needed for the fracture
210     2 tabs of Tyl 3x daily for 5 days           advil
607     nan                                         advil
700     surgery scheduled for 01/01/2017            advil
515     nan                                         advil
019     Call my office if bunion pain persist       advil
        after 3 days
604     f/up appt. @Hospital X. cont w/advil        advil                           Hospital X
</code>```

***But expected Output:

```<code>data:
ID      Notes                                       Drug                Dosage      Location        Treatment   Date
604     Take 2 tablets of advil & 3 caps of pen     advil:penicilin     0:250mg
        250mg twice daily
602     Stop pen but cont. with advil               advil                                           fracture
        as needed for the fracture
210     2 tabs of Tyl 3x daily for 5 days           Tylenol
607     nan
700     surgery scheduled for 01/01/2017                                                            surgery     01/01/2017
515     nan
019     Call my office if bunion pain persist                                                       bunion
        after 3 days
604     f/up appt. @Hospital X. cont w/advil        advil                           Hospital X
</code>```

I'd be more than grateful if I can get this duplication fixed. Thanks!

Body:
I'm here again hoping to find a solution to my coding nightmare. I have a dictionary term_dict with list of terms as keys and term category as values. And a dataframe data with ID and Notes columns. The task is to find matching terms in the data.Notes using the term_dict for every data.ID record.

  term_dict{
  Ibuprofen 800mg     :     Drug
  Hip Replacement Surgery : Treatment
  Tylenol   AM          :   Drug
  Mild Dislocation      :   Treatment
  Advil                  :  Drug
  Fractured Tibia       :   Treatment
  Quinone               :   Drug
  Fever                 :   Treatment
  Penicillin 250mg      :   Drug
  Histerectomy          :   Treatment
  Surgical removal of bunion :  Treatment
  Therapy               :   Treatment
  Bunion                :   Treatment
  Hospita X             :   Location
  mg                    :   Dosage
  stop                  :   Exclusion
}

data:
ID      Notes
604     Take 2 tablets of advil & 3 caps of pen
        250mg twice daily
602     Stop pen but cont. with advil
        as needed for the fracture
210     2 tabs of Tyl 3x daily for 5 days
607     nan
700     surgery scheduled for 01/01/2017
515     nan
019     Call my office if bunion pain persist
        after 3 days
604     f/up appt. @Hospital X

So far, this is my code:

lists = []
for s in data['Notes']:
    cleanNotes = " " + " ".join(re.split(r'[^a-z 0-9]|[w/]',s.lower())) + " "
    for k, v in term_dict.items():
        k = " %s "%k
        if k in cleanNotes and v != exclusion:
            if k in cleanNotes and v == 'drug':
                lists.append(k)
                data['Drug'] = ':'.join(str(lists))
            elif k in cleanNotes and v == 'location':
                lists.append(k)
                data['Location'] = ' '.join(str(lists))
            elif k in cleanNotes and v == 'treatment':
                lists.append(k)
                data['Treatment'] = ':'.join(str(lists))
            elif k in cleanNotes and v == 'dosage':
                lists.append(k)
                data['Dosage'] = ':'.join(str(lists))
        else:
            for s in data.Notes:
            matches = list(datefinder.find_dates(s.lower()))
            data['Date'] = ', '.join([str(dates) for dates in matches])

....and my output is not what's expected because the code just populates the new columns of the dataframe with matches from he last record of the dataframe:

data:
ID      Notes                                       Drug                Dosage      Location        Treatment   Date
604     Take 2 tablets of advil & 3 caps of pen     advil                           Hospital X
        250mg twice daily
602     Stop pen but cont. with advil               advil                           Hospital X
        as needed for the fracture
210     2 tabs of Tyl 3x daily for 5 days           advil
607     nan                                         advil
700     surgery scheduled for 01/01/2017            advil
515     nan                                         advil
019     Call my office if bunion pain persist       advil
        after 3 days
604     f/up appt. @Hospital X. cont w/advil        advil                           Hospital X

***But expected Output:

data:
ID      Notes                                       Drug                Dosage      Location        Treatment   Date
604     Take 2 tablets of advil & 3 caps of pen     advil:penicilin     0:250mg
        250mg twice daily
602     Stop pen but cont. with advil               advil                                           fracture
        as needed for the fracture
210     2 tabs of Tyl 3x daily for 5 days           Tylenol
607     nan
700     surgery scheduled for 01/01/2017                                                            surgery     01/01/2017
515     nan
019     Call my office if bunion pain persist                                                       bunion
        after 3 days
604     f/up appt. @Hospital X. cont w/advil        advil                           Hospital X

I'd be more than grateful if I can get this duplication fixed. Thanks!

Body:
The essence of your error is this. You assign every element of that column to the same value:

In [114]: import pandas as pd

In [115]: df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD'))

In [116]: df.head()
Out[116]:
          A         B         C         D
0 -0.896291 -0.277551  0.926559  0.522212
1 -0.265559 -1.300435 -0.079514 -1.083569
2 -0.534509  0.298264 -1.361829  0.750666
3  0.318937 -0.407164  0.080020  0.499435
4 -0.161574 -1.012471  0.631092  1.368540

In [117]: df['NewCol'] = 'something here'

In [119]: df.head()
Out[119]:
          A         B         C         D          NewCol
0 -0.896291 -0.277551  0.926559  0.522212  something here
1 -0.265559 -1.300435 -0.079514 -1.083569  something here
2 -0.534509  0.298264 -1.361829  0.750666  something here
3  0.318937 -0.407164  0.080020  0.499435  something here
4 -0.161574 -1.012471  0.631092  1.368540  something here

To fix this, what you can do is create empty columns up front, like this:

In [120]: df = pd.DataFrame(np.random.randn(50, 1), columns=['Notes'])

In [121]: df['Drug'] = ""
     ...: df['Location'] = ""
     ...: df['Treatment'] = ""
     ...: df['Dosage'] = ""
     ...:

In [122]: df.head()
Out[122]:
      Notes Drug Location Treatment Dosage
0  0.325993
1 -0.561066
2  0.555040
3  0.001332
4  0.400009

When looping over notes, use an enumerated loop:

for i, s in enumerate(data['Notes']):

Then, when the need arises, just set that cell appropriately:

df.set_value(i, 'Drug', 'advil')


问:
Titlecasing a string with exceptions
Is there a standard way in Python to titlecase a string (i.e. words start with uppercase characters, all remaining cased characters have lowercase) but leaving articles like and, in, and of lowercased?

答:
One-liner using list comprehension and the ternary operator

```<code>reslt = " ".join([word.title() if word not in "the a on in of an" else word for word in "Wow, a python one liner for titles".split(" ")])
print(reslt)
</code>```

Breakdown:

for word in "Wow, a python one liner for titles".split(" ") Splits the string into an list and initiates a for loop (in the list comprehenstion)

word.title() if word not in "the a on in of an" else word uses native method title() to title case the string if it's not an article

" ".join joins the list elements with a seperator of (space)

Title: Titlecasing a string with exceptions

Body:
One-liner using list comprehension and the ternary operator

reslt = " ".join([word.title() if word not in "the a on in of an" else word for word in "Wow, a python one liner for titles".split(" ")])
print(reslt)

Breakdown:

for word in "Wow, a python one liner for titles".split(" ") Splits the string into an list and initiates a for loop (in the list comprehenstion)

word.title() if word not in "the a on in of an" else word uses native method title() to title case the string if it's not an article

" ".join joins the list elements with a seperator of (space)


答:
Check the android developer site, mainly the following

1 . Supporting Multiple Screens

2 . User Interface Guidelines

Title: How to make an application compatible in all Android phones?

Body:
Pls help me to solve my issue.. In most of my application the Ui design is not compatible for all Android devices.. ie..all the widgets are not aligning in proper order in all phones.. i want to develop an application which should fit all phone size and resolution ( large phones, normal ones and in small ones) ..pls resolve this issue...

Thanks in advance...


问:
Simulating Orbits
So I'm trying to simulate the earth travelling around the sun where the velocity of the earth is determined by the angle its at to the origin and the horizontal. I did this by creating a function that uses tanh (opposite/adjacent) rule for triangles, O_correction(x,y). The problem is that instead of a circular orbit its instead spiralling out and I'm not sure why.

```<code>scene = canvas()
scene.background = color.white

O = 0
ball = sphere(pos=vector(10,0,0), radius=0.1, color=color.blue)

x = ball.pos.x
y = ball.pos.y

def O_correction(x,y):
    O = math.atan((((y)**2)**0.5)/(((x)**2)**0.5))
    answer = O
    if x >= 0 and y >= 0:
        answer = O
    if x < 0 and y >= 0:
        answer = pi - O
    if x <= 0 and y < 0:
        answer = O + pi
    if x > 0 and y < 0:
        answer =pi*2 - O
    return answer

t =0
while t < 100:
    x = ball.pos.x
    y = ball.pos.y
    print = (float(O_correction(x,y))
    print = ((x**2) + (y**2))**0.5)
    ball.pos.x -= sin(O_correction(x,y))
    ball.pos.y += cos(O_correction(x,y))
    print(" ")
    t += 1
</code>```

Would very much appreciate some help,
Cheers

答:
I don't know python, but I know physics.

At each step you move the Earth a fixed distance along a tangent to the orbit, rather than along the orbit itself. That gives you an outward spiral (which will actually get less severe as you go out).

Try making the time increment smaller (e.g. by dividing the position adjustment by 100), and the spiral effect will get much smaller.

If you want to do better than that, you'll need a different formula. You could either impose a circular orbit, or do something based on conserved quantities (which requires a considerable understanding of basic physics).

Title: Simulating Orbits

Body:
So I'm trying to simulate the earth travelling around the sun where the velocity of the earth is determined by the angle its at to the origin and the horizontal. I did this by creating a function that uses tanh (opposite/adjacent) rule for triangles, O_correction(x,y). The problem is that instead of a circular orbit its instead spiralling out and I'm not sure why.

scene = canvas()
scene.background = color.white

O = 0
ball = sphere(pos=vector(10,0,0), radius=0.1, color=color.blue)

x = ball.pos.x
y = ball.pos.y

def O_correction(x,y):
    O = math.atan((((y)**2)**0.5)/(((x)**2)**0.5))
    answer = O
    if x >= 0 and y >= 0:
        answer = O
    if x < 0 and y >= 0:
        answer = pi - O
    if x <= 0 and y < 0:
        answer = O + pi
    if x > 0 and y < 0:
        answer =pi*2 - O
    return answer

t =0
while t < 100:
    x = ball.pos.x
    y = ball.pos.y
    print = (float(O_correction(x,y))
    print = ((x**2) + (y**2))**0.5)
    ball.pos.x -= sin(O_correction(x,y))
    ball.pos.y += cos(O_correction(x,y))
    print(" ")
    t += 1

Would very much appreciate some help,
Cheers


问:
Extract the particular portion from a String
I have the below String variable

```<code>String s = "abc,xyz,lmn,ijk";
</code>```

I want to extract only the portion of the String (i.e - 'lmn')

And, Should not use in-built functions like, SubString(), Split(), IndexOf(). But I can use charArray()

And this question was asked in my interview.

I tried the below code,
But not sure how to proceed. Can any one please provide your thoughts?

```<code>    String s = "abc,xyz,lmn,ijk";
    int counter = 0;

    char[] ch = s.toCharArray();
    for (int i = 0; i < ch.length; i++) {
        if (ch[i] == ',') {
            counter++;
        }

    }
</code>```

答:
Here's one way:

```<code>public static void main(String[] args) {
    String s = "abc,xyz,lmn,ijk";
    char[] ch = s.toCharArray();
    int counter = 0;
    int place = 2;

    for (int i = 0; i < ch.length-2; i++) {
        if(ch[i] == ',') {
            counter++;
        }
        if(counter == place && ch[i] != ',') {
            System.out.print(ch[i]);
        }
    }
}
</code>```

It prints everything after the second comma, but before the third one.

Body:
I have the below String variable

String s = "abc,xyz,lmn,ijk";

I want to extract only the portion of the String (i.e - 'lmn')

And, Should not use in-built functions like, SubString(), Split(), IndexOf(). But I can use charArray()

And this question was asked in my interview.

I tried the below code,
But not sure how to proceed. Can any one please provide your thoughts?

    String s = "abc,xyz,lmn,ijk";
    int counter = 0;

    char[] ch = s.toCharArray();
    for (int i = 0; i < ch.length; i++) {
        if (ch[i] == ',') {
            counter++;
        }

    }

Body:
Here's one way:

public static void main(String[] args) {
    String s = "abc,xyz,lmn,ijk";
    char[] ch = s.toCharArray();
    int counter = 0;
    int place = 2;

    for (int i = 0; i < ch.length-2; i++) {
        if(ch[i] == ',') {
            counter++;
        }
        if(counter == place && ch[i] != ',') {
            System.out.print(ch[i]);
        }
    }
}

It prints everything after the second comma, but before the third one.


问:
Curve fitting without toolbox
Without the curve fit toolbox how do you fit a function to data in MATLAB?

In particular, how do you fit a function that isn't a polynomial, e.g., if I want to fit a function like y = x^(1/3) + 5 where it is not an integer?

答:
If you know the form of the function you want to fit but do not know its parameters, you can use fminsearch to find the parameters that would fit your data. If you have data (possibly noisy) that you want to fit to y=x^a + bwhere aand bare unknown (here I will assume that the true values are a=1/3 and b=5) this is how I'd have a quick answer:

Here I generate my data (you would not have to do that in a real life case)

```<code>>> x = linspace(0,5,10);
>> y = x.^(1/3) + 5;
>> y_noisy = y + 0.1*rand(size(y));
</code>```

Then I define the function I want to minimize with respect to a and b and minimize it with fminsearch. In this case, I minimize the integral of the square of the difference between my data and the function used for the fit. Below I have defined two functions, one with the noisy data, and one without noise. You see that in the absence of noise you recover exactly the values of aand b.

NB: fminsearch wotks with a vector of parameters (v in my case). I took a=v(1)and b=v(2). You also have to provide some initial guess for v(here [1 1]).

```<code>>> err_noisy  = @(v) trapz(x,(y_noisy - x.^v(1)-v(2)).^2);
>> err = @(v) trapz(x,(y - x.^v(1)-v(2)).^2);
>> v_noisy = fminsearch(err_noisy,[1 1])

v_noisy =

    0.3345    5.0594

>> v = fminsearch(err,[1 1])

v =

    0.3333    5.0000
</code>```

Last comment, in cases where you have constraints on the values of aand bit is sometimes useful to perform some change of variable. For example if you know that a>0, you might want to identify log(a) and then convert the identified value to a.

Hope this helps.

A.

Title: Curve fitting without toolbox

Body:
If you know the form of the function you want to fit but do not know its parameters, you can use fminsearch to find the parameters that would fit your data. If you have data (possibly noisy) that you want to fit to y=x^a + bwhere aand bare unknown (here I will assume that the true values are a=1/3 and b=5) this is how I'd have a quick answer:

Here I generate my data (you would not have to do that in a real life case)

>> x = linspace(0,5,10);
>> y = x.^(1/3) + 5;
>> y_noisy = y + 0.1*rand(size(y));

Then I define the function I want to minimize with respect to a and b and minimize it with fminsearch. In this case, I minimize the integral of the square of the difference between my data and the function used for the fit. Below I have defined two functions, one with the noisy data, and one without noise. You see that in the absence of noise you recover exactly the values of aand b.

NB: fminsearch wotks with a vector of parameters (v in my case). I took a=v(1)and b=v(2). You also have to provide some initial guess for v(here [1 1]).

>> err_noisy  = @(v) trapz(x,(y_noisy - x.^v(1)-v(2)).^2);
>> err = @(v) trapz(x,(y - x.^v(1)-v(2)).^2);
>> v_noisy = fminsearch(err_noisy,[1 1])

v_noisy =

    0.3345    5.0594

>> v = fminsearch(err,[1 1])

v =

    0.3333    5.0000

Last comment, in cases where you have constraints on the values of aand bit is sometimes useful to perform some change of variable. For example if you know that a>0, you might want to identify log(a) and then convert the identified value to a.

Hope this helps.

A.


问:
How to stop selenium webdriver from waiting for page load?
Sometimes when i run a test, website never stops loading and my test stucks on it. How can i set driver.get() method to not wait for page load? If its impossible are there any work arounds or other methods that could replace driver.get()?</p>

答:
We can set pageLoadTimeout, once set it wil be there throught the webdriver session, and if the exception is thrown because of timeout then we can't restore same session so need to create new instance.</p>

```<code>        WebDriver driver = new FirefoxDriver();

        //waits 10 seconds for page to load
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        try {
            driver.get("https://yourdomain.com");
        } catch (TimeoutException e) {
            driver.close();
            driver.quit();

            //create new instance of webdriver
            driver = new FirefoxDriver();

            //waits 5 minutes for page to load
            driver.manage().timeouts().pageLoadTimeout(300, TimeUnit.SECONDS);
            driver.get("https://yourdomain.com");
        }
</code>```

Body:
We can set pageLoadTimeout, once set it wil be there throught the webdriver session, and if the exception is thrown because of timeout then we can't restore same session so need to create new instance.

        WebDriver driver = new FirefoxDriver();

        //waits 10 seconds for page to load
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        try {
            driver.get("https://yourdomain.com");
        } catch (TimeoutException e) {
            driver.close();
            driver.quit();

            //create new instance of webdriver
            driver = new FirefoxDriver();

            //waits 5 minutes for page to load
            driver.manage().timeouts().pageLoadTimeout(300, TimeUnit.SECONDS);
            driver.get("https://yourdomain.com");
        }


问:
Smarty template directories - map include paths to call templates in different folders
Is it possible to override the

```<code>{include file='fake/path/to/template.tpl'}
</code>```

to go to actually include a template in a different folder?

```<code>real/path/to/template.tpl
</code>```

I am asking this because we recently moved some parts of our code (plugins) into the vendor folder and we are trying to find an easy solution without changing every single smarty file. (there are hundreds of them)

PS. If we could avoid the use of symlinks it would be great!

答:
You could write a function that takes a string (fake url) and outputs a string (real url).

```<code>function getRealURL($tpl_filename) {
    $path = '../real/path/to/';
    if(file_exists($path.$ui_view)) {
        return $ui_view;
    }
    return $tpl_filename;
}
</code>```

I am using a similar function with other factors but this is the basics of it with some validation that the new file exists with the given path. It can also easily be used with whitelists of files in specific directories.

I believe you can call it like this.
    {include file='fake/path/to/template.tpl'|getRealURL}

Body:
Is it possible to override the

{include file='fake/path/to/template.tpl'}

to go to actually include a template in a different folder?

real/path/to/template.tpl

I am asking this because we recently moved some parts of our code (plugins) into the vendor folder and we are trying to find an easy solution without changing every single smarty file. (there are hundreds of them)

PS. If we could avoid the use of symlinks it would be great!

Body:
You could write a function that takes a string (fake url) and outputs a string (real url).

function getRealURL($tpl_filename) {
    $path = '../real/path/to/';
    if(file_exists($path.$ui_view)) {
        return $ui_view;
    }
    return $tpl_filename;
}

I am using a similar function with other factors but this is the basics of it with some validation that the new file exists with the given path. It can also easily be used with whitelists of files in specific directories.

I believe you can call it like this.
    {include file='fake/path/to/template.tpl'|getRealURL}


问:
Image in Dropdown Div (onclick) won't activate the dropdown
So we have a simple dropdown, but when you click the image, it doesn't activate the dropdown.

Since we've done this in Shopify there are a few code segments that make it difficult to write out. So I've just recreated in CodePen. As you can see in the example, clicking on the image does not activate the dropdown.

https://codepen.io/anon/pen/eRLbYw

HTML

```<code><div class="dropdownprod">
              <div onclick="dropDowntown()" class="dropbtn">
                <span class="dropdowncheese">Styles</span>PRODUCT TITLE<img class="dropimg2" src="https://upload.wikimedia.org/wikipedia/commons/e/e1/Small_rhombihexahedron.png" style="height:45px;"></div>
              <div id="myDropdown" class="dropdown-content">
               THE DROPDOWN CONTENT GOES HERE
              </div>
             </div>
</code>```

JS

```<code>/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function dropDowntown() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
</code>```

But if you click on the image, and inspect source, the code part is going purple. It's just not changing. Is there a reason for this?

答: Its because of your window.onclick function to close the dropdown.  When you click the image or span, dropDowntown() fires adding the class, then window.onclick() fires instantly removing it.  Add the span and image to your if statement so they do not trigger the closing script.

Body:
So we have a simple dropdown, but when you click the image, it doesn't activate the dropdown.

Since we've done this in Shopify there are a few code segments that make it difficult to write out. So I've just recreated in CodePen. As you can see in the example, clicking on the image does not activate the dropdown.

https://codepen.io/anon/pen/eRLbYw

HTML

                StylesPRODUCT TITLE

               THE DROPDOWN CONTENT GOES HERE

JS

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function dropDowntown() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

But if you click on the image, and inspect source, the code part is going purple. It's just not changing. Is there a reason for this?


问:
mtl, reader, exceptt & stacking order
So this is going to be a bit long, because I'm not sure how to frame this question more generally. The good news is that I have a code sample at the bottom of the question, the idea is just to make it build & elegant :-)

I have a couple of functions which have signatures like:

```<code>calledFunction
  :: (MonadReader env m, HasToken env, MonadIO m)
  => m (Either MyError MyResult)

calledFunction2
  :: (MonadReader env m, HasToken env, MonadIO m)
  => m (Either MyError MyResult2)
</code>```

And I'd like to get in the end a result of type ExceptT String IO MyResult3 which I get by combining MyResult & MyResult2.

Now it's very nice that calledFunction returns an Either because I can leverage:

```<code>ExceptT :: m (Either e a) -> ExceptT e m a
</code>```

And I just type EitherT calledFunction and I won't have anymore m (Either MyError MyResult) but straight ExceptT MyError m MyResult). Progress!

But I also need to give to calledFunction the reader context it wants. Now, I would do that with runReaderT. I have now come to the ExceptT MyError m MyResult transformer stack, so naturally the ReaderT should go where the m is.. So ExceptT MyError (ReaderT Config IO) MyResult...

Except, how do I 'fill in' the readerT with the value to read, since it's at the bottom of the transformer stack? And if I reverse the stack to have the reader at the toplevel, then runReaderT comes naturally, but I don't see how to use EitherT to transform my Either in an ExceptT elegantly...

```<code>import Control.Monad.Reader
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Except
import Control.Monad.IO.Class
import Control.Error -- 'error' package

class HasToken a where
    getToken :: a -> String
data Config = Config String
instance HasToken Config where
    getToken (Config x) = x

data MyError = MyError String deriving Show
data MyResult = MyResult String
data MyResult2 = MyResult2 String

data MyResult3 = MyResult3 MyResult MyResult2

calledFunction
  :: (MonadReader env m, HasToken env, MonadIO m)
  => m (Either MyError MyResult)
calledFunction = undefined

calledFunction2
  :: (MonadReader env m, HasToken env, MonadIO m)
  => m (Either MyError MyResult2)
calledFunction2 = undefined

cfg = Config "test"

main = undefined

test :: ExceptT MyError IO MyResult3
test = do
    -- calling runReaderT each time defeats the purpose..
    r1 <- ExceptT (runReaderT calledFunction cfg)
    r2 <- ExceptT (runReaderT calledFunction2 cfg)
    return $ MyResult3 r1 r2

test1 = runReaderT test2 cfg

test2 :: ReaderT Config (ExceptT MyError IO) MyResult3
test2 = do
    -- how to make this compile?
    let cfg = Config "test"
    r1 <- ExceptT calledFunction
    r2 <- ExceptT calledFunction2
    return $ MyResult3 r1 r2
</code>```

答:
You can use hoist from Control.Monad.Morph to run the Reader below the ExceptT:

```<code>ghci> let foo = undefined :: ExceptT () (ReaderT () IO) ()
ghci> :t hoist (flip runReaderT ()) foo
hoist (flip runReaderT ()) foo :: ExceptT () IO ()
</code>```

It's also easy to do it yourself, you just have to unwrap with runExceptT, supply the environment with runReader, and re-wrap the result in the ExceptT constructor:

```<code>ghci> :t \env -> ExceptT . flip runReaderT env . runExceptT
\env -> ExceptT . flip runReaderT env . runExceptT
    :: r -> ExceptT e (ReaderT r m) a -> ExceptT e m a
</code>```

Title: mtl, reader, exceptt & stacking order

Body:
So this is going to be a bit long, because I'm not sure how to frame this question more generally. The good news is that I have a code sample at the bottom of the question, the idea is just to make it build & elegant :-)

I have a couple of functions which have signatures like:

calledFunction
  :: (MonadReader env m, HasToken env, MonadIO m)
  => m (Either MyError MyResult)

calledFunction2
  :: (MonadReader env m, HasToken env, MonadIO m)
  => m (Either MyError MyResult2)

And I'd like to get in the end a result of type ExceptT String IO MyResult3 which I get by combining MyResult & MyResult2.

Now it's very nice that calledFunction returns an Either because I can leverage:

ExceptT :: m (Either e a) -> ExceptT e m a

And I just type EitherT calledFunction and I won't have anymore m (Either MyError MyResult) but straight ExceptT MyError m MyResult). Progress!

But I also need to give to calledFunction the reader context it wants. Now, I would do that with runReaderT. I have now come to the ExceptT MyError m MyResult transformer stack, so naturally the ReaderT should go where the m is.. So ExceptT MyError (ReaderT Config IO) MyResult...

Except, how do I 'fill in' the readerT with the value to read, since it's at the bottom of the transformer stack? And if I reverse the stack to have the reader at the toplevel, then runReaderT comes naturally, but I don't see how to use EitherT to transform my Either in an ExceptT elegantly...

import Control.Monad.Reader
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Except
import Control.Monad.IO.Class
import Control.Error -- 'error' package

class HasToken a where
    getToken :: a -> String
data Config = Config String
instance HasToken Config where
    getToken (Config x) = x

data MyError = MyError String deriving Show
data MyResult = MyResult String
data MyResult2 = MyResult2 String

data MyResult3 = MyResult3 MyResult MyResult2

calledFunction
  :: (MonadReader env m, HasToken env, MonadIO m)
  => m (Either MyError MyResult)
calledFunction = undefined

calledFunction2
  :: (MonadReader env m, HasToken env, MonadIO m)
  => m (Either MyError MyResult2)
calledFunction2 = undefined

cfg = Config "test"

main = undefined

test :: ExceptT MyError IO MyResult3
test = do
    -- calling runReaderT each time defeats the purpose..
    r1 <- ExceptT (runReaderT calledFunction cfg)
    r2 <- ExceptT (runReaderT calledFunction2 cfg)
    return $ MyResult3 r1 r2

test1 = runReaderT test2 cfg

test2 :: ReaderT Config (ExceptT MyError IO) MyResult3
test2 = do
    -- how to make this compile?
    let cfg = Config "test"
    r1 <- ExceptT calledFunction
    r2 <- ExceptT calledFunction2
    return $ MyResult3 r1 r2

Body:
You can use hoist from Control.Monad.Morph to run the Reader below the ExceptT:

ghci> let foo = undefined :: ExceptT () (ReaderT () IO) ()
ghci> :t hoist (flip runReaderT ()) foo
hoist (flip runReaderT ()) foo :: ExceptT () IO ()

It's also easy to do it yourself, you just have to unwrap with runExceptT, supply the environment with runReader, and re-wrap the result in the ExceptT constructor:

ghci> :t \env -> ExceptT . flip runReaderT env . runExceptT
\env -> ExceptT . flip runReaderT env . runExceptT
    :: r -> ExceptT e (ReaderT r m) a -> ExceptT e m a