问:
MySQL limit syntax with Query performance
I want to know how it is affected in query performance to use limit syntax
There are 180000 rows. So I would select data using limit syntax.
So I want to know the relationship between limit syntax and query performance.</p>

答:
LIMIT usually saves part of the cost of sending large result sets from the MySQL server to the requesting client. It's  good to use LIMIT if you need only a few result set rows, rather than simply skipping un-needed rows on the client side.

There's a notorious performance antipattern using LIMIT.  A query like this

```<code> SELECT a,whole,mess,of,columns,...
   FROM big_table JOIN big_tableb ON something JOIN big_tablec ON something ....
  ORDER BY whole, mess DESC
  LIMIT 5
</code>```

in MySQL wastes server resources (time and RAM). Why? It generates a big result set, then sorts it, then discards all but a few rows.

Another performance antipattern is LIMIT small_number, big_number applied to a complex result set. It has to romp through many rows to get a small number of rows.

You can work around these with a deferred join pattern, something like this:

```<code>   SELECT a,whole,mess,of,columns,..
     FROM (
         SELECT big_table_id
          FROM big_table JOIN big_tableb ON something JOIN big_tablec ON something ....
         ORDER BY whole, mess DESC
         LIMIT 5, 200000
        ) ids,
   JOIN big_table ON ids.big_table_id = big_table.big_table_id
   JOIN big_tableb ON something JOIN big_tablec ON  something ...
</code>```

This pattern orders and then discard just some id values rather than a whole mess of columns.

Using LIMIT really helps performance in situations where the result set is  ordered via an index.  For example, if you have an index on datestamp and you do

```<code> SELECT datestamp, col, col
   FROM table
  ORDER BY datestamp DESC
  LIMIT 20
</code>```

the MySQL query planner can scan backwards through the datestamp index and retrieve just twenty rows.

Body:
LIMIT usually saves part of the cost of sending large result sets from the MySQL server to the requesting client. It's  good to use LIMIT if you need only a few result set rows, rather than simply skipping un-needed rows on the client side.

There's a notorious performance antipattern using LIMIT.  A query like this

 SELECT a,whole,mess,of,columns,...
   FROM big_table JOIN big_tableb ON something JOIN big_tablec ON something ....
  ORDER BY whole, mess DESC
  LIMIT 5

in MySQL wastes server resources (time and RAM). Why? It generates a big result set, then sorts it, then discards all but a few rows.

Another performance antipattern is LIMIT small_number, big_number applied to a complex result set. It has to romp through many rows to get a small number of rows.

You can work around these with a deferred join pattern, something like this:

   SELECT a,whole,mess,of,columns,..
     FROM (
         SELECT big_table_id
          FROM big_table JOIN big_tableb ON something JOIN big_tablec ON something ....
         ORDER BY whole, mess DESC
         LIMIT 5, 200000
        ) ids,
   JOIN big_table ON ids.big_table_id = big_table.big_table_id
   JOIN big_tableb ON something JOIN big_tablec ON  something ...

This pattern orders and then discard just some id values rather than a whole mess of columns.

Using LIMIT really helps performance in situations where the result set is  ordered via an index.  For example, if you have an index on datestamp and you do

 SELECT datestamp, col, col
   FROM table
  ORDER BY datestamp DESC
  LIMIT 20

the MySQL query planner can scan backwards through the datestamp index and retrieve just twenty rows.


来源: stackexchange

问:
Prolog: replace an element in a list at a specified index
I'd like to have a Prolog predicate that can replace an element in a list at a specified index.

Example:

```<code>% replace(+List,+Index,+Value,-NewList).
?- L=[a,b,c,d], replace(L,1,z,L2).
L2 = [a,z,c,d]
</code>```

I don't know how to do this. Thanks for your help! Loïc.

答:
Another way I came up with, which I think is correct (?). I don't know about the runtime complexity.

```<code>replace(I, L, E, K) :-
  nth0(I, L, _, R),
  nth0(I, K, E, R).
</code>```

Usage:

```<code>?- replace(2, [1, 2, 3, 4, 5], 10, X).
X = [1, 2, 10, 4, 5].
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'd like to have a Prolog predicate that can replace an element in a list at a specified index.

Example:

% replace(+List,+Index,+Value,-NewList).
?- L=[a,b,c,d], replace(L,1,z,L2).
L2 = [a,z,c,d]

I don't know how to do this. Thanks for your help! Loïc.

Body:
Another way I came up with, which I think is correct (?). I don't know about the runtime complexity.

replace(I, L, E, K) :-
  nth0(I, L, _, R),
  nth0(I, K, E, R).

Usage:

?- replace(2, [1, 2, 3, 4, 5], 10, X).
X = [1, 2, 10, 4, 5].


问:
Tableview creating multiple times inside cellforrowatindexpath delegate method
I have two tableviews in my screen. 1 is maintableview, 2 is inside 1st tableviewcell I am displaying this 2nd tableview. So, I am able to differentiating while displaying date for each tableview.

But, Issue is, once I pressed on 2nd tableview cell data, I am reloading particular cell of 1st tableview cell, inside that cell I am created 2nd tableview, so, Whenever I pressed on 2nd tableview cell, 2nd tableview is repeatedly creating and adding to 1st tableviewcell.

So, code is follows inside cellforrowatindexpath delegate method

//1st tableview delegate method and reloading this indexpath multiple times by whenever clicking 2nd tableview cells data

```<code>else if indexPath.row == 1 {
//some action doing code

//later 2nd tableview creation
            //for no of event days like day1, day2 etc
                noOfEventDaysTableView = UITableView(frame: CGRect(x:(cell?.secondCircleGraph.frame.maxX)! + 5,y:10,width:60,height:50), style: .plain)
                cell?.contentView.addSubview(noOfEventDaysTableView)
                noOfEventDaysTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
                noOfEventDaysTableView.delegate = self
                noOfEventDaysTableView.dataSource = self
                noOfEventDaysTableView.backgroundColor = UIColor.clear
                noOfEventDaysTableView.separatorColor = UIColor.clear
                noOfEventDaysTableView.rowHeight = 20.0

}
</code>```

While scrolling 2nd tableview data, its coming like creating again cells.
PFA.

How to avoid once created 2nd tableview, second restrict to create again?

I can avoid by doing following

```<code>         noOfEventDaysTableView.removeFromSuperview()
</code>```

Is there any better solution for this?
Any suggestions. Thanks!

答: This problem occurs because of dequeuing so,Enumerate the contentView of the main tableView cell before adding to check for existence of any UITableView subView if not exists add it . . .

Body:
I have two tableviews in my screen. 1 is maintableview, 2 is inside 1st tableviewcell I am displaying this 2nd tableview. So, I am able to differentiating while displaying date for each tableview.

But, Issue is, once I pressed on 2nd tableview cell data, I am reloading particular cell of 1st tableview cell, inside that cell I am created 2nd tableview, so, Whenever I pressed on 2nd tableview cell, 2nd tableview is repeatedly creating and adding to 1st tableviewcell.

So, code is follows inside cellforrowatindexpath delegate method

//1st tableview delegate method and reloading this indexpath multiple times by whenever clicking 2nd tableview cells data

else if indexPath.row == 1 {
//some action doing code

//later 2nd tableview creation
            //for no of event days like day1, day2 etc
                noOfEventDaysTableView = UITableView(frame: CGRect(x:(cell?.secondCircleGraph.frame.maxX)! + 5,y:10,width:60,height:50), style: .plain)
                cell?.contentView.addSubview(noOfEventDaysTableView)
                noOfEventDaysTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
                noOfEventDaysTableView.delegate = self
                noOfEventDaysTableView.dataSource = self
                noOfEventDaysTableView.backgroundColor = UIColor.clear
                noOfEventDaysTableView.separatorColor = UIColor.clear
                noOfEventDaysTableView.rowHeight = 20.0

}

While scrolling 2nd tableview data, its coming like creating again cells.
PFA.

How to avoid once created 2nd tableview, second restrict to create again?

I can avoid by doing following

         noOfEventDaysTableView.removeFromSuperview()

Is there any better solution for this?
Any suggestions. Thanks!


问:
How to validate 8 to 10 digit long phone number?
In my android application, phone number field used. 8 to 10 digit input value given by the user. How to validate  8 to 10 digit phone number using PHONE_REGEX?

I have already tried this method,

```<code>private static final String PHONE_REGEX = "\\d{8-10}";

  public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}
</code>```

答:
You can use this for validation.</p>

```<code>    public static boolean isValidIndianMobile(String mobile) {

            if (mobile == null || mobile.trim().length() <= 0) {
                return false;
            }
            mobile = removeAllSpace(mobile);

            Pattern pattern = Pattern.compile("[7-9][0-9]{9}");
            Matcher matcher = pattern.matcher(mobile);
            return matcher.matches();
        }

   public static String removeAllSpace(String s) {
           if (s == null) return "";
           return s.replaceAll("\\s", "");
   }
</code>```

Body:
In my android application, phone number field used. 8 to 10 digit input value given by the user. How to validate  8 to 10 digit phone number using PHONE_REGEX?

I have already tried this method,

private static final String PHONE_REGEX = "\\d{8-10}";

  public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}

Body:
You can use this for validation.

    public static boolean isValidIndianMobile(String mobile) {

            if (mobile == null || mobile.trim().length() <= 0) {
                return false;
            }
            mobile = removeAllSpace(mobile);

            Pattern pattern = Pattern.compile("[7-9][0-9]{9}");
            Matcher matcher = pattern.matcher(mobile);
            return matcher.matches();
        }

   public static String removeAllSpace(String s) {
           if (s == null) return "";
           return s.replaceAll("\\s", "");
   }


问:
Add Value in rectangle in d3.js
I have created plunker for detail view.

I want to add hovered chart point in rectangle red box.

Help needed.

```<code>Thanks in advance.
</code>```

答:
Well in your code you are appending the text with in the rect DOM.
That is the reason why you don't see the text.

The solution would be
Step 1:

Create the Text (In our case 3 Text )

```<code>var textG = mouseG.append('text')
                .attr('y',height+25)
                .attr('font-family',"sans-serif")
                .attr('font-size',"8")
                .attr('fill', 'Black')
                .style("text-anchor", "middle")
var textB = mouseG.append('text')
                .attr('y',height+15)
                .attr('font-family',"sans-serif")
                .attr('font-size',"8")
                .attr('fill', 'Black')
                .style("text-anchor", "middle")
var textR = mouseG.append('text')
                .attr('y',height + 8)
                .attr('font-family',"sans-serif")
                .attr('font-size',"8")
                .attr('fill', 'Black')
                .style("text-anchor", "middle")
</code>```

Step 2:

On mouse out make the opacity 0.

```<code>    d3.select("#test")
      .style("opacity", "0");
    textG
      .style("opacity", "0");
    textB
      .style("opacity", "0");
    textR
      .style("opacity", "0");
</code>```

Since you don't want to see the text as mouse is out.

Step 3:

On mouse over set the text and x of the text DOM

```<code>        if (i ==2){
          textG.text(y.invert(pos.y).toFixed(2))
                  .attr('x',mouse[0])
        }
        if (i ==1){
          textB.text(y.invert(pos.y).toFixed(2))
                  .attr('x',mouse[0])
        }
        if (i ==0){
          textR.text(y.invert(pos.y).toFixed(2))
                  .attr('x',mouse[0])
        }
</code>```

working code here

Title: Add Value in rectangle in d3.js

Body:
I have created plunker for detail view.

I want to add hovered chart point in rectangle red box.

Help needed.

Thanks in advance.

Body:
Well in your code you are appending the text with in the rect DOM.
That is the reason why you don't see the text.

The solution would be
Step 1:

Create the Text (In our case 3 Text )

var textG = mouseG.append('text')
                .attr('y',height+25)
                .attr('font-family',"sans-serif")
                .attr('font-size',"8")
                .attr('fill', 'Black')
                .style("text-anchor", "middle")
var textB = mouseG.append('text')
                .attr('y',height+15)
                .attr('font-family',"sans-serif")
                .attr('font-size',"8")
                .attr('fill', 'Black')
                .style("text-anchor", "middle")
var textR = mouseG.append('text')
                .attr('y',height + 8)
                .attr('font-family',"sans-serif")
                .attr('font-size',"8")
                .attr('fill', 'Black')
                .style("text-anchor", "middle")

Step 2:

On mouse out make the opacity 0.

    d3.select("#test")
      .style("opacity", "0");
    textG
      .style("opacity", "0");
    textB
      .style("opacity", "0");
    textR
      .style("opacity", "0");

Since you don't want to see the text as mouse is out.

Step 3:

On mouse over set the text and x of the text DOM

        if (i ==2){
          textG.text(y.invert(pos.y).toFixed(2))
                  .attr('x',mouse[0])
        }
        if (i ==1){
          textB.text(y.invert(pos.y).toFixed(2))
                  .attr('x',mouse[0])
        }
        if (i ==0){
          textR.text(y.invert(pos.y).toFixed(2))
                  .attr('x',mouse[0])
        }

working code here


问:
__init__() missing 1 required positional argument 'address'
Here is my code. I have this erro message:
TypeError: init() missing 1 required positional argument: 'address'
what do you think seems to be the problem?

```<code>class Person:
def __init__(self, name, address):
    self.name = name
    self.address = address

def say_name(self):
    print('Hello, my name is', self.name)
def say_address(self):
    print('Hello, my name address', self.address)

p = Person('Swaroop')
q = Person('Duisburg')

p.say_name()
q.say_address()
</code>```

答:
Your __init__ is declared as taking a name and an address:

```<code>def __init__(self, name, address):
</code>```

This means that you need to provide both of them, so the following is not valid:

```<code>p = Person('Swaroop')
</code>```

If you have use cases where the address cannot be provided, then you can make the argument optional:

```<code>def __init__(self, name, address=None):
</code>```

The above statement will give address a default value of None if the argument is not provided.

Taking a closer look at your code it seems you wanted to provide a name and an address as two separate objects:

```<code>p = Person('Swaroop') # name
q = Person('Duisburg') # address
</code>```

Note that arguments are identified by position, so on q, Duisburg will correspond to the name argument.

You can achieve what you want by using just one object:

```<code>p = Person('Swaroop', 'Duisburg')
p.say_name()
p.say_address()
</code>```

Body:
Here is my code. I have this erro message:
TypeError: init() missing 1 required positional argument: 'address'
what do you think seems to be the problem?

class Person:
def __init__(self, name, address):
    self.name = name
    self.address = address

def say_name(self):
    print('Hello, my name is', self.name)
def say_address(self):
    print('Hello, my name address', self.address)

p = Person('Swaroop')
q = Person('Duisburg')

p.say_name()
q.say_address()

Body:
Your __init__ is declared as taking a name and an address:

def __init__(self, name, address):

This means that you need to provide both of them, so the following is not valid:

p = Person('Swaroop')

If you have use cases where the address cannot be provided, then you can make the argument optional:

def __init__(self, name, address=None):

The above statement will give address a default value of None if the argument is not provided.

Taking a closer look at your code it seems you wanted to provide a name and an address as two separate objects:

p = Person('Swaroop') # name
q = Person('Duisburg') # address

Note that arguments are identified by position, so on q, Duisburg will correspond to the name argument.

You can achieve what you want by using just one object:

p = Person('Swaroop', 'Duisburg')
p.say_name()
p.say_address()


问:
why there is a difference in output in CSS : li a VS li,a
why there is a difference in output in CSS:

```<code>li a
</code>```

from https://www.w3schools.com/code/tryit.asp?filename=FM0HPU6L0R35

versus

```<code>li,a
</code>```

from https://www.w3schools.com/code/tryit.asp?filename=FM0HQKZG79HR

答:
Adding to @Florinache

Instead of writing 2 separate CSS selectors we can combine all these styles into one rule property by separating the individual selectors with a comma like below:

```<code>li,a {
       display: block;
    color: white;
    text-align: center;
    padding: 16px;
    text-decoration: none;
}
</code>```

In your link replace the list with the below code and you will see the difference.

```<code><ul>
  <li>Home</li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
</ul>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
why there is a difference in output in CSS:

li a

from https://www.w3schools.com/code/tryit.asp?filename=FM0HPU6L0R35

versus

li,a

from https://www.w3schools.com/code/tryit.asp?filename=FM0HQKZG79HR

Body:
Adding to @Florinache

Instead of writing 2 separate CSS selectors we can combine all these styles into one rule property by separating the individual selectors with a comma like below:

li,a {
       display: block;
    color: white;
    text-align: center;
    padding: 16px;
    text-decoration: none;
}

In your link replace the list with the below code and you will see the difference.

<ul>
  <li>Home</li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
</ul>


问:
Google Analytics Event Tracking not Appearing in Real Time
This event and all onclick events like it are not tracking in Google Analytics Real Time.  Any idea why not?

```<code><a href="mailto:email@domain.com" class="white" onclick="ga('send', 'event', 'Connect', 'Submit', 'Value Goes Here');">email@domain.com</a>
</code>```

This is not specific to mailto links.  This is for any link where I'm trying to use onclick event tracking.

In case you're wondering I do not have an IP filter set.

答: We're using gatag.js (newer version of ga.js). I was still using the syntax from ga.js  The syntax for tracking an event is slightly different in the newer gatag.js.  That was my issue.</p>

Body:
This event and all onclick events like it are not tracking in Google Analytics Real Time.  Any idea why not?

email@domain.com

This is not specific to mailto links.  This is for any link where I'm trying to use onclick event tracking.

In case you're wondering I do not have an IP filter set.


问:
how to reload the Table view data when tap on UILabel(UITapGestureRecognizer)
I am new to objective c, and i am very interested in learn new technologies.

I have a UITapGestureRecognizer on a label. I am using 2 label ,when i tap on label1 load some data Tableview and when I tap on label 2 i want to change the Tableview.

I didn't find any solution for my requirement. so anyone help me .

suggest me guy's how to change the TableView data when tap on UILabel.

答:
I assume you have setup the datasource/delegate methods for the tableview? Then change necessary things within these methods when the label is tapped and simply call

[self.tableView reloadData]

If you don't understand anything about what I'm saying then I advise you to first read some manuals about tableviews before starting asking questions on SO :)


问:
Loading View in Swift
quick question! Sorry for noobiness in advance. I recentely started developing iOS applications and wanted to load a view for clicking a button. Im working in swift4. </p>

```<code> @IBAction func btnAddItem_AddDrinks_Click(_ sender: Any) {
        //[self dismissViewControllerAnimated:YES completion:nil];
        //[self.navigationController popViewControllerAnimated:YES];
        if strIsSpecial == nil {
            ValidationString.sharedManager().showAlert(withTitle: "", messageBody: "Please select either Regular, Special or Free")
        }
        else if ValidationString.sharedManager().isNullString(txtfldOunce.text!) == true {
          //  ValidationString.sharedManager().showAlert(withTitle: ALERT_TITLE, messageBody: "Ounce" + (ALERT_FIELD_SHOULD_NOT_BLANK))

            let alert = UIAlertController(title: "Alert", message: "Ounces shouldn't be left blank", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
        else if ValidationString.sharedManager().isNullString(txtfldUserReference_AddDrinks.text!) == true {

            let alert = UIAlertController(title: "Alert", message: "Drink Name shouldn't be left blank", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)

            //ValidationString.sharedManager().showAlert(withTitle: ALERT_TITLE, messageBody: "Drink Name" + (ALERT_FIELD_SHOULD_NOT_BLANK))
        }
        else {
            if view_Loading != nil {
                view_Loading?.removeFromSuperview()
                view_Loading = nil
                obj_LoadView = nil
            }
            obj_LoadView = LoadView(frame: <#CGRect#>)
            view_Loading = obj_LoadView?.showActivity("Loading....")
            view.addSubview(view_Loading!)
            view.isUserInteractionEnabled = false
</code>```

<p>The current error is "Editor is placeholder" for  obj_LoadView = LoadView(frame: <#CGRect#>). I know I need to put something for CGRect, but unsure what. Any help is appreciated, thanks! </p>

答:
I personally like to create my own activityIndicatorView

class LoadingView: UIView {

    private var activityIndicatorView: UIActivityIndicatorView {

        let view = UIActivityIndicatorView(activityIndicatorStyle: .white)
        view.startAnimating()

        view.center = self.center
        return view
    }

    private var isPresenting: Bool = false

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .black
        self.alpha = 0.0
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func present() {
        guard let window = UIApplication.shared.keyWindow else { return }
        window.addSubview(self)
        fadeIn()
    }

    func dismiss() {
        guard isPresenting == true else { return }
        fadeOut()
    }

    private func fadeIn() {
        UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
            self.alpha = 0.5
        }) { (bool: Bool) in
            self.addSubview(self.activityIndicatorView)
            self.isPresenting = true
        }
    }

    private func fadeOut() {
        UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
            self.alpha = 0.0
        }) { (bool: Bool) in
            self.removeFromSuperview()
            self.isPresenting = false
        }
    }
}```

Title: Loading View in Swift

Body:
quick question! Sorry for noobiness in advance. I recentely started developing iOS applications and wanted to load a view for clicking a button. Im working in swift4.

 @IBAction func btnAddItem_AddDrinks_Click(_ sender: Any) {
        //[self dismissViewControllerAnimated:YES completion:nil];
        //[self.navigationController popViewControllerAnimated:YES];
        if strIsSpecial == nil {
            ValidationString.sharedManager().showAlert(withTitle: "", messageBody: "Please select either Regular, Special or Free")
        }
        else if ValidationString.sharedManager().isNullString(txtfldOunce.text!) == true {
          //  ValidationString.sharedManager().showAlert(withTitle: ALERT_TITLE, messageBody: "Ounce" + (ALERT_FIELD_SHOULD_NOT_BLANK))

            let alert = UIAlertController(title: "Alert", message: "Ounces shouldn't be left blank", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
        else if ValidationString.sharedManager().isNullString(txtfldUserReference_AddDrinks.text!) == true {

            let alert = UIAlertController(title: "Alert", message: "Drink Name shouldn't be left blank", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)

            //ValidationString.sharedManager().showAlert(withTitle: ALERT_TITLE, messageBody: "Drink Name" + (ALERT_FIELD_SHOULD_NOT_BLANK))
        }
        else {
            if view_Loading != nil {
                view_Loading?.removeFromSuperview()
                view_Loading = nil
                obj_LoadView = nil
            }
            obj_LoadView = LoadView(frame: <#CGRect#>)
            view_Loading = obj_LoadView?.showActivity("Loading....")
            view.addSubview(view_Loading!)
            view.isUserInteractionEnabled = false

The current error is "Editor is placeholder" for  obj_LoadView = LoadView(frame: <#CGRect#>). I know I need to put something for CGRect, but unsure what. Any help is appreciated, thanks!


问:
Comparing std::functions for equality?
How can I compare two C++11 std::functions with operator==, and return true if both of said functions refer to the same function pointer?

答: If the std::function<T(U...)> f is a member function,the fnPointer will be null.

Title: Comparing std::functions for equality?


问:
viewpager using bottom navigation view is not swiping the fragments
I want to swipe the tabs given at bottom. For that I have used ViewPager using BottomNavigationView by this. My code is given below.

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/navigation"
        android:layout_alignParentTop="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:menu="@menu/bottom_navigation_items"
        android:background="@color/colorPrimary"
        app:itemIconTint="@color/colorAccent"
        app:itemTextColor="@android:color/white"></android.support.design.widget.BottomNavigationView>
</RelativeLayout>
</code>```

Java code is

```<code>    public class MainActivity extends AppCompatActivity {
    BottomNavigationView bottomNavigationView;
    ViewPager viewPager;
    MenuItem prevMenuItem;
    FragmentWallet fragmentWallet;
    FragmentNavigationDrawer fragmentNavigationDrawer;
    FragmentHome fragmentHome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.action_menu_home:
                        viewPager.setCurrentItem(0);
                        break;
                    case R.id.action_menu_wallet:
                        viewPager.setCurrentItem(1);
                        break;
                    case R.id.action_menu_navigation_d:
                        viewPager.setCurrentItem(2);
                        break;
                }

                return false;
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (prevMenuItem != null) {
                    prevMenuItem.setChecked(false);
                } else {
                    bottomNavigationView.getMenu().getItem(0).setChecked(false);
                }
                Log.d("page", "onPageSelected: " + position);
                bottomNavigationView.getMenu().getItem(position).setChecked(true);
                prevMenuItem = bottomNavigationView.getMenu().getItem(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        setupViewPager(viewPager);

    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        fragmentHome = new FragmentHome(); // this should be in `FragmentPagerAdapter.getItem()`
        fragmentWallet = new FragmentWallet(); // this should be in `FragmentPagerAdapter.getItem()`
        fragmentNavigationDrawer = new FragmentNavigationDrawer(); // this should be in `FragmentPagerAdapter.getItem()`

        viewPagerAdapter.addFragment(fragmentHome); // this can cause crashes
        viewPagerAdapter.addFragment(fragmentWallet); // this can cause crashes
        viewPagerAdapter.addFragment(fragmentNavigationDrawer); // this can cause crashes
        viewPager.setAdapter(viewPagerAdapter);
    }
}
</code>```

View Pager Adapter code is

```<code> public class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>(); // this line can cause crashes

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }
    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment) {
        mFragmentList.add(fragment);  // this line can cause crashes
    }
}
</code>```

It works good for navigating from one fragment to another, but it is not swiping the fragments. Please help,or should I have to switch some another solution.

答:
Remove this part:</p>

```<code>viewPager.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });
</code>```

Body:
I want to swipe the tabs given at bottom. For that I have used ViewPager using BottomNavigationView by this. My code is given below.

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/navigation"
        android:layout_alignParentTop="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:menu="@menu/bottom_navigation_items"
        android:background="@color/colorPrimary"
        app:itemIconTint="@color/colorAccent"
        app:itemTextColor="@android:color/white"></android.support.design.widget.BottomNavigationView>
</RelativeLayout>

Java code is

    public class MainActivity extends AppCompatActivity {
    BottomNavigationView bottomNavigationView;
    ViewPager viewPager;
    MenuItem prevMenuItem;
    FragmentWallet fragmentWallet;
    FragmentNavigationDrawer fragmentNavigationDrawer;
    FragmentHome fragmentHome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.action_menu_home:
                        viewPager.setCurrentItem(0);
                        break;
                    case R.id.action_menu_wallet:
                        viewPager.setCurrentItem(1);
                        break;
                    case R.id.action_menu_navigation_d:
                        viewPager.setCurrentItem(2);
                        break;
                }

                return false;
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (prevMenuItem != null) {
                    prevMenuItem.setChecked(false);
                } else {
                    bottomNavigationView.getMenu().getItem(0).setChecked(false);
                }
                Log.d("page", "onPageSelected: " + position);
                bottomNavigationView.getMenu().getItem(position).setChecked(true);
                prevMenuItem = bottomNavigationView.getMenu().getItem(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        setupViewPager(viewPager);

    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        fragmentHome = new FragmentHome(); // this should be in `FragmentPagerAdapter.getItem()`
        fragmentWallet = new FragmentWallet(); // this should be in `FragmentPagerAdapter.getItem()`
        fragmentNavigationDrawer = new FragmentNavigationDrawer(); // this should be in `FragmentPagerAdapter.getItem()`

        viewPagerAdapter.addFragment(fragmentHome); // this can cause crashes
        viewPagerAdapter.addFragment(fragmentWallet); // this can cause crashes
        viewPagerAdapter.addFragment(fragmentNavigationDrawer); // this can cause crashes
        viewPager.setAdapter(viewPagerAdapter);
    }
}

View Pager Adapter code is

 public class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>(); // this line can cause crashes

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }
    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment) {
        mFragmentList.add(fragment);  // this line can cause crashes
    }
}

It works good for navigating from one fragment to another, but it is not swiping the fragments. Please help,or should I have to switch some another solution.

Body:
Remove this part:

viewPager.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });


答:
If you are adding tableview as a "addSubview(noOfEventDaysTableView)" in "cellForRowAt indexPath" . Then please add them in tableview cell methods awakeFromNib().

```<code>override func awakeFromNib() {
    super.awakeFromNib()
    noOfEventDaysTableView = UITableView(frame: CGRect(x:(cell?.secondCircleGraph.frame.maxX)! + 5,y:10,width:60,height:50), style: .plain)
    cell?.contentView.addSubview(noOfEventDaysTableView)
    // Initialization code
}
</code>```

And for compare the table view set the tag value for tableView

```<code>tableView.tag = 999
</code>```

Title: Tableview creating multiple times inside cellforrowatindexpath delegate method

Body:
If you are adding tableview as a "addSubview(noOfEventDaysTableView)" in "cellForRowAt indexPath" . Then please add them in tableview cell methods awakeFromNib().

override func awakeFromNib() {
    super.awakeFromNib()
    noOfEventDaysTableView = UITableView(frame: CGRect(x:(cell?.secondCircleGraph.frame.maxX)! + 5,y:10,width:60,height:50), style: .plain)
    cell?.contentView.addSubview(noOfEventDaysTableView)
    // Initialization code
}

And for compare the table view set the tag value for tableView

tableView.tag = 999


问:
shell Can't exit while loop normally.
```<code>$ cat Judge_file.sh
#!/bin/bash
i=1
while [ $i ];do
    read -p "Enter your MO or attribute name: " name
    if [ $name = "q" ];then
        i=0
        continue
    else
        grep -q $name *.txt    #check character existence in currently directory of all .txt file
        if [ $? -eq 0 ];then
            echo "Name exists,send to file 2"
            echo $name >> 2.txt
        else
            echo "Name missing,send to file 1"
            echo $name >> 1.txt
        fi
    fi
done
$ . ./Judge_file.sh
Enter your MO or attribute name: chenghuang
Name exists,send to file 2
Enter your MO or attribute name: llkk
Name missing,send to file 1
Enter your MO or attribute name: q
Enter your MO or attribute name: q
Enter your MO or attribute name: q
</code>```

This is a program used for judge a character existence.

When I type "q", it should be exited. but why it still let me input.

and one thing really strange when I verified the while [ $i ] as while [ 0 ] ,then while loop still let me input , until I type Ctrl+c exit.

答:
Well I'll pick the important part of your script for the problem:

Instead:

```<code>...
if [ $name = "q" ];then
    i=0
    continue
else
...
</code>```

you should have:

```<code>...
if [ $name = "q" ];then
    i=0
    break
else
...
</code>```

Then the script will terminate when you press the q key.

The continue continues to the end of the loop.  If you want to terminate the while loop you have to use break.

First edit

Based on the comment I think you misunderstood the bash [] meaning.

The while [0] is same as tests 0.  Which is always true and thus leading to a endless loop.

I would really recommend using true/false instead of 1/0.  To rewrite your code with continue:

```<code>#!/bin/bash
i=true
while $i;do
    read -p "Enter your MO or attribute name: " name
    if [ $name = "q" ];then
        i=false
        continue
    else
        grep -q $name *.txt    #check character existence in currently directory of all .txt file
        if [ $? -eq 0 ];then
            echo "Name exists,send to file 2"
            echo $name >> 2.txt
        else
            echo "Name missing,send to file 1"
            echo $name >> 1.txt
        fi
    fi
done
</code>```

If you insist on using 1/0 you can do it as following

```<code>#!/bin/bash
i=1
while (( $i ));do
    read -p "Enter your MO or attribute name: " name
    if [ $name = "q" ];then
        i=0
        continue
    else
        grep -q $name *.txt    #check character existence in currently directory of all .txt file
        if [ $? -eq 0 ];then
            echo "Name exists,send to file 2"
            echo $name >> 2.txt
        else
            echo "Name missing,send to file 1"
            echo $name >> 1.txt
        fi
    fi
done
</code>```

Now it probably behaves like you would expect 0 as false and 1 as true.

Title: shell Can't exit while loop normally.

Body:
$ cat Judge_file.sh
#!/bin/bash
i=1
while [ $i ];do
    read -p "Enter your MO or attribute name: " name
    if [ $name = "q" ];then
        i=0
        continue
    else
        grep -q $name *.txt    #check character existence in currently directory of all .txt file
        if [ $? -eq 0 ];then
            echo "Name exists,send to file 2"
            echo $name >> 2.txt
        else
            echo "Name missing,send to file 1"
            echo $name >> 1.txt
        fi
    fi
done
$ . ./Judge_file.sh
Enter your MO or attribute name: chenghuang
Name exists,send to file 2
Enter your MO or attribute name: llkk
Name missing,send to file 1
Enter your MO or attribute name: q
Enter your MO or attribute name: q
Enter your MO or attribute name: q

This is a program used for judge a character existence.

When I type "q", it should be exited. but why it still let me input.

and one thing really strange when I verified the while [ $i ] as while [ 0 ] ,then while loop still let me input , until I type Ctrl+c exit.

Body:
Well I'll pick the important part of your script for the problem:

Instead:

...
if [ $name = "q" ];then
    i=0
    continue
else
...

you should have:

...
if [ $name = "q" ];then
    i=0
    break
else
...

Then the script will terminate when you press the q key.

The continue continues to the end of the loop.  If you want to terminate the while loop you have to use break.

First edit

Based on the comment I think you misunderstood the bash [] meaning.

The while [0] is same as tests 0.  Which is always true and thus leading to a endless loop.

I would really recommend using true/false instead of 1/0.  To rewrite your code with continue:

#!/bin/bash
i=true
while $i;do
    read -p "Enter your MO or attribute name: " name
    if [ $name = "q" ];then
        i=false
        continue
    else
        grep -q $name *.txt    #check character existence in currently directory of all .txt file
        if [ $? -eq 0 ];then
            echo "Name exists,send to file 2"
            echo $name >> 2.txt
        else
            echo "Name missing,send to file 1"
            echo $name >> 1.txt
        fi
    fi
done

If you insist on using 1/0 you can do it as following

#!/bin/bash
i=1
while (( $i ));do
    read -p "Enter your MO or attribute name: " name
    if [ $name = "q" ];then
        i=0
        continue
    else
        grep -q $name *.txt    #check character existence in currently directory of all .txt file
        if [ $? -eq 0 ];then
            echo "Name exists,send to file 2"
            echo $name >> 2.txt
        else
            echo "Name missing,send to file 1"
            echo $name >> 1.txt
        fi
    fi
done

Now it probably behaves like you would expect 0 as false and 1 as true.


问:
Is this an abuse of Scala pattern matching?
As in most languages, Scala has an if statement. However, using pattern matching I can achieve the exact (?) same result using code of the form:

```<code>(condition) match {
  case true =>  { /* handle the true case */ }
  case false => { /* handle the false case */ }
}
</code>```

This feels like an abuse of the mechanism, but I find it hard to explain why. Can wiser heads help me understand the position?

答:
The match compiles to the equivalent of

```<code>val scrutinee = condition
if (scrutinee == true) /* handle success case  */
else if (scrutinee == false) /* handle failure case */
else throw new MatchException()
</code>```

so it's semantically identical. But why would you? It's more verbose, more syntax-heavy, and less clear than the if expression.

Body:
As in most languages, Scala has an if statement. However, using pattern matching I can achieve the exact (?) same result using code of the form:

(condition) match {
  case true =>  { /* handle the true case */ }
  case false => { /* handle the false case */ }
}

This feels like an abuse of the mechanism, but I find it hard to explain why. Can wiser heads help me understand the position?

Body:
The match compiles to the equivalent of

val scrutinee = condition
if (scrutinee == true) /* handle success case  */
else if (scrutinee == false) /* handle failure case */
else throw new MatchException()

so it's semantically identical. But why would you? It's more verbose, more syntax-heavy, and less clear than the if expression.


问:
window.print() not working in Chrome
In the below code, the window.print() function not working in Chrome.what to do?

 <input type="text" placeholder="Enter Item Name" size="20">

 <input type="num" placeholder="quantity" size="20" id="qty">

 <input type="text" placeholder="prize" size="20" id="rs"> <button onclick="mul()" id="add">add </button>

 <input type="text"  size="20" id="amt">  <input type="text" size="7" id="total"> <button onclick="print()" id="print"> print

```

答:
Just call window.print() in the onclick of button. No need to define a function for it.</p>

```<code><body>
<div class="row">
 <div class="col-sm-3" id="itemin"> <input type="text" placeholder="Enter Item Name" size="20"> </div>
 <div class="col-sm-2" id="qtyin">
   <input type="num" placeholder="quantity" size="20" id="qty"></div>
 <div class="col-sm-3" id="rsin"> <input type="text" placeholder="prize" size="20" id="rs"> <button onclick="mul()" id="add">Add </button> </div>
 <div class="col-sm-3" id="amtin">
   <input type="text"  size="20" id="amt">
   <input type="text" size="7" id="total">
   <button onclick="window.print()" id="print">Print</button>
    </div>
</body>
</code>```

Title: window.print() not working in Chrome

Body:
Just call window.print() in the onclick of button. No need to define a function for it.

<body>
<div class="row">
 <div class="col-sm-3" id="itemin"> <input type="text" placeholder="Enter Item Name" size="20"> </div>
 <div class="col-sm-2" id="qtyin">
   <input type="num" placeholder="quantity" size="20" id="qty"></div>
 <div class="col-sm-3" id="rsin"> <input type="text" placeholder="prize" size="20" id="rs"> <button onclick="mul()" id="add">Add </button> </div>
 <div class="col-sm-3" id="amtin">
   <input type="text"  size="20" id="amt">
   <input type="text" size="7" id="total">
   <button onclick="window.print()" id="print">Print</button>
    </div>
</body>


问:
Api calls chaining to some limit Rxjava2 + Retrofit2
I'm using Retrofit2 with Rxjava to make API calls. I have to make multiple API calls ( of the same API ), let's say 100 of them. Now I want, at max 5 of them to be executed parallelly. So if 5 API calls are going on, 6th one should wait. As soon as any one of those ongoing 5 calls is completed, 6th one should start. I don't want this in bulk of 5 where first 5 completes and only after that next 5 happens.

I'm not sure how can I achieve with Rxjava and that's why I don't have any snippet to post. Any help would be great

答:
RxJava has certain operators that can limit the number of threads in action.

```<code>observable
  .flatMap( input -> apiCallReturningObservable( input ), 5 )
  .subscribe();
</code>```

will have a maximum of 5 invocations of apiCallReturningObservable() at one time.

Body:
RxJava has certain operators that can limit the number of threads in action.

observable
  .flatMap( input -> apiCallReturningObservable( input ), 5 )
  .subscribe();

will have a maximum of 5 invocations of apiCallReturningObservable() at one time.


问:
ms Access '16 - Continuous form - OrderBy textbox value created with expression
I have a form that shows the records from Table-A, it is a continuous form. I have a textbox that uses a DCount expression to count records from Table-B that share the same SOP-Number.

```<code>=DCount("*","[Table-B]","SOP = " & [SOP])
</code>```

This works but I don't know how I would go about sorting that column based of the resulting values. The other columns are sorted thus:

```<code>" ORDER BY [FIELD NAME] ASC;"
</code>```

So without a field I don't know how (or if) I can sort the form.
Could I create a RecordSet to store the values then sort by that field (I don't know if this is even possible)

Thank you

Dan

Access 2016 (365)

答:
You could change the datasource to

select ,DCount('''[Table-B],'SOP=' & SOP) from [Table-A]
order by DCount('*''[Table-B],'SOP=' & SOP)

This is not a good soulution i Table-A is big.

Body:
I have a form that shows the records from Table-A, it is a continuous form. I have a textbox that uses a DCount expression to count records from Table-B that share the same SOP-Number.

=DCount("*","[Table-B]","SOP = " & [SOP])

This works but I don't know how I would go about sorting that column based of the resulting values. The other columns are sorted thus:

" ORDER BY [FIELD NAME] ASC;"

So without a field I don't know how (or if) I can sort the form.
Could I create a RecordSet to store the values then sort by that field (I don't know if this is even possible)

Thank you

Dan

Access 2016 (365)


问:
Error: [ng:areq] Argument 'fn' is not a function, got undefined (problems with Angular service)
I have a problem with an Angular 1.x Service. This is the code:

```<code>export const MyService = () => {

   //some code
};
</code>```

And when I try to inject that Service into this Controller...

```<code>export default function MyController(MyService) {
    'ngInject';

    //some code
}
</code>```

...it throws the following error:

```<code>Error: [ng:areq] Argument 'fn' is not a function, got undefined
</code>```

How can I fix it?

答: Fixed it!! It was just a matter of mistyping </p>

Body:
I have a problem with an Angular 1.x Service. This is the code:

export const MyService = () => {

   //some code
};

And when I try to inject that Service into this Controller...

export default function MyController(MyService) {
    'ngInject';

    //some code
}

...it throws the following error:

Error: [ng:areq] Argument 'fn' is not a function, got undefined

How can I fix it?


问:
Help me find the problem with my solution to Project Euler #12 in Haskell
I'm a total newbie to Haskell, and programming in general, but I'm trying to work through some Project Euler problems because I do like problem solving.  However, I have a problem with problem #12.

I devised a solution I thought would work, but alas, it does not.

Can you help me by opening my eyes to the problem with my code,
and maybe push me in the right direction towards fixing it?  Thank you.

Here is the code:

```<code>triangleNumber = scanl1 (+) [1..]

factors n = [x | x <- [1..n], n `mod` x == 0]

numFactors = length . factors

eulerTwelve = find ((>500) . numFactors) triangleNumber
</code>```

Thank you very much!  :)

答:
I copied it and what it threw me was an error that find couldn't be found. That is because you need to import the module List where find is in:

```<code>import Data.List
</code>```

By the way, you should optimize your factors function.

ContentLicense: CC BY-SA 2.5

Body:
I'm a total newbie to Haskell, and programming in general, but I'm trying to work through some Project Euler problems because I do like problem solving.  However, I have a problem with problem #12.

I devised a solution I thought would work, but alas, it does not.

Can you help me by opening my eyes to the problem with my code,
and maybe push me in the right direction towards fixing it?  Thank you.

Here is the code:

triangleNumber = scanl1 (+) [1..]

factors n = [x | x <- [1..n], n `mod` x == 0]

numFactors = length . factors

eulerTwelve = find ((>500) . numFactors) triangleNumber

Thank you very much!  :)

Body:
I copied it and what it threw me was an error that find couldn't be found. That is because you need to import the module List where find is in:

import Data.List

By the way, you should optimize your factors function.


问:
obj-c app is not localized programmatically
I try to change the language programmatically through the extension of NSBundle -- NSBundle setLanguage: (NSString *) language. I have several application localizations.

Some localizations work correctly, but when installing Spanish and Italian languages, instead of localized strings, I see the names of the localizable.strings parameters. The same happens with some other languages, but not with all the lines.

Tell me please what can be the problem

UPD:

here is some of the lines in English:

```<code>"CLOSE_TITLE"         = "Close";
"PAYMENT_TITLE"       = "Pay";
"PAYMENT_TITLE_IN"    = "Deposit";
</code>```

and they are also in Spanish:

```<code>"CLOSE_TITLE" = "Cerrar";
"PAYMENT_TITLE" = "Retirar";
"PAYMENT_TITLE_IN" = "Depositar";
</code>```

There is code of extension:

```<code>#import "NSBundle+Language.h"
#import <objc/runtime.h>

static const char _bundle=0;

@interface BundleEx : NSBundle
@end

@implementation BundleEx
-(NSString*)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName
{
    NSBundle* bundle=objc_getAssociatedObject(self, &_bundle);
    return bundle ? [bundle localizedStringForKey:key value:value table:tableName] : [super localizedStringForKey:key value:value table:tableName];
}
@end

@implementation NSBundle (Language)

+(void)setLanguage:(NSString*)language
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
                  {
                      object_setClass([NSBundle mainBundle],[BundleEx class]);
                  });
    objc_setAssociatedObject([NSBundle mainBundle], &_bundle, language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
</code>```

答: How are you dragging the new localization files to the project? I found out that when you add new languages to xCode, it's best to first remove the whole folder from xCode completely and then drag everything including the new languages back all at the same time :)</p>

Body:
I try to change the language programmatically through the extension of NSBundle -- NSBundle setLanguage: (NSString *) language. I have several application localizations.

Some localizations work correctly, but when installing Spanish and Italian languages, instead of localized strings, I see the names of the localizable.strings parameters. The same happens with some other languages, but not with all the lines.

Tell me please what can be the problem

UPD:

here is some of the lines in English:

"CLOSE_TITLE"         = "Close";
"PAYMENT_TITLE"       = "Pay";
"PAYMENT_TITLE_IN"    = "Deposit";

and they are also in Spanish:

"CLOSE_TITLE" = "Cerrar";
"PAYMENT_TITLE" = "Retirar";
"PAYMENT_TITLE_IN" = "Depositar";

There is code of extension:

#import "NSBundle+Language.h"
#import <objc/runtime.h>

static const char _bundle=0;

@interface BundleEx : NSBundle
@end

@implementation BundleEx
-(NSString*)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName
{
    NSBundle* bundle=objc_getAssociatedObject(self, &_bundle);
    return bundle ? [bundle localizedStringForKey:key value:value table:tableName] : [super localizedStringForKey:key value:value table:tableName];
}
@end

@implementation NSBundle (Language)

+(void)setLanguage:(NSString*)language
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
                  {
                      object_setClass([NSBundle mainBundle],[BundleEx class]);
                  });
    objc_setAssociatedObject([NSBundle mainBundle], &_bundle, language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end


问:
Rolling join in data.table doesn't give desired output
I have a data.table (dt) with 3 columns ("times","name","price"). I aim to find the price when I input a number and a time value. However, when I input a time that is not in the dt I want to get the next (or the last) price that it had.
I am doing this, but it doesn't seem to work as I get NA if the price is not in the dt.

```<code>library(data.table)
dt <- data.table(
times = c("2017-02-13 07:02:45","2017-02-13 07:02:48","2017-02-13 07:02:49"),
name = c("name1", "name1", "name1"),
price = c(10,15,20)
)

setkey(dt, times, name)

nm = "name1"
tt = "2017-02-13 07:02:46"
dt[times == tt & name == nm]

pricelookup <- function(tt, nm, data = dt) {
dt[J(tt, nm), roll = TRUE][, price]
}
pricelookup(tt,nm)
</code>```

答:
Maybe a non-equi join is better. Using:

```<code>dt[CJ(tt, nm), on = .(times <= V1, name = V2)]
</code>```

gives:

```<code>                 times  name price
1: 2017-02-13 07:02:46 name1    10
</code>```

In your function:

```<code>pricelookup <- function(tt, nm, data = dt) {
  dt[CJ(tt, nm), on = .(times <= V1, name = V2)][, price]
}
</code>```

which now will give the correct output:

```<code>> pricelookup(tt, nm)
[1] 10
</code>```

When you only want the first result for the join, add mult = 'first' to the join operation. To see what this does, compare the output of the following two joins:

```<code>> dt[CJ(tt, nm), on = .(times >= V1, name = V2)]
                 times  name price
1: 2017-02-13 07:02:46 name1    15
2: 2017-02-13 07:02:46 name1    20

> dt[CJ(tt, nm), on = .(times >= V1, name = V2), mult = 'first']
                 times  name price
1: 2017-02-13 07:02:46 name1    15
</code>```

Used data:

```<code>dt <- data.table(
  times = as.POSIXct(c("2017-02-13 07:02:45","2017-02-13 07:02:48","2017-02-13 07:02:49"), format = "%Y-%m-%d %H:%M:%S"),
  name = c("name1", "name1", "name1"),
  price = c(10,15,20)
)

setkey(dt, times, name)

nm = "name1"
tt = as.POSIXct("2017-02-13 07:02:46", format = "%Y-%m-%d %H:%M:%S")
</code>```

Body:
I have a data.table (dt) with 3 columns ("times","name","price"). I aim to find the price when I input a number and a time value. However, when I input a time that is not in the dt I want to get the next (or the last) price that it had.
I am doing this, but it doesn't seem to work as I get NA if the price is not in the dt.

library(data.table)
dt <- data.table(
times = c("2017-02-13 07:02:45","2017-02-13 07:02:48","2017-02-13 07:02:49"),
name = c("name1", "name1", "name1"),
price = c(10,15,20)
)

setkey(dt, times, name)

nm = "name1"
tt = "2017-02-13 07:02:46"
dt[times == tt & name == nm]

pricelookup <- function(tt, nm, data = dt) {
dt[J(tt, nm), roll = TRUE][, price]
}
pricelookup(tt,nm)

Body:
Maybe a non-equi join is better. Using:

dt[CJ(tt, nm), on = .(times <= V1, name = V2)]

gives:

                 times  name price
1: 2017-02-13 07:02:46 name1    10

In your function:

pricelookup <- function(tt, nm, data = dt) {
  dt[CJ(tt, nm), on = .(times <= V1, name = V2)][, price]
}

which now will give the correct output:

> pricelookup(tt, nm)
[1] 10

When you only want the first result for the join, add mult = 'first' to the join operation. To see what this does, compare the output of the following two joins:

> dt[CJ(tt, nm), on = .(times >= V1, name = V2)]
                 times  name price
1: 2017-02-13 07:02:46 name1    15
2: 2017-02-13 07:02:46 name1    20

> dt[CJ(tt, nm), on = .(times >= V1, name = V2), mult = 'first']
                 times  name price
1: 2017-02-13 07:02:46 name1    15

Used data:

dt <- data.table(
  times = as.POSIXct(c("2017-02-13 07:02:45","2017-02-13 07:02:48","2017-02-13 07:02:49"), format = "%Y-%m-%d %H:%M:%S"),
  name = c("name1", "name1", "name1"),
  price = c(10,15,20)
)

setkey(dt, times, name)

nm = "name1"
tt = as.POSIXct("2017-02-13 07:02:46", format = "%Y-%m-%d %H:%M:%S")


问:
Generating repeated HTML code without a Repeater
How do I duplicate a block of html at the click of a button (for example, add a new row to a non-ASP table)?

My first thought was to use an ASP Repeater. However Repeaters are designed to be databound. While there are some workarounds to using a Repeater to repeat code that isn't databound, this seems like the wrong way to go about it.

ASP.NET has to have a recommended way to do this. I don't think one has to resort to AJAX for this (cue the laser-focus of your responses to be on AJAX...).

I made a JSFiddle to visualize the problem, although I'm not necessarily asking for a JS solution:

example html:

```<code><table>
  <thead>
    <th>Col1</th>
    <th>Col2</th>
  </thead>
  <tbody>
    <tr>
      <td><input type="text" value=""></td>
      <td><button>Button</button></td>
    </tr>
  </tbody>
</table>
<button>Add Row</button>
</code>```

答: You can duplicate the row by clicking the button. For this you need to assign Id to Row, and then get this row by Id in Javascript function being called in onclick attribute of button. after getting this you can append the html of this row to lastly added row in table. In this way you can add multiple rows by multiple clicks of button. Hopefully this will help you!</p>

Body:
How do I duplicate a block of html at the click of a button (for example, add a new row to a non-ASP table)?

My first thought was to use an ASP Repeater. However Repeaters are designed to be databound. While there are some workarounds to using a Repeater to repeat code that isn't databound, this seems like the wrong way to go about it.

ASP.NET has to have a recommended way to do this. I don't think one has to resort to AJAX for this (cue the laser-focus of your responses to be on AJAX...).

I made a JSFiddle to visualize the problem, although I'm not necessarily asking for a JS solution:

example html:

    Col1
    Col2

      <input type="text" value="">
      <button>Button</button>

<button>Add Row</button>


问:
Changing this Python program to have function def()
The following Python program flips a coin several times, then reports the longest series of heads and tails. I am trying to convert this program into a program that uses functions so it uses basically less code. I am very new to programming and my teacher requested this of us, but I have no idea how to do it. I know I'm supposed to have the function accept 2 parameters: a string or list, and a character to search for. The function should return, as the value of the function, an integer which is the longest sequence of that character in that string. The function shouldn't accept input or output from the user.

```<code>import random

print("This program flips a coin several times, \nthen reports the longest
series of heads and tails")

cointoss = int(input("Number of times to flip the coin: "))

varlist = []
i = 0
varstring = ' '

 while i < cointoss:
    r = random.choice('HT')

    varlist.append(r)
    varstring = varstring + r
    i += 1

print(varstring)

print(varlist)

print("There's this many heads: ",varstring.count("H"))
print("There's this many tails: ",varstring.count("T"))
print("Processing input...")

i = 0
longest_h = 0
longest_t = 0
inarow = 0
prevIn = 0

while i < cointoss:
    print(varlist[i])
    if varlist[i] == 'H':
        prevIn += 1
        if prevIn > longest_h:
            longest_h = prevIn
        print("",longest_h,"")

        inarow = 0

    if varlist[i] == 'T':
        inarow += 1
        if inarow > longest_t:
            longest_t = inarow
        print("",longest_t,"")

        prevIn = 0

    i += 1
print ("The longest series of heads is: ",longest_h)

print ("The longest series of tails is: ",longest_t)
</code>```

If this is asking too much, any explanatory help would be really nice instead. All I've got so far is:

```<code>def flip (a, b):
    flipValue = random.randint
</code>```

but it's barely anything.

答:
Counting the longest run

Let see what you have asked for

I'm supposed to have the function accept 2 parameters: a string or list,

or, generalizing just a bit, a sequence

and a character

again, we'd speak, generically, of an item

to search for. The function should return, as the value of the
    function, an integer which is the longest sequence of that character
    in that string.

My implementation of the function you are asking for, complete of doc
string, is

```<code>def longest_run(i, s):
    'Counts the longest run of item "i" in sequence "s".'
    c, m = 0, 0
    for el in s:
        if el==i:
            c += 1
        elif c:
            m = m if m >= c else c
            c = 0
    return m
</code>```

We initialize c (current run) and m (maximum run so far) to zero,
then we loop, looking at every element el of the argument sequence s.

The logic is straightforward but for elif c: whose block is executed at the end of a run (because c is greater than zero and logically True) but not when the previous item (not the current one) was not equal to i. The savings are small but are savings...

Flipping coins (and more...)

How can we simulate flipping n coins?  We abstract the problem and recognize that flipping n coins corresponds to choosing from a collection of possible outcomes (for a coin, either head or tail) for n times.

As it happens, the random module of the standard library has the exact answer to this problem

```<code>In [52]: random.choices?
Signature: choices(population, weights=None, *, cum_weights=None, k=1)
Docstring:
Return a k sized list of population elements chosen with replacement.

If the relative weights or cumulative weights are not specified,
the selections are made with equal probability.
File:      ~/lib/miniconda3/lib/python3.6/random.py
Type:      method
</code>```

Our implementation, aimed at hiding details, could be

```<code>def roll(n, l):
    '''Rolls "n" times a dice/coin whose face values are listed in "l".

    E.g., roll(2, range(1,21)) -> [12, 4] simulates rolling 2 icosahedron dices.
'''
    from random import choices
    return choices(l, k=n)
</code>```

Putting this together

```<code>def longest_run(i, s):
    'Counts the longest run of item "i" in sequence "s".'
    c, m = 0, 0
    for el in s:
        if el==i:
            c += 1
        elif c:
            m = m if m >= c else c
            c = 0
    return m
def roll(n, l):
    '''Rolls "n" times a dice/coin whose face values are listed in "l".

    E.g., roll(2, range(1,21)) -> [12, 4] simulates rolling 2 icosahedron dices.
'''
    from random import choices
    return choices(l, k=n)

N = 100 # n. of flipped coins
h_or_t = ['h', 't']
random_seq_of_h_or_t = flip(N, h_or_t)
max_h = longest_run('h', random_seq_of_h_or_t)
max_t = longest_run('t', random_seq_of_h_or_t)
</code>```

Body:
The following Python program flips a coin several times, then reports the longest series of heads and tails. I am trying to convert this program into a program that uses functions so it uses basically less code. I am very new to programming and my teacher requested this of us, but I have no idea how to do it. I know I'm supposed to have the function accept 2 parameters: a string or list, and a character to search for. The function should return, as the value of the function, an integer which is the longest sequence of that character in that string. The function shouldn't accept input or output from the user.

import random

print("This program flips a coin several times, \nthen reports the longest
series of heads and tails")

cointoss = int(input("Number of times to flip the coin: "))

varlist = []
i = 0
varstring = ' '

 while i < cointoss:
    r = random.choice('HT')

    varlist.append(r)
    varstring = varstring + r
    i += 1

print(varstring)

print(varlist)

print("There's this many heads: ",varstring.count("H"))
print("There's this many tails: ",varstring.count("T"))
print("Processing input...")

i = 0
longest_h = 0
longest_t = 0
inarow = 0
prevIn = 0

while i < cointoss:
    print(varlist[i])
    if varlist[i] == 'H':
        prevIn += 1
        if prevIn > longest_h:
            longest_h = prevIn
        print("",longest_h,"")

        inarow = 0

    if varlist[i] == 'T':
        inarow += 1
        if inarow > longest_t:
            longest_t = inarow
        print("",longest_t,"")

        prevIn = 0

    i += 1
print ("The longest series of heads is: ",longest_h)

print ("The longest series of tails is: ",longest_t)

If this is asking too much, any explanatory help would be really nice instead. All I've got so far is:

def flip (a, b):
    flipValue = random.randint

but it's barely anything.

Body:
Counting the longest run

Let see what you have asked for

I'm supposed to have the function accept 2 parameters: a string or list,

or, generalizing just a bit, a sequence

and a character

again, we'd speak, generically, of an item

to search for. The function should return, as the value of the
    function, an integer which is the longest sequence of that character
    in that string.

My implementation of the function you are asking for, complete of doc
string, is

def longest_run(i, s):
    'Counts the longest run of item "i" in sequence "s".'
    c, m = 0, 0
    for el in s:
        if el==i:
            c += 1
        elif c:
            m = m if m >= c else c
            c = 0
    return m

We initialize c (current run) and m (maximum run so far) to zero,
then we loop, looking at every element el of the argument sequence s.

The logic is straightforward but for elif c: whose block is executed at the end of a run (because c is greater than zero and logically True) but not when the previous item (not the current one) was not equal to i. The savings are small but are savings...

Flipping coins (and more...)

How can we simulate flipping n coins?  We abstract the problem and recognize that flipping n coins corresponds to choosing from a collection of possible outcomes (for a coin, either head or tail) for n times.

As it happens, the random module of the standard library has the exact answer to this problem

In [52]: random.choices?
Signature: choices(population, weights=None, *, cum_weights=None, k=1)
Docstring:
Return a k sized list of population elements chosen with replacement.

If the relative weights or cumulative weights are not specified,
the selections are made with equal probability.
File:      ~/lib/miniconda3/lib/python3.6/random.py
Type:      method

Our implementation, aimed at hiding details, could be

def roll(n, l):
    '''Rolls "n" times a dice/coin whose face values are listed in "l".

    E.g., roll(2, range(1,21)) -> [12, 4] simulates rolling 2 icosahedron dices.
'''
    from random import choices
    return choices(l, k=n)

Putting this together

def longest_run(i, s):
    'Counts the longest run of item "i" in sequence "s".'
    c, m = 0, 0
    for el in s:
        if el==i:
            c += 1
        elif c:
            m = m if m >= c else c
            c = 0
    return m
def roll(n, l):
    '''Rolls "n" times a dice/coin whose face values are listed in "l".

    E.g., roll(2, range(1,21)) -> [12, 4] simulates rolling 2 icosahedron dices.
'''
    from random import choices
    return choices(l, k=n)

N = 100 # n. of flipped coins
h_or_t = ['h', 't']
random_seq_of_h_or_t = flip(N, h_or_t)
max_h = longest_run('h', random_seq_of_h_or_t)
max_t = longest_run('t', random_seq_of_h_or_t)


问:
Is it possible to change the background color of QLPreviewController?
I'm attempting to view a PDF using QLPreviewController and I'm struggling to change some of the view attributes such as Navigation Bar header and the background of the view.

I was able to change the translucency of the Navigation Bar after subclassing QLPreviewController and changing the self.navigationController.navigationBar.translucency = NO; in the didViewAppear method, however I am unable to make changes to the navigationBar.title or the backgroundColor attributes of the self.view.backgroundColor.

Both the title and the background color will flicker when the view first loads but are immediately superseded by the PDF title string and the PDF itself which overlays the background color of the view.  The PDF pages appear over a black background.

I want to first know IF it's possible to subclass or otherwise change that background color to my own custom color, then I would love to know if anyone has any suggestions or know a decent solution to changing that background color.

The same goes for the title value to a lesser extent.

答:
In Swift 4 subclass UINavigationController and put in it:</p>

```<code>    override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    UINavigationBar.appearance(whenContainedInInstancesOf: [QLPreviewController.self]).isTranslucent = false
    UINavigationBar.appearance(whenContainedInInstancesOf: [QLPreviewController.self]).tintColor = #colorLiteral(red: 0.1889409125, green: 0.6918108463, blue: 0.9730117917, alpha: 1)
    UINavigationBar.appearance(whenContainedInInstancesOf: [QLPreviewController.self]).titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
  }
</code>```

Body:
In Swift 4 subclass UINavigationController and put in it:

    override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    UINavigationBar.appearance(whenContainedInInstancesOf: [QLPreviewController.self]).isTranslucent = false
    UINavigationBar.appearance(whenContainedInInstancesOf: [QLPreviewController.self]).tintColor = #colorLiteral(red: 0.1889409125, green: 0.6918108463, blue: 0.9730117917, alpha: 1)
    UINavigationBar.appearance(whenContainedInInstancesOf: [QLPreviewController.self]).titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
  }


问:
Java String.matches regex with OR pipe
I am trying to make the following match, but it is not returning true as I would expect:

```<code>String attrs = "id|fullname|email|title";
String regex = "fullname|email";
return attrs.matches(regex);
</code>```

Instead it returns false.

Why is this? I expect the | pipe in attrs to be interpreted literally as an ASCII character, and the | pipe in regex to be interpreted according to regular expressions (i.e. OR).

The reason I ask is because I am writing an application where I let the user set the attributes in the format attr1|attr2|attr3|..., and I want to verify his/her input by matching it against the possible attribute values: attr1|attr2|attr3|...|attr[n].

Help appreciated,

ktm

Got it working by doing

```<code>String regex = "id.*|fullname.*|email.*|title.*";
String attrs = "fullname|email";
return attrs.matches(regex);
</code>```

答:
The problem is that the pipe character is a meta-character in regexes.  It therefore needs to be escaped if you want to match a literal '|' character.

```<code>String attrs = "id|fullname|email|title";
String regex = "fullname\\|email";
return attrs.matches(regex);
</code>```

The other problem is that your usecase really needs to be using find rather than matches, and the String API does not support find.  This means you need to rewrite it to use an explicit Pattern and Matcher; e.g.

```<code>String attrs = "id|fullname|email|title";
Pattern regex = Pattern.compile("fullname\\|email");
return regex.matcher(attrs).find();
</code>```

But even this is not right:

What you really need to do (I think) is match the supplied attributes independent of the order in which the user provides them.

Naive regexes above will mismatch if the user enters something like "meaningfullname".

Really, this is getting too complicated to do using regexes.  Instead, you are better off with something like this:

```<code>List<String> attrs = Arrays.asList(
        new String[] {"id", "fullname", "email", "title"});
String[] suppliedAttrs = supplied.split("\\|");
for (String s: suppliedAttrs) {
    if (!attrs.contains(s)) {
        throw new IllegalArgumentException("'" + s + "' is not valid");
    }
}
</code>```

or if you just want to test if the attributes contain one or more of fullname and  email

```<code>String[] suppliedAttrs = supplied.split("\\|");
for (String s: suppliedAttrs) {
    if (s.equals("fullname") || s.equals("email")) {
        System.err.println("BINGO!");
    }
}
</code>```

Title: Java String.matches regex with OR pipe

Body:
I am trying to make the following match, but it is not returning true as I would expect:

String attrs = "id|fullname|email|title";
String regex = "fullname|email";
return attrs.matches(regex);

Instead it returns false.

Why is this? I expect the | pipe in attrs to be interpreted literally as an ASCII character, and the | pipe in regex to be interpreted according to regular expressions (i.e. OR).

The reason I ask is because I am writing an application where I let the user set the attributes in the format attr1|attr2|attr3|..., and I want to verify his/her input by matching it against the possible attribute values: attr1|attr2|attr3|...|attr[n].

Help appreciated,

ktm

Got it working by doing

String regex = "id.*|fullname.*|email.*|title.*";
String attrs = "fullname|email";
return attrs.matches(regex);

Body:
The problem is that the pipe character is a meta-character in regexes.  It therefore needs to be escaped if you want to match a literal '|' character.

String attrs = "id|fullname|email|title";
String regex = "fullname\\|email";
return attrs.matches(regex);

The other problem is that your usecase really needs to be using find rather than matches, and the String API does not support find.  This means you need to rewrite it to use an explicit Pattern and Matcher; e.g.

String attrs = "id|fullname|email|title";
Pattern regex = Pattern.compile("fullname\\|email");
return regex.matcher(attrs).find();

But even this is not right:

What you really need to do (I think) is match the supplied attributes independent of the order in which the user provides them.

Naive regexes above will mismatch if the user enters something like "meaningfullname".

Really, this is getting too complicated to do using regexes.  Instead, you are better off with something like this:

List<String> attrs = Arrays.asList(
        new String[] {"id", "fullname", "email", "title"});
String[] suppliedAttrs = supplied.split("\\|");
for (String s: suppliedAttrs) {
    if (!attrs.contains(s)) {
        throw new IllegalArgumentException("'" + s + "' is not valid");
    }
}

or if you just want to test if the attributes contain one or more of fullname and  email

String[] suppliedAttrs = supplied.split("\\|");
for (String s: suppliedAttrs) {
    if (s.equals("fullname") || s.equals("email")) {
        System.err.println("BINGO!");
    }
}


问:
How can i fix NumberFormatException?
I know this error is caused by a number format exception but i don't know how to fix it. i'v tried to do a function to Check if the variable is a Number or String
and here is my code

```<code>public boolean checkNumber(String x) {
   try{
       Integer.parseInt(x);
       return true;
   }catch(NumberFormatException ex){
       return false;
   }
}
</code>```

and this is a function takes a parameter of format dd/mm/yyyy,
split and store it in an array, then call the previous function to determine if all index are integer number or not.

```<code>public boolean CheckBirthDate(String birthdate){
    int B = 0;
    String Line = birthdate;
    String[] seprated = Line.split("/");
    if( checkNumber(seprated[0])  && checkNumber(seprated[1])  && checkNumber(seprated[2])) {
        B = 1;
    }
    if(seprated.length == 3 && Integer.parseInt(seprated[0]) <= 31  && Integer.parseInt(seprated[1]) <=   12 && Integer.parseInt(seprated[2]) >= 1950 &&  Integer.parseInt(seprated[2]) <= 2017 && B == 1){
        return true;
    }else{
        return false;
    }
}
</code>```

答:
I would recommend to debug in order to figure out where the error ocurs.

Any way, the last conditional, I suggest you to change the order. You first check if strings are numbers, thats perfect, then you store the result in a variable, fine. The thing is that the way conditionals work could be the problem here.
You check whether are numbers or not at the end, and should be done at the begining, like:

```<code>if (B == 1 && seprated.length == 3 && Integer.parseInt(seprated[0]) <= 31 && Integer.parseInt(seprated[1]) <= 12
        && Integer.parseInt(seprated[2]) >= 1950 && Integer.parseInt(seprated[2]) <= 2017) {
        return true;
    } else {
        return false;
    }
</code>```

This way first checks the first conditional, and if it is false, it doesnt keep doing the other conditions because  false & true  is always false

Title: How can i fix NumberFormatException?

Body:
I know this error is caused by a number format exception but i don't know how to fix it. i'v tried to do a function to Check if the variable is a Number or String
and here is my code

public boolean checkNumber(String x) {
   try{
       Integer.parseInt(x);
       return true;
   }catch(NumberFormatException ex){
       return false;
   }
}

and this is a function takes a parameter of format dd/mm/yyyy,
split and store it in an array, then call the previous function to determine if all index are integer number or not.

public boolean CheckBirthDate(String birthdate){
    int B = 0;
    String Line = birthdate;
    String[] seprated = Line.split("/");
    if( checkNumber(seprated[0])  && checkNumber(seprated[1])  && checkNumber(seprated[2])) {
        B = 1;
    }
    if(seprated.length == 3 && Integer.parseInt(seprated[0]) <= 31  && Integer.parseInt(seprated[1]) <=   12 && Integer.parseInt(seprated[2]) >= 1950 &&  Integer.parseInt(seprated[2]) <= 2017 && B == 1){
        return true;
    }else{
        return false;
    }
}

Body:
I would recommend to debug in order to figure out where the error ocurs.

Any way, the last conditional, I suggest you to change the order. You first check if strings are numbers, thats perfect, then you store the result in a variable, fine. The thing is that the way conditionals work could be the problem here.
You check whether are numbers or not at the end, and should be done at the begining, like:

if (B == 1 && seprated.length == 3 && Integer.parseInt(seprated[0]) <= 31 && Integer.parseInt(seprated[1]) <= 12
        && Integer.parseInt(seprated[2]) >= 1950 && Integer.parseInt(seprated[2]) <= 2017) {
        return true;
    } else {
        return false;
    }

This way first checks the first conditional, and if it is false, it doesnt keep doing the other conditions because  false & true  is always false


问:
How do I view login history for my PC using Windows 7

Start->“eventvwr”.

Then expanding  Windows Logs, I have selected  Security.

But I did not get proper details of login history.

答:
The event viewer (eventvwr.exe) contains some relevant records but you would need to create your own logon/logon script through a policy in order to maintain suitable records, e.g. like so:
@echo off
if not exist c:\Logs md c:\Logs
echo Logon: %date% %time:~0,5% %UserName% >> c:\Logs\History.txt

From -> https://answers.microsoft.com/en-us/windows/forum/windows_7-security/how-do-i-view-login-history-for-my-pc-using/a0172887-1071-47fb-b0a3-6ca9360efdbf?auth=1


答:
I'm going to gamble here and suggest that executing the following query just once to create an index suitable for your query should reduce the query time by at least a second...

```<code>CREATE INDEX returnstatus ON Recipe_Data(404_Without_200,Failures_Without_Success)
</code>```

See:  http://dev.mysql.com/doc/refman/5.0/en/create-index.html for creating indexes, and http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html for how indexes are used in queries.

Failing that, view all running processes on mysql to see if a currently running query from any source just refuses to die while consuming all the server's time and kill it.  See: http://dev.mysql.com/doc/refman/5.0/en/kill.html

Failing that, determine what else each record may have in common to avoid having to reference each one individually by ID number in your IN statement.  If necessary, add another table column to track that commonality.  Then, add column(s) having that commonality to the above index and filter by that in your WHERE clause instead of using the IN statement.  For example, if you want only those ID numbers to print out on page, have a visible column as type: tinyint with value 0 to exclude, and value 1 to include in your search results, then add visible column to your indexs and WHERE clause to speed up the query.  You wouldn't need that IN statement at all.

Perhaps your in statement is dynamically built using a previous query.  If that's the case, try pulling all rows with Recipe_Data WHERE 404_Without_200 = 0 AND Failures_Without_Success = 0.  Then in your PHP script, simply discard a record in your fetch loop if the RHD_No doesn't match an expected value.

Title: MySQL Query IN() Clause Slow on Indexed Column

Body:
I Have a MySQL query that is being generated by a PHP script, the query will look something like this:

SELECT * FROM Recipe_Data WHERE 404_Without_200 = 0 AND Failures_Without_Success = 0 AND RHD_No IN (10, 24, 34, 41, 43, 51, 57, 59, 61, 67, 84, 90, 272, 324, 402, 405, 414, 498, 500, 501, 510, 559, 562, 595, 632, 634, 640, 643, 647, 651, 703, 714, 719, 762, 765, 776, 796, 812, 814, 815, 822, 848, 853, 855, 858, 866, 891, 920, 947, 956, 962, 968, 1049, 1054, 1064, 1065, 1070, 1100, 1113, 1119, 1130, 1262, 1287, 1292, 1313, 1320, 1327, 1332, 1333, 1335, 1340, 1343, 1344, 1346, 1349, 1352, 1358, 1362, 1365, 1482, 1495, 1532, 1533, 1537, 1549, 1550, 1569, 1571, 1573, 1574, 1596, 1628, 1691, 1714, 1720, 1735, 1755, 1759, 1829, 1837, 1844, 1881, 1919, 2005, 2022, 2034, 2035, 2039, 2054, 2076, 2079, 2087, 2088, 2089, 2090, 2091, 2092, 2154, 2155, 2156, 2157, 2160, 2162, 2164, 2166, 2169, 2171, 2174, 2176, 2178, 2179, 2183, 2185, 2186, 2187, 2201, 2234, 2236, 2244, 2245, 2250, 2255, 2260, 2272, 2280, 2281, 2282, 2291, 2329, 2357, 2375, 2444, 2451, 2452, 2453, 2454, 2456, 2457, 2460, 2462, 2464, 2465, 2467, 2468, 2469, 2470, 2473, 2474, 2481, 2485, 2487, 2510, 2516, 2519, 2525, 2540, 2545, 2547, 2553, 2571, 2579, 2580, 2587, 2589, 2597, 2602, 2611, 2629, 2660, 2662, 2700, 2756, 2825, 2833, 2835, 2858, 2958, 2963, 2964, 3009, 3090, 3117, 3118, 3120, 3121, 3122, 3123, 3126, 3127, 3129, 3130, 3133, 3135, 3137, 3138, 3139, 3141, 3142, 3145, 3146, 3147, 3151, 3152, 3155, 3193, 3201, 3204, 3219, 3221, 3222, 3223, 3224, 3225, 3226, 3227, 3228, 3229, 3231, 3232, 3233, 3234, 3235, 3237, 3239, 3246, 3250, 3253, 3259, 3261, 3291, 3315, 3328, 3377, 3381, 3383, 3384, 3385, 3387, 3388, 3389, 3390, 3396, 3436, 3463, 3465, 3467, 3470, 3471, 3484, 3507, 3515, 3554, 3572, 3641, 3672, 3683, 3689, 3690, 3692, 3693, 3694, 3697, 3698, 3705, 3711, 3713, 3715, 3716, 3717, 3719, 3720, 3722, 3726, 3727, 3732, 3737, 3763, 3767, 3770, 3771, 3772, 3773, 3803, 3810, 3812, 3816, 3846, 3847, 3848, 3851, 3874, 3882, 3902, 3903, 3906, 3908, 3916, 3924, 3967, 3987, 4006, 4030, 4043, 4045, 4047, 4058, 4067, 4107, 4108, 4114, 4115, 4131, 4132, 4133, 4137, 4138, 4139, 4140, 4141, 4142, 4146, 4150, 4151, 4152, 4153, 4157, 4158, 4160, 4163, 4166, 4167, 4171, 4179, 4183, 4221, 4225, 4242, 4257, 4435, 4437, 4438, 4443, 4446, 4449, 4450, 4451, 4452, 4454, 4460, 4550, 4557, 4618, 4731, 4775, 4804, 4972, 5025, 5026, 5039, 5042, 5294, 5578, 5580, 5599, 5602, 5649, 5726, 5779, 5783, 5931, 5934, 5936, 5939, 5940, 5941, 5978, 6044, 6056, 6113, 6116, 6118, 6122, 6123, 6125, 6127, 6128, 6129, 6130, 6131, 6135, 6141, 6145, 6147, 6150, 6152, 6153, 6154, 6160, 6166, 6169);

The column RHD_No is the primary key for this database, and there are about 400,000 rows total. The problem is, the query is extremely slow, it's often around 2 seconds, but I've seen it get as long as 10.

When I try to explain the query, everything seems like it should be fine:

+----+-------------+-------------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table       | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | Recipe_Data | range | PRIMARY       | PRIMARY | 4       | NULL |  420 | Using where |
+----+-------------+-------------+-------+---------------+---------+---------+------+------+-------------+

When I profile the query I get:

mysql> show profile;
+--------------------------------+----------+
| Status                         | Duration |
+--------------------------------+----------+
| starting                       | 0.000015 |
| checking query cache for query | 0.000266 |
| Opening tables                 | 0.000009 |
| System lock                    | 0.000004 |
| Table lock                     | 0.000006 |
| init                           | 0.000115 |
| optimizing                     | 0.000038 |
| statistics                     | 0.000797 |
| preparing                      | 0.000047 |
| executing                      | 0.000002 |
| Sending data                   | 2.675270 |
| end                            | 0.000007 |
| query end                      | 0.000003 |
| freeing items                  | 0.000071 |
| logging slow query             | 0.000002 |
| logging slow query             | 0.000058 |
| cleaning up                    | 0.000005 |
+--------------------------------+----------+

I've been working on this problem for a long time and I haven't been able to find a solution. Is there anything overtly wrong with this query? I don't see how looking at 420 rows should take 2+ seconds.

Body:
I'm going to gamble here and suggest that executing the following query just once to create an index suitable for your query should reduce the query time by at least a second...

CREATE INDEX returnstatus ON Recipe_Data(404_Without_200,Failures_Without_Success)

See:  http://dev.mysql.com/doc/refman/5.0/en/create-index.html for creating indexes, and http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html for how indexes are used in queries.

Failing that, view all running processes on mysql to see if a currently running query from any source just refuses to die while consuming all the server's time and kill it.  See: http://dev.mysql.com/doc/refman/5.0/en/kill.html

Failing that, determine what else each record may have in common to avoid having to reference each one individually by ID number in your IN statement.  If necessary, add another table column to track that commonality.  Then, add column(s) having that commonality to the above index and filter by that in your WHERE clause instead of using the IN statement.  For example, if you want only those ID numbers to print out on page, have a visible column as type: tinyint with value 0 to exclude, and value 1 to include in your search results, then add visible column to your indexs and WHERE clause to speed up the query.  You wouldn't need that IN statement at all.

Perhaps your in statement is dynamically built using a previous query.  If that's the case, try pulling all rows with Recipe_Data WHERE 404_Without_200 = 0 AND Failures_Without_Success = 0.  Then in your PHP script, simply discard a record in your fetch loop if the RHD_No doesn't match an expected value.


问:
extracting components from json dictionary
I have a json dictionary (result_dict_tag) as follows:

```<code>{'10644906845': {'photo': {'id': '10644906845',
   'tags': {'tag': [{'_content': 'srilanka',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-23098',
      'machine_tag': 0,
      'raw': 'sri lanka'},
     {'_content': 'navy',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-7137',
      'machine_tag': 0,
      'raw': 'navy'},
     {'_content': 'vessel',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-8792',
      'machine_tag': 0,
      'raw': 'vessel'}]}},
  'stat': 'ok'},
      '11778819726': {'photo': {'id': '11778819726',
   'tags': {'tag': [{'_content': 'sri',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-12165',
      'machine_tag': 0,
      'raw': 'sri'},
     {'_content': 'lanka',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-12166',
      'machine_tag': 0,
      'raw': 'lanka'},
     {'_content': 'mirissa',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-1158107',
      'machine_tag': 0,
      'raw': 'mirissa'}]}},
  'stat': 'ok'}}
</code>```

What I want is to extract the 'raw' words from each dictionary (e.g.result_dict_tag['10644906845']['photo']["tags"]['tag'][0]['raw']) and and create a dataframe consisting user id and relevant raw words for each user. I feel this need some for loop. I have written one and it only results the 'raw' words related to first user only. I have gone through documentation and various questions similar to this. But couldn't figure it out. Any help is appreciated.

答:
If I have understood you correctly, what you want is a list of dicts with each dict containing an id and a row.

Add these lines of code below your dict:

```<code>new_list = result_dict_tag['10644906845']['photo']["tags"]['tag']

new_desired_list = []

for index in range(len(new_list)):

  tempDict = {}

  for key in new_list[index]:

      if(key=='id'):
          tempDict['id'] = new_list[index][key]

      if(key=='raw'):
          tempDict['row'] = new_list[index][key]

  new_desired_list.append(tempDict)

print(new_desired_list)
</code>```

Body:
I have a json dictionary (result_dict_tag) as follows:

{'10644906845': {'photo': {'id': '10644906845',
   'tags': {'tag': [{'_content': 'srilanka',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-23098',
      'machine_tag': 0,
      'raw': 'sri lanka'},
     {'_content': 'navy',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-7137',
      'machine_tag': 0,
      'raw': 'navy'},
     {'_content': 'vessel',
      'author': '34665545@N05',
      'authorname': 'CrishyM',
      'id': '34660205-10644906845-8792',
      'machine_tag': 0,
      'raw': 'vessel'}]}},
  'stat': 'ok'},
      '11778819726': {'photo': {'id': '11778819726',
   'tags': {'tag': [{'_content': 'sri',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-12165',
      'machine_tag': 0,
      'raw': 'sri'},
     {'_content': 'lanka',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-12166',
      'machine_tag': 0,
      'raw': 'lanka'},
     {'_content': 'mirissa',
      'author': '44455081@N07',
      'authorname': 'Vinchel',
      'id': '44433751-11778819726-1158107',
      'machine_tag': 0,
      'raw': 'mirissa'}]}},
  'stat': 'ok'}}

What I want is to extract the 'raw' words from each dictionary (e.g.result_dict_tag['10644906845']['photo']["tags"]['tag'][0]['raw']) and and create a dataframe consisting user id and relevant raw words for each user. I feel this need some for loop. I have written one and it only results the 'raw' words related to first user only. I have gone through documentation and various questions similar to this. But couldn't figure it out. Any help is appreciated.

Body:
If I have understood you correctly, what you want is a list of dicts with each dict containing an id and a row.

Add these lines of code below your dict:

new_list = result_dict_tag['10644906845']['photo']["tags"]['tag']

new_desired_list = []

for index in range(len(new_list)):

  tempDict = {}

  for key in new_list[index]:

      if(key=='id'):
          tempDict['id'] = new_list[index][key]

      if(key=='raw'):
          tempDict['row'] = new_list[index][key]

  new_desired_list.append(tempDict)

print(new_desired_list)