问:
Cant' get WinAppDriver working with appium 1.6.3
I am trying to run a simple test of launching a calculator app on windows 10 64bit, I have got appium@1.6.3 installed. As per the doc with installation of appium, winappdriver will also be installed. However when I try to run my test, I see below error, which complains about winappdriver not installed.

```<code>C:\WINDOWS\system32>appium
[Appium] Welcome to Appium v1.6.3
[Appium] Appium REST http interface listener started on 0.0.0.0:4723
[HTTP] --> POST /wd/hub/session {"desiredCapabilities":{"app":"Microsoft.WindowsCalculator_8wekyb3d8bbwe!App","platformName":"Windows","deviceName":"WindowsPC"}}
[debug] [MJSONWP] Calling AppiumDriver.createSession() with args: [{"app":"Microsoft.WindowsCalculator_8wekyb3d8bbwe!App","platformName":"Windows","deviceName":"WindowsPC"},null,null,null,null]
[Appium] Creating new WindowsDriver session
[Appium] Capabilities:
[Appium]   app: 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App'
[Appium]   platformName: 'Windows'
[Appium]   deviceName: 'WindowsPC'
[BaseDriver] The following capabilities were provided, but are not recognized by appium: app.
[BaseDriver] Session created with session id: c0c6c7e6-b782-4b14-8192-bc78e5b38008
[WinAppDriver] Verifying WinAppDriver is installed with correct checksum
[HTTP] <-- POST /wd/hub/session - - ms - -
[debug] [WinAppDriver] Deleting WinAppDriver session
[MJSONWP] Encountered internal error running command: Error: Could not verify WinAppDriver install; re-run install
    at WinAppDriver.start$ (../../lib/winappdriver.js:35:13)
    at tryCatch (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:67:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:315:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:100:21)
    at GeneratorFunctionPrototype.invoke (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:136:37)
</code>```

Also attaching my test script:

```<code>var wd = require("wd");
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var should = chai.should();
//enable chai assertion chaining
chaiAsPromised.transferPromiseness = wd.transferPromiseness;

var serverConfig = {
    host:'127.0.0.1',
    port:4723,

};

var capabilities = {
    app:'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App',
    platformName:'Windows',
    deviceName:'WindowsPC'
};

var driver;

describe('test calculator',function(){
it('test launch calculator',function(done){

  driver = wd.promiseChainRemote(serverConfig);
  console.log(driver)
  this.timeout(10000);
    var cap=driver.init(capabilities);
    console.log(cap)
         done();
})
});
</code>```

答:
I noticed that the version of appium and the windows driver have a tight dependency. When installing appium via the desktop app, it won't work. You get the wrong version.

While installing, it downloads the windows driver in your appdata/temp folder. You should remove it.

When installing appium via nmp it will work better, this one downloads the correct windows driver.

When you didn't remove the temp folder download also this one will fail, because it takes that windows driver...

Body:
I am trying to run a simple test of launching a calculator app on windows 10 64bit, I have got appium@1.6.3 installed. As per the doc with installation of appium, winappdriver will also be installed. However when I try to run my test, I see below error, which complains about winappdriver not installed.

C:\WINDOWS\system32>appium
[Appium] Welcome to Appium v1.6.3
[Appium] Appium REST http interface listener started on 0.0.0.0:4723
[HTTP] --> POST /wd/hub/session {"desiredCapabilities":{"app":"Microsoft.WindowsCalculator_8wekyb3d8bbwe!App","platformName":"Windows","deviceName":"WindowsPC"}}
[debug] [MJSONWP] Calling AppiumDriver.createSession() with args: [{"app":"Microsoft.WindowsCalculator_8wekyb3d8bbwe!App","platformName":"Windows","deviceName":"WindowsPC"},null,null,null,null]
[Appium] Creating new WindowsDriver session
[Appium] Capabilities:
[Appium]   app: 'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App'
[Appium]   platformName: 'Windows'
[Appium]   deviceName: 'WindowsPC'
[BaseDriver] The following capabilities were provided, but are not recognized by appium: app.
[BaseDriver] Session created with session id: c0c6c7e6-b782-4b14-8192-bc78e5b38008
[WinAppDriver] Verifying WinAppDriver is installed with correct checksum
[HTTP] <-- POST /wd/hub/session - - ms - -
[debug] [WinAppDriver] Deleting WinAppDriver session
[MJSONWP] Encountered internal error running command: Error: Could not verify WinAppDriver install; re-run install
    at WinAppDriver.start$ (../../lib/winappdriver.js:35:13)
    at tryCatch (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:67:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:315:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:100:21)
    at GeneratorFunctionPrototype.invoke (C:\Users\bhawsar\AppData\Roaming\npm\node_modules\appium\node_modules\babel-runtime\regenerator\runtime.js:136:37)

Also attaching my test script:

var wd = require("wd");
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var should = chai.should();
//enable chai assertion chaining
chaiAsPromised.transferPromiseness = wd.transferPromiseness;

var serverConfig = {
    host:'127.0.0.1',
    port:4723,

};

var capabilities = {
    app:'Microsoft.WindowsCalculator_8wekyb3d8bbwe!App',
    platformName:'Windows',
    deviceName:'WindowsPC'
};

var driver;

describe('test calculator',function(){
it('test launch calculator',function(done){

  driver = wd.promiseChainRemote(serverConfig);
  console.log(driver)
  this.timeout(10000);
    var cap=driver.init(capabilities);
    console.log(cap)
         done();
})
});


来源: stackexchange

问:
Undefined method for <variable>_cont in spree - Ruby on Rails
I am trying to do a search in the spree backend in reviews listing page.
But am getting undefined method error for the fields. Eg: undefined method title_cont' , undefined methodreview _cont'.

Hereby am posting my controller:

reviews_controller.rb

```<code>class Spree::Admin::ReviewsController < Spree::Admin::ResourceController
      helper Spree::ReviewsHelper

     def index
     @reviews = Spree::Review.ransack(params[:q]).result
     end

      def approve
      r = Spree::Review.find(params[:id])

      if r.update_attribute(:approved, true)
      flash[:notice] = Spree.t("info_approve_review")
      else
      flash[:error] = Spree.t("error_approve_review")
      end
      redirect_to admin_reviews_path
      end

      def edit
      if @review.product.nil?
      flash[:error] = Spree.t("error_no_product")
      redirect_to admin_reviews_path and return
      end
      end

      private

      def collection
      params[:q] ||= {}
      @search = Spree::Review.ransack(params[:q])
      @collection = @search.result.includes([:product, :user, :feedback_reviews]).page(params[:page]).per(params[:per_page])
      end
      end
</code>```

Model File : review.rb

```<code>class Spree::Review < ActiveRecord::Base

      belongs_to :product, touch: true
      belongs_to :user, :class_name => Spree.user_class.to_s
      has_many   :feedback_reviews

      after_save :recalculate_product_rating, :if => :approved?
      after_destroy :recalculate_product_rating

      validates :name, presence: true
      validates :review, presence: true

      validates :rating, numericality: { only_integer: true,
      greater_than_or_equal_to: 1,
      less_than_or_equal_to: 5,
      message: Spree.t('you_must_enter_value_for_rating') }

      default_scope { order("spree_reviews.created_at DESC") }

      scope :localized, ->(lc) { where('spree_reviews.locale = ?', lc) }
      scope :most_recent_first, -> { order('spree_reviews.created_at DESC') }
      scope :oldest_first, -> { reorder('spree_reviews.created_at ASC') }
      scope :preview, -> { limit(Spree::Reviews::Config[:preview_size]).oldest_first }
      scope :approved, -> { where(approved: true) }
      scope :not_approved, -> { where(approved: false) }
      scope :default_approval_filter, -> { Spree::Reviews::Config[:include_unapproved_reviews] ? all : approved }

      def feedback_stars
      return 0 if feedback_reviews.size <= 0
      ((feedback_reviews.sum(:rating) / feedback_reviews.size) + 0.5).floor
      end

      def set_search
      @search=Product.search(params[:q])
      end

      def recalculate_product_rating
      self.product.recalculate_rating if product.present?
      end
      end
</code>```

Index.html.erb

```<code><% content_for :table_filter do %>
<div data-hook="admin_reviews_index_search">
 <%= search_form_for [:admin, @search] do |f| %>
 <div class="alpha three columns">
    <div class="field">
    <%= label_tag nil, Spree.t(:user) %><br />
    <%= f.text_field :name_cont,:size => 25 %>
    </div>
</div>
<div class="four columns">
    <div class="field">
        <%= label_tag nil, Spree.t(:title) -%><br/>
        <%= f.text_field :title_cont, :size => 25%>
    </div>
</div>
<div class="four columns">
    <div class="field">
        <%= label_tag nil, Spree.t(:review) -%><br/>
        <%= f.text_field :review_cont, :size => 25 ,:value => ""%>
    </div>
</div>
<div class="two columns omega">

</div>

    <div class="clear"></div>

    <div class="form-buttons actions filter-actions" data-hook="admin_reviews_index_search_buttons">
        <%= button Spree.t(:search), 'icon-search' %>
    </div>
<%- end -%>
</code>```

Getting undefined when i use the above mentioned variables. Please help me to solve this.

答:
@cliffs - To be able to search by using ransack gem, you will first have to whitelist all those fields on which you wanna perform the search. So in your review.rb model add the following line if you are inheriting it from Spree::Base -

self.whitelisted_ransackable_attributes = %w[title, review]

else if you are inheriting it from ActiveRecord::Base you have to define ransackable_attributes as a class method

```<code>def self.ransackable_attributes(auth_object = nil)
    ['title','review','user']
end
</code>```

and now try to search using ransack.

Hope this helps you.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to do a search in the spree backend in reviews listing page.
But am getting undefined method error for the fields. Eg: undefined method title_cont' , undefined methodreview _cont'.

Hereby am posting my controller:

reviews_controller.rb

class Spree::Admin::ReviewsController < Spree::Admin::ResourceController
      helper Spree::ReviewsHelper

     def index
     @reviews = Spree::Review.ransack(params[:q]).result
     end

      def approve
      r = Spree::Review.find(params[:id])

      if r.update_attribute(:approved, true)
      flash[:notice] = Spree.t("info_approve_review")
      else
      flash[:error] = Spree.t("error_approve_review")
      end
      redirect_to admin_reviews_path
      end

      def edit
      if @review.product.nil?
      flash[:error] = Spree.t("error_no_product")
      redirect_to admin_reviews_path and return
      end
      end

      private

      def collection
      params[:q] ||= {}
      @search = Spree::Review.ransack(params[:q])
      @collection = @search.result.includes([:product, :user, :feedback_reviews]).page(params[:page]).per(params[:per_page])
      end
      end

Model File : review.rb

class Spree::Review < ActiveRecord::Base

      belongs_to :product, touch: true
      belongs_to :user, :class_name => Spree.user_class.to_s
      has_many   :feedback_reviews

      after_save :recalculate_product_rating, :if => :approved?
      after_destroy :recalculate_product_rating

      validates :name, presence: true
      validates :review, presence: true

      validates :rating, numericality: { only_integer: true,
      greater_than_or_equal_to: 1,
      less_than_or_equal_to: 5,
      message: Spree.t('you_must_enter_value_for_rating') }

      default_scope { order("spree_reviews.created_at DESC") }

      scope :localized, ->(lc) { where('spree_reviews.locale = ?', lc) }
      scope :most_recent_first, -> { order('spree_reviews.created_at DESC') }
      scope :oldest_first, -> { reorder('spree_reviews.created_at ASC') }
      scope :preview, -> { limit(Spree::Reviews::Config[:preview_size]).oldest_first }
      scope :approved, -> { where(approved: true) }
      scope :not_approved, -> { where(approved: false) }
      scope :default_approval_filter, -> { Spree::Reviews::Config[:include_unapproved_reviews] ? all : approved }

      def feedback_stars
      return 0 if feedback_reviews.size <= 0
      ((feedback_reviews.sum(:rating) / feedback_reviews.size) + 0.5).floor
      end

      def set_search
      @search=Product.search(params[:q])
      end

      def recalculate_product_rating
      self.product.recalculate_rating if product.present?
      end
      end

Index.html.erb

<% content_for :table_filter do %>

 <%= search_form_for [:admin, @search] do |f| %>

    <%= label_tag nil, Spree.t(:user) %>

    <%= f.text_field :name_cont,:size => 25 %>

        <%= label_tag nil, Spree.t(:title) -%>

        <%= f.text_field :title_cont, :size => 25%>

        <%= label_tag nil, Spree.t(:review) -%>

        <%= f.text_field :review_cont, :size => 25 ,:value => ""%>

        <%= button Spree.t(:search), 'icon-search' %>

<%- end -%>

Getting undefined when i use the above mentioned variables. Please help me to solve this.

Body:
@cliffs - To be able to search by using ransack gem, you will first have to whitelist all those fields on which you wanna perform the search. So in your review.rb model add the following line if you are inheriting it from Spree::Base -

self.whitelisted_ransackable_attributes = %w[title, review]

else if you are inheriting it from ActiveRecord::Base you have to define ransackable_attributes as a class method

def self.ransackable_attributes(auth_object = nil)
    ['title','review','user']
end

and now try to search using ransack.

Hope this helps you.


问:
What is impression CTR, Request RPM, Impression RPM in admob

I'm not getting this Impression CTR , Request RPM, Impression RPM.
how this all is calculated? and what should I do for more estimated earnings.

does higher CTR increase earnings?
will constantly showing ad in app (more impressions) will increase earnings?

答: Most General questions that everyone is wants to know on how much download, the revenue would come . its all about ad mob ads show policy, the business market around the world generate account on ad mob as advertiser and developer as a publisher, advertiser gives their ads to ad mob in banner , interstitial form,rewarded video as they wants to promote their goods in different countries, and select price to show ,number of countries, and paid is detected on these basis , (more in plus given in ad mob policies) ads are showing on these basis that are promoted by advertiser for a specific territoriality, google takes money from advertiser and take the little percentage and then giving to publisher for ads monetizing means to developer, if the ads impression rate is high you will get more revenue.</p>


问:
possible all combinations of list of length n in python without itertools
How can i get all possible combinations of list of length n in python i have written a code for string but list i am not able to do can any one help me.

```<code>def combo(w, l):
    lst = []
    for i in range(len(w)):
        if l == 1:
            lst.append(w[i])
        for c in combo(w[i+1:], l-1):
            lst.append(w[i] + c)
    return lst

comb=map(list,combo('12345',3))
</code>```

above code is to get the combinations of string it gives correct output:

```<code>['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']
</code>```

Body:
How can i get all possible combinations of list of length n in python i have written a code for string but list i am not able to do can any one help me.

def combo(w, l):
    lst = []
    for i in range(len(w)):
        if l == 1:
            lst.append(w[i])
        for c in combo(w[i+1:], l-1):
            lst.append(w[i] + c)
    return lst

comb=map(list,combo('12345',3))

above code is to get the combinations of string it gives correct output:

['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']

Body:
You can also just use itertools.combinations:

>>> import itertools

>>> print(["".join(x) for x in itertools.combinations('12345', 2)])
['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']

>>> print([list(x) for x in itertools.combinations(['1', '2', '3', '4', '5'], 2)])
[['1', '2'], ['1', '3'], ['1', '4'], ['1', '5'], ['2', '3'], ['2', '4'], ['2', '5'], ['3', '4'], ['3', '5'], ['4', '5']]

>>> print(["".join(x) for x in itertools.combinations(['1', '2', '3', '4', '5'], 2)])
['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']


问:
POST data is not being passed to other view controller
I am running into a small problem with my project. I am new to iOS development, and I am running into a slight problem trying to pass some data that I have pulled out of a response body in JSON format. I am able to print out the correct data from the server right after I assign it to a variable in the class, but once I prepare and perform a segue, it doesn't seem to pass over. Here is my first viewController:

```<code>import UIKit
import SwiftyJSON

class ViewController: UIViewController {
    @IBOutlet weak var emailAddress: UITextField!
    @IBOutlet weak var userPassword: UITextField!
    var returned_email: String!
    var returned_pass: String!
    var current_exp: Int!
    var needed_exp: Int!

    @IBAction func getUserDataBtn(_ sender: Any) {
        if emailAddress.text != "" && userPassword.text != ""
        {
            let session = URLSession.shared
            let parameters = ["nameValuePairs":["username": emailAddress.text, "password": userPassword.text]]
            guard let myURL = URL(string: "<protected url>") else {return}
            var request = URLRequest(url: myURL, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 300.0)

            request.httpMethod = "POST"
            guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {return}
            request.httpBody = httpBody
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")

            session.dataTask(with: request, completionHandler: { (data, response, error) in
                if let myData = data{
                    do{
                        let json = try JSONSerialization.jsonObject(with: myData, options: .mutableContainers) as! [String:Any]
                        self.returned_email = json["username"] as! String
                        self.returned_pass = json["password"] as! String
                        self.current_exp = json["curr_exp"] as! Int
                        self.needed_exp = json["needed_exp"] as! Int
                    }
                    catch{
                        print(error)
                    }
                    self.performSegue(withIdentifier: "GetUserDataSegue", sender: self)
                }
            }).resume()
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if(segue.identifier == "GetUserDataSegue"){
            guard let viewController = segue.destination as? UserDataController else {return}
            viewController.myUN = returned_email
            viewController.myPW = returned_pass
            viewController.myCurrExp = current_exp
            viewController.myNeedExp = needed_exp
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        }
}
</code>```

Here is my other viewcontroller:

```<code>import UIKit

class UserDataController: UIViewController {
    var myUN: String!
    var myPW: String!
    var myCurrExp: Int!
    var myNeedExp: Int!

    @IBOutlet weak var password: UILabel!
    @IBOutlet weak var username: UILabel!
    @IBOutlet weak var current_exp: UILabel!
    @IBOutlet weak var needed_exp: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        username.text = myUN
        password.text = myPW
        current_exp.text = String(describing: myCurrExp)
        needed_exp.text = String(describing: myNeedExp)
        // Do any additional setup after loading the view.
    }
}
</code>```

What I am trying to accomplish with this test project is to have a person enter in their username and password, hit "get user data" button, be taken to the second viewcontroller with all of their information displayed in the provided labels. I am able to get the correct data from the database on the server, and I am able to receive it and save it to the local variables in the first viewcontroller. Any help would be appreciated! I am using Swift 4 and Xcode 9, if that has any impact on answers.

Thank you for your time!

答:
Once I started running break points in my code, I found out that once I leave the closure of the session, my class variables are not stored any more. I'm not sure what is causing that to happen

That sounds a lot like a case of mistaken identity, i.e. you somehow have two instances of ViewController, and the one initiating the segue isn't the one that's the source view controller in the segue. Since you're already passing self for the sender parameter in your call to performSegue(withIdentifier:sender:), check to see if sender == self in prepare(for:sender:).

Body:
I am running into a small problem with my project. I am new to iOS development, and I am running into a slight problem trying to pass some data that I have pulled out of a response body in JSON format. I am able to print out the correct data from the server right after I assign it to a variable in the class, but once I prepare and perform a segue, it doesn't seem to pass over. Here is my first viewController:

import UIKit
import SwiftyJSON

class ViewController: UIViewController {
    @IBOutlet weak var emailAddress: UITextField!
    @IBOutlet weak var userPassword: UITextField!
    var returned_email: String!
    var returned_pass: String!
    var current_exp: Int!
    var needed_exp: Int!

    @IBAction func getUserDataBtn(_ sender: Any) {
        if emailAddress.text != "" && userPassword.text != ""
        {
            let session = URLSession.shared
            let parameters = ["nameValuePairs":["username": emailAddress.text, "password": userPassword.text]]
            guard let myURL = URL(string: "<protected url>") else {return}
            var request = URLRequest(url: myURL, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 300.0)

            request.httpMethod = "POST"
            guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {return}
            request.httpBody = httpBody
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")

            session.dataTask(with: request, completionHandler: { (data, response, error) in
                if let myData = data{
                    do{
                        let json = try JSONSerialization.jsonObject(with: myData, options: .mutableContainers) as! [String:Any]
                        self.returned_email = json["username"] as! String
                        self.returned_pass = json["password"] as! String
                        self.current_exp = json["curr_exp"] as! Int
                        self.needed_exp = json["needed_exp"] as! Int
                    }
                    catch{
                        print(error)
                    }
                    self.performSegue(withIdentifier: "GetUserDataSegue", sender: self)
                }
            }).resume()
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if(segue.identifier == "GetUserDataSegue"){
            guard let viewController = segue.destination as? UserDataController else {return}
            viewController.myUN = returned_email
            viewController.myPW = returned_pass
            viewController.myCurrExp = current_exp
            viewController.myNeedExp = needed_exp
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        }
}

Here is my other viewcontroller:

import UIKit

class UserDataController: UIViewController {
    var myUN: String!
    var myPW: String!
    var myCurrExp: Int!
    var myNeedExp: Int!

    @IBOutlet weak var password: UILabel!
    @IBOutlet weak var username: UILabel!
    @IBOutlet weak var current_exp: UILabel!
    @IBOutlet weak var needed_exp: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        username.text = myUN
        password.text = myPW
        current_exp.text = String(describing: myCurrExp)
        needed_exp.text = String(describing: myNeedExp)
        // Do any additional setup after loading the view.
    }
}

What I am trying to accomplish with this test project is to have a person enter in their username and password, hit "get user data" button, be taken to the second viewcontroller with all of their information displayed in the provided labels. I am able to get the correct data from the database on the server, and I am able to receive it and save it to the local variables in the first viewcontroller. Any help would be appreciated! I am using Swift 4 and Xcode 9, if that has any impact on answers.

Thank you for your time!


问:
How will closures in Java enable API design to replace language design?
I can see some of the benefits of closures, such as how they can have their place in simplifying existing libraries and making some future design easier and more efficient.

However, one of the key points mentioned in the draft proposal (http://www.javac.info/consensus-closures-jsr.html) is in section 2.5, point e:

(The specification will improve the language by)

e) enabling future API design to replace language design for extending the Java platform.

I'm struggling to see how this is the case, surely language design is just that - the design of the language itself, and can't be replaced by an API unless Java opens up all sorts of weird APIs using closures for modifying the language (which I highly doubt will happen.)

Can anyone shed some light on this and perhaps provide an example of something that required a language change previously but, with the addition of closures, no longer requires one?

答:
For anyone who hasn't read the draft proposal, here is a little more detail from later in the same document:

The addition of closures simplifies the evolution of the Java platform. Many existing language RFEs in Sun's public bug database can retargeted as API requests for methods that receive closures. Many future needs for additional statement forms can instead be met by the addition of library methods.

ContentLicense: CC BY-SA 2.5


问:
how to replace part of a string with a double c++
I have been searching on stack overflow and the web and cannot seem to find an answer to my question.

How do you replace part of a string with a variable

Example: I want to replace the "#N" at the end of this string with the variable 'number'.

First Attempt:

```<code>string firstline= "will find the answer in Chapter #N.";
firstline.replace(firstline.begin(),firstline,end(),"#N",number);
</code>```

turns out the replace function doesn't allow you to pass those as variables.

Second Attempt:

I found a youtube tutorial that changed part of a string with another string.

```<code>string replace_all(string str, const string &from, const string &to)
{
int pos=0;
int flen= from.length();
int tlen = to.length();
while((pos= str.find(from,pos)) != -1)
{
   str.replace(pos,flen,to);
   pos += tlen;
}
return str;
}

int main()
{
char str[] = "will find the answer in Chapter #N."
cout<< replace_all(str, "we", "you");
return 0;
}
</code>```

Made some changes to have the 3rd parameter be a double, but I'm still unable to get anywhere with it.

Any help to get me to the correct answer would be greatly appreciated.

EDIT:
   @sneha made the suggestion that I change the variable to a string using to_string()

I did that suggestion and my code can now compile, however I'm unable to successfully change the string.  The output is still "will find the answer in Chapter #N."

```<code>int main()
{
double number =20;
char str[] = "will find the answer in Chapter #N."
cout<< replace_all(str, "we", to_string(number));
return 0;
}

string replace_all(string str, const string &from, const string &to)
{
int pos=0;
int flen= from.length();
int tlen = to.length();
while((pos= str.find(from,pos)) != -1)
{
   str.replace(pos,flen,to);
   pos += tlen;
}
return str;
}
</code>```

答:
```<code>#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
    string firstline= "will find the answer in Chapter #N.";
    if(firstline.find("#N") != string::npos)
        firstline.replace(firstline.find("#N"), string("#N").size(), to_string(5));
    cout<<firstline<<endl;
    // will find the answer in Chapter 5.
    return 0;
}
</code>```

Body:
I have been searching on stack overflow and the web and cannot seem to find an answer to my question.

How do you replace part of a string with a variable

Example: I want to replace the "#N" at the end of this string with the variable 'number'.

First Attempt:

string firstline= "will find the answer in Chapter #N.";
firstline.replace(firstline.begin(),firstline,end(),"#N",number);

turns out the replace function doesn't allow you to pass those as variables.

Second Attempt:

I found a youtube tutorial that changed part of a string with another string.

string replace_all(string str, const string &from, const string &to)
{
int pos=0;
int flen= from.length();
int tlen = to.length();
while((pos= str.find(from,pos)) != -1)
{
   str.replace(pos,flen,to);
   pos += tlen;
}
return str;
}

int main()
{
char str[] = "will find the answer in Chapter #N."
cout<< replace_all(str, "we", "you");
return 0;
}

Made some changes to have the 3rd parameter be a double, but I'm still unable to get anywhere with it.

Any help to get me to the correct answer would be greatly appreciated.

EDIT:
   @sneha made the suggestion that I change the variable to a string using to_string()

I did that suggestion and my code can now compile, however I'm unable to successfully change the string.  The output is still "will find the answer in Chapter #N."

int main()
{
double number =20;
char str[] = "will find the answer in Chapter #N."
cout<< replace_all(str, "we", to_string(number));
return 0;
}

string replace_all(string str, const string &from, const string &to)
{
int pos=0;
int flen= from.length();
int tlen = to.length();
while((pos= str.find(from,pos)) != -1)
{
   str.replace(pos,flen,to);
   pos += tlen;
}
return str;
}


问:
SQL Query to query data hierarchically in the same table
I have the following table, which has a list of subjects and objects related with the same relationship.

```
    |---------------------------------------|
    |Subject    |Relationship    |Object    |
    |---------------------------------------|
    |A          |x               |B         |
    |B          |x               |C         |
    |B          |x               |D         |
    |C          |x               |E         |
    |D          |x               |F         |
    |P          |x               |G         |
    |---------------------------------------|
```

My need is to write a SQL to get all the related Subjects and Objects given an initial subject.

For example:

If "C" is given as the initial subject, output should be "C" and "E" (because "C" related to "E" with "x")

If "A" is given as the initial subject, output should be "A", "B", "C", "D", "E" and "F". Explanation,

"A" is related to "B"

"B" is related to "C" and "D"

"C" is related to "E"

"D" is related to "F"

答:
SAP HANA doesn't support general recursive common table expressions (CTEs).
Instead, for one very common use case like this one (hierarchy processing), a specific set of functions is available (with HANA 2 SP2):

```<code>with h as (SELECT * FROM HIERARCHY (
            SOURCE (select "Subject" as parent_id,
                            "Object" as node_id
                    from rels
                    order by "Subject" asc)
            ORPHAN ROOT ))
SELECT
     node_id
FROM
    HIERARCHY_DESCENDANTS (
         SOURCE h
         START WHERE parent_id ='A');
</code>```

With the HIERARCHY function HANA creates a hierarchy data structure from your input data. I named your table rels in this example.
The SOURCE part declares how the source table/view shall be interpreted to make up a hierarchy. ORPHAN ROOT declares that nodes that are not connected to another node are made "root" nodes. That is to say, that hierarchies don't have to be proper cycle free trees, but can have orphan nodes as well as multiple roots and cycles.

This hierarchy construction is captured in the common table expression h, but could also be put into a view or materialised into a (temporary) table.

The next step is using the HIERARCHY_DESCENDANTS function to have HANA "walk down" the hierarchy branch starting with the 'A' node.
This results in

```<code>NODE_ID
B
C
E
D
F
</code>```

The starting node can be "unioned" to the result set if necessary.

More details on the hierarchy functionality can be found in the HANA documentation here

Body:
I have the following table, which has a list of subjects and objects related with the same relationship.

    |---------------------------------------|
    |Subject    |Relationship    |Object    |
    |---------------------------------------|
    |A          |x               |B         |
    |B          |x               |C         |
    |B          |x               |D         |
    |C          |x               |E         |
    |D          |x               |F         |
    |P          |x               |G         |
    |---------------------------------------|

My need is to write a SQL to get all the related Subjects and Objects given an initial subject.

For example:

If "C" is given as the initial subject, output should be "C" and "E" (because "C" related to "E" with "x")

If "A" is given as the initial subject, output should be "A", "B", "C", "D", "E" and "F". Explanation,

"A" is related to "B"

"B" is related to "C" and "D"

"C" is related to "E"

"D" is related to "F"

Body:
SAP HANA doesn't support general recursive common table expressions (CTEs).
Instead, for one very common use case like this one (hierarchy processing), a specific set of functions is available (with HANA 2 SP2):

with h as (SELECT * FROM HIERARCHY (
            SOURCE (select "Subject" as parent_id,
                            "Object" as node_id
                    from rels
                    order by "Subject" asc)
            ORPHAN ROOT ))
SELECT
     node_id
FROM
    HIERARCHY_DESCENDANTS (
         SOURCE h
         START WHERE parent_id ='A');

With the HIERARCHY function HANA creates a hierarchy data structure from your input data. I named your table rels in this example.
The SOURCE part declares how the source table/view shall be interpreted to make up a hierarchy. ORPHAN ROOT declares that nodes that are not connected to another node are made "root" nodes. That is to say, that hierarchies don't have to be proper cycle free trees, but can have orphan nodes as well as multiple roots and cycles.

This hierarchy construction is captured in the common table expression h, but could also be put into a view or materialised into a (temporary) table.

The next step is using the HIERARCHY_DESCENDANTS function to have HANA "walk down" the hierarchy branch starting with the 'A' node.
This results in

NODE_ID
B
C
E
D
F

The starting node can be "unioned" to the result set if necessary.

More details on the hierarchy functionality can be found in the HANA documentation here


答:
```<code>#include <iostream>
#include <string>
using namespace std;

void Replace(string& s, double v) {
    auto it = s.find("#N");
    if (it != string::npos) s.replace(it, 2, to_string(v));
}

int main() {
    string firstline = "will find the answer in Chapter #N.";
    Replace(firstline, 12.35);
    cout << firstline << endl;
    return 0;
}
</code>```

Title: how to replace part of a string with a double c++


答:
Change the double variable to string using

```<code>    std::to_string(c1)
</code>```

Then replace the string with it

EDIT:

```<code>string replace_all(string str, const string &from, const string &to) {
int flen= from.length();
auto val = str.find("#N");
if (val != string::npos) str.replace(val, flen, to);
return str;
}
</code>```

Here npos means no position- string not found.
Hope this helps.

Body:
Change the double variable to string using

    std::to_string(c1)

Then replace the string with it

EDIT:

string replace_all(string str, const string &from, const string &to) {
int flen= from.length();
auto val = str.find("#N");
if (val != string::npos) str.replace(val, flen, to);
return str;
}

Here npos means no position- string not found.
Hope this helps.


问:
How to make Fixed objects
I have 2 objects left is without Rigidbody and right is with Rigidbody(is Kinematic=false).I can pass through the left one and the right one I can move.How to make in order that the character doesn't pass and move the objects?

Without Rigidbody

With Rigidbody

Character

```<code>using System.Collections;
using UnityEngine;

public class Person_controller : MonoBehaviour {
    public float rotationPeriod = 0.3f;
    public float sideLength = 1f;

    bool isRotate = false;
    float directionX = 0;
    float directionZ = 0;

    Vector3 startPos;
    float rotationTime = 0;
    float radius;
    Quaternion fromRotation;
    Quaternion toRotation;

    void Start () {
        radius = sideLength * Mathf.Sqrt (2f) / 2f;
    }

    void Update () {
        float x = 0;
        float y = 0;

        x = Input.GetAxisRaw ("Horizontal");
        if (x == 0) {
            y = Input.GetAxisRaw ("Vertical");
        }

        if ((x != 0 || y != 0) && !isRotate) {
            directionX = y;
            directionZ = x;
            startPos = transform.position;
            fromRotation = transform.rotation;
            transform.Rotate (directionZ * 90, 0, directionX * 90,            Space.World);
            toRotation = transform.rotation;
            transform.rotation = fromRotation;
            rotationTime = 0;

            isRotate = true;
        }
    }

    void FixedUpdate() {

        if (isRotate) {

            rotationTime += Time.fixedDeltaTime;
            float ratio = Mathf.Lerp(0, 1, rotationTime / rotationPeriod);

            float thetaRad = Mathf.Lerp(0, Mathf.PI / 2f, ratio);
            float distanceX = (-directionX * radius * (Mathf.Cos (45f *    Mathf.Deg2Rad) - Mathf.Cos (45f * Mathf.Deg2Rad + thetaRad)))*sideLength;
            float distanceY = radius * (Mathf.Sin(45f * Mathf.Deg2Rad + thetaRad) - Mathf.Sin (45f * Mathf.Deg2Rad));
            float distanceZ = directionZ * radius * (Mathf.Cos (45f * Mathf.Deg2Rad) - Mathf.Cos (45f * Mathf.Deg2Rad + thetaRad));
            transform.position = new Vector3(startPos.x + distanceX, startPos.y + distanceY, startPos.z + distanceZ);

            transform.rotation = Quaternion.Lerp(fromRotation, toRotation,    ratio);

            if (ratio == 1) {
                isRotate = false;
                directionX = 0;
                directionZ = 0;
                rotationTime = 0;
            }
        }
    }
}
</code>```

答:
if isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore. The rigidbody will be under full control of animation or script control by changing transform.position

Title Chart of collision on the bottom of this page

ContentLicense: CC BY-SA 4.0

Title: How to make Fixed objects

Body:
I have 2 objects left is without Rigidbody and right is with Rigidbody(is Kinematic=false).I can pass through the left one and the right one I can move.How to make in order that the character doesn't pass and move the objects?

Without Rigidbody

With Rigidbody

Character

using System.Collections;
using UnityEngine;

public class Person_controller : MonoBehaviour {
    public float rotationPeriod = 0.3f;
    public float sideLength = 1f;

    bool isRotate = false;
    float directionX = 0;
    float directionZ = 0;

    Vector3 startPos;
    float rotationTime = 0;
    float radius;
    Quaternion fromRotation;
    Quaternion toRotation;

    void Start () {
        radius = sideLength * Mathf.Sqrt (2f) / 2f;
    }

    void Update () {
        float x = 0;
        float y = 0;

        x = Input.GetAxisRaw ("Horizontal");
        if (x == 0) {
            y = Input.GetAxisRaw ("Vertical");
        }

        if ((x != 0 || y != 0) && !isRotate) {
            directionX = y;
            directionZ = x;
            startPos = transform.position;
            fromRotation = transform.rotation;
            transform.Rotate (directionZ * 90, 0, directionX * 90,            Space.World);
            toRotation = transform.rotation;
            transform.rotation = fromRotation;
            rotationTime = 0;

            isRotate = true;
        }
    }

    void FixedUpdate() {

        if (isRotate) {

            rotationTime += Time.fixedDeltaTime;
            float ratio = Mathf.Lerp(0, 1, rotationTime / rotationPeriod);

            float thetaRad = Mathf.Lerp(0, Mathf.PI / 2f, ratio);
            float distanceX = (-directionX * radius * (Mathf.Cos (45f *    Mathf.Deg2Rad) - Mathf.Cos (45f * Mathf.Deg2Rad + thetaRad)))*sideLength;
            float distanceY = radius * (Mathf.Sin(45f * Mathf.Deg2Rad + thetaRad) - Mathf.Sin (45f * Mathf.Deg2Rad));
            float distanceZ = directionZ * radius * (Mathf.Cos (45f * Mathf.Deg2Rad) - Mathf.Cos (45f * Mathf.Deg2Rad + thetaRad));
            transform.position = new Vector3(startPos.x + distanceX, startPos.y + distanceY, startPos.z + distanceZ);

            transform.rotation = Quaternion.Lerp(fromRotation, toRotation,    ratio);

            if (ratio == 1) {
                isRotate = false;
                directionX = 0;
                directionZ = 0;
                rotationTime = 0;
            }
        }
    }
}


问:
Using Gsub to capture the first letter after a colon : and transform it into uppercase
I need to capture the first letter after the colon : and transform it into uppercase. My input is:

```<code>ID1423:Bellatorias obiri           18 Aug 2006
ID2533:Caretta caretta             16 Jul 2000
ID342:Cyclodomorphus praealtus     24 Dec 2009
ID8777:Dermochelys coriacea         8 Jan 2009
ID922:Egernia stokesii badia       16 Jul 2000
</code>```

The code I am using is reptiledata <- gsub("(\w)(\w+)", ":\U\1", reptile_data, perl = TRUE)

and I am getting an output like this:

```<code>> reptiledata
[1] "c(:1, :1, :2, 8, :1, :1, :1, :1, :1, :1, :1, :2, 4, :1, :1, :1)"
[2] "c(2, 6, 3, 5, 6, 6, 6, 6, 6, 6, 6, 4, 1, 2, 6, 6)"

etc...
</code>```

I need a generic gsub code that will transform many first letter characters after the colon into uppercase and not just the ones shown. Thanks for any help!

答:
Try using gsub in Perl mode with the uppercase replacement modififier \U:

```<code>gsub(":([A-Za-z])", ":\\U\\1", str, perl=TRUE)
</code>```

This will replace any colon followed by a single letter with a colon followed by the uppercase version of that letter.  We could make this pattern more specific if you find it firing on text which should not be modified.

Demo

Body:
I need to capture the first letter after the colon : and transform it into uppercase. My input is:

ID1423:Bellatorias obiri           18 Aug 2006
ID2533:Caretta caretta             16 Jul 2000
ID342:Cyclodomorphus praealtus     24 Dec 2009
ID8777:Dermochelys coriacea         8 Jan 2009
ID922:Egernia stokesii badia       16 Jul 2000

The code I am using is reptiledata <- gsub("(\w)(\w+)", ":\U\1", reptile_data, perl = TRUE)

and I am getting an output like this:

> reptiledata
[1] "c(:1, :1, :2, 8, :1, :1, :1, :1, :1, :1, :1, :2, 4, :1, :1, :1)"
[2] "c(2, 6, 3, 5, 6, 6, 6, 6, 6, 6, 6, 4, 1, 2, 6, 6)"

etc...

I need a generic gsub code that will transform many first letter characters after the colon into uppercase and not just the ones shown. Thanks for any help!

Body:
Try using gsub in Perl mode with the uppercase replacement modififier \U:

gsub(":([A-Za-z])", ":\\U\\1", str, perl=TRUE)

This will replace any colon followed by a single letter with a colon followed by the uppercase version of that letter.  We could make this pattern more specific if you find it firing on text which should not be modified.

Demo


问:
Drag&Drop and Duration change in anychart Gantt chart
I cannot figure out what to listen after, when using drag&drop or duration cahnge in an anychart Gantt chart

I get data from a json call and have the following code

```<code>chart = anychart.ganttResource();
chart.data(anychart.data.tree(data, 'asTable'));
var dataGrid = chart.dataGrid();
chart.editing(true);
</code>```

I'm locking at https://docs.anychart.com/Gantt_Chart/Live_Edit_UI_and_API in the documentation, but it doesnot say what to listen after.
I have tried to do

```<code>var tree = anychart.data.tree(data, 'asTable');
tree.listen("treeItemUpdate", function(e) {
              alert("test");
            });
</code>```

But the alert does not show.
EDIT:
I do get the alert, seems I had a typo in my code.

The drag&drop and duration change is working fine, but I need to store the changes in the DB, but as I wrote I cannot see what trickers it.

EDIT2:

I have changed the alert to show the information mentioned in the documentation, so I have

```<code>tree.listen("treeItemUpdate", function(e) {
                console.log(e);
              alert("test " + e.type + " " + e.item + " " + e.path + " " + e.field + " " + e.value + " " );
            });
</code>```

The alert gives something like this

```<code>test treeitemupdate [object Object] periods,2,start periods 1512574122684
test treeitemupdate [object Object] periods,2,end periods 1512583122684
</code>```

While the consolelog shows

```<code>Object { type: "treeitemupdate", target: {…}, c: {…}, f: false, l: false, yA: true, item: {…}, path: […], field: "periods", value: 1512405943770 }
</code>```

opening the item gives me this, but I cannot see how to work with this data

```<code>item: {…}
P: Object { b: {…}, P: null, f: […], … }
b: Object { yb: false, yj: undefined, ai: {…}, … }
c: Object { nc: true, depth: 1, index: 2, … }
f: Array []
g: Object { id: "270", rowHeight: 15, periods: […] }
h: Object {  }
__proto__: Object { get: g.get(), set: g.set(), Ve: g.Ve(), … }
</code>```

My chart looks like this
Gantt Chart

My json is like this

```<code>[{"id":"0",
"collapsed":false,
"rowHeight":15,
"userLevel":"0"
},{
"id":"4",
"collapsed":false,
"rowHeight":15,
"name":"(1 - jnb) Bjerre, Janine Nedergaard ",
"userLevel":"3"
},{
"id":"270",
"parent":"4",
"rowHeight":15,
"periods":[{
    "id":"270_2",
    "stoke":"none",
    "start":"1512370800000",
    "end":"1512464400000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"270"
    },{
    "id":"474_3",
    "stoke":"none",
    "start":"1512543600000",
    "end":"1512547200000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"474"
    },{
    "id":"140_6",
    "stoke":"none",
    "start":"1512548100000",
    "end":"1512743400000",
    "fill":"#DCE4EF",
    "personID":4,"id_task":"140"}]
},{
"id":"488",
"parent":"4",
"rowHeight":15,
"periods":[{"
    id":"488_4",
    "stoke":"none",
    "start":"1512543600000",
    "end":"1512547200000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"488"
    },{
    "id":"485_7",
    "stoke":"none",
    "start":"1512554400000",
    "end":"1512561600000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"485"
    },{
    "id":"247_8",
    "stoke":"none",
    "start":"1512564960000",
    "end":"1512568560000",
    "fill":"#FFFFFF",
    "personID":4,
    "id_task":"247"}]
},{
"id":"372",
"parent":"4",
"rowHeight":15,
"periods":[{
    "id":"372_5",
    "stoke":"none",
    "start":"1512547200000",
    "end":"1512556200000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"372"
    },{
    "id":"222_9",
    "stoke":"none",
    "start":"1512565200000",
    "end":"1512568800000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"222"}]
},{
"id":"313",
"parent":"4",
"rowHeight":15,
"periods":[{
    "id":"313_10",
    "stoke":"none",
    "start":"1512566400000",
    "end":"1512570000000",
    "fill":"#FFFFFF",
    "personID":4,
    "id_task":"313"}]
},{
"id":"26",
"collapsed":false,
"rowHeight":15,
"name":"(aal) Aalb\u00e6k, Arne ",
"userLevel":"3"
 },{
"id":"423",
"parent":"26",
"rowHeight":15,
"periods":[{
    "id":"423_12",
    "stoke":"none",
    "start":"1512370800000",
    "end":"1512401400000",
    "fill":"#DCE4EF",
    "personID":26,
    "id_task":"423"}]
},{
"id":"6",
"collapsed":false,
"rowHeight":15,
"name":"(tc) Clausen, Tom ",
"userLevel":"1"
},{
"id":"436",
"parent":"6",
"rowHeight":15,
"periods":[{
    "id":"436_14",
    "stoke":"none",
    "start":"1512367200000",
    "end":"1512738000000",
    "fill":"#DCE4EF",
    "personID":6,
    "id_task":"436"}],
},{
"id":"508",
"parent":"6",
"rowHeight":15,
"periods":[{
    "id":"508_15",
    "stoke":"none",
    "start":"1512370800000",
    "end":"1512471600000",
    "fill":"#DCE4EF",
    "personID":6,
    "id_task":"508"}]
}]
</code>```

And I need to identify the id_task I have in my periods.

So I rephrase my question and ask for guidance to how I use the data I get in my listen(), especially how I identify the object I working on and get the data in that object

答:
You were almost there! Try the following listener with your Gantt Chart and your JSON data:

```<code>            tree.listen("treeItemUpdate", function(e) {
            var periodInfo = e.item.get('periods')[e.path[1]];
            console.log('treeItemUpdate - ' + 'row ID: ' + e.item.get('id') + ', id_task: ' + periodInfo.id_task +
            ', personID: ' + periodInfo.personID + ', ' + e.path[2] + ': ' + e.value);

//next line will show you the unformatted period info which is modified
           // console.log(periodInfo);
        });
</code>```

Now you will get info about a period you are modifying.

Body:
I cannot figure out what to listen after, when using drag&drop or duration cahnge in an anychart Gantt chart

I get data from a json call and have the following code

chart = anychart.ganttResource();
chart.data(anychart.data.tree(data, 'asTable'));
var dataGrid = chart.dataGrid();
chart.editing(true);

I'm locking at https://docs.anychart.com/Gantt_Chart/Live_Edit_UI_and_API in the documentation, but it doesnot say what to listen after.
I have tried to do

var tree = anychart.data.tree(data, 'asTable');
tree.listen("treeItemUpdate", function(e) {
              alert("test");
            });

But the alert does not show.
EDIT:
I do get the alert, seems I had a typo in my code.

The drag&drop and duration change is working fine, but I need to store the changes in the DB, but as I wrote I cannot see what trickers it.

EDIT2:

I have changed the alert to show the information mentioned in the documentation, so I have

tree.listen("treeItemUpdate", function(e) {
                console.log(e);
              alert("test " + e.type + " " + e.item + " " + e.path + " " + e.field + " " + e.value + " " );
            });

The alert gives something like this

test treeitemupdate [object Object] periods,2,start periods 1512574122684
test treeitemupdate [object Object] periods,2,end periods 1512583122684

While the consolelog shows

Object { type: "treeitemupdate", target: {…}, c: {…}, f: false, l: false, yA: true, item: {…}, path: […], field: "periods", value: 1512405943770 }

opening the item gives me this, but I cannot see how to work with this data

item: {…}
P: Object { b: {…}, P: null, f: […], … }
b: Object { yb: false, yj: undefined, ai: {…}, … }
c: Object { nc: true, depth: 1, index: 2, … }
f: Array []
g: Object { id: "270", rowHeight: 15, periods: […] }
h: Object {  }
__proto__: Object { get: g.get(), set: g.set(), Ve: g.Ve(), … }

My chart looks like this
Gantt Chart

My json is like this

[{"id":"0",
"collapsed":false,
"rowHeight":15,
"userLevel":"0"
},{
"id":"4",
"collapsed":false,
"rowHeight":15,
"name":"(1 - jnb) Bjerre, Janine Nedergaard ",
"userLevel":"3"
},{
"id":"270",
"parent":"4",
"rowHeight":15,
"periods":[{
    "id":"270_2",
    "stoke":"none",
    "start":"1512370800000",
    "end":"1512464400000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"270"
    },{
    "id":"474_3",
    "stoke":"none",
    "start":"1512543600000",
    "end":"1512547200000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"474"
    },{
    "id":"140_6",
    "stoke":"none",
    "start":"1512548100000",
    "end":"1512743400000",
    "fill":"#DCE4EF",
    "personID":4,"id_task":"140"}]
},{
"id":"488",
"parent":"4",
"rowHeight":15,
"periods":[{"
    id":"488_4",
    "stoke":"none",
    "start":"1512543600000",
    "end":"1512547200000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"488"
    },{
    "id":"485_7",
    "stoke":"none",
    "start":"1512554400000",
    "end":"1512561600000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"485"
    },{
    "id":"247_8",
    "stoke":"none",
    "start":"1512564960000",
    "end":"1512568560000",
    "fill":"#FFFFFF",
    "personID":4,
    "id_task":"247"}]
},{
"id":"372",
"parent":"4",
"rowHeight":15,
"periods":[{
    "id":"372_5",
    "stoke":"none",
    "start":"1512547200000",
    "end":"1512556200000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"372"
    },{
    "id":"222_9",
    "stoke":"none",
    "start":"1512565200000",
    "end":"1512568800000",
    "fill":"#DCE4EF",
    "personID":4,
    "id_task":"222"}]
},{
"id":"313",
"parent":"4",
"rowHeight":15,
"periods":[{
    "id":"313_10",
    "stoke":"none",
    "start":"1512566400000",
    "end":"1512570000000",
    "fill":"#FFFFFF",
    "personID":4,
    "id_task":"313"}]
},{
"id":"26",
"collapsed":false,
"rowHeight":15,
"name":"(aal) Aalb\u00e6k, Arne ",
"userLevel":"3"
 },{
"id":"423",
"parent":"26",
"rowHeight":15,
"periods":[{
    "id":"423_12",
    "stoke":"none",
    "start":"1512370800000",
    "end":"1512401400000",
    "fill":"#DCE4EF",
    "personID":26,
    "id_task":"423"}]
},{
"id":"6",
"collapsed":false,
"rowHeight":15,
"name":"(tc) Clausen, Tom ",
"userLevel":"1"
},{
"id":"436",
"parent":"6",
"rowHeight":15,
"periods":[{
    "id":"436_14",
    "stoke":"none",
    "start":"1512367200000",
    "end":"1512738000000",
    "fill":"#DCE4EF",
    "personID":6,
    "id_task":"436"}],
},{
"id":"508",
"parent":"6",
"rowHeight":15,
"periods":[{
    "id":"508_15",
    "stoke":"none",
    "start":"1512370800000",
    "end":"1512471600000",
    "fill":"#DCE4EF",
    "personID":6,
    "id_task":"508"}]
}]

And I need to identify the id_task I have in my periods.

So I rephrase my question and ask for guidance to how I use the data I get in my listen(), especially how I identify the object I working on and get the data in that object

Body:
You were almost there! Try the following listener with your Gantt Chart and your JSON data:

            tree.listen("treeItemUpdate", function(e) {
            var periodInfo = e.item.get('periods')[e.path[1]];
            console.log('treeItemUpdate - ' + 'row ID: ' + e.item.get('id') + ', id_task: ' + periodInfo.id_task +
            ', personID: ' + periodInfo.personID + ', ' + e.path[2] + ': ' + e.value);

//next line will show you the unformatted period info which is modified
           // console.log(periodInfo);
        });

Now you will get info about a period you are modifying.


问:
Ruby XML Builder, how to create this namespace?
I'm using Ruby's XML Builder and trying to find the proper syntax to recreate the following RSS 2.0 declaration:

```<code><rss version="2.0"
xmlns:g="http://base.google.com/ns/1.0">
</code>```

What's the appropriate way of going about this with XML Builder to put together the above block?

答:
Try this builder script:

```<code>xml.rss :version => "2.0", "xmlns:g" => "http://base.google.com/ns/1.0" do
end
</code>```

This will yield:

```<code><rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
</rss>
</code>```

Body:
I'm using Ruby's XML Builder and trying to find the proper syntax to recreate the following RSS 2.0 declaration:

<rss version="2.0"
xmlns:g="http://base.google.com/ns/1.0">

What's the appropriate way of going about this with XML Builder to put together the above block?

Body:
Try this builder script:

xml.rss :version => "2.0", "xmlns:g" => "http://base.google.com/ns/1.0" do
end

This will yield:

<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
</rss>


问:
How do you evenly distribute columns in a FlatList?
I have a grid-like FlatList that is 3x3. I want the 3 columns to be distributed evenly based on the container (screen) width. In a normal view this would be accomplished by justifyContent: 'space-between', but this doesn't do anything when used through contentContainerStyle.

```<code><FlatList
  contentContainerStyle={{ justifyContent: 'space-between' }}
  horizontal={false}
  scrollEnabled={false}
  numColumns={3}
  data={this.props.icons}
  extraData={this.props.selectedIcon}
  renderItem={this.renderItem}
  keyExtractor={this.keyExtractor}
/>
</code>```

As you can see the icons are all pushed to the left.

答:
I got a grid in FlatList like this:

```<code>const arr = ['1','1','1','1','1','1','1','1','1',];

<FlatList
    numColumns={3}
    data={arr}
    renderItem={this._renderItem}
/>

_renderItem = ({item}) => {
    return <Text style={{flex:1}}>{item}</Text>
};
</code>```

There is also a library for grids, if you want to get fancy easily:

https://github.com/GeekyAnts/react-native-easy-grid

Body:
I have a grid-like FlatList that is 3x3. I want the 3 columns to be distributed evenly based on the container (screen) width. In a normal view this would be accomplished by justifyContent: 'space-between', but this doesn't do anything when used through contentContainerStyle.

<FlatList
  contentContainerStyle={{ justifyContent: 'space-between' }}
  horizontal={false}
  scrollEnabled={false}
  numColumns={3}
  data={this.props.icons}
  extraData={this.props.selectedIcon}
  renderItem={this.renderItem}
  keyExtractor={this.keyExtractor}
/>

As you can see the icons are all pushed to the left.

Body:
I got a grid in FlatList like this:

const arr = ['1','1','1','1','1','1','1','1','1',];

<FlatList
    numColumns={3}
    data={arr}
    renderItem={this._renderItem}
/>

_renderItem = ({item}) => {
    return <Text style={{flex:1}}>{item}</Text>
};

There is also a library for grids, if you want to get fancy easily:

https://github.com/GeekyAnts/react-native-easy-grid


问:
Future(<not completed>) when Future.map Combinator Used
After using a Future.map to process the first Future, the second dependent Future is always Future(<not completed>) once Future.onComplete is called back.  Other constructions using two Futures never exhibit this behaviour.

Can anyone explain why Future.onComplete is being called although the future is apparently not complete?

Scala 2.12.3 is used.  Cut and paste the following to evaluate this problem, if needed.

```<code>import scala.collection.mutable.ListBuffer
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Success}

object FutureNotCompleted {

  def threadNumber: String = f"${Thread.currentThread().getId.toInt}%2d"

  /////////////////////////////////////////////////////
  // Future completion control
  /////////////////////////////////////////////////////

  var futures: ListBuffer[Future[Any]] = ListBuffer()

  def add(future: Future[Any]): Unit = synchronized(futures += future)

  def remove(future: Future[Any]): Unit = synchronized(futures = futures.filter(_ != future))

  def loopTillCompleted: Unit = {
    var futuresOnList = true;

    while (futuresOnList) {
      Thread.sleep(100)
      for (future <- futures) {
        if (future.isCompleted) {
          future.value.get match {
            case Success(v) => println(s"${threadNumber} Success: ${v}")
            case Failure(e) => println(s"${threadNumber} Error: ${e}")
          }
          remove(future)
        }
      }
      if (futures.size == 0) futuresOnList = false
    }
  }

  /////////////////////////////////////////////////////
  // Future factory
  /////////////////////////////////////////////////////

  def createRegisteredFuture: Future[Int] = {
    val future = createFuture
    add(future)
    future
  }

  def createFuture: Future[Int] = Future {
    val i = (Math.random() * 1000).toInt
    println(s"${threadNumber} Future work start: ${i}")
    Thread.sleep((Math.random() * 1000).toLong)
    println(s"${threadNumber} Future work stop:  ${i}")
    if (Math.random > 0.7) throw new RuntimeException(s"${threadNumber} Error for ${i}")
    i
  }

  /////////////////////////////////////////////////////
  // Functions exhibiting Future use conditions
  /////////////////////////////////////////////////////

  def futureDoesNotComplete: Unit = {

    val f1 = createRegisteredFuture
    val f2 = f1.map {
      i => createRegisteredFuture
    }
    // This is never completed at the time the 'onComplete' callback is called
    f2.onComplete({
      case Success(j) => println(s"${threadNumber} j: ${j} ")
      case Failure(e) => println(s"${threadNumber} f2 Failure: ${e}")
    })

    loopTillCompleted
    println(s"${threadNumber} All done.")
  }

  def futureCompletes: Unit = {

    val f1 = createRegisteredFuture

    f1.onComplete({
      case Success(i) => {
        val f2 = createRegisteredFuture
        f2.onComplete({
          case Success(j) => println(s"${threadNumber} i: ${i} j: ${j} ${i}+${j}=${i + j}")
          case Failure(e) => println(s"${threadNumber} f2 Failure: ${e}")
        })
      }
      case Failure(e) => println(s"${threadNumber} f1 Failure: ${e}")
    })

    loopTillCompleted
    println(s"${threadNumber} All done.")
  }

  def futureCompletesFor: Unit = {

    for {
      f1 <- createRegisteredFuture
      f2 <- createRegisteredFuture
    } yield {
      println(s"f1: ${f1} f2: ${f2}: f1+f2=${f1+f2}")
    }

    loopTillCompleted
    println(s"${threadNumber} All done.")
  }

  def main(a: Array[String]): Unit = {
    //    futureCompletes
    futureDoesNotComplete
    //    futureCompletesFor
  }

}
</code>```

答:
I'm not 100% sure what the desired behavior here is exactly, but I would try flatMap here, you really want to onComplete the whole future chain I think. If this is the issue then you're just completing the outer future, and that's what I suspect since when you use for (which is working) it does the same as flatMap.

```<code>10 Future work start: 791
10 Future work stop:  791
11 Future work start: 819
11 Future work stop:  819
11 j: 819
 1 Success: 791
 1 Success: 819
 1 All done.
</code>```

I would change map to flatMap here, since createRegisteredFuture creates a future itself.

```<code>val f2 = f1.flatMap {
      i => createRegisteredFuture
}
</code>```

Body:
After using a Future.map to process the first Future, the second dependent Future is always Future(<not completed>) once Future.onComplete is called back.  Other constructions using two Futures never exhibit this behaviour.

Can anyone explain why Future.onComplete is being called although the future is apparently not complete?

Scala 2.12.3 is used.  Cut and paste the following to evaluate this problem, if needed.

import scala.collection.mutable.ListBuffer
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Success}

object FutureNotCompleted {

  def threadNumber: String = f"${Thread.currentThread().getId.toInt}%2d"

  /////////////////////////////////////////////////////
  // Future completion control
  /////////////////////////////////////////////////////

  var futures: ListBuffer[Future[Any]] = ListBuffer()

  def add(future: Future[Any]): Unit = synchronized(futures += future)

  def remove(future: Future[Any]): Unit = synchronized(futures = futures.filter(_ != future))

  def loopTillCompleted: Unit = {
    var futuresOnList = true;

    while (futuresOnList) {
      Thread.sleep(100)
      for (future <- futures) {
        if (future.isCompleted) {
          future.value.get match {
            case Success(v) => println(s"${threadNumber} Success: ${v}")
            case Failure(e) => println(s"${threadNumber} Error: ${e}")
          }
          remove(future)
        }
      }
      if (futures.size == 0) futuresOnList = false
    }
  }

  /////////////////////////////////////////////////////
  // Future factory
  /////////////////////////////////////////////////////

  def createRegisteredFuture: Future[Int] = {
    val future = createFuture
    add(future)
    future
  }

  def createFuture: Future[Int] = Future {
    val i = (Math.random() * 1000).toInt
    println(s"${threadNumber} Future work start: ${i}")
    Thread.sleep((Math.random() * 1000).toLong)
    println(s"${threadNumber} Future work stop:  ${i}")
    if (Math.random > 0.7) throw new RuntimeException(s"${threadNumber} Error for ${i}")
    i
  }

  /////////////////////////////////////////////////////
  // Functions exhibiting Future use conditions
  /////////////////////////////////////////////////////

  def futureDoesNotComplete: Unit = {

    val f1 = createRegisteredFuture
    val f2 = f1.map {
      i => createRegisteredFuture
    }
    // This is never completed at the time the 'onComplete' callback is called
    f2.onComplete({
      case Success(j) => println(s"${threadNumber} j: ${j} ")
      case Failure(e) => println(s"${threadNumber} f2 Failure: ${e}")
    })

    loopTillCompleted
    println(s"${threadNumber} All done.")
  }

  def futureCompletes: Unit = {

    val f1 = createRegisteredFuture

    f1.onComplete({
      case Success(i) => {
        val f2 = createRegisteredFuture
        f2.onComplete({
          case Success(j) => println(s"${threadNumber} i: ${i} j: ${j} ${i}+${j}=${i + j}")
          case Failure(e) => println(s"${threadNumber} f2 Failure: ${e}")
        })
      }
      case Failure(e) => println(s"${threadNumber} f1 Failure: ${e}")
    })

    loopTillCompleted
    println(s"${threadNumber} All done.")
  }

  def futureCompletesFor: Unit = {

    for {
      f1 <- createRegisteredFuture
      f2 <- createRegisteredFuture
    } yield {
      println(s"f1: ${f1} f2: ${f2}: f1+f2=${f1+f2}")
    }

    loopTillCompleted
    println(s"${threadNumber} All done.")
  }

  def main(a: Array[String]): Unit = {
    //    futureCompletes
    futureDoesNotComplete
    //    futureCompletesFor
  }

}

Body:
I'm not 100% sure what the desired behavior here is exactly, but I would try flatMap here, you really want to onComplete the whole future chain I think. If this is the issue then you're just completing the outer future, and that's what I suspect since when you use for (which is working) it does the same as flatMap.

10 Future work start: 791
10 Future work stop:  791
11 Future work start: 819
11 Future work stop:  819
11 j: 819
 1 Success: 791
 1 Success: 819
 1 All done.

I would change map to flatMap here, since createRegisteredFuture creates a future itself.

val f2 = f1.flatMap {
      i => createRegisteredFuture
}


问:
Count times a name matches a code in excel
What I am trying to do is loop through a column of names (includes repeated names) and create a count of the times they appear and a call code matches.

This is my source table

```<code>EventID Name    Code
1811    Tom     CC,CA,CS
1809    Jane    CA,
1523    Bill    CS,CA
1637    Tom     CA,CC
1514    Jane    CS,CA,CC
1728    Bill    CC,CA
1397    Sam     CC
1873    Sally   CS
</code>```

For example in the below table I want to match all the times Tom appears with the call code CC, in this instance 2.

```<code>Name    Count (CC)
Tom     2
Jane
Bill
Sam
Sally
</code>```

I can search the text to see if CC exists in the list. My source column is O in the below.

```<code>=SUMPRODUCT(--ISNUMBER(SEARCH("CC",O6)))
</code>```

Cannot figure how to get it to sum for each occurrence of a person however.

答:
Maybe something like:

```<code>=COUNTIFS(L:L,L10,M:M,"=*CC*")
</code>```

provided "CC" is limited to once per cell.

Body:
What I am trying to do is loop through a column of names (includes repeated names) and create a count of the times they appear and a call code matches.

This is my source table

EventID Name    Code
1811    Tom     CC,CA,CS
1809    Jane    CA,
1523    Bill    CS,CA
1637    Tom     CA,CC
1514    Jane    CS,CA,CC
1728    Bill    CC,CA
1397    Sam     CC
1873    Sally   CS

For example in the below table I want to match all the times Tom appears with the call code CC, in this instance 2.

Name    Count (CC)
Tom     2
Jane
Bill
Sam
Sally

I can search the text to see if CC exists in the list. My source column is O in the below.

=SUMPRODUCT(--ISNUMBER(SEARCH("CC",O6)))

Cannot figure how to get it to sum for each occurrence of a person however.

Body:
Maybe something like:

=COUNTIFS(L:L,L10,M:M,"=*CC*")

provided "CC" is limited to once per cell.


问:
JCarousel and Cufon aren't co-operating: animation makes cufon go away
I'm using cufon with jCarousel.

The Carousel has five items in it and rotates right to left -- they go off the screen to the left, in other words. You can see it here.

http://www.foursquare.org/site/test

If I leave the carousel on default behavior, it gets to the 5th slide and then slides back to the right fast, and everything displays properly.

If I set the carousel to 'circular', the cufon headlines disappear after the first rotation; i.e. they don't come with the rest of the slide when the first slide gets appended to the right of the last slide.

Do you know what I can do to get jCarousel and Cufon to co-operate or communicate so that the headlines don't disappear in this situation?

TTFN
Travis

答:
I ran into this problem with a variation of coda-slider. What seemed to work for me, instead of using

```<code>visibility:hidden
</code>```

I used

```<code>display:none
</code>```

and

```<code>display:block
</code>```

to reveal.

Body:
I ran into this problem with a variation of coda-slider. What seemed to work for me, instead of using

visibility:hidden

I used

display:none

and

display:block

to reveal.


问:
Which OWASP Top10 and SANS Top 25 for SonarQube 6.7 LTS?
I just downloaded SonarQube 6.7 LTS.  I know it'll detect OWASP Top 10 and SANS Top 25...but which versions of those lists?

For instance, does the built-in tag scan for OWASP Top 10 - 2013 or 2017 or 2010?

Does the built-in tag scan for SANS Top 25 - 2009 or 2010 or 2011?

答:
You can find information about OWASP and SANS in the documentation page. The page contains links to the security version-pages used in the latest SonarQube version (6.7 LTS). Based on the links provided:

CWE/SANS TOP 25: Version 3.0 Updated June 27, 2011

OWASP: 2013-Top 10

See also this:

To find rules that relate to any of these standards, you can search
  rules either by tag or by text. The standards that a rule relates to
  will be listed in the See section at the bottom of the rule
  description.

So it is not the case that all rules can already be detected/analyzed.


问:
Get global variables from map
I would like to have a groovy file for my Jenkins pipeline shared library that would store several keys with default values and be able to call and get the value of individual keys from other functions in different groovy functions such as test.groovy. I am not sure how I should or can structure the groovy file.

/vars/settings.groovy

```<code>def configuration = [
    artifactoryURL: 'artifactory.example.com',
    daysToKeep: 14,
    maxRetry: 3 ]
</code>```

/var/test.groovy

```<code>globalVariables.get('artifactoryURL')   // I would like this to return "artifactory.example.com"
</code>```

Any help would be appreciated.

Update:

I got this to work as follows:

```<code>/vars/settings.groovy

#!/usr/bin/groovy
def getConfig() {
def config = [
    artifactoryURL: 'artifactory.example.com',
    daysToKeep: 14,
    maxRetry: 3
]
return config
}

def getValue(name) {
    return config[name]
}

/vars/retrieveValue.groovy

...
echo "value is " + settings.getConfig()
echo "new value is " + settings.getValue('artifactoryURL')
...
</code>```

Output:

```<code>value is [artifactoryURL:artifactory.example.com, daysToKeep:14, maxRetry:3]
new value is artifactory.example.com
</code>```

Is this correct syntax?
Is there a way to simplify these?

答:
Use config file Provider Plugin.

Setup config file in Jenkins > Manage Jenkins > Managed Files

```<code>artifactoryURL ="artifactory.example.com"
daysToKeep =14
maxRetry =3
</code>```

In you Jenkinsfile you can call as follow:

```<code>node {
stage('configFile Plugin') {

 def myFileId = 'your_file_id'
 configFileProvider([configFile(fileId: myFileId, variable: 'artifactoryURL')]){
   sh "cat ${env.artifactoryURL}"
 }

 }
}
</code>```

Title: Get global variables from map

Body:
I would like to have a groovy file for my Jenkins pipeline shared library that would store several keys with default values and be able to call and get the value of individual keys from other functions in different groovy functions such as test.groovy. I am not sure how I should or can structure the groovy file.

/vars/settings.groovy

def configuration = [
    artifactoryURL: 'artifactory.example.com',
    daysToKeep: 14,
    maxRetry: 3 ]

/var/test.groovy

globalVariables.get('artifactoryURL')   // I would like this to return "artifactory.example.com"

Any help would be appreciated.

Update:

I got this to work as follows:

/vars/settings.groovy

#!/usr/bin/groovy
def getConfig() {
def config = [
    artifactoryURL: 'artifactory.example.com',
    daysToKeep: 14,
    maxRetry: 3
]
return config
}

def getValue(name) {
    return config[name]
}

/vars/retrieveValue.groovy

...
echo "value is " + settings.getConfig()
echo "new value is " + settings.getValue('artifactoryURL')
...

Output:

value is [artifactoryURL:artifactory.example.com, daysToKeep:14, maxRetry:3]
new value is artifactory.example.com

Is this correct syntax?
Is there a way to simplify these?

Body:
Use config file Provider Plugin.

Setup config file in Jenkins > Manage Jenkins > Managed Files

artifactoryURL ="artifactory.example.com"
daysToKeep =14
maxRetry =3

In you Jenkinsfile you can call as follow:

node {
stage('configFile Plugin') {

 def myFileId = 'your_file_id'
 configFileProvider([configFile(fileId: myFileId, variable: 'artifactoryURL')]){
   sh "cat ${env.artifactoryURL}"
 }

 }
}


问:
Wrong Position after Filtering and on Click in Recyclerview
I have Implemented SearchView in my App. But the Problem I am facing is the recycler view returns the wrong position after filtering. How can i get the exact position after filtering.

Here is my code of Adapter:-

```<code>public class UserListAdapter extends Adapter<UserListAdapter.DataObjectHolder> implements Filterable {
private static MyClickListener myClickListener;
public Activity activity;
Bitmap bitmap;
ImageView imgUserBig;
TextView txtUserName;
RelativeLayout userProfileView;
private ArrayList<DataObject> mArrayList;
private ArrayList<DataObject> mFilteredList;

public UserListAdapter(Activity a, ArrayList<DataObject> d, ImageView mImgUserBig, RelativeLayout viewLinear, TextView txtUsername) {

    this.activity = a;
    this.mArrayList = d;
    this.mFilteredList = d;
    this.imgUserBig = mImgUserBig;
    this.userProfileView = viewLinear;
    this.txtUserName = txtUsername;
}

public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new DataObjectHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_user_list, parent, false));
}

public void onBindViewHolder(final DataObjectHolder holder, final int position) {
    holder.txtName.setText((mFilteredList.get(position)).getmName());
    holder.txtUserName.setText((mFilteredList.get(position)).getmUsername());
    Glide.with(activity.getApplicationContext()).load((mFilteredList.get(position)).getmImage()).into(holder.imgUser);
    Glide.with(activity).load((mFilteredList.get(position)).getmImage()).asBitmap().into(new SimpleTarget<Bitmap>(Integer.MIN_VALUE, Integer.MIN_VALUE) {
        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
            bitmap = resource;
            (mFilteredList.get(position)).setBitmap(bitmap);
        }
    });
    holder.imgUser.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            if ((mFilteredList.get(position)).getBitmap() != null && imgUserBig != null) {
                zoomImageFromThumb(holder.imgUser, (mFilteredList.get(position)).getBitmap(), (mFilteredList.get(position)).getmImage(), (mFilteredList.get(position)).getmUsername());
            }
        }
    });
}

public int getItemCount() {
    return mFilteredList.size();
}

public void setOnItemClickListener(MyClickListener myClickListener) {
    UserListAdapter.myClickListener = myClickListener;
}

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            String charString = charSequence.toString();
            if (charString.isEmpty()) {
                mFilteredList = mArrayList;
            }else {
                ArrayList<DataObject> filteredList = new ArrayList<>();
                for (DataObject userData : mArrayList) {
                    if (userData.getmUsername().toLowerCase().contains(charString) || userData.getmName().toLowerCase().contains(charString)) {
                        filteredList.add(userData);
                    }
                }
                mFilteredList = filteredList;
            }
            FilterResults filterResults = new FilterResults();
            filterResults.values = mFilteredList;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            mFilteredList = (ArrayList<DataObject>) results.values;
            notifyDataSetChanged();
        }
    };
}

public interface MyClickListener {
    void onItemClick(int i, View view);
}

public Object getItem(int position) {
    return mFilteredList.get(position);
}

public class DataObjectHolder extends ViewHolder implements OnClickListener {
    ImageView imgUser;
    TextView txtName;
    TextView txtUserName;

    public DataObjectHolder(View itemView) {
        super(itemView);
        txtName = (TextView) itemView.findViewById(R.id.txtname);
        txtUserName = (TextView) itemView.findViewById(R.id.txtusername);
        imgUser = (ImageView) itemView.findViewById(R.id.img_user);
        itemView.setOnClickListener(this);
    }

    public void onClick(View v) {
        UserListAdapter.myClickListener.onItemClick(getPosition(), v);
    }
}}
</code>```

I am calling getPosition() Method to get the position of the item, but it returns the old position, not the filtered one. Any Help will be Appreciated.

答:
Use this class to implement the scroll listener before recyclerview reaches to its end . It notify when 5 items are left to be scrolled . See Code below.

Just put it in your projectas a separate class

```<code>import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;

public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener
{
    public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();
private int previousTotal = 0; // The total number of items in the dataset after the last load
private boolean loading = true; // True if we are still waiting for the last set of data to load.
private int visibleThreshold = 5; // The minimum amount of items to have below your current scroll position before loading more.
int firstVisibleItem, visibleItemCount, totalItemCount;

private int current_page = 0;

private StaggeredGridLayoutManager mLinearLayoutManager;
private LinearLayoutManager mLinearLayoutManagerG;

public EndlessRecyclerOnScrollListener(StaggeredGridLayoutManager linearLayoutManager)
{
    this.mLinearLayoutManager = linearLayoutManager;
}

public EndlessRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager)
{
    this.mLinearLayoutManagerG = linearLayoutManager;
    mLinearLayoutManager = null;
}

public void reset()
{
    current_page = 0;
    previousTotal = 0;
    loading = true;
}

public void setThresHold(int threshold)
{
    visibleThreshold = threshold;
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy)
{
    super.onScrolled(recyclerView, dx, dy);

    if (mLinearLayoutManager != null)
    {
        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = mLinearLayoutManager.getItemCount();
        firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPositions(null)[0];

        if (loading)
        {
            if (totalItemCount > previousTotal)
            {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold))
        {
            // End has been reached

            // Do something
            current_page++;

            onLoadMore(current_page);

            loading = true;
        }
    }
    else
    {
        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = mLinearLayoutManagerG.getItemCount();
        firstVisibleItem = mLinearLayoutManagerG.findFirstVisibleItemPosition();

        if (loading)
        {
            if (totalItemCount > previousTotal)
            {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold))
        {
            // End has been reached

            // Do something
            current_page++;

            onLoadMore(current_page);

            loading = true;
        }

    }

    countChange(firstVisibleItem);
}

public abstract void onLoadMore(int current_page);

public abstract void countChange(int currentVisibleCount);
}
</code>```

Use it like this

```<code>endlessRecyclerOnScrollListener = new EndlessRecyclerOnScrollListener(pass your layout manager here)
    {
        @Override
        public void onLoadMore(int current_page) {
            pageNumber++;
            // Hit your api for more records
        }

        @Override
        public void countChange(int currentVisibleCount) {

        }
    };

    recyclerView.setOnScrollListener(endlessRecyclerOnScrollListener);
</code>```

There is a variable named current_page , By default it starts from 0 , you can change it according to your api. visibleThreshold says that before how many items your onLoadMore method should be called .

Example: If the visibleThreshold is 5 and total data in the list is 20, then onLoadMore will be called when your recyclerview is scrolled upto 15th position.

Let me know if you have more queries.

Body:
I have Implemented SearchView in my App. But the Problem I am facing is the recycler view returns the wrong position after filtering. How can i get the exact position after filtering.

Here is my code of Adapter:-

public class UserListAdapter extends Adapter<UserListAdapter.DataObjectHolder> implements Filterable {
private static MyClickListener myClickListener;
public Activity activity;
Bitmap bitmap;
ImageView imgUserBig;
TextView txtUserName;
RelativeLayout userProfileView;
private ArrayList<DataObject> mArrayList;
private ArrayList<DataObject> mFilteredList;

public UserListAdapter(Activity a, ArrayList<DataObject> d, ImageView mImgUserBig, RelativeLayout viewLinear, TextView txtUsername) {

    this.activity = a;
    this.mArrayList = d;
    this.mFilteredList = d;
    this.imgUserBig = mImgUserBig;
    this.userProfileView = viewLinear;
    this.txtUserName = txtUsername;
}

public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new DataObjectHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_user_list, parent, false));
}

public void onBindViewHolder(final DataObjectHolder holder, final int position) {
    holder.txtName.setText((mFilteredList.get(position)).getmName());
    holder.txtUserName.setText((mFilteredList.get(position)).getmUsername());
    Glide.with(activity.getApplicationContext()).load((mFilteredList.get(position)).getmImage()).into(holder.imgUser);
    Glide.with(activity).load((mFilteredList.get(position)).getmImage()).asBitmap().into(new SimpleTarget<Bitmap>(Integer.MIN_VALUE, Integer.MIN_VALUE) {
        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
            bitmap = resource;
            (mFilteredList.get(position)).setBitmap(bitmap);
        }
    });
    holder.imgUser.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            if ((mFilteredList.get(position)).getBitmap() != null && imgUserBig != null) {
                zoomImageFromThumb(holder.imgUser, (mFilteredList.get(position)).getBitmap(), (mFilteredList.get(position)).getmImage(), (mFilteredList.get(position)).getmUsername());
            }
        }
    });
}

public int getItemCount() {
    return mFilteredList.size();
}

public void setOnItemClickListener(MyClickListener myClickListener) {
    UserListAdapter.myClickListener = myClickListener;
}

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            String charString = charSequence.toString();
            if (charString.isEmpty()) {
                mFilteredList = mArrayList;
            }else {
                ArrayList<DataObject> filteredList = new ArrayList<>();
                for (DataObject userData : mArrayList) {
                    if (userData.getmUsername().toLowerCase().contains(charString) || userData.getmName().toLowerCase().contains(charString)) {
                        filteredList.add(userData);
                    }
                }
                mFilteredList = filteredList;
            }
            FilterResults filterResults = new FilterResults();
            filterResults.values = mFilteredList;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            mFilteredList = (ArrayList<DataObject>) results.values;
            notifyDataSetChanged();
        }
    };
}

public interface MyClickListener {
    void onItemClick(int i, View view);
}

public Object getItem(int position) {
    return mFilteredList.get(position);
}

public class DataObjectHolder extends ViewHolder implements OnClickListener {
    ImageView imgUser;
    TextView txtName;
    TextView txtUserName;

    public DataObjectHolder(View itemView) {
        super(itemView);
        txtName = (TextView) itemView.findViewById(R.id.txtname);
        txtUserName = (TextView) itemView.findViewById(R.id.txtusername);
        imgUser = (ImageView) itemView.findViewById(R.id.img_user);
        itemView.setOnClickListener(this);
    }

    public void onClick(View v) {
        UserListAdapter.myClickListener.onItemClick(getPosition(), v);
    }
}}

I am calling getPosition() Method to get the position of the item, but it returns the old position, not the filtered one. Any Help will be Appreciated.

Body:
Use this class to implement the scroll listener before recyclerview reaches to its end . It notify when 5 items are left to be scrolled . See Code below.

Just put it in your projectas a separate class

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;

public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener
{
    public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();
private int previousTotal = 0; // The total number of items in the dataset after the last load
private boolean loading = true; // True if we are still waiting for the last set of data to load.
private int visibleThreshold = 5; // The minimum amount of items to have below your current scroll position before loading more.
int firstVisibleItem, visibleItemCount, totalItemCount;

private int current_page = 0;

private StaggeredGridLayoutManager mLinearLayoutManager;
private LinearLayoutManager mLinearLayoutManagerG;

public EndlessRecyclerOnScrollListener(StaggeredGridLayoutManager linearLayoutManager)
{
    this.mLinearLayoutManager = linearLayoutManager;
}

public EndlessRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager)
{
    this.mLinearLayoutManagerG = linearLayoutManager;
    mLinearLayoutManager = null;
}

public void reset()
{
    current_page = 0;
    previousTotal = 0;
    loading = true;
}

public void setThresHold(int threshold)
{
    visibleThreshold = threshold;
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy)
{
    super.onScrolled(recyclerView, dx, dy);

    if (mLinearLayoutManager != null)
    {
        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = mLinearLayoutManager.getItemCount();
        firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPositions(null)[0];

        if (loading)
        {
            if (totalItemCount > previousTotal)
            {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold))
        {
            // End has been reached

            // Do something
            current_page++;

            onLoadMore(current_page);

            loading = true;
        }
    }
    else
    {
        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = mLinearLayoutManagerG.getItemCount();
        firstVisibleItem = mLinearLayoutManagerG.findFirstVisibleItemPosition();

        if (loading)
        {
            if (totalItemCount > previousTotal)
            {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold))
        {
            // End has been reached

            // Do something
            current_page++;

            onLoadMore(current_page);

            loading = true;
        }

    }

    countChange(firstVisibleItem);
}

public abstract void onLoadMore(int current_page);

public abstract void countChange(int currentVisibleCount);
}

Use it like this

endlessRecyclerOnScrollListener = new EndlessRecyclerOnScrollListener(pass your layout manager here)
    {
        @Override
        public void onLoadMore(int current_page) {
            pageNumber++;
            // Hit your api for more records
        }

        @Override
        public void countChange(int currentVisibleCount) {

        }
    };

    recyclerView.setOnScrollListener(endlessRecyclerOnScrollListener);

There is a variable named current_page , By default it starts from 0 , you can change it according to your api. visibleThreshold says that before how many items your onLoadMore method should be called .

Example: If the visibleThreshold is 5 and total data in the list is 20, then onLoadMore will be called when your recyclerview is scrolled upto 15th position.

Let me know if you have more queries.


问:
Ionic 3 enable swipe back for a single page
I've disabled 'swipe back' globally, both in root component and module config

```<code><ion-nav #appNav [root]="rootPage" swipeBackEnabled="false"></ion-nav>

...
IonicModule.forRoot(MobileApplication, {swipeBackEnabled: false}),
...
</code>```

I need though to enable it for one page only. So'm trying to set it by passing a nav instance to constructor and then setting swipeBackEnabled to true.

```<code>ionViewWillEnter() {
    this.nav.swipeBackEnabled = true;
    console.log('swipeBackEnabled ' + this.nav.swipeBackEnabled);
    console.log('canGoBack ' + this.nav.canGoBack());
    console.log('canSwipeBack ' + this.nav.canSwipeBack());
}
</code>```

Logging swipeBackEnabled and canGoBack returns true, but canSwipeBack returns false. If I add a swipe event somewhere in my template and log those values on right swipe, it logs all the values as true. However, nothing happens, seems like swipe back is not working? Am I missing something?

For reference, I'm using Ionic 3.9.2 and @ionic/app-scripts 3.1.4. Thanks in advance

答:
to do this create an id for your ion-menu like i have given main-menu. to access it in your controller part.

app.html

```<code><ion-menu [content]="appNav" id="main-menu">
....
....
</ion-menu>
<ion-nav #appNav [root]="rootPage" swipeBackEnabled="false"></ion-nav>
</code>```

inside your app.component.ts file place the below code inside your constructor

```<code>  menuCtrl.swipeEnable(false, 'main-menu');
</code>```

so the above code acts as disabling the side menu swipe to open functionality through entire app.

lets say you want to enable the swipe to open side menu in only one page so add the below code

```<code>this.menuCtrl.swipeEnable(true, 'main-menu');
</code>```

this will enable the swipe to open the side menu functionality.

Note: Once you used the swipeEnable(true,'main-menu'); this will be able to access to the entire app. Inorder to resolve it use in only one the respeted page page and disable is to the previous page and next page respected to the current page.

only enable it on the current page and disable it on the front and back page of that current page

UPDATE:

another way to achive this is enable and disable it on the same page.

```<code>ionViewDidEnter(){
    this.menuCtrl.swipeEnable(true, 'main-menu');
}
</code>```

and disable it on the same page by using ionviewdidleave

```<code>ionViewDidLeave(){
    this.menuCtrl.swipeEnable(false, 'main-menu');
}
</code>```

So the above code will do the both method enabling and disabling the side-menu

Body:
I've disabled 'swipe back' globally, both in root component and module config

<ion-nav #appNav [root]="rootPage" swipeBackEnabled="false"></ion-nav>

...
IonicModule.forRoot(MobileApplication, {swipeBackEnabled: false}),
...

I need though to enable it for one page only. So'm trying to set it by passing a nav instance to constructor and then setting swipeBackEnabled to true.

ionViewWillEnter() {
    this.nav.swipeBackEnabled = true;
    console.log('swipeBackEnabled ' + this.nav.swipeBackEnabled);
    console.log('canGoBack ' + this.nav.canGoBack());
    console.log('canSwipeBack ' + this.nav.canSwipeBack());
}

Logging swipeBackEnabled and canGoBack returns true, but canSwipeBack returns false. If I add a swipe event somewhere in my template and log those values on right swipe, it logs all the values as true. However, nothing happens, seems like swipe back is not working? Am I missing something?

For reference, I'm using Ionic 3.9.2 and @ionic/app-scripts 3.1.4. Thanks in advance

Body:
to do this create an id for your ion-menu like i have given main-menu. to access it in your controller part.

app.html

<ion-menu [content]="appNav" id="main-menu">
....
....
</ion-menu>
<ion-nav #appNav [root]="rootPage" swipeBackEnabled="false"></ion-nav>

inside your app.component.ts file place the below code inside your constructor

  menuCtrl.swipeEnable(false, 'main-menu');

so the above code acts as disabling the side menu swipe to open functionality through entire app.

lets say you want to enable the swipe to open side menu in only one page so add the below code

this.menuCtrl.swipeEnable(true, 'main-menu');

this will enable the swipe to open the side menu functionality.

Note: Once you used the swipeEnable(true,'main-menu'); this will be able to access to the entire app. Inorder to resolve it use in only one the respeted page page and disable is to the previous page and next page respected to the current page.

only enable it on the current page and disable it on the front and back page of that current page

UPDATE:

another way to achive this is enable and disable it on the same page.

ionViewDidEnter(){
    this.menuCtrl.swipeEnable(true, 'main-menu');
}

and disable it on the same page by using ionviewdidleave

ionViewDidLeave(){
    this.menuCtrl.swipeEnable(false, 'main-menu');
}

So the above code will do the both method enabling and disabling the side-menu