问:
How to reference *.d.ts in vscode globally
To enable intellisense in vscode for frameworks such as jasmine, we need to reference the typing file explicitly at the top of every typescript file like below:

```<code>/// <reference path="./node_modules/@types/jasmine/index.d.ts" />
</code>```

Is there a way to globally reference all the typing files in vscode so we don't need to reference them in each typescript file?

答:
If you have a tsconfig.json, typings from node_modules/@types should be picked up automatically. You can make sure you TS file is part of your tsconfig.json by running the TypeScript: Go to Project Configuration command in VSCode

If you have a tsconfig.json but still are not seeing the jasmine typings, try updating your tsconfig.json to explicitly include the jasmine types:

```<code>{
    "compilerOptions": {
        ...
    },
    "typeAcquisition": {
        "include": [
            "jasmine"
        ]
    }
}
</code>```

If that still isn't working, please file a bug

Body:
To enable intellisense in vscode for frameworks such as jasmine, we need to reference the typing file explicitly at the top of every typescript file like below:

/// <reference path="./node_modules/@types/jasmine/index.d.ts" />

Is there a way to globally reference all the typing files in vscode so we don't need to reference them in each typescript file?

Body:
If you have a tsconfig.json, typings from node_modules/@types should be picked up automatically. You can make sure you TS file is part of your tsconfig.json by running the TypeScript: Go to Project Configuration command in VSCode

If you have a tsconfig.json but still are not seeing the jasmine typings, try updating your tsconfig.json to explicitly include the jasmine types:

{
    "compilerOptions": {
        ...
    },
    "typeAcquisition": {
        "include": [
            "jasmine"
        ]
    }
}

If that still isn't working, please file a bug


来源: stackexchange

问:
Simple Form: creating a new record from another controller
I have a Home controller with an index view that acts like a search box that lets the user query a First Table or Second Table through a select box. After a user enters a search term, he will be redirected to the index page of the First or Second model with the search results for that model.

A Search record must be created each time a query is submitted with the search type and search term. However, I don't know how to create a new Search object using simple_form from a different controller, which is the Home controller in this case.

Home Controller

```<code>def index
  @find = Find.new
</code>```

Home Index View

```<code>= simple_form_for @find, url: finds_path, method: :post do |f|
  = f.input :search_type, :collection => [['First', 'First'], ['Second', 'Second']]
  = f.input :search_term
  = f.button :submit
</code>```

Finds Controller

```<code>def new
  @find = Find.new
end

def create
  @find = Find.new(find_params)
  if params[:search_type] == 'First'
    redirect_to first_path
  elsif params[:search_type] == 'Second'
    redirect_to second_path
  else
    redirect_to root_path
  end
end

private

def find_params
  params.permit(:search_term, :search_type, :utf8, :authenticity_token,
    :find, :commit, :locale)
  # the params seem to come from the Home controller so I added them just to see if they will go through :(
end
</code>```

It doesn't save. Instead it gives:

```<code>Started POST "/en/finds"
Processing by FindsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"..", "find"=>{"search_type"=>"First", "search_term"=>"Something"}, "commit"=>"Create Find", "locale"=>"en"}
Unpermitted parameter: :find
Redirected to http://localhost:3000/en
</code>```

答:
You need to save, you are just initializing the attributes..

```<code>@find = Find.new(find_params)
@find.save!
</code>```

OR

```<code>@find = Find.create!(find_params)
</code>```

Also, strong parameters should be

```<code>def find_params
  params.require(:find).permit(:search_term, :search_type)
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a Home controller with an index view that acts like a search box that lets the user query a First Table or Second Table through a select box. After a user enters a search term, he will be redirected to the index page of the First or Second model with the search results for that model.

A Search record must be created each time a query is submitted with the search type and search term. However, I don't know how to create a new Search object using simple_form from a different controller, which is the Home controller in this case.

Home Controller

def index
  @find = Find.new

Home Index View

= simple_form_for @find, url: finds_path, method: :post do |f|
  = f.input :search_type, :collection => [['First', 'First'], ['Second', 'Second']]
  = f.input :search_term
  = f.button :submit

Finds Controller

def new
  @find = Find.new
end

def create
  @find = Find.new(find_params)
  if params[:search_type] == 'First'
    redirect_to first_path
  elsif params[:search_type] == 'Second'
    redirect_to second_path
  else
    redirect_to root_path
  end
end

private

def find_params
  params.permit(:search_term, :search_type, :utf8, :authenticity_token,
    :find, :commit, :locale)
  # the params seem to come from the Home controller so I added them just to see if they will go through :(
end

It doesn't save. Instead it gives:

Started POST "/en/finds"
Processing by FindsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"..", "find"=>{"search_type"=>"First", "search_term"=>"Something"}, "commit"=>"Create Find", "locale"=>"en"}
Unpermitted parameter: :find
Redirected to http://localhost:3000/en

Body:
You need to save, you are just initializing the attributes..

@find = Find.new(find_params)
@find.save!

OR

@find = Find.create!(find_params)

Also, strong parameters should be

def find_params
  params.require(:find).permit(:search_term, :search_type)
end


问:
Flatpickr - Date changes automatically to american version instead of UK Format.
I am using flat pickr and the date that gets given to the input would be as such:

01/02/1991 (Day 1 / Month Feb / Year 1991.

However when I add the class flatpickr it converts the date to:

02/01/1991

The american version of the date.

I thought that I could fix this easily by doing the below code:

```<code>init() {
    let flatPicker = document.querySelector('.flatpickr')

    if (flatPicker) {
        flatPickr.l10ns.default.weekdays.shorthand = ['S', 'M', 'T', 'W', 'T', 'F', 'S']

        new flatPickr(flatPicker,
            {
                nextArrow: '<svg class="icon icon-arrow-right"><use xlink:href="/dist/assets/svg-definition/symbol-defs.svg#icon-arrow-right"></use></svg>',
                prevArrow: '<svg class="icon icon-arrow-left"><use xlink:href="/dist/assets/svg-definition/symbol-defs.svg#icon-arrow-left"></use></svg>',

                // Date format
                altInput: true,
                altFormat: 'd-m-Y',

                // Default Date
                dateFormat: 'd-m-Y'
            }
        );
    }
}
</code>```

The important bit I thought would be the dateFormat: 'd-m-Y'.

Can anyone else spot what I am doing wrong here?

Many thanks

答:
You need a custom date parser. Because d.m.y is not standard date format.
Before flatpickr() add this code below and it needs moment.js

```<code>Flatpickr.defaultConfig.parseDate = function(str) {
    return moment.utc(str, "DD.MM.YYYY").toDate();
}
</code>```

Body:
I am using flat pickr and the date that gets given to the input would be as such:

01/02/1991 (Day 1 / Month Feb / Year 1991.

However when I add the class flatpickr it converts the date to:

02/01/1991

The american version of the date.

I thought that I could fix this easily by doing the below code:

init() {
    let flatPicker = document.querySelector('.flatpickr')

    if (flatPicker) {
        flatPickr.l10ns.default.weekdays.shorthand = ['S', 'M', 'T', 'W', 'T', 'F', 'S']

        new flatPickr(flatPicker,
            {
                nextArrow: '<svg class="icon icon-arrow-right"><use xlink:href="/dist/assets/svg-definition/symbol-defs.svg#icon-arrow-right"></use></svg>',
                prevArrow: '<svg class="icon icon-arrow-left"><use xlink:href="/dist/assets/svg-definition/symbol-defs.svg#icon-arrow-left"></use></svg>',

                // Date format
                altInput: true,
                altFormat: 'd-m-Y',

                // Default Date
                dateFormat: 'd-m-Y'
            }
        );
    }
}

The important bit I thought would be the dateFormat: 'd-m-Y'.

Can anyone else spot what I am doing wrong here?

Many thanks

Body:
You need a custom date parser. Because d.m.y is not standard date format.
Before flatpickr() add this code below and it needs moment.js

Flatpickr.defaultConfig.parseDate = function(str) {
    return moment.utc(str, "DD.MM.YYYY").toDate();
}


问:
Clarification of Scala function
I am trying to execute this function

```<code>def sumofdouble[T <:Number] (as:T*): Double = as.foldLeft(0d)(_ + _.doubleValue)
</code>```

If I try using this function like this,

```<code>sumofdouble(1,2)
</code>```

I am getting this error

```<code><console>:13: error: inferred type arguments [Int] do not conform to method sumofdouble's type parameter bounds [T <: Number]
sumofdouble(1,2)
</code>```

Isn't Integer a subtype of Number? Please explain if I am missing something.

答:
Looks like you are using java.lang.Number. Unfortunatelly, numeric types in scala do not inherit from this class (for reference look at Int definition - like other scala's numerics it inherits directly from AnyVal - http://www.scala-lang.org/api/2.12.0/scala/Int.html) - it is simply not in their hierarchy. What you want to use is the implicit Numeric type class to convert your numbers.

def foo[T](as: T*)(implicit n: Numeric[T]) = as.foldLeft(0d)(_ + n.toDouble(_))

See this question for further information - Scala equivalent of Java's Number.

Title: Clarification of Scala function

Body:
I am trying to execute this function

def sumofdouble[T <:Number] (as:T*): Double = as.foldLeft(0d)(_ + _.doubleValue)

If I try using this function like this,

sumofdouble(1,2)

I am getting this error

<console>:13: error: inferred type arguments [Int] do not conform to method sumofdouble's type parameter bounds [T <: Number]
sumofdouble(1,2)

Isn't Integer a subtype of Number? Please explain if I am missing something.


问:
RecyclerView ItemTouchHelper Buttons on Swipe
I am trying to port some iOS functionality to Android.

I intent to create a table where on swipe to the left shows 2 button: Edit and Delete.

I have been playing with it and I know I am very close. The secret really lies on the method OnChildDraw.

I would like to Draw a Rect that fits the text Delete then draw the Edit text besides it with their respective background color. The remaining white space when clicked should restore the row to its initial position.

I have managed to paint the background while the user is swiping to the sides but I don't know how to add the listeners and once it is swiped to the side, the dragging function begins to misbehave.

I am working on Xamarin but pure java solutions also are accepted as I can easily port them to c#.

```<code>    public class SavedPlacesItemTouchHelper : ItemTouchHelper.SimpleCallback
    {
        private SavedPlacesRecyclerviewAdapter adapter;
        private Paint paint = new Paint();
        private Context context;

        public SavedPlacesItemTouchHelper(Context context, SavedPlacesRecyclerviewAdapter adapter) : base(ItemTouchHelper.ActionStateIdle, ItemTouchHelper.Left)
        {
            this.context = context;
            this.adapter = adapter;
        }

        public override bool OnMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target)
        {
            return false;
        }

        public override void OnSwiped(RecyclerView.ViewHolder viewHolder, int direction)
        {
        }

        public override void OnChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
        {
            float translationX = dX;
            View itemView = viewHolder.ItemView;
            float height = (float)itemView.Bottom - (float)itemView.Top;

            if (actionState == ItemTouchHelper.ActionStateSwipe && dX <= 0) // Swiping Left
            {
                 translationX = -Math.Min(-dX, height * 2);
                paint.Color = Color.Red;
                RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
                c.DrawRect(background, paint);

                //viewHolder.ItemView.TranslationX = translationX;
            }
            else if (actionState == ItemTouchHelper.ActionStateSwipe && dX > 0) // Swiping Right
            {
                translationX = Math.Min(dX, height * 2);
                paint.Color = Color.Red;
                RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
                c.DrawRect(background, paint);
            }

            base.OnChildDraw(c, recyclerView, viewHolder, translationX, dY, actionState, isCurrentlyActive);
        }
    }
}
</code>```

This is what I currently have.

If you know how to add listeners or any suggestions please leave a comment!

UPDATE:

I just realized that on double tap on the white remaining space of the row already restore the row to its initial state. Not a single tap though :(

答:
If you use a RecyclerView, try to use OnScrollListener. Do something like this.

```<code> private class YourOnScrollListener extends RecyclerView.OnScrollListener {

    private boolean directionLeft;

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            if (directionLeft) drawButtons();
            //Draw buttons here if you want them to be drawn after scroll is finished
            //here you can play with states, to draw buttons or erase it whenever you want
        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        if (dx < 0) directionLeft = true;
        else directionLeft = false;
    }

}
</code>```

Body:
I am trying to port some iOS functionality to Android.

I intent to create a table where on swipe to the left shows 2 button: Edit and Delete.

I have been playing with it and I know I am very close. The secret really lies on the method OnChildDraw.

I would like to Draw a Rect that fits the text Delete then draw the Edit text besides it with their respective background color. The remaining white space when clicked should restore the row to its initial position.

I have managed to paint the background while the user is swiping to the sides but I don't know how to add the listeners and once it is swiped to the side, the dragging function begins to misbehave.

I am working on Xamarin but pure java solutions also are accepted as I can easily port them to c#.

    public class SavedPlacesItemTouchHelper : ItemTouchHelper.SimpleCallback
    {
        private SavedPlacesRecyclerviewAdapter adapter;
        private Paint paint = new Paint();
        private Context context;

        public SavedPlacesItemTouchHelper(Context context, SavedPlacesRecyclerviewAdapter adapter) : base(ItemTouchHelper.ActionStateIdle, ItemTouchHelper.Left)
        {
            this.context = context;
            this.adapter = adapter;
        }

        public override bool OnMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target)
        {
            return false;
        }

        public override void OnSwiped(RecyclerView.ViewHolder viewHolder, int direction)
        {
        }

        public override void OnChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
        {
            float translationX = dX;
            View itemView = viewHolder.ItemView;
            float height = (float)itemView.Bottom - (float)itemView.Top;

            if (actionState == ItemTouchHelper.ActionStateSwipe && dX <= 0) // Swiping Left
            {
                 translationX = -Math.Min(-dX, height * 2);
                paint.Color = Color.Red;
                RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
                c.DrawRect(background, paint);

                //viewHolder.ItemView.TranslationX = translationX;
            }
            else if (actionState == ItemTouchHelper.ActionStateSwipe && dX > 0) // Swiping Right
            {
                translationX = Math.Min(dX, height * 2);
                paint.Color = Color.Red;
                RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
                c.DrawRect(background, paint);
            }

            base.OnChildDraw(c, recyclerView, viewHolder, translationX, dY, actionState, isCurrentlyActive);
        }
    }
}

This is what I currently have.

If you know how to add listeners or any suggestions please leave a comment!

UPDATE:

I just realized that on double tap on the white remaining space of the row already restore the row to its initial state. Not a single tap though :(

Body:
If you use a RecyclerView, try to use OnScrollListener. Do something like this.

 private class YourOnScrollListener extends RecyclerView.OnScrollListener {

    private boolean directionLeft;

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            if (directionLeft) drawButtons();
            //Draw buttons here if you want them to be drawn after scroll is finished
            //here you can play with states, to draw buttons or erase it whenever you want
        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        if (dx < 0) directionLeft = true;
        else directionLeft = false;
    }

}


问:
Deleting a record from table in MS ACCESS 2010
I am trying to delete records from the subreport that created with multiple tables data.
Below is the code I write for this

```<code>CurrentDb.Execute "DELETE FROM StateBudget " & " WHERE S_ID=" & ("SLELECT ID FROM States " & " WHERE State=" & Me.subformStateBudget.Form.Recordset.Fields("State"))
</code>```

And error appear like this

syntax error (missing operator) in query expression 'S_ID=SELECT ID
  FROM States WHERE State=????'.

答:
Check this out

```<code>  CurrentDb.Execute "DELETE FROM StateBudget WHERE S_ID IN (SELECT ID FROM States WHERE State=" & Me.subformStateBudget.Form.Recordset.Fields("State") & ")"
</code>```

And by the way You have got misspelling in select, You add that string wrongly. That Bracket before Select should be inside the string and many more.

Body:
I am trying to delete records from the subreport that created with multiple tables data.
Below is the code I write for this

CurrentDb.Execute "DELETE FROM StateBudget " & " WHERE S_ID=" & ("SLELECT ID FROM States " & " WHERE State=" & Me.subformStateBudget.Form.Recordset.Fields("State"))

And error appear like this

syntax error (missing operator) in query expression 'S_ID=SELECT ID
  FROM States WHERE State=????'.

Body:
Check this out

  CurrentDb.Execute "DELETE FROM StateBudget WHERE S_ID IN (SELECT ID FROM States WHERE State=" & Me.subformStateBudget.Form.Recordset.Fields("State") & ")"

And by the way You have got misspelling in select, You add that string wrongly. That Bracket before Select should be inside the string and many more.


问:
How to add more feature to a official postgres image from docker hub?
If use the official postgres image:

https://hub.docker.com/_/postgres/

is a simple way to use PostgreSQL database.

But if I need to use some PostgreSQL extention such as pgroonga:

https://pgroonga.github.io

How to add this to that official PostgreSQL image?

Run that image as a container, then sign in to it add extention, finally make a new image? Is it possible?

If there exists a official pgroonga image will be good, but there isn't now:

https://hub.docker.com/u/groonga/

The last way, make a image for groonga, the links to postgres container when run the full stack.

Which way is good to such a case when using container to deploy mordern web application?

答:
You should have a look (let us suppose you will use Debian) at

https://pgroonga.github.io/install/debian.html

So you have some commands to launch, so more or less such a Dockerfile should do the trick

FROM postgres
RUN apt udate -y && apt install -y -V apt-transport-https \
&& echo "deb https://packages.groonga.org/debian/ jessie main" >> /etc/apt/sources.list.d/groonga.list \
&& echo "deb-src https://packages.groonga.org/debian/ jessie main" >> /etc/apt/sources.list.d/groonga.list \
&&...

I guess you see the method

Remember that in a Dockerfile, you can't answer "Yes" or "no" to any command, so you must automate all the commands.
If you can't automate all, you can do some part,  get an image, launch it with a bash prompt (or sh or zsh...), do interactively the needed commands hard to automate, and then you

docker commit

see the doc

https://docs.docker.com/engine/reference/commandline/commit/

also, in a Dockerfile, by default, you are root, so no need to sudo unless you use  the Dockerfile directive

USER myuser


问:
adding and deleting form rows with javascript
I created a form where add button adds another row with name, email and age in the form and delete deletes it.  However, jquery code does not work as intended. I am a beginner in jquery to figure out what mistake I have made. I looked through similar questions in Stackoverflow but could'nt figure it out.

$(document).ready(function(){
     var max_fields= 10;
     var wrapper  = $("#commentForm");
     var add_button = $("#addButton");
     var delete_button = $('#deleteButton')

     var x=1;
     add_button.click(function(e){
      e.preventDefault();

      if (x < max_fields){
       x++;
       $(wrapper).append('<input id="bname" name="name" minlength="2" type="text" required/>', '<input id="bemail" name="email" type="email" required/', '<input id="bage" name="age" type="number" required/>' )
      }

     });
      $(wrapper).on("click","#deleteButton", function(e){

       e.preventDefault();$(this).parent('p').remove();
       x--;

      })

     });
      ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
    <section class="container">
     <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
     <fieldset>
      <input type="checkbox"/>

      <p>
       <span> Name </span> <br>
       <label for="aname" ></label>
       <input id="bname" name="name" minlength="2" type="text" required/>
      </p>
      <p>
       <span> Email </span> <br>
       <label for="aemail" ></label>
       <input id="bemail" name="email" type="email" required/>
      </p>
      <p>
       <span> Age </span> <br>
       <label for="aage" ></label>
       <input id="bage" name="age" type="number" required/>
      </p>

      <div class="input_fields_wrap">

       <div class="addButton">
        <button  type="button" value="add">Add</button>
       </div>

       <div class="deleteButton">
        <button type="button" value="delete">Delete</button>
       </div>
      </div>

     </fieldset>
     </form>

     </section>

    </body></code>```

Thank you.

答:
You have very minor mistake in your code.

Your Code:

```<code>var wrapper  = $("#commentForm");
var add_button = $("#addButton");
var delete_button = $('#deleteButton')
</code>```

It Should be like this

```<code>var wrapper  = $("#commentForm");
var add_button = $(".addButton");
/* '#' is used to refer ID, '.' is used for classes*/
var delete_button = $('.deleteButton')
</code>```

Body:
I created a form where add button adds another row with name, email and age in the form and delete deletes it.  However, jquery code does not work as intended. I am a beginner in jquery to figure out what mistake I have made. I looked through similar questions in Stackoverflow but could'nt figure it out.

$(document).ready(function(){
     var max_fields= 10;
     var wrapper  = $("#commentForm");
     var add_button = $("#addButton");
     var delete_button = $('#deleteButton')

     var x=1;
     add_button.click(function(e){
      e.preventDefault();

      if (x < max_fields){
       x++;
       $(wrapper).append('<input id="bname" name="name" minlength="2" type="text" required/>', '<input id="bemail" name="email" type="email" required/', '<input id="bage" name="age" type="number" required/>' )
      }

     });
      $(wrapper).on("click","#deleteButton", function(e){

       e.preventDefault();$(this).parent('p').remove();
       x--;

      })

     });

     <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
     <fieldset>
      <input type="checkbox"/>

        Name

       <input id="bname" name="name" minlength="2" type="text" required/>

        Email

       <input id="bemail" name="email" type="email" required/>

        Age

       <input id="bage" name="age" type="number" required/>

        <button  type="button" value="add">Add</button>

        <button type="button" value="delete">Delete</button>

     </fieldset>
     </form>

Thank you.

Body:
You have very minor mistake in your code.

Your Code:

var wrapper  = $("#commentForm");
var add_button = $("#addButton");
var delete_button = $('#deleteButton')

It Should be like this

var wrapper  = $("#commentForm");
var add_button = $(".addButton");
/* '#' is used to refer ID, '.' is used for classes*/
var delete_button = $('.deleteButton')


问:
Problem with deploying rails app to heroku while running "heroku create" command
Has anyone seen this problem before?
When I try to run the command "heroku create", I get long error with directories related to ruby.

C:\Rails\Waterloop3>heroku create

Creating severe-samurai-489.... done

Created http://severe-samurai-489.heroku.com/ | git@heroku.com:severe-samurai-48
9.git

C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/helpers.rb:78:in ``': No such file or directory - git remote (Errno::ENOENT)

```<code>    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/helpe
</code>```

rs.rb:78:in `block in shell'

```<code>    from C:/Ruby192/lib/ruby/1.9.1/fileutils.rb:121:in `chdir'

    from C:/Ruby192/lib/ruby/1.9.1/fileutils.rb:121:in `cd'

    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/helpe
</code>```

rs.rb:78:in `shell'

```<code>    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/comma
</code>```

nds/app.rb:265:in `create_git_remote'

```<code>    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/comma
</code>```

nds/app.rb:49:in `create'

```<code>    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/comma
</code>```

nd.rb:48:in `run_internal'

```<code>    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/comma
</code>```

nd.rb:20:in `run'

```<code>    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/bin/heroku:13:in
</code>```

`'

```<code>    from C:/Ruby192/bin/heroku:19:in `load'

    from C:/Ruby192/bin/heroku:19:in `<main>'
</code>```

答:
This line:

```<code>C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/helpers.rb:78:in ``': No such file or directory - git remote (Errno::ENOENT)
</code>```

Says that the heroku gem is try to run git and can't find it. Do you have git installed and running from the command line? It is a requirement, since it is what Heroku uses to manage deployments.

ContentLicense: CC BY-SA 2.5

Body:
Has anyone seen this problem before?
When I try to run the command "heroku create", I get long error with directories related to ruby.

C:\Rails\Waterloop3>heroku create

Creating severe-samurai-489.... done

Created http://severe-samurai-489.heroku.com/ | git@heroku.com:severe-samurai-48
9.git

C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/helpers.rb:78:in ``': No such file or directory - git remote (Errno::ENOENT)

    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/helpe

rs.rb:78:in `block in shell'

    from C:/Ruby192/lib/ruby/1.9.1/fileutils.rb:121:in `chdir'

    from C:/Ruby192/lib/ruby/1.9.1/fileutils.rb:121:in `cd'

    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/helpe

rs.rb:78:in `shell'

    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/comma

nds/app.rb:265:in `create_git_remote'

    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/comma

nds/app.rb:49:in `create'

    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/comma

nd.rb:48:in `run_internal'

    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/comma

nd.rb:20:in `run'

    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/bin/heroku:13:in

`'

    from C:/Ruby192/bin/heroku:19:in `load'

    from C:/Ruby192/bin/heroku:19:in `'

Body:
This line:

C:/Ruby192/lib/ruby/gems/1.9.1/gems/heroku-1.14.10/lib/heroku/helpers.rb:78:in ``': No such file or directory - git remote (Errno::ENOENT)

Says that the heroku gem is try to run git and can't find it. Do you have git installed and running from the command line? It is a requirement, since it is what Heroku uses to manage deployments.


问:
After getting the search value by Ajax, redirect to result another View
The parameter, search, comes from Index view by Ajax post. After the search process I want to send the employees object to Result view. Result action and view are in the same controller and same view folder. But RedirectToAction(employees) doesn't affect. There is no problem about getting search value from view by Ajax or about getting corresponding employees from database, all of them are fine. This post says you cannot redirect from Ajax post. I don't know how can I redirect & send the employees object to Result view. I don't want to make this via ViewBag.

```<code>[HttpPost]
public async Task<IActionResult> Result([FromBody]string search)
{
    if (string.IsNullOrEmpty(search))
    {
        return NotFound();
    }

    IEnumerable<Employee> employees = await _context.Employees.Where(e => e.Surname == search).ToListAsync();
    return RedirectToAction("Index", employees);
}
</code>```

```<code>$(document).ready(function () {
    $('.SearchButton').on('click', function (e) {
        e.preventDefault();
        var searchVal = $('.Search').val();
        console.log(searchVal);
        $.ajax(
        {
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: '@Url.Action("Index", "Employee")',
            data: JSON.stringify(searchVal),
            dataType: 'json',
            success: function (response) {
                console.log(response);
            },
            error: function (response) {
                console.log(response.message);
            }
        });
    });
});
</code>```

答:
I created a Result view instead of trying to redirect to Index view, removed the HttpPost and FromBody attribute from Result action, changed the "return RedirectToAction("Index", employees)" to "return View(employee)"

```<code>public async Task<IActionResult> Result(string search)
{
    if (string.IsNullOrEmpty(search))
    {
        return NotFound();
    }

    IEnumerable<Employee> employees = await _context.Employees.Where(e => e.Surname == search).ToListAsync();
    return View(employees);
}
</code>```

```<code><input type="text" class="Search" placeholder="Search by surname" /><a class="SearchButton">Search</a>
</code>```

Then delete the whole jQuery code and replace with this lines of code:

```<code>$(document).ready(function () {
    $('.SearchButton').on('click', function (e) {
        window.location.href = '@Url.Action("Result")' + '/?search=' + $('.Search').val();
    });
});
</code>```

Body:
The parameter, search, comes from Index view by Ajax post. After the search process I want to send the employees object to Result view. Result action and view are in the same controller and same view folder. But RedirectToAction(employees) doesn't affect. There is no problem about getting search value from view by Ajax or about getting corresponding employees from database, all of them are fine. This post says you cannot redirect from Ajax post. I don't know how can I redirect & send the employees object to Result view. I don't want to make this via ViewBag.

[HttpPost]
public async Task<IActionResult> Result([FromBody]string search)
{
    if (string.IsNullOrEmpty(search))
    {
        return NotFound();
    }

    IEnumerable<Employee> employees = await _context.Employees.Where(e => e.Surname == search).ToListAsync();
    return RedirectToAction("Index", employees);
}

$(document).ready(function () {
    $('.SearchButton').on('click', function (e) {
        e.preventDefault();
        var searchVal = $('.Search').val();
        console.log(searchVal);
        $.ajax(
        {
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: '@Url.Action("Index", "Employee")',
            data: JSON.stringify(searchVal),
            dataType: 'json',
            success: function (response) {
                console.log(response);
            },
            error: function (response) {
                console.log(response.message);
            }
        });
    });
});

Body:
I created a Result view instead of trying to redirect to Index view, removed the HttpPost and FromBody attribute from Result action, changed the "return RedirectToAction("Index", employees)" to "return View(employee)"

public async Task<IActionResult> Result(string search)
{
    if (string.IsNullOrEmpty(search))
    {
        return NotFound();
    }

    IEnumerable<Employee> employees = await _context.Employees.Where(e => e.Surname == search).ToListAsync();
    return View(employees);
}

<input type="text" class="Search" placeholder="Search by surname" /><a class="SearchButton">Search</a>

Then delete the whole jQuery code and replace with this lines of code:

$(document).ready(function () {
    $('.SearchButton').on('click', function (e) {
        window.location.href = '@Url.Action("Result")' + '/?search=' + $('.Search').val();
    });
});


问:
how to control state of checkbox of child view in ExpandableListview android
In my ExpandableListview, I am using Imageview and Checkbox that resembles the shape image and name,

When I tick the checkbox of particular child item , the other child item also gets ticked , after scrolling the checked state changes ,

I needed multiple values to be selected.

Please help me to get this solved , I am in very need of this . Googled but not found working in my case

Thanks in advance.

```<code>public View getChildView(int groupPosition, final int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {

_childText = (String) getChild(groupPosition, childPosition);

int itemType = getChildType(groupPosition,childPosition);

Log.e("childPosition", "karjeevch "+childPosition);

ViewHolder viewHolder = null;
switch (itemType) {

case 0:
    viewHolder = null;
    if (convertView==null) {
        viewHolder=new ViewHolder();
        convertView = infalInflater.inflate(R.layout.list_child_shape, null);
        viewHolder.shape_name = (CheckBox) convertView.findViewById(R.id.shape_chk_box);
        viewHolder.img_shape_icon=(ImageView)convertView.findViewById(R.id.img_shape);

        imageLoader.DisplayImage("http://rosycontact.com/shashvat/images/"+_childText+".png", viewHolder.img_shape_icon);
        viewHolder.shape_name.setText(_childText);
        convertView.setTag(viewHolder);

        final CheckBox shape_name_temp=viewHolder.shape_name;
        viewHolder.shape_name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (shape_name_temp.isChecked()==true) {
                    All_link.SHAPE=shape_name_temp.getText().toString();
                }
            }
        });

        //new PerformBackgroungTask().execute();
    }
    else{
        viewHolder=(ViewHolder)convertView.getTag();
    }
    return convertView;
    //break;

case 1:

    viewHolder = null;
    if (convertView==null) {
        viewHolder=new ViewHolder();
        convertView = infalInflater.inflate(R.layout.list_child_carat, null);
        viewHolder.carat_from = (TextView) convertView.findViewById(R.id.ed_carat_from);
        viewHolder.carat_to = (TextView) convertView.findViewById(R.id.ed_carat_to);

        viewHolder.carat_from.setText("jdsv");
        viewHolder.carat_to.setText("jdsv");

        All_link.CARAT_FROM=viewHolder.carat_from.getText().toString();
        All_link.CARAT_TO=viewHolder.carat_to.getText().toString();

    }
    else{
        viewHolder=(ViewHolder)convertView.getTag();
    }
    return convertView;

case 2:

    viewHolder = null;
    if (convertView==null) {
        viewHolder=new ViewHolder();

        convertView = infalInflater.inflate(R.layout.list_child_color, null);
        viewHolder.color_from = (Spinner) convertView.findViewById(R.id.spn_color_from);
        viewHolder.color_to = (Spinner) convertView.findViewById(R.id.spn_color_to);

        ArrayAdapter adapter = new ArrayAdapter(_context, android.R.layout.simple_spinner_item, SearchActivity.color_list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        viewHolder.color_from.setAdapter(adapter);
        viewHolder.color_to.setAdapter(adapter);

        convertView.setTag(viewHolder);

        final Spinner color_from_temp=viewHolder.color_from;
        final Spinner color_to_temp=viewHolder.color_to;

        // Changing textcolor
        viewHolder.color_from.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view,
                        int position, long id) {
                    // TODO Auto-generated method stub

                    All_link.COLOR_FROM=color_from_temp.getSelectedItem().toString();
                       ((TextView) parent.getChildAt(0)).setTextColor(Color.parseColor("#003974"));
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    // TODO Auto-generated method stub
                }
            });
        viewHolder.color_to.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub

                All_link.COLOR_TO=color_to_temp.getSelectedItem().toString();
                   ((TextView) parent.getChildAt(0)).setTextColor(Color.parseColor("#003974"));
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });
    }
    else{
        viewHolder=(ViewHolder)convertView.getTag();
    }
    return convertView;
</code>```

答:
List view, recycler view follows Lazy loading concept and reuses the views you have created. Imagine it like a screen can hold  view at max and list has 1000 items, android uses the same 10 view for the 1000 items. You have to update the new item depending on the value of the new item and you have to do it for every new item else it will use the previous view with checked state of checkbox. I have explained it theoretically hope it helps.
Tell me in case you want a practical implementation.

Body:
In my ExpandableListview, I am using Imageview and Checkbox that resembles the shape image and name,

When I tick the checkbox of particular child item , the other child item also gets ticked , after scrolling the checked state changes ,

I needed multiple values to be selected.

Please help me to get this solved , I am in very need of this . Googled but not found working in my case

Thanks in advance.

public View getChildView(int groupPosition, final int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {

_childText = (String) getChild(groupPosition, childPosition);

int itemType = getChildType(groupPosition,childPosition);

Log.e("childPosition", "karjeevch "+childPosition);

ViewHolder viewHolder = null;
switch (itemType) {

case 0:
    viewHolder = null;
    if (convertView==null) {
        viewHolder=new ViewHolder();
        convertView = infalInflater.inflate(R.layout.list_child_shape, null);
        viewHolder.shape_name = (CheckBox) convertView.findViewById(R.id.shape_chk_box);
        viewHolder.img_shape_icon=(ImageView)convertView.findViewById(R.id.img_shape);

        imageLoader.DisplayImage("http://rosycontact.com/shashvat/images/"+_childText+".png", viewHolder.img_shape_icon);
        viewHolder.shape_name.setText(_childText);
        convertView.setTag(viewHolder);

        final CheckBox shape_name_temp=viewHolder.shape_name;
        viewHolder.shape_name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (shape_name_temp.isChecked()==true) {
                    All_link.SHAPE=shape_name_temp.getText().toString();
                }
            }
        });

        //new PerformBackgroungTask().execute();
    }
    else{
        viewHolder=(ViewHolder)convertView.getTag();
    }
    return convertView;
    //break;

case 1:

    viewHolder = null;
    if (convertView==null) {
        viewHolder=new ViewHolder();
        convertView = infalInflater.inflate(R.layout.list_child_carat, null);
        viewHolder.carat_from = (TextView) convertView.findViewById(R.id.ed_carat_from);
        viewHolder.carat_to = (TextView) convertView.findViewById(R.id.ed_carat_to);

        viewHolder.carat_from.setText("jdsv");
        viewHolder.carat_to.setText("jdsv");

        All_link.CARAT_FROM=viewHolder.carat_from.getText().toString();
        All_link.CARAT_TO=viewHolder.carat_to.getText().toString();

    }
    else{
        viewHolder=(ViewHolder)convertView.getTag();
    }
    return convertView;

case 2:

    viewHolder = null;
    if (convertView==null) {
        viewHolder=new ViewHolder();

        convertView = infalInflater.inflate(R.layout.list_child_color, null);
        viewHolder.color_from = (Spinner) convertView.findViewById(R.id.spn_color_from);
        viewHolder.color_to = (Spinner) convertView.findViewById(R.id.spn_color_to);

        ArrayAdapter adapter = new ArrayAdapter(_context, android.R.layout.simple_spinner_item, SearchActivity.color_list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        viewHolder.color_from.setAdapter(adapter);
        viewHolder.color_to.setAdapter(adapter);

        convertView.setTag(viewHolder);

        final Spinner color_from_temp=viewHolder.color_from;
        final Spinner color_to_temp=viewHolder.color_to;

        // Changing textcolor
        viewHolder.color_from.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view,
                        int position, long id) {
                    // TODO Auto-generated method stub

                    All_link.COLOR_FROM=color_from_temp.getSelectedItem().toString();
                       ((TextView) parent.getChildAt(0)).setTextColor(Color.parseColor("#003974"));
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    // TODO Auto-generated method stub
                }
            });
        viewHolder.color_to.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub

                All_link.COLOR_TO=color_to_temp.getSelectedItem().toString();
                   ((TextView) parent.getChildAt(0)).setTextColor(Color.parseColor("#003974"));
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });
    }
    else{
        viewHolder=(ViewHolder)convertView.getTag();
    }
    return convertView;


问:
How to exclude single files when using MSBuild Scanner
We are using the SonarQube Scanner for MSBuild (1.1.0.0) and have a solution containing multiple projects.

There is a SonarQube.Analysis.xml in the solution root folder which we supply to the scanners cli.

```<code><SonarQubeAnalysisProperties  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.sonarsource.com/msbuild/integration/2015/1">
    <Property Name="sonar.cs.opencover.reportsPaths">output/nunit-coverage.xml</Property>
    <Property Name="sonar.cs.nunit.reportsPaths">output/nunit-result.xml</Property>

    <Property Name="sonar.exclusions">Project1/Migrations/*</Property>
    <Property Name="sonar.coverage.exclusions">Project1/Migrations/*</Property>
</SonarQubeAnalysisProperties>
</code>```

Now the problem is: Project1/Migrations/* seems not to get excluded because the Base dir is set to .../Project1 during the scan. The same happens for all other projects in the solution. The result is that .../Project1/Project1/Migrations/* is an unknown path.

So what is the recommended way to exclude a whole directory from coverage and sourcecode analytics when using MSBuild Scanner?

答:
Try to put the exclusions in the project file (.csproj) itself, something like:

```<code><ItemGroup>
     <SonarQubeSetting Include="sonar.exclusions">
          <Value>**/Migrations/*</Value>
     </SonarQubeSetting>
</ItemGroup>
</code>```

See Appendix 2: Configuring the SonarQube Scanner for MSBuild.

Body:
We are using the SonarQube Scanner for MSBuild (1.1.0.0) and have a solution containing multiple projects.

There is a SonarQube.Analysis.xml in the solution root folder which we supply to the scanners cli.

<SonarQubeAnalysisProperties  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.sonarsource.com/msbuild/integration/2015/1">
    <Property Name="sonar.cs.opencover.reportsPaths">output/nunit-coverage.xml</Property>
    <Property Name="sonar.cs.nunit.reportsPaths">output/nunit-result.xml</Property>

    <Property Name="sonar.exclusions">Project1/Migrations/*</Property>
    <Property Name="sonar.coverage.exclusions">Project1/Migrations/*</Property>
</SonarQubeAnalysisProperties>

Now the problem is: Project1/Migrations/* seems not to get excluded because the Base dir is set to .../Project1 during the scan. The same happens for all other projects in the solution. The result is that .../Project1/Project1/Migrations/* is an unknown path.

So what is the recommended way to exclude a whole directory from coverage and sourcecode analytics when using MSBuild Scanner?

Body:
Try to put the exclusions in the project file (.csproj) itself, something like:

<ItemGroup>
     <SonarQubeSetting Include="sonar.exclusions">
          <Value>**/Migrations/*</Value>
     </SonarQubeSetting>
</ItemGroup>

See Appendix 2: Configuring the SonarQube Scanner for MSBuild.


问:
Verifying null collection with null elements inside
My problem is that a collection has a null value, and any "utils" method return that the collection is not empty. There are other "elegant" options?

This code throws a null pointer exception:

```<code>    public static void main(String[] args) {
    ArrayList<String> strings = new ArrayList<>();
    strings.add(null);

    if(CollectionUtils.isNotEmpty(strings)) {
        for (String s : strings) {
            System.out.println(s.length());
        }
    }
}
</code>```

答:
You can check if there are nulls in the collection and/or filter like in the following code:</p>

```<code>public static void main(String[] args) {
    List<String> strings = new ArrayList<>();
    strings.add("one");
    strings.add(null);
    strings.add("two");

    // has a null value?
    final boolean hasNulls = strings.stream()
            .anyMatch(Objects::isNull);
    System.out.println("has nulls: " + hasNulls);

    // filter null values
    strings = strings.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toList());

    System.out.println("filtered: " + strings.toString());
}
</code>```

Body:
My problem is that a collection has a null value, and any "utils" method return that the collection is not empty. There are other "elegant" options?

This code throws a null pointer exception:

    public static void main(String[] args) {
    ArrayList<String> strings = new ArrayList<>();
    strings.add(null);

    if(CollectionUtils.isNotEmpty(strings)) {
        for (String s : strings) {
            System.out.println(s.length());
        }
    }
}

Body:
You can check if there are nulls in the collection and/or filter like in the following code:

public static void main(String[] args) {
    List<String> strings = new ArrayList<>();
    strings.add("one");
    strings.add(null);
    strings.add("two");

    // has a null value?
    final boolean hasNulls = strings.stream()
            .anyMatch(Objects::isNull);
    System.out.println("has nulls: " + hasNulls);

    // filter null values
    strings = strings.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toList());

    System.out.println("filtered: " + strings.toString());
}


问:
mysql persistent connection
How to close a mysql  persistent connection?</p>

答:
You can't, simply wait for database server restart to reset all connection or maximum allow connection exceeded

There is no reason to issue persistent connection as it just hold the connection resource without release, another word, if your site having lots of traffic, soon you will get a connection error message.

And there is no reason to use mysql related function, switch to mysqli or pdo.

Title: mysql persistent connection


问:
Navbar link scroll to top
What I want to do is that when "Home" is clicked on the navbar, it should scroll to the top of the page, but I can't seem to get anything working. I'm to get it to work on the same .html so I'm using  on the same page</p>

```<code><nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container text-center">
        <div id="navbar" class="navbar-collapse">
            <ul class="nav navbar-nav">
                <li><a href="#home">Home</a></li>
                <li><a href="#feedback">Feedback</a></li>
                <li><a href="#about">About me</a></li>
                <li><a href="#contact">Contact</a></li>
            </ul>
        </div>
    </div>
</nav>

<script>
    $("#home").on("click", function() {
        $("body").scrollTop(0);
    });
</script>
</code>```

答:
Here you can do with this code.

You can't use #home directly in jQuery because it is not a id.

So you should use it like this $("a[href='#home']").on("click", function() {

Hope this example will helps you.

$("a[href='#home']").on("click", function() {
    $('body').animate({
            scrollTop: 0
    },
    500); //this will helps you to smooth scroll to top
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
height: 500px;
}
nav {
position: fixed;
}</code>```

Home

Feedback

About me

Contact

    ```

Title: Navbar link scroll to top

Body:
What I want to do is that when "Home" is clicked on the navbar, it should scroll to the top of the page, but I can't seem to get anything working. I'm to get it to work on the same .html so I'm using  on the same page

Home

Feedback

About me

Contact

Body:
Here you can do with this code.

You can't use #home directly in jQuery because it is not a id.

So you should use it like this $("a[href='#home']").on("click", function() {

Hope this example will helps you.

$("a[href='#home']").on("click", function() {
    $('body').animate({
            scrollTop: 0
    },
    500); //this will helps you to smooth scroll to top
});

body {
height: 500px;
}
nav {
position: fixed;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container text-center">
            <div id="navbar" class="navbar-collapse">
                <ul class="nav navbar-nav">
                    <li><a href="#home">Home</a></li>
                    <li><a href="#feedback">Feedback</a></li>
                    <li><a href="#about">About me</a></li>
                    <li><a href="#contact">Contact</a></li>
                </ul>
            </div>
        </div>
    </nav>


问:
Angular js .push method for Json file not working
When i try to enter random data into an Array or Json file through .push method its not working
here is my code
Array Code is

```<code> $scope.stock =[{
"name":"Pepsi",
"price":65,
"color":"black",
"avaliable":true}]
</code>```

trying to bind through ng-model

```<code><form ng-submit="addItem()">
    <input type="text" placeholder="Name" ng-model="newName" />
    <input type="text" placeholder="Price" ng-model="newPrice" />
    <input type="text" placeholder="color" ng-model="newcolor" />
    <input class="submit" type="submit" value="Add New Item" />
</form>
</code>```

the JS code is

```<code>$scope.addItem = function(){
    $scope.stock.push({
        name: $scope.newName,
        price: parseInt($scope.newPrice),
        color: $scope.newcolor,
        avaliable: true
    });
</code>```

答:
Its working for angular 1.4.6 please check here Jsfiddle demo</p>

```<code>angular.module('myApp', ['ngStorage']).controller('ctrl',
  function($scope, $localStorage) {

    $scope.stock = [{
      "name": "Pepsi",
      "price": 65,
      "color": "black",
      "avaliable": true
    }]

    $scope.addItem = function() {
      $scope.stock.push({
        name: $scope.newName,
        price: parseInt($scope.newPrice),
        color: $scope.newcolor,
        avaliable: true
      });
    }
  });
</code>```

Body:
When i try to enter random data into an Array or Json file through .push method its not working
here is my code
Array Code is

 $scope.stock =[{
"name":"Pepsi",
"price":65,
"color":"black",
"avaliable":true}]

trying to bind through ng-model

<form ng-submit="addItem()">
    <input type="text" placeholder="Name" ng-model="newName" />
    <input type="text" placeholder="Price" ng-model="newPrice" />
    <input type="text" placeholder="color" ng-model="newcolor" />
    <input class="submit" type="submit" value="Add New Item" />
</form>

the JS code is

$scope.addItem = function(){
    $scope.stock.push({
        name: $scope.newName,
        price: parseInt($scope.newPrice),
        color: $scope.newcolor,
        avaliable: true
    });

Body:
Its working for angular 1.4.6 please check here Jsfiddle demo

angular.module('myApp', ['ngStorage']).controller('ctrl',
  function($scope, $localStorage) {

    $scope.stock = [{
      "name": "Pepsi",
      "price": 65,
      "color": "black",
      "avaliable": true
    }]

    $scope.addItem = function() {
      $scope.stock.push({
        name: $scope.newName,
        price: parseInt($scope.newPrice),
        color: $scope.newcolor,
        avaliable: true
      });
    }
  });


问:
willHideViewController not calld when application is in landscape mode
I am creating an iPhone universal application and implemented the  willHideViewController method. This method is called on the iPad portrait mode but not called on the iPad landscape mode.
Can anyone give the solutions?</p>

答:
willHideViewController has been deprecated since iOS8 (source)

You need to use splitViewController:willChangeToDisplayMode: method instead because there are no garantee that willHideViewController will continue to work properly (and you found a case where it's not !)


问:
ReplaceOne throws duplicate key exception
My app receives data from a remote server and calls ReplaceOne to either insert new or replace existing document with a given key with Upsert = true. (the key is made anonymous with *) The code only runs in a single thread.

However, occasionally, the app crashes with the following error:

```<code>Unhandled Exception: MongoDB.Driver.MongoWriteException: A write operation resulted in an error.
  E11000 duplicate key error collection: ****.orders index: _id_ dup key: { : "****-********-********-************" } ---> MongoDB.Driver.MongoBulkWriteException`1[MongoDB.Bson.BsonDocument]: A bulk write operation resulted in one or more errors.
  E11000 duplicate key error collection: ****.orders index: _id_ dup key: { : "****-********-********-************" }
   at MongoDB.Driver.MongoCollectionImpl`1.BulkWrite(IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionBase`1.ReplaceOne(FilterDefinition`1 filter, TDocument replacement, UpdateOptions options, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MongoDB.Driver.MongoCollectionBase`1.ReplaceOne(FilterDefinition`1 filter, TDocument replacement, UpdateOptions options, CancellationToken cancellationToken)
   at Dashboard.Backend.AccountMonitor.ProcessOrder(OrderField& order)
   at Dashboard.Backend.AccountMonitor.OnRtnOrder(Object sender, OrderField& order)
   at XAPI.Callback.XApi._OnRtnOrder(IntPtr ptr1, Int32 size1)
   at XAPI.Callback.XApi.OnRespone(Byte type, IntPtr pApi1, IntPtr pApi2, Double double1, Double double2, IntPtr ptr1, Int32 size1, IntPtr ptr2, Int32 size2, IntPtr ptr3, Int32 size3)
Aborted (core dumped)
</code>```

My question is, why is it possible to have dup key when I use ReplaceOne with Upsert = true options?

The app is working in the following environment and runtime:

```<code>.NET Command Line Tools (1.0.0-preview2-003121)

Product Information:
 Version:            1.0.0-preview2-003121
 Commit SHA-1 hash:  1e9d529bc5

Runtime Environment:
 OS Name:     ubuntu
 OS Version:  16.04
 OS Platform: Linux
 RID:         ubuntu.16.04-x64
</code>```

And MongoDB.Driver 2.3.0-rc1.

答:
I can co-sign on this one:</p>

```<code>    public async Task ReplaceOneAsync(T item)
    {
        try
        {
            await _mongoCollection.ReplaceOneAsync(x => x.Id.Equals(item.Id), item, new UpdateOptions { IsUpsert = true });
        }
        catch (MongoWriteException)
        {
            var count = await _mongoCollection.CountAsync(x => x.Id.Equals(item.Id)); // lands here - and count == 1 !!!
        }
    }
</code>```

Body:
My app receives data from a remote server and calls ReplaceOne to either insert new or replace existing document with a given key with Upsert = true. (the key is made anonymous with *) The code only runs in a single thread.

However, occasionally, the app crashes with the following error:

Unhandled Exception: MongoDB.Driver.MongoWriteException: A write operation resulted in an error.
  E11000 duplicate key error collection: ****.orders index: _id_ dup key: { : "****-********-********-************" } ---> MongoDB.Driver.MongoBulkWriteException`1[MongoDB.Bson.BsonDocument]: A bulk write operation resulted in one or more errors.
  E11000 duplicate key error collection: ****.orders index: _id_ dup key: { : "****-********-********-************" }
   at MongoDB.Driver.MongoCollectionImpl`1.BulkWrite(IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionBase`1.ReplaceOne(FilterDefinition`1 filter, TDocument replacement, UpdateOptions options, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at MongoDB.Driver.MongoCollectionBase`1.ReplaceOne(FilterDefinition`1 filter, TDocument replacement, UpdateOptions options, CancellationToken cancellationToken)
   at Dashboard.Backend.AccountMonitor.ProcessOrder(OrderField& order)
   at Dashboard.Backend.AccountMonitor.OnRtnOrder(Object sender, OrderField& order)
   at XAPI.Callback.XApi._OnRtnOrder(IntPtr ptr1, Int32 size1)
   at XAPI.Callback.XApi.OnRespone(Byte type, IntPtr pApi1, IntPtr pApi2, Double double1, Double double2, IntPtr ptr1, Int32 size1, IntPtr ptr2, Int32 size2, IntPtr ptr3, Int32 size3)
Aborted (core dumped)

My question is, why is it possible to have dup key when I use ReplaceOne with Upsert = true options?

The app is working in the following environment and runtime:

.NET Command Line Tools (1.0.0-preview2-003121)

Product Information:
 Version:            1.0.0-preview2-003121
 Commit SHA-1 hash:  1e9d529bc5

Runtime Environment:
 OS Name:     ubuntu
 OS Version:  16.04
 OS Platform: Linux
 RID:         ubuntu.16.04-x64

And MongoDB.Driver 2.3.0-rc1.

Body:
I can co-sign on this one:

    public async Task ReplaceOneAsync(T item)
    {
        try
        {
            await _mongoCollection.ReplaceOneAsync(x => x.Id.Equals(item.Id), item, new UpdateOptions { IsUpsert = true });
        }
        catch (MongoWriteException)
        {
            var count = await _mongoCollection.CountAsync(x => x.Id.Equals(item.Id)); // lands here - and count == 1 !!!
        }
    }


问:
Java XML - Java changes me ' and " to ' and " when I generate the XML File
I'm adding a new register to XML File. This File has a speacial characters like ' and ". And when I generate the XML File the transformerFactory changes me this to ' and ".

This is my code:

```<code>Document document = documentBuilder.parse("Input.xml");
//Here I add the nodes in document
DOMSource source = new DOMSource(document);

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();

StreamResult result = new StreamResult("Result.xml");
transformer.transform(source, result);
</code>```

I tried add this lines in transfomer, but didn't work:

```<code>    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
</code>```

Example:

Input:

```<code><Users>
  <User Name="Daniel">
      <Option Name="Salt">jJ='\Cl%MST"U.ivm/FwI+TJC=IalOJg2z8\L}b;<=OZ}qz`|_|[`y~)J,pEbWx_</Option>
  </User>
</Users>
</code>```

Output: I added Tom with other option Salt and when I generate the XMl Java changes me this characters ' and " from Daniel and others users:

```<code><Users>
   <User Name="Daniel">
     <Option Name="Salt">jJ='\Cl%MST"U.ivm/FwI+TJC=IalOJg2z8\L}b;<=OZ}qz`|_|[`y~)J,pEbWx_</Option>
   </User>
   <User Name="Tom">
     <Option Name="Salt">salt1234</Option>
   </User>
 </Users>
</code>```

What I want:

```<code><Users>
       <User Name="Daniel">
         //Here there are &apos and &quot and in output no
         <Option Name="Salt">jJ='\Cl%MST"U.ivm/FwI+TJC=IalOJg2z8\L}b;<=OZ}qz`|_|[`y~)J,pEbWx_</Option>
       </User>
       <User Name="Tom">
         <Option Name="Salt">salt1234</Option>
       </User>
     </Users>
</code>```

How can escape this special characters when I generete the new XML File?

Thanks!

答: If you want the literal ' in your output, then you just need to escape the &. The input should be &apos;.

Body:
I'm adding a new register to XML File. This File has a speacial characters like ' and ". And when I generate the XML File the transformerFactory changes me this to ' and ".

This is my code:

Document document = documentBuilder.parse("Input.xml");
//Here I add the nodes in document
DOMSource source = new DOMSource(document);

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();

StreamResult result = new StreamResult("Result.xml");
transformer.transform(source, result);

I tried add this lines in transfomer, but didn't work:

    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

Example:

Input:

<Users>
  <User Name="Daniel">
      <Option Name="Salt">jJ='\Cl%MST"U.ivm/FwI+TJC=IalOJg2z8\L}b;<=OZ}qz`|_|[`y~)J,pEbWx_</Option>
  </User>
</Users>

Output: I added Tom with other option Salt and when I generate the XMl Java changes me this characters ' and " from Daniel and others users:

<Users>
   <User Name="Daniel">
     <Option Name="Salt">jJ='\Cl%MST"U.ivm/FwI+TJC=IalOJg2z8\L}b;<=OZ}qz`|_|[`y~)J,pEbWx_</Option>
   </User>
   <User Name="Tom">
     <Option Name="Salt">salt1234</Option>
   </User>
 </Users>

What I want:

<Users>
       <User Name="Daniel">
         //Here there are &apos and &quot and in output no
         <Option Name="Salt">jJ='\Cl%MST"U.ivm/FwI+TJC=IalOJg2z8\L}b;<=OZ}qz`|_|[`y~)J,pEbWx_</Option>
       </User>
       <User Name="Tom">
         <Option Name="Salt">salt1234</Option>
       </User>
     </Users>

How can escape this special characters when I generete the new XML File?

Thanks!

Body: If you want the literal &apos; in your output, then you just need to escape the &. The input should be &amp;apos;.


问:
Xamarin Forms HtmlLoad nuGet don't work on ios
I'm new in Xamarin, C# and VisualStudio
In my proyect Im trying display HTML content in a label using Html Label

follow the steps in android work fine but in ios i have this error:

this is my finishedlaunching in appdelegate

```<code>public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        //Call HtmlLabelRenderer.Initialize() before Xamarin.Forms.Forms.Init() in AppDelegate.cs
        HtmlLabelRenderer.Initialize();

        global::Xamarin.Forms.Forms.Init();

        LoadApplication(new App());

        return base.FinishedLaunching(app, options);
    }
</code>```

in the line of "global::Xamarin.Forms.Forms.Init() show me this error when launch;

System.TypeLoadException
Could not load type Plugin.HtmlLabel.HtmlLabel, Plugin.HtmlLabel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null while decoding custom attribute: (null)

I try clean and rebuild, delete obj and bin folders and don't work, I think im missing some steps

Thanx for help

答: With the new versión (1.0.3) this problem is fixed!</p>

Body:
I'm new in Xamarin, C# and VisualStudio
In my proyect Im trying display HTML content in a label using Html Label

follow the steps in android work fine but in ios i have this error:

this is my finishedlaunching in appdelegate

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        //Call HtmlLabelRenderer.Initialize() before Xamarin.Forms.Forms.Init() in AppDelegate.cs
        HtmlLabelRenderer.Initialize();

        global::Xamarin.Forms.Forms.Init();

        LoadApplication(new App());

        return base.FinishedLaunching(app, options);
    }

in the line of "global::Xamarin.Forms.Forms.Init() show me this error when launch;

System.TypeLoadException
Could not load type Plugin.HtmlLabel.HtmlLabel, Plugin.HtmlLabel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null while decoding custom attribute: (null)

I try clean and rebuild, delete obj and bin folders and don't work, I think im missing some steps

Thanx for help


问:
ADAL renewing token using AcquireTokenAsync and existing JWT token
I have a JWT token via initial login that is set to expire in 60mins. I want to renew this token so that the user is not logged out.

For this, am using the AcquireTokenAsync call withing that 60mins window using the UserAssertion

public static async Task RenewToken(string resourceUri)
{
    var authContext = new AuthenticationContext(Authority);
    var authHeader = HttpContext.Current.Request.Headers["Authorization"];
    var userAccessToken = authHeader.Substring(authHeader.LastIndexOf(' ')).Trim();
    var userAssertion = new  UserAssertion(userAccessToken);

    // keeps returning the same access token with same expiry
    var authResult = await authContext.AcquireTokenAsync(resourceUri, ClientId, userAssertion);

    var userInfo = authResult.UserInfo;
    var apiAccessToken = authResult.AccessToken;
    var expiry = authResult.ExpiresOn.UtcDateTime.ToString("u");
}
```

Is it that the above call with an existing JWT token can be used only once the token is expired?

Any inputs appreciated.

答:
According to your code seems you want to refresh token on web api(service) side, on service side you shouldn't renew access tokens.  The client app should do that operation.

With ADAL, your app will get the access and refresh token the first time an end user logs in, then you can use refresh token to get new access token silently (AcquireTokenSilentAsync) when the access token expires and a refresh token is available & valid.

Access tokens can be refreshed using the refresh-token for a maximum period of time of 90 days with a 14 day expiration sliding window from the date that the access token was acquired by prompting the user.

Checkout our code sample implementing this scenario for more help. If i misunderstand your scenario , please feel free to let me know .

ContentLicense: CC BY-SA 4.0

Body:
I have a JWT token via initial login that is set to expire in 60mins. I want to renew this token so that the user is not logged out.

For this, am using the AcquireTokenAsync call withing that 60mins window using the UserAssertion

public static async Task RenewToken(string resourceUri)
{
    var authContext = new AuthenticationContext(Authority);
    var authHeader = HttpContext.Current.Request.Headers["Authorization"];
    var userAccessToken = authHeader.Substring(authHeader.LastIndexOf(' ')).Trim();
    var userAssertion = new  UserAssertion(userAccessToken);

    // keeps returning the same access token with same expiry
    var authResult = await authContext.AcquireTokenAsync(resourceUri, ClientId, userAssertion);

    var userInfo = authResult.UserInfo;
    var apiAccessToken = authResult.AccessToken;
    var expiry = authResult.ExpiresOn.UtcDateTime.ToString("u");
}

Is it that the above call with an existing JWT token can be used only once the token is expired?

Any inputs appreciated.


问:
Large text is going back of Imageview

```<code> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:id="@+id/Chartimg"
        android:layout_margin="5dp"
        android:padding="5dp" />
     <TextView
        android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/InfoView_ItemName"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxLines="1" />        <TextView
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/IvItemID"
        android:layout_below="@id/InfoView_ItemName" />
    <ImageView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_next_item"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:scaleType="centerInside" />
</RelativeLayout>
 </FrameLayout>
</code>```

I am creating litview when the listview item have large text it is going back to the image view here I am posting my code. please give me any solution but

答:
You should use android:layout_toLeftOf

Positions the right edge of this view to the left of the given anchor
  view ID. Accommodates right margin of this view and left margin of
  anchor view.

Title: Large text is going back of Imageview

Body:
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@android:drawable/ic_menu_gallery"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:id="@+id/Chartimg"
        android:layout_margin="5dp"
        android:padding="5dp" />
     <TextView
        android:text="Medium Textcbvvvccgcvcvcbcvbvvbcvbvcbvcb"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/InfoView_ItemName"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxLines="1" />        <TextView
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/Chartimg"
        android:id="@+id/IvItemID"
        android:layout_below="@id/InfoView_ItemName" />
    <ImageView
        android:layout_width="30dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_action_next_item"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:scaleType="centerInside" />
</RelativeLayout>
 </FrameLayout>

I am creating litview when the listview item have large text it is going back to the image view here I am posting my code. please give me any solution but


问:
Simple Form: creating a new record from another controller
I have a Home controller with an index view that acts like a search box that lets the user query a First Table or Second Table through a select box. After a user enters a search term, he will be redirected to the index page of the First or Second model with the search results for that model.

A Search record must be created each time a query is submitted with the search type and search term. However, I don't know how to create a new Search object using simple_form from a different controller, which is the Home controller in this case.

Home Controller

```<code>def index
  @find = Find.new
</code>```

Home Index View

```<code>= simple_form_for @find, url: finds_path, method: :post do |f|
  = f.input :search_type, :collection => [['First', 'First'], ['Second', 'Second']]
  = f.input :search_term
  = f.button :submit
</code>```

Finds Controller

```<code>def new
  @find = Find.new
end

def create
  @find = Find.new(find_params)
  if params[:search_type] == 'First'
    redirect_to first_path
  elsif params[:search_type] == 'Second'
    redirect_to second_path
  else
    redirect_to root_path
  end
end

private

def find_params
  params.permit(:search_term, :search_type, :utf8, :authenticity_token,
    :find, :commit, :locale)
  # the params seem to come from the Home controller so I added them just to see if they will go through :(
end
</code>```

It doesn't save. Instead it gives:

```<code>Started POST "/en/finds"
Processing by FindsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"..", "find"=>{"search_type"=>"First", "search_term"=>"Something"}, "commit"=>"Create Find", "locale"=>"en"}
Unpermitted parameter: :find
Redirected to http://localhost:3000/en
</code>```

答:
Unpermitted parameter: :find

Your find_params should be just

```<code>def find_params
  params.require(:find).permit(:search_type, :search_term)
end
</code>```

You should access the search_type with params[:find][:search_type]

```<code>if params[:find][:search_type] == 'First'
  redirect_to first_path
elsif params[:find][:search_type] == 'Second'
  redirect_to second_path
  else
  redirect_to root_path
end
</code>```

Also, I would suggest renaming the Find model as it conflicts with ActiveRecord#FinderMethods

Body:
I have a Home controller with an index view that acts like a search box that lets the user query a First Table or Second Table through a select box. After a user enters a search term, he will be redirected to the index page of the First or Second model with the search results for that model.

A Search record must be created each time a query is submitted with the search type and search term. However, I don't know how to create a new Search object using simple_form from a different controller, which is the Home controller in this case.

Home Controller

def index
  @find = Find.new

Home Index View

= simple_form_for @find, url: finds_path, method: :post do |f|
  = f.input :search_type, :collection => [['First', 'First'], ['Second', 'Second']]
  = f.input :search_term
  = f.button :submit

Finds Controller

def new
  @find = Find.new
end

def create
  @find = Find.new(find_params)
  if params[:search_type] == 'First'
    redirect_to first_path
  elsif params[:search_type] == 'Second'
    redirect_to second_path
  else
    redirect_to root_path
  end
end

private

def find_params
  params.permit(:search_term, :search_type, :utf8, :authenticity_token,
    :find, :commit, :locale)
  # the params seem to come from the Home controller so I added them just to see if they will go through :(
end

It doesn't save. Instead it gives:

Started POST "/en/finds"
Processing by FindsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"..", "find"=>{"search_type"=>"First", "search_term"=>"Something"}, "commit"=>"Create Find", "locale"=>"en"}
Unpermitted parameter: :find
Redirected to http://localhost:3000/en

Body:
Unpermitted parameter: :find

Your find_params should be just

def find_params
  params.require(:find).permit(:search_type, :search_term)
end

You should access the search_type with params[:find][:search_type]

if params[:find][:search_type] == 'First'
  redirect_to first_path
elsif params[:find][:search_type] == 'Second'
  redirect_to second_path
  else
  redirect_to root_path
end

Also, I would suggest renaming the Find model as it conflicts with ActiveRecord#FinderMethods


问:
How to use data from a database with a MS Bot
I am going to do my next project on ChatBot for my client. I am a .net person, so planning to use MS Bot with C#.

My question is on creating the Database part. We have a existing Database which has data related to Project Management and others which is currently being used for a web application.

What we are expecting from the Bot is, if a person(say, a manager of particular project)wants to know the count of people under him, he can use the Bot to get the count, rather than go to the web application and figure out.

How will this database work for Bot application.
How will I create the table structure to identify the questions to be asked to BOT and its responses and fetch data and then display to user.
How can we make my Bot fetch data from this DB, if someone asks question.
How can I store these responses.

I am totally confused. My Client do not want to use LUIS, but want similar thing to be built with our Database and can be called via RestAPI.

Kindly help with any article or advise to start my work with.

答:
Consider the bot you made as a back-end server written in C#.

It just gets requests and sends responses.

So nothing special is needed for connecting it to DB.

Simply connect it to DB as you'd connect a ASP.NET website to DB.


问:
Multiple-File Template Implementation
With normal functions, the declaration and definition are often separated across multiple files like so:

```<code>// Foo.h

namespace Foo
{
    void Bar();
}
</code>```

.

```<code>// Foo.cpp

#include "Foo.h"

void Foo::Bar()
{
    cout << "Inside function." << endl;
}
</code>```

It is my understanding that this cannot be done with templates.  The declaration and definition must not be separate because the appropriate form of the template is created "on-demand" when needed.

So, how and where are templates typically defined in a multiple-file project like this?  My intuition is that it would be in Foo.cpp because that's where the "meat" of functions normally is, but on the other hand it's the header file that's going to be included.

答:
Template code stays in the .hh file.  There's no reason to make them separate files, though it is good practice to put the definitions after all the declarations.

When the compiler generates template code, it flags it so that the linker knows that the instantiation of a template in one compilation unit (i.e. .o file) is the exact same code as one in another unit.  It will keep one and discard the rest, rather than bailing out with a "multiply defined symbol" error.

This is true of modern compilers with good template support.  In the case of GCC, since 2.8.  (I know, I wrote a lot of code for gcc 2.7.2.2 before they smartened the linker up and you had to jump through hoops to make templates build right.)

Title: Multiple-File Template Implementation

Body:
With normal functions, the declaration and definition are often separated across multiple files like so:

// Foo.h

namespace Foo
{
    void Bar();
}

.

// Foo.cpp

#include "Foo.h"

void Foo::Bar()
{
    cout << "Inside function." << endl;
}

It is my understanding that this cannot be done with templates.  The declaration and definition must not be separate because the appropriate form of the template is created "on-demand" when needed.

So, how and where are templates typically defined in a multiple-file project like this?  My intuition is that it would be in Foo.cpp because that's where the "meat" of functions normally is, but on the other hand it's the header file that's going to be included.


问:
Usage of Razor expressions with or without string quotes
Regarding Razor expression usage (ASP.Net) cases, there are two cases  commonly met:

```<code><div title="@MyClass.Test"></div>
</code>```

and

```<code><div title=@MyClass.Test></div>
</code>```

As they both seem to work the same on
Razor 2.0, I would like to know if there are any differences, especially in corner cases (null/malfored values etc).

Eventually I would also like to know which is best as a practice to follow. Thank you in advance.

答:
The rules for HTML attributes can be found here. The quotes are usually optional, but if there is a space in the value of MyClass.Test then you'll need them.

I would say best practice is to include them as it doesn't hurt and will save you problems if there are spaces in the value.

Body:
Regarding Razor expression usage (ASP.Net) cases, there are two cases  commonly met:

and

As they both seem to work the same on
Razor 2.0, I would like to know if there are any differences, especially in corner cases (null/malfored values etc).

Eventually I would also like to know which is best as a practice to follow. Thank you in advance.


问:
Tivoli Common Reporting Installation fails on Linux for missing prerequisites on Workload Scheduler
For Linux operating system, Tivoli Common Reporting installation fails for missing prerequisites. The error message is the following:

CRIMA1217E: A problem occurred during the execution of the /opt/IBM/JazzSM/install/reporting_services/tcrWrapperInstall.xml file.
  Two defects have been opened to Jazz for Service Management development team.

答:
to circumvent the problem, install the following libraries:

libpng16-16-1.6.13-2.4.1.i586.rpm

openmotif-libs-32bit-2.3.4-25.3.x86_64.rpm

openmotif-libs-2.3.4-25.3.x86_64.rpm

openmotif22-libs-32bit-2.2.4-189.1.x86_64.rpm

openmotif22-libs-2.2.4-189.1.x86_64.rpm


问:
How to list all files of a given directory in Mac terminal except a file or directory
I want to display all the files in the working directory except for a file or directory. We have --exclude option in Ubuntu for dir command.

To be more specific, am trying to move files of my working directory to a subdirectory using this command:

```<code>git ls-tree -z --name-only HEAD | xargs -0 -I {} git mv {} sub_directory/
</code>```

And, while doing that, I don't want to move few files and directories. How can that be achieved in Mac?

答: if you want to move files with certain file or directory excluded, it is recommended to use rsync command. you can also use git clean to remove untracked files from the working tree.

Body:
I want to display all the files in the working directory except for a file or directory. We have --exclude option in Ubuntu for dir command.

To be more specific, am trying to move files of my working directory to a subdirectory using this command:

git ls-tree -z --name-only HEAD | xargs -0 -I {} git mv {} sub_directory/

And, while doing that, I don't want to move few files and directories. How can that be achieved in Mac?


问:
How to modify the value in the database
Using SQL Server and VB6

Table1

Date Time

```<code>20090801 060000
20090802 162000
</code>```

Date Format: yyyymmdd
Time Format: HHMMSS

Date & Time Column Datatype is varchar

When i select a Date in a Datetimepicker and modify the time.  The should update in the table.

Expected Output

```<code>01-08-2009 (DatetimePicker value)
080000 (Textbox value)
</code>```

The Above value should update in the table

How to make a code for the above condition.

Need code help.

答:
Try something like this.

```<code>Dim strDateTime as string

strDateTime = Format$(DateTimePicker.Value, "MMDDYYYY mmhhss")
</code>```

Update our the database with a recordset

```<code>rs.Fields["DateTimeField"] = strDateTime
rs.Update'
</code>```

I hope this points you in the right direction

Title: How to modify the value in the database

Body:
Using SQL Server and VB6

Table1

Date Time

20090801 060000
20090802 162000

Date Format: yyyymmdd
Time Format: HHMMSS

Date & Time Column Datatype is varchar

When i select a Date in a Datetimepicker and modify the time.  The should update in the table.

Expected Output

01-08-2009 (DatetimePicker value)
080000 (Textbox value)

The Above value should update in the table

How to make a code for the above condition.

Need code help.

Body:
Try something like this.

Dim strDateTime as string

strDateTime = Format$(DateTimePicker.Value, "MMDDYYYY mmhhss")

Update our the database with a recordset

rs.Fields["DateTimeField"] = strDateTime
rs.Update'

I hope this points you in the right direction


问:
How to generate a jar file for the java program which has property file
How to generate a jar file for the java program which has property file</p>
```<code>public class Download_logfiles {
/**
 * Download_logfiles class has to be public because another class uses the
 * Download_logfiles class
 */

private static URL URLObj;
/**
 * variable set for the server links from which the log files to be
 * downloaded
 */
private static URLConnection connect;
/** Variable for URL connection */
static String filename = "";
/** Variable used for extracting the servers */
static String user = "";
/** Variable used for user id */
static String pass = "";
/** Variable used for password */

static String download = "";
static Set<String> urls = new HashSet<String>();
static Set<String> comp = new HashSet<String>();
static Set<String> envir = new HashSet<String>();
static Properties prop = new Properties();

public static void main(String[] args)
        throws IOException { /** program entry point */

    System.out.println("argument count:" + args.length + " content:" + args);

    if(args.length==0)
    {
        System.out.println("Please enter the property file via arguments!!!");   /**Go to run configuration and under arguments enter the path **/
        System.exit(0);
    }

    readConfigProperties(args[0]);
    configUIParameter();
    Hashtable<String, String> loginfo = Validation();
    String componentavx = loginfo
            .get("component"); /** extract component information */
    String environmentProd = loginfo
            .get("environment"); /** extract environment information */
    config(componentavx, environmentProd);
    user = loginfo.get(
            "user"); /** extract login information from the property file */
    pass = loginfo.get("pass");

    try { /** Usage of Try catch handlers */
        String currentURL;
        Iterator<String> iter = urls.iterator();
        System.out.println(iter);

        while (iter.hasNext()) { /** Start iterating over URLs */

            currentURL = iter.next();
            StringTokenizer st = new StringTokenizer(currentURL,
                    "/."); /**
                             * The string tokenizer class allows an
                             * application to break a string into tokens
                             */
            st.nextToken();
            String filePrefix = st.nextToken();
            System.out.println("Url: " + currentURL);

            boolean moreFilesAvailable = true; /**
                                                 * check condition for all
                                                 * log files available in
                                                 * the server
                                                 */

            for (int i = 0; moreFilesAvailable; i++) {

                File file = null;

                if (i != 0) { /** Handle the condition */
                    URLObj = new URL(currentURL + filename + "." + i);

                } else {
                    URLObj = new URL(currentURL + filename);

                }
</code>```

答:
You need to pass the path to your file properties into a jvm using -D

```<code>-Dname=$pathto yourjar anyargs..
</code>```

you can get it in your application likethis :

```<code>String location = System.getProperty(name);
</code>```

Body:
How to generate a jar file for the java program which has property file

public class Download_logfiles {
/**
 * Download_logfiles class has to be public because another class uses the
 * Download_logfiles class
 */

private static URL URLObj;
/**
 * variable set for the server links from which the log files to be
 * downloaded
 */
private static URLConnection connect;
/** Variable for URL connection */
static String filename = "";
/** Variable used for extracting the servers */
static String user = "";
/** Variable used for user id */
static String pass = "";
/** Variable used for password */

static String download = "";
static Set<String> urls = new HashSet<String>();
static Set<String> comp = new HashSet<String>();
static Set<String> envir = new HashSet<String>();
static Properties prop = new Properties();

public static void main(String[] args)
        throws IOException { /** program entry point */

    System.out.println("argument count:" + args.length + " content:" + args);

    if(args.length==0)
    {
        System.out.println("Please enter the property file via arguments!!!");   /**Go to run configuration and under arguments enter the path **/
        System.exit(0);
    }

    readConfigProperties(args[0]);
    configUIParameter();
    Hashtable<String, String> loginfo = Validation();
    String componentavx = loginfo
            .get("component"); /** extract component information */
    String environmentProd = loginfo
            .get("environment"); /** extract environment information */
    config(componentavx, environmentProd);
    user = loginfo.get(
            "user"); /** extract login information from the property file */
    pass = loginfo.get("pass");

    try { /** Usage of Try catch handlers */
        String currentURL;
        Iterator<String> iter = urls.iterator();
        System.out.println(iter);

        while (iter.hasNext()) { /** Start iterating over URLs */

            currentURL = iter.next();
            StringTokenizer st = new StringTokenizer(currentURL,
                    "/."); /**
                             * The string tokenizer class allows an
                             * application to break a string into tokens
                             */
            st.nextToken();
            String filePrefix = st.nextToken();
            System.out.println("Url: " + currentURL);

            boolean moreFilesAvailable = true; /**
                                                 * check condition for all
                                                 * log files available in
                                                 * the server
                                                 */

            for (int i = 0; moreFilesAvailable; i++) {

                File file = null;

                if (i != 0) { /** Handle the condition */
                    URLObj = new URL(currentURL + filename + "." + i);

                } else {
                    URLObj = new URL(currentURL + filename);

                }

Body:
You need to pass the path to your file properties into a jvm using -D

-Dname=$pathto yourjar anyargs..

you can get it in your application likethis :

String location = System.getProperty(name);