问:
Foreach loop for children skipping to last child in XML file
Okay, my script is supposed to open an XML file, recursively loop through all the tags, children, children of children, and so forth spitting out information as we go. Today I noticed an interesting bug in that my foreach loop that is supposed to loop through the children is skipping directly to the last child and I really have no clue as to why.

```<code>function theHunt($node)
{
    $tagName = '';
    print 'I am starting with ' . $node->getName() . ' It should have ' . $node->count() . ' children. The first child should be: ' . $node->children()->getName() . '<br>';

    foreach ($node->children() as $child);
    {
        print $child->getName() . '<br>';
        if (isset($child))
        {
            print 'I found: ' . $child->getName() . ' I\'ll see if it has kids' . '<br>';
            $this->theHunt($child);
        }
        else
        {
            print 'No kids here, I\'m going to stop digging.<br>';
        }
        //Now that I am all the way down or working my way back up. I start gathering my information.
        $tagName = $node -> getName();
        if($this->rootNode->$tagName[0] !== NULL)
        {
            foreach ($this->rootNode->$tagName[0]->attributes() as $a => $b) ;
            {
                //echo $a, '="', $b, "<br>";
            }
        }
        //print_r($node);
        print'<br> I kicked out <br>';

    }
}
</code>```

The really weird part is that the line:

```<code>print 'I am starting with ' . $node->getName() . ' It should have ' . $node->count() . ' children. The first child should be: ' . $node->children()->getName() . '<br>';
</code>```

Is outputting all the correct information, but the moment I drop into the foreach loop I skip right to the very last child.

答:
Your code is mishandling the tree structure. You should follow the structure below:</p>

```<code>function theHunt($node)
{
    foreach ($node->children() as $child);
    {
        if (isset($child))
        { //has children
          theHunt($child); //go one level down
        }
        else
        { //this is a child
          //enum thru its attributes
        }
    }
}
</code>```

Body:
Okay, my script is supposed to open an XML file, recursively loop through all the tags, children, children of children, and so forth spitting out information as we go. Today I noticed an interesting bug in that my foreach loop that is supposed to loop through the children is skipping directly to the last child and I really have no clue as to why.

function theHunt($node)
{
    $tagName = '';
    print 'I am starting with ' . $node->getName() . ' It should have ' . $node->count() . ' children. The first child should be: ' . $node->children()->getName() . '
';

    foreach ($node->children() as $child);
    {
        print $child->getName() . '
';
        if (isset($child))
        {
            print 'I found: ' . $child->getName() . ' I\'ll see if it has kids' . '
';
            $this->theHunt($child);
        }
        else
        {
            print 'No kids here, I\'m going to stop digging.
';
        }
        //Now that I am all the way down or working my way back up. I start gathering my information.
        $tagName = $node -> getName();
        if($this->rootNode->$tagName[0] !== NULL)
        {
            foreach ($this->rootNode->$tagName[0]->attributes() as $a => $b) ;
            {
                //echo $a, '="', $b, "
";
            }
        }
        //print_r($node);
        print'
 I kicked out
';

    }
}

The really weird part is that the line:

print 'I am starting with ' . $node->getName() . ' It should have ' . $node->count() . ' children. The first child should be: ' . $node->children()->getName() . '
';

Is outputting all the correct information, but the moment I drop into the foreach loop I skip right to the very last child.

Body:
Your code is mishandling the tree structure. You should follow the structure below:

function theHunt($node)
{
    foreach ($node->children() as $child);
    {
        if (isset($child))
        { //has children
          theHunt($child); //go one level down
        }
        else
        { //this is a child
          //enum thru its attributes
        }
    }
}


来源: stackexchange

问:
Invoke a method in an Object that was created inside a function
I am confused by this question and not even the JavaScript MDN is clarifying the concept for me.

There is a function called invokeMethod and in that function I have to create an Object. The Object includes a Method. I need to invoke the Method in the Object using bracket notation but nothing needs to be returned.

Here is the Question and my code. I keep getting error messages when I try to call the method in the function parentheses.

Question: method is a string that contains the name of a method on the object
Invoke this method using bracket notation.
Nothing needs to be returned.

Input Example:

```<code>{ foo: function() {} }, 'foo'
</code>```

My code:

```<code>function invokeMethod(object, method) {
  // code here
  const obj = {
    name: 'kung',
    foo: function(){
      console.log('foo');
    }
  };
}

invokeMethod(obj[foo]);
</code>```

答:
Maybe this could help.

Look at your function I'm seen that you have as arguments two elements object and method. So, your functions it's bad doing this

```<code>function invokeMethod(object, method) {
  // code here
  const obj = {
    name: 'kung',
    foo: function(){
      console.log('foo');
    }
  };
}
</code>```

if you are going to receive the obj-function, you should have just this,

```<code>function invokeMethod(method)
</code>```

Now, Following your example, I'm going to think that you really want to receive the obj-function. So, in that case, you should do this.

```<code>const obj = {
    name: 'kung',
    foo: function(){
      console.log('foo');
    }
  };

function invokeMethod(obj, method) {
  if((method in obj) && typeof obj[method] ==="function"){

    return obj[method]();
  }
}

invokeMethod(obj, 'foo');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am confused by this question and not even the JavaScript MDN is clarifying the concept for me.

There is a function called invokeMethod and in that function I have to create an Object. The Object includes a Method. I need to invoke the Method in the Object using bracket notation but nothing needs to be returned.

Here is the Question and my code. I keep getting error messages when I try to call the method in the function parentheses.

Question: method is a string that contains the name of a method on the object
Invoke this method using bracket notation.
Nothing needs to be returned.

Input Example:

{ foo: function() {} }, 'foo'

My code:

function invokeMethod(object, method) {
  // code here
  const obj = {
    name: 'kung',
    foo: function(){
      console.log('foo');
    }
  };
}

invokeMethod(obj[foo]);

Body:
Maybe this could help.

Look at your function I'm seen that you have as arguments two elements object and method. So, your functions it's bad doing this

function invokeMethod(object, method) {
  // code here
  const obj = {
    name: 'kung',
    foo: function(){
      console.log('foo');
    }
  };
}

if you are going to receive the obj-function, you should have just this,

function invokeMethod(method)

Now, Following your example, I'm going to think that you really want to receive the obj-function. So, in that case, you should do this.

const obj = {
    name: 'kung',
    foo: function(){
      console.log('foo');
    }
  };

function invokeMethod(obj, method) {
  if((method in obj) && typeof obj[method] ==="function"){

    return obj[method]();
  }
}

invokeMethod(obj, 'foo');


问:
Set Min Value for Android Seek bar
```<code>private static int INCREMENT_BY = 10;
private static int MAX = 1000;
private static int MIN = 0;
SeekBar seekbar_min, seekbar_max;
private int max = 0, min = 0;

 seekbar_min.setProgress(MIN);
    seekbar_min.incrementProgressBy(INCREMENT_BY);
    seekbar_min.setMax(MAX);
    seekbar_min.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            progress = progress / INCREMENT_BY;
            progress = progress * INCREMENT_BY;
            if (progress < 100) {
                min = progress * 10;
            } else if (progress < 300) {
                min = progress * 50;
            } else if (progress < 900) {
                min = progress * 100;
            } else {
                min = progress * MAX;
            }
            tv_price_min.setText(String.valueOf(min));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (seekBar.getProgress() != MIN || seekBar.getProgress() != MAX){
                if (seekBar.getProgress() < 100) {
                    max = seekBar.getProgress() + 10;
                } else if (seekBar.getProgress() < 300) {
                    max = seekBar.getProgress() + 50;
                } else if (seekBar.getProgress() < 900) {
                    max = seekBar.getProgress() + 100;
                } else {
                    max = seekBar.getProgress() + MAX;
                }
                seekbar_max.setProgress(max);
            }
        }
    });

    seekbar_max.incrementProgressBy(INCREMENT_BY);
    seekbar_max.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            progress = progress / INCREMENT_BY;
            progress = progress * INCREMENT_BY;
            if (progress < 100) {
                max = progress * 10;
            } else if (progress < 300) {
                max = progress * 50;
            } else if (progress < 900) {
                max = progress * 100;
            } else {
                max = progress * MAX;
            }
            tv_price_max.setText(String.valueOf(max));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });
</code>```

The Seek bar is for maximum price must have the minimum value, which is Minimum Seek bar current value. I can do this successfully, but the problem is that, the maximum seek bar allows to change the min value to until 0, which i do not want.

答:
Try this, I was able to do this on one of my projects. In this case, the maximum is 23 and the minimum is 8.</p>

```<code>        seekBarLength = findViewById(R.id.seekBarLength);
        seekBarLength.setMax(23-8);
        seekBarLength.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progress += 8;
                textViewPasswordLength.setText(progress + "");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
</code>```

Title: Set Min Value for Android Seek bar

Body:
private static int INCREMENT_BY = 10;
private static int MAX = 1000;
private static int MIN = 0;
SeekBar seekbar_min, seekbar_max;
private int max = 0, min = 0;

 seekbar_min.setProgress(MIN);
    seekbar_min.incrementProgressBy(INCREMENT_BY);
    seekbar_min.setMax(MAX);
    seekbar_min.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            progress = progress / INCREMENT_BY;
            progress = progress * INCREMENT_BY;
            if (progress < 100) {
                min = progress * 10;
            } else if (progress < 300) {
                min = progress * 50;
            } else if (progress < 900) {
                min = progress * 100;
            } else {
                min = progress * MAX;
            }
            tv_price_min.setText(String.valueOf(min));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (seekBar.getProgress() != MIN || seekBar.getProgress() != MAX){
                if (seekBar.getProgress() < 100) {
                    max = seekBar.getProgress() + 10;
                } else if (seekBar.getProgress() < 300) {
                    max = seekBar.getProgress() + 50;
                } else if (seekBar.getProgress() < 900) {
                    max = seekBar.getProgress() + 100;
                } else {
                    max = seekBar.getProgress() + MAX;
                }
                seekbar_max.setProgress(max);
            }
        }
    });

    seekbar_max.incrementProgressBy(INCREMENT_BY);
    seekbar_max.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            progress = progress / INCREMENT_BY;
            progress = progress * INCREMENT_BY;
            if (progress < 100) {
                max = progress * 10;
            } else if (progress < 300) {
                max = progress * 50;
            } else if (progress < 900) {
                max = progress * 100;
            } else {
                max = progress * MAX;
            }
            tv_price_max.setText(String.valueOf(max));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

The Seek bar is for maximum price must have the minimum value, which is Minimum Seek bar current value. I can do this successfully, but the problem is that, the maximum seek bar allows to change the min value to until 0, which i do not want.

Body:
Try this, I was able to do this on one of my projects. In this case, the maximum is 23 and the minimum is 8.

        seekBarLength = findViewById(R.id.seekBarLength);
        seekBarLength.setMax(23-8);
        seekBarLength.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progress += 8;
                textViewPasswordLength.setText(progress + "");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


问:
Sorting vector keeps modifying data and prints incorrect results
So my code basically maps a students ID and Name to his or her grade and many functions and consists of internal functions which allows you to search for a particular student by grade, ID etc.

One particular function I'm trying to implement is something that prints the grade of all the inputted students in descending order.

Program Class

```<code>#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
class student{
public:
student();
student(int,string);
int id;
string name;
};

class table{
public:
void InsertStudent(student x, int y);
void PrintAll(table t);
void SearchbyID(student x);
void SearchbyGrade(int y);
void SortbyGrade(table t);

private:
map<student, int > records;

};
</code>```

Main function

```<code>int main (){
table t;
string command;
int id;
string name;
int grade;
student x;
while ( cin >> command ){

if (command=="InsertStudent"){

cin >> id >> name>> grade;

student s(id,name);
t.InsertStudent(s,grade);
}else if (command == "PrintAll"){
t.PrintAll(t);
}else if (command == "SearchbyID"){
cin >> x.id;
t.SearchbyID(x);
}else if (command == "SearchbyGrade"){
cin >> grade;
t.SearchbyGrade(grade);
}
else if (command == "SortbyGrade"){
t.SortbyGrade(t);
}
else if (command == "exit"){
return 0;
 }
 }
}
</code>```

SortbyGrade Function

To simplify the same, I included the following struct.

```<code>struct information{
string id;
string name;
string grade;
};

void table::SortbyGrade(table t){
map<student,int>::iterator itr;
information a;
vector<information> v;
for(itr=records.begin();itr!=records.end();itr++)
{
    a.id=(*itr).first.id;
    a.name=(*itr).first.name;
    a.grade=(*itr).second;
    v.push_back(a);
}
vector<information>::iterator itr2;
sort(v.begin(),v.end(),compare);
for(itr2=v.begin();itr2!=v.end();itr2++){
    cout<<(*itr2).id<<" "<<(*itr2).name<<" "<<(*itr2).grade<<endl;
}
}
</code>```

In this segment of code, I'm basically copying the key and the values from the map on to the vector to implement the sort algorithm

Comparison function for descending sort

```<code>bool compare(const information &a, const information & b){
if(a.grade>b.grade)
    return true;
else if(a.grade<b.grade)
    return false;
 else
    return a.id<b.id;
}
</code>```

Sameple Input and Output

Input

InsertStudent 2016001 David 97

InsertStudent 2016002 Alice 88

InsertStudent 2016003 Jackson 100

InsertStudent 2016004 Eric 60

InsertStudent 2016005 John 97

InsertStudent 2016006 Michael 79

Output

Jackson d

David a

John a

Alice X

 Michael O

 Eric

This indicates the sort is being performed correctly, however the information seems to have been altered.

答:
I've created a minimal example for you to reproduce the behavior:

```<code>#include <string>
#include <iostream>

int main() {
    std::string s;
    s = 100;
    std::cout << s << std::endl;
}
</code>```

Before you read further, can you figure out the reason on your own now?

std::string::operator= has a few overloads, and the one that fits the most here is std::string::operator=(char ch). 100 is ASCII code for 'd' so that is what Jackson's grade turns into when you assign its value to a string grade in your information struct.

Body:
So my code basically maps a students ID and Name to his or her grade and many functions and consists of internal functions which allows you to search for a particular student by grade, ID etc.

One particular function I'm trying to implement is something that prints the grade of all the inputted students in descending order.

Program Class

#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
class student{
public:
student();
student(int,string);
int id;
string name;
};

class table{
public:
void InsertStudent(student x, int y);
void PrintAll(table t);
void SearchbyID(student x);
void SearchbyGrade(int y);
void SortbyGrade(table t);

private:
map<student, int > records;

};

Main function

int main (){
table t;
string command;
int id;
string name;
int grade;
student x;
while ( cin >> command ){

if (command=="InsertStudent"){

cin >> id >> name>> grade;

student s(id,name);
t.InsertStudent(s,grade);
}else if (command == "PrintAll"){
t.PrintAll(t);
}else if (command == "SearchbyID"){
cin >> x.id;
t.SearchbyID(x);
}else if (command == "SearchbyGrade"){
cin >> grade;
t.SearchbyGrade(grade);
}
else if (command == "SortbyGrade"){
t.SortbyGrade(t);
}
else if (command == "exit"){
return 0;
 }
 }
}

SortbyGrade Function

To simplify the same, I included the following struct.

struct information{
string id;
string name;
string grade;
};

void table::SortbyGrade(table t){
map<student,int>::iterator itr;
information a;
vector<information> v;
for(itr=records.begin();itr!=records.end();itr++)
{
    a.id=(*itr).first.id;
    a.name=(*itr).first.name;
    a.grade=(*itr).second;
    v.push_back(a);
}
vector<information>::iterator itr2;
sort(v.begin(),v.end(),compare);
for(itr2=v.begin();itr2!=v.end();itr2++){
    cout<<(*itr2).id<<" "<<(*itr2).name<<" "<<(*itr2).grade<<endl;
}
}

In this segment of code, I'm basically copying the key and the values from the map on to the vector to implement the sort algorithm

Comparison function for descending sort

bool compare(const information &a, const information & b){
if(a.grade>b.grade)
    return true;
else if(a.grade<b.grade)
    return false;
 else
    return a.id<b.id;
}

Sameple Input and Output

Input

InsertStudent 2016001 David 97

InsertStudent 2016002 Alice 88

InsertStudent 2016003 Jackson 100

InsertStudent 2016004 Eric 60

InsertStudent 2016005 John 97

InsertStudent 2016006 Michael 79

Output

Jackson d

David a

John a

Alice X

 Michael O

 Eric

This indicates the sort is being performed correctly, however the information seems to have been altered.

Body:
I've created a minimal example for you to reproduce the behavior:

#include <string>
#include <iostream>

int main() {
    std::string s;
    s = 100;
    std::cout << s << std::endl;
}

Before you read further, can you figure out the reason on your own now?

std::string::operator= has a few overloads, and the one that fits the most here is std::string::operator=(char ch). 100 is ASCII code for 'd' so that is what Jackson's grade turns into when you assign its value to a string grade in your information struct.


问:
How to do actions when scroll view reached bottom end?
I have an Activity with a scroll view and 2 buttons, When open this activity both buttons are disabled. What I want is, when I reach the end of the scroll view,  enable both buttons to user to accept or decline the content. How can I do this in simple way.

Button before enabled

Thanks in advance.

答:
I have done this things with webView here is my code, hope it will help you.

```<code>webView.setOnScrollChangedCallback(new ObservableWebView.OnScrollChangedCallback() {
                @Override
                public void onScroll(int l, int t) {
                    int tek = (int) Math.floor(webView.getContentHeight() * webView.getScale());

                    if (tek - webView.getScrollY() <= webView.getHeight() + 5) {
                        // enable your button
                    }

                }
            });
</code>```

this is the class

```<code>public class ObservableWebView extends WebView
{
    private OnScrollChangedCallback mOnScrollChangedCallback;
public ObservableWebView(final Context context)
{
    super(context);
}

public ObservableWebView(final Context context, final AttributeSet attrs)
{
    super(context, attrs);
}

public ObservableWebView(final Context context, final AttributeSet attrs, final int defStyle)
{
    super(context, attrs, defStyle);
}

@Override
protected void onScrollChanged(final int l, final int t, final int oldl, final int oldt)
{
    super.onScrollChanged(l, t, oldl, oldt);
    if(mOnScrollChangedCallback != null) mOnScrollChangedCallback.onScroll(l, t);
}

public OnScrollChangedCallback getOnScrollChangedCallback()
{
    return mOnScrollChangedCallback;
}

public void setOnScrollChangedCallback(final OnScrollChangedCallback onScrollChangedCallback)
{
    mOnScrollChangedCallback = onScrollChangedCallback;
}

/**
 * Impliment in the activity/fragment/view that you want to listen to the webview
 */
public static interface OnScrollChangedCallback
{
    public void onScroll(int l, int t);
}
</code>```

}

happy coding.

ContentLicense: CC BY-SA 4.0

Body:
I have done this things with webView here is my code, hope it will help you.

webView.setOnScrollChangedCallback(new ObservableWebView.OnScrollChangedCallback() {
                @Override
                public void onScroll(int l, int t) {
                    int tek = (int) Math.floor(webView.getContentHeight() * webView.getScale());

                    if (tek - webView.getScrollY() <= webView.getHeight() + 5) {
                        // enable your button
                    }

                }
            });

this is the class

public class ObservableWebView extends WebView
{
    private OnScrollChangedCallback mOnScrollChangedCallback;
public ObservableWebView(final Context context)
{
    super(context);
}

public ObservableWebView(final Context context, final AttributeSet attrs)
{
    super(context, attrs);
}

public ObservableWebView(final Context context, final AttributeSet attrs, final int defStyle)
{
    super(context, attrs, defStyle);
}

@Override
protected void onScrollChanged(final int l, final int t, final int oldl, final int oldt)
{
    super.onScrollChanged(l, t, oldl, oldt);
    if(mOnScrollChangedCallback != null) mOnScrollChangedCallback.onScroll(l, t);
}

public OnScrollChangedCallback getOnScrollChangedCallback()
{
    return mOnScrollChangedCallback;
}

public void setOnScrollChangedCallback(final OnScrollChangedCallback onScrollChangedCallback)
{
    mOnScrollChangedCallback = onScrollChangedCallback;
}

/**
 * Impliment in the activity/fragment/view that you want to listen to the webview
 */
public static interface OnScrollChangedCallback
{
    public void onScroll(int l, int t);
}

}

happy coding.


问:
Using Tensorflow TF-Slim without slim.learning.train()
TF-Slim uses its own training loop. However, I would like to use a TF-Slim model (Resnet50) while still using my own tensorflow training loop. The TF-Slim model simply outputs the prediction and I calculate my own total loss. I am able to train the model without error and training error seems to converge. I am asking because I experienced issues with batch normalization during evaluation (the error is very high compared to the training error). I found out that this might be due to insufficient training steps. But I want to make sure that I am not using TF-Slim incorrectly.

The TF-Slim training procedure looks like this:

```<code>#create_train_op ensures that each time we ask for the loss, the
update_ops
# are run and the gradients being computed are applied too.

train_op = slim.learning.create_train_op(total_loss, optimizer)
logdir = ... # Where checkpoints are stored.

slim.learning.train(
    train_op,
    logdir,
    number_of_steps=1000,
    save_summaries_secs=300,
    save_interval_secs=600):
</code>```

I don't want to use the train_opbut something like this

```<code>def update_gradients(update_ops, optimizer, total_loss, variables_to_train, global_step, summaries):
  for grad, var in gradients:
      if grad is not None:
        summaries.add(tf.summary.histogram(var.op.name + '/gradients', grad))
  grad_updates = optimizer.apply_gradients(gradients,
                                         global_step=global_step)
  update_ops.append(grad_updates)

  update_op = tf.group(*update_ops)
  with tf.control_dependencies([update_op]):
      train_tensor = tf.identity(total_loss, name='train_op')
      return train_tensor
</code>```

and then call sess.run(train_tensor)

Does this cause any issues internally? I read here that one should use train_op: github issues

Or is it simply not allowed to pass, for example, train_tensor into the
 slim.learning.train() function directly?

答: I think you can try to override the train_step_fn in the parameter-list of slim.learning.train() to realize it</p>

Body:
TF-Slim uses its own training loop. However, I would like to use a TF-Slim model (Resnet50) while still using my own tensorflow training loop. The TF-Slim model simply outputs the prediction and I calculate my own total loss. I am able to train the model without error and training error seems to converge. I am asking because I experienced issues with batch normalization during evaluation (the error is very high compared to the training error). I found out that this might be due to insufficient training steps. But I want to make sure that I am not using TF-Slim incorrectly.

The TF-Slim training procedure looks like this:

#create_train_op ensures that each time we ask for the loss, the
update_ops
# are run and the gradients being computed are applied too.

train_op = slim.learning.create_train_op(total_loss, optimizer)
logdir = ... # Where checkpoints are stored.

slim.learning.train(
    train_op,
    logdir,
    number_of_steps=1000,
    save_summaries_secs=300,
    save_interval_secs=600):

I don't want to use the train_opbut something like this

def update_gradients(update_ops, optimizer, total_loss, variables_to_train, global_step, summaries):
  for grad, var in gradients:
      if grad is not None:
        summaries.add(tf.summary.histogram(var.op.name + '/gradients', grad))
  grad_updates = optimizer.apply_gradients(gradients,
                                         global_step=global_step)
  update_ops.append(grad_updates)

  update_op = tf.group(*update_ops)
  with tf.control_dependencies([update_op]):
      train_tensor = tf.identity(total_loss, name='train_op')
      return train_tensor

and then call sess.run(train_tensor)

Does this cause any issues internally? I read here that one should use train_op: github issues

Or is it simply not allowed to pass, for example, train_tensor into the
 slim.learning.train() function directly?


问:
How to Align smaller text on top of larger text
I have three text items in a container. The middle text has the larger font. I would like to align the top the first item to the top of the second item.

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
}

.large {
  font-size: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <p class="first">One</p>
    <p class="large">Two</p>
    <p>Three</p>
  </div>
</body></code>```

https://jsfiddle.net/7ofrravh/2/

The only way I can think of to do this is to use absolute position but this gets out of line when I change the screen size. I want to be able to change the size of the screen and have everything stay in place. Does anyone know a way to do this?

答:
You would need to change the code to look more like this:

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
  margin:0;
}

.large {
  font-size: 50px;
  line-height:1;
}

.first {
  vertical-align:top;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <p class="first">One</p>
    <p class="large">Two</p>
    <p>Three</p>
  </div>
</body></code>```

Body:
I have three text items in a container. The middle text has the larger font. I would like to align the top the first item to the top of the second item.

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
}

.large {
  font-size: 50px;
}

One

Two

Three

https://jsfiddle.net/7ofrravh/2/

The only way I can think of to do this is to use absolute position but this gets out of line when I change the screen size. I want to be able to change the size of the screen and have everything stay in place. Does anyone know a way to do this?

Body:
You would need to change the code to look more like this:

.container {
  border: 1px solid black;
}

.container p {
  display: inline-block;
  margin:0;
}

.large {
  font-size: 50px;
  line-height:1;
}

.first {
  vertical-align:top;
}

<body>
  <div class="container">
    <p class="first">One</p>
    <p class="large">Two</p>
    <p>Three</p>
  </div>
</body>


问:
set DateTime to start of month
How can I set a DateTime to the first of the month in C#?</p>

答:
Hope this helps you.

textbox1.Text = "01-" + DateTime.Now.ToString("MMM-yyyy");

Title: set DateTime to start of month


问:
a non recursive approach to the problem of generating combinations at fault
I wanted a non recursive approach to the problem of generating combination of certain set of characters or numbers.

So, given a subset k of numbers n, generate all the possible combination  n!/k!(n-k)!

The recursive method would give a combination, given the previous one combination.

A non recursive method would generate a combination of a given value of loop index i.

I approached the problem with this code:

Tested with n = 4 and k = 3, and it works, but if I change k to a number > 3 it does not work.

Is it due to the fact that (n-k)! in case of n = 4 and k = 3 is 1. and if k > 3 it will be more than 1?

Thanks.

```<code>int facto(int x);

int len,fact,rem=0,pos=0;
int str[7];
int avail[7];

   str[0] = 1;
   str[1] = 2;
   str[2] = 3;
   str[3] = 4;
   str[4] = 5;
   str[5] = 6;
   str[6] = 7;

  int tot=facto(n) / facto(n-k) / facto(k);

for (int i=0;i<tot;i++)
{

       avail[0]=1;
       avail[1]=2;
       avail[2]=3;
       avail[3]=4;
       avail[4]=5;
       avail[5]=6;
avail[6]=7;

    rem = facto(i+1)-1;
    cout<<rem+1<<". ";
    for(int j=len;j>0;j--)
    {
        int div = facto(j);
        pos = rem / div;
        rem = rem % div;
        cout<<avail[pos]<<" ";
        avail[pos]=avail[j];

    }
    cout<<endl;
}

int facto(int x)
{
    int fact=1;
    while(x>0) fact*=x--;
    return fact;
}
</code>```

答:
Consider that your iterator is a number of k digits in base n. In C/C++ you can represent it as an array of ints of size k where every element is in the range from 0 to n-1).

Then, to iterate from one position to the next you only need to increment the number.

That will give you all the permutations. In order to get combinations you have to impose an additional condition that is that digits must be in ascending order.

For instance with k = 3, n = 3: 000 001 002 011 012 022 111 112 122 222

Implementing that constraint in C is also pretty simple, on the increment operation used to iterate, instead of setting the rightmost digits to zero when there is a carry, you have to set them to the same value as the leftmost digit changed.

update: some code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXK 100

int
main(int argc, char *argv[]) {
    int digits[MAXK];

    int k = atol(argv[1]);
    int n = atol(argv[2]);
    int i, left;

    memset(digits, 0, sizeof(digits));

    while(1) {
        for (i = k; i--; ) {
            printf("%d", digits[i]);
            printf((i ? "-" : "\n"));
        }

        for (i = k; i--; ) {
            left = ++digits[i];
            if (left < n) {
                while (++i < k) digits[i] = left;
                break;
            }
        }
        if (i < 0) break;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I wanted a non recursive approach to the problem of generating combination of certain set of characters or numbers.

So, given a subset k of numbers n, generate all the possible combination  n!/k!(n-k)!

The recursive method would give a combination, given the previous one combination.

A non recursive method would generate a combination of a given value of loop index i.

I approached the problem with this code:

Tested with n = 4 and k = 3, and it works, but if I change k to a number > 3 it does not work.

Is it due to the fact that (n-k)! in case of n = 4 and k = 3 is 1. and if k > 3 it will be more than 1?

Thanks.

int facto(int x);

int len,fact,rem=0,pos=0;
int str[7];
int avail[7];

   str[0] = 1;
   str[1] = 2;
   str[2] = 3;
   str[3] = 4;
   str[4] = 5;
   str[5] = 6;
   str[6] = 7;

  int tot=facto(n) / facto(n-k) / facto(k);

for (int i=0;i<tot;i++)
{

       avail[0]=1;
       avail[1]=2;
       avail[2]=3;
       avail[3]=4;
       avail[4]=5;
       avail[5]=6;
avail[6]=7;

    rem = facto(i+1)-1;
    cout<<rem+1<<". ";
    for(int j=len;j>0;j--)
    {
        int div = facto(j);
        pos = rem / div;
        rem = rem % div;
        cout<<avail[pos]<<" ";
        avail[pos]=avail[j];

    }
    cout<<endl;
}

int facto(int x)
{
    int fact=1;
    while(x>0) fact*=x--;
    return fact;
}

Body:
Consider that your iterator is a number of k digits in base n. In C/C++ you can represent it as an array of ints of size k where every element is in the range from 0 to n-1).

Then, to iterate from one position to the next you only need to increment the number.

That will give you all the permutations. In order to get combinations you have to impose an additional condition that is that digits must be in ascending order.

For instance with k = 3, n = 3: 000 001 002 011 012 022 111 112 122 222

Implementing that constraint in C is also pretty simple, on the increment operation used to iterate, instead of setting the rightmost digits to zero when there is a carry, you have to set them to the same value as the leftmost digit changed.

update: some code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXK 100

int
main(int argc, char *argv[]) {
    int digits[MAXK];

    int k = atol(argv[1]);
    int n = atol(argv[2]);
    int i, left;

    memset(digits, 0, sizeof(digits));

    while(1) {
        for (i = k; i--; ) {
            printf("%d", digits[i]);
            printf((i ? "-" : "\n"));
        }

        for (i = k; i--; ) {
            left = ++digits[i];
            if (left < n) {
                while (++i < k) digits[i] = left;
                break;
            }
        }
        if (i < 0) break;
    }
}


问:
Tab sliding - how to?
The problem is with tab activity. when i'm run this app with  is worked fine.but when i slide or tap the tab it's totally shut down.please anyone help me out.

```<code>    public class MainActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;

    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    tab1 tab1 = new tab1();
                    return tab1;

                case 1:
                    tab2 tab2 = new tab2();
                    return tab2;
                case 3:
                    tab3 tab3 =new tab3();
                    return tab3;

                default: return null ;
            }

        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Protisthan";
                case 1:`enter code here`
                    return "Eknojore";
                case 2:
                    return "Onnorokom";
            }
            return null;
        }
    }
}
</code>```

and here is logcat file . app run smoothly but when i try to chage the tab then it's get cushed.

```<code>11-14 12:08:12.460 30777-30777/? I/art: Late-enabling -Xcheck:jni
11-14 12:08:12.535 30777-30777/? I/System.out: Sending WAIT chunk
11-14 12:08:12.729 30777-30783/com.example.mn.tabt I/art: Debugger is active
11-14 12:08:12.736 30777-30777/com.example.mn.tabt I/System.out: Debugger has connected
11-14 12:08:12.736 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:12.936 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.136 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.336 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.537 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.737 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.938 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:14.138 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:14.339 30777-30777/com.example.mn.tabt I/System.out: debugger has settled (1406)
11-14 12:08:14.356 30777-30777/com.example.mn.tabt W/System: ClassLoader referenced unknown path: /data/app/com.example.mn.tabt-1/lib/arm64
11-14 12:08:14.399 30777-30777/com.example.mn.tabt W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
11-14 12:08:14.544 30777-30777/com.example.mn.tabt I/HwSecImmHelper: mSecurityInputMethodService is null
11-14 12:08:14.557 30777-30777/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:14.649 30777-30849/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:14.649 30777-30849/com.example.mn.tabt I/OpenGLRenderer: Initialized EGL, version 1.4
11-14 12:08:14.655 30777-30849/com.example.mn.tabt W/OpenGLRenderer: load: so=/system/lib64/libhwuibp.so
                                                                     dlopen failed: library "/system/lib64/libhwuibp.so" not found
11-14 12:08:14.655 30777-30849/com.example.mn.tabt W/OpenGLRenderer: Initialize Binary Program Cache: Load Failed
11-14 12:08:14.655 30777-30849/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:21.698 30777-30777/com.example.mn.tabt I/Process: Sending signal. PID: 30777 SIG: 9
</code>```

`

here the tab1 class. similarly i create two more class.for 3 fragment.
 `

```<code>    public class tab1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab1, container, false);
        return rootView;
    }

}
</code>```

if anyone want to see the xml file of main class . here it is .

`

```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

  </android.support.design.widget.CoordinatorLayout>
</code>```

`

答:
There is an another solution for this problem

```<code>private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager); //Replace your line to this

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

//method for adding fragment to the adapter

private void setupViewPager(ViewPager viewPager) {
    SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new TabOne(), "ONE");
    adapter.addFragment(new TabSecond(), "TWO");
    adapter.addFragment(new TabThird(), "THREE");
    viewPager.setAdapter(adapter);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    // add this method in your adapter
    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

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

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

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
</code>```

}

Title: Tab sliding - how to?

Body:
The problem is with tab activity. when i'm run this app with  is worked fine.but when i slide or tap the tab it's totally shut down.please anyone help me out.

    public class MainActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;

    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    tab1 tab1 = new tab1();
                    return tab1;

                case 1:
                    tab2 tab2 = new tab2();
                    return tab2;
                case 3:
                    tab3 tab3 =new tab3();
                    return tab3;

                default: return null ;
            }

        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Protisthan";
                case 1:`enter code here`
                    return "Eknojore";
                case 2:
                    return "Onnorokom";
            }
            return null;
        }
    }
}

and here is logcat file . app run smoothly but when i try to chage the tab then it's get cushed.

11-14 12:08:12.460 30777-30777/? I/art: Late-enabling -Xcheck:jni
11-14 12:08:12.535 30777-30777/? I/System.out: Sending WAIT chunk
11-14 12:08:12.729 30777-30783/com.example.mn.tabt I/art: Debugger is active
11-14 12:08:12.736 30777-30777/com.example.mn.tabt I/System.out: Debugger has connected
11-14 12:08:12.736 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:12.936 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.136 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.336 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.537 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.737 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:13.938 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:14.138 30777-30777/com.example.mn.tabt I/System.out: waiting for debugger to settle...
11-14 12:08:14.339 30777-30777/com.example.mn.tabt I/System.out: debugger has settled (1406)
11-14 12:08:14.356 30777-30777/com.example.mn.tabt W/System: ClassLoader referenced unknown path: /data/app/com.example.mn.tabt-1/lib/arm64
11-14 12:08:14.399 30777-30777/com.example.mn.tabt W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
11-14 12:08:14.544 30777-30777/com.example.mn.tabt I/HwSecImmHelper: mSecurityInputMethodService is null
11-14 12:08:14.557 30777-30777/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:14.649 30777-30849/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:14.649 30777-30849/com.example.mn.tabt I/OpenGLRenderer: Initialized EGL, version 1.4
11-14 12:08:14.655 30777-30849/com.example.mn.tabt W/OpenGLRenderer: load: so=/system/lib64/libhwuibp.so
                                                                     dlopen failed: library "/system/lib64/libhwuibp.so" not found
11-14 12:08:14.655 30777-30849/com.example.mn.tabt W/OpenGLRenderer: Initialize Binary Program Cache: Load Failed
11-14 12:08:14.655 30777-30849/com.example.mn.tabt E/HAL: load: id=gralloc != hmi->id=gralloc
11-14 12:08:21.698 30777-30777/com.example.mn.tabt I/Process: Sending signal. PID: 30777 SIG: 9

`

here the tab1 class. similarly i create two more class.for 3 fragment.
 `

    public class tab1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab1, container, false);
        return rootView;
    }

}

if anyone want to see the xml file of main class . here it is .

`

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

  </android.support.design.widget.CoordinatorLayout>

`

Body:
There is an another solution for this problem

private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager); //Replace your line to this

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

//method for adding fragment to the adapter

private void setupViewPager(ViewPager viewPager) {
    SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new TabOne(), "ONE");
    adapter.addFragment(new TabSecond(), "TWO");
    adapter.addFragment(new TabThird(), "THREE");
    viewPager.setAdapter(adapter);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    // add this method in your adapter
    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

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

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

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

}


问:
Unknown column '$data' in 'field list' in codeigniter
Im trying to insert data in my database and this error appears:

Error Number: 1054

Unknown column '$data' in 'field list'

INSERT INTO crud ($data) VALUES ('')

Filename: C:/AppServ/www/parcial/system/database/DB_driver.php

Line Number: 691

This is my form:

```<code> <?php echo form_open('home/save',['class'=>'form-horizontal']); ?>
  <fieldset>

      <label for="exampleInputEmail1">Titulo</label>
    <?php echo form_input(['name'=>'id','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('')]); ?>

      <?php echo form_input(['name'=>'titulo','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('titulo')]); ?>

      <label for="exampleInputEmail1">Resumen</label>
  <?php echo form_input(['name'=>'resumen','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('resumen')]); ?>

      <label for="exampleInputEmail1">Ano</label>
    <?php echo form_input(['name'=>'ano','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('ano')]); ?>

          <label for="exampleInputEmail1">Pais</label>
      <?php echo form_input(['name'=>'pais','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('pais')]); ?>
      <label for="exampleInputEmail1">Protagonista</label>
        <?php echo form_input(['name'=>'progatonista','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('protagonista')]); ?>
  <br>

  <?php echo form_close(); ?>
<?php echo form_submit(['value'=>'Submit', 'class'=>'btn btn-primary']); ?>
</code>```

This is my function to save records:

```<code>  public function save() {

    $data = $this->input->post();
$this->load->model('Crudmodel');
if($this->Crudmodel->saveRecords($data)) {

}
}
</code>```

this is my code to insert:

```<code>public function saveRecords($data) {

  return  $this->db->insert('crud','$data');

}
</code>```

What can i do? please help me

答:
```<code>Remove inverted comma from data field in it should be like below
return  $this->db->insert('crud',$data);
</code>```

Body:
Im trying to insert data in my database and this error appears:

Error Number: 1054

Unknown column '$data' in 'field list'

INSERT INTO crud ($data) VALUES ('')

Filename: C:/AppServ/www/parcial/system/database/DB_driver.php

Line Number: 691

This is my form:

 <?php echo form_open('home/save',['class'=>'form-horizontal']); ?>
  <fieldset>

      Titulo
    <?php echo form_input(['name'=>'id','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('')]); ?>

      <?php echo form_input(['name'=>'titulo','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('titulo')]); ?>

      Resumen
  <?php echo form_input(['name'=>'resumen','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('resumen')]); ?>

      Ano
    <?php echo form_input(['name'=>'ano','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('ano')]); ?>

          Pais
      <?php echo form_input(['name'=>'pais','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('pais')]); ?>
      Protagonista
        <?php echo form_input(['name'=>'progatonista','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('protagonista')]); ?>

  <?php echo form_close(); ?>
<?php echo form_submit(['value'=>'Submit', 'class'=>'btn btn-primary']); ?>

This is my function to save records:

  public function save() {

    $data = $this->input->post();
$this->load->model('Crudmodel');
if($this->Crudmodel->saveRecords($data)) {

}
}

this is my code to insert:

public function saveRecords($data) {

  return  $this->db->insert('crud','$data');

}

What can i do? please help me


问:
Can not get button to turn uipageviewcontroller page programmatically (Using Pages extension)
I'm fiddling with uipageviewcontroller and I'm trying to go to the next page by pressing a button rather than swiping. I found a neat extension on github called 'Pages' that is supposed to be robust and easy to use, but I can't for the life of me figure this out.

The extension itself comes with previous and next button in the navigation area but I don't want those, I want to be able to press a button on the actual screen and have it go to the next page. Has anyone had any experience with this extension?

AppDelegate

```<code>import UIKit
import Pages
import Imaginary

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?

  func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //let pages = pagesControllerInCode()
    let pages = pagesControllerInStoryboard()

    let navigationController = UINavigationController(rootViewController: pages)

    pages.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Previous Page",
      style: .plain,
      target: pages,
      action: #selector(PagesController.moveBack))

    pages.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next Page",
      style: .plain,
      target: pages,
      action: #selector(PagesController.moveForward))

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.rootViewController = navigationController
    window?.makeKeyAndVisible()

    pages.enableSwipe = false
    pages.showBottomLine = false

    return true
  }

  private func pagesControllerInCode() -> PagesController {
    var viewControllers: [UIViewController] = []

    for i in 0..<5 {
      if let imageURL = URL(string: "https://unsplash.it/375/667/?image=\(i+10)") {
        let viewController = ViewController()
        viewController.imageView.setImage(url: imageURL)

        viewControllers.append(viewController)
      }
    }

    let pages = PagesController(viewControllers)

    pages.enableSwipe = false
    pages.showBottomLine = false

    return pages
  }

  private func pagesControllerInStoryboard() -> PagesController {
    let storyboardIds = ["One","Two"]

    return PagesController(storyboardIds)
  }
}
</code>```

ViewController

```<code>import UIKit
import Pages

class ViewController: UIViewController {

  lazy var imageView = UIImageView()

  override func viewDidLoad() {
    super.viewDidLoad()

  }

  override func viewDidLayoutSubviews() {
    //corrects scrollview frame to allow for full-screen view controller pages
    for subView in self.view.subviews {
      if subView is UIScrollView {
        subView.frame = self.view.bounds
        subView.backgroundColor = UIColor.clear
      }
    }
    super.viewDidLayoutSubviews()
  }

  @IBAction func test(_ sender: UIButton) {
    NSLog("Test")
    // This is where I've been trying to figure out how to turn the page programmatically
    }
}
</code>```

答:
Check my answer at - https://stackoverflow.com/a/47278437/6080920

I had used a pageViewController that is added with multiple ViewController and Disabled scroll gestures that a pageViewController have by default and added some buttons that will allow to navigate user in pageViewController

Hope it helps you

Output ScreenShot : With pageViewController embedded with multiple viewController that have UITableView in it

Body:
I'm fiddling with uipageviewcontroller and I'm trying to go to the next page by pressing a button rather than swiping. I found a neat extension on github called 'Pages' that is supposed to be robust and easy to use, but I can't for the life of me figure this out.

The extension itself comes with previous and next button in the navigation area but I don't want those, I want to be able to press a button on the actual screen and have it go to the next page. Has anyone had any experience with this extension?

AppDelegate

import UIKit
import Pages
import Imaginary

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?

  func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //let pages = pagesControllerInCode()
    let pages = pagesControllerInStoryboard()

    let navigationController = UINavigationController(rootViewController: pages)

    pages.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Previous Page",
      style: .plain,
      target: pages,
      action: #selector(PagesController.moveBack))

    pages.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next Page",
      style: .plain,
      target: pages,
      action: #selector(PagesController.moveForward))

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.rootViewController = navigationController
    window?.makeKeyAndVisible()

    pages.enableSwipe = false
    pages.showBottomLine = false

    return true
  }

  private func pagesControllerInCode() -> PagesController {
    var viewControllers: [UIViewController] = []

    for i in 0..<5 {
      if let imageURL = URL(string: "https://unsplash.it/375/667/?image=\(i+10)") {
        let viewController = ViewController()
        viewController.imageView.setImage(url: imageURL)

        viewControllers.append(viewController)
      }
    }

    let pages = PagesController(viewControllers)

    pages.enableSwipe = false
    pages.showBottomLine = false

    return pages
  }

  private func pagesControllerInStoryboard() -> PagesController {
    let storyboardIds = ["One","Two"]

    return PagesController(storyboardIds)
  }
}

ViewController

import UIKit
import Pages

class ViewController: UIViewController {

  lazy var imageView = UIImageView()

  override func viewDidLoad() {
    super.viewDidLoad()

  }

  override func viewDidLayoutSubviews() {
    //corrects scrollview frame to allow for full-screen view controller pages
    for subView in self.view.subviews {
      if subView is UIScrollView {
        subView.frame = self.view.bounds
        subView.backgroundColor = UIColor.clear
      }
    }
    super.viewDidLayoutSubviews()
  }

  @IBAction func test(_ sender: UIButton) {
    NSLog("Test")
    // This is where I've been trying to figure out how to turn the page programmatically
    }
}


问:
Update multiple records with one form in MYSQL
I need to update multiple records in a single form but am not sure how to proceed. The following is the code I am using to insert the fields into the database originally.

```<code>$case = date(ymdHis);

//register into database
if (!empty($p1_firstname)) mysql_query ("INSERT INTO cases VALUES ('$case','$date_booked','$p1_firstname','$p1_lastname ''$city’)");

if (!empty($p2_firstname)) $register_case = mysql_query ("INSERT INTO cases VALUES ('$case','$date_booked','$p2_firstname','$p2_lastname','$city’)");
</code>```

I have an update form which displays data for however many records there are for each "case". How can I use UPDATE to edit information in different rows when each row has the same identifier ($case)?

答:
After normalizing your database then each of your records will have a unique identifier you can use for update queries.

Your current script is also prone to sql injection. You should never trust a user's input.

Body:
I need to update multiple records in a single form but am not sure how to proceed. The following is the code I am using to insert the fields into the database originally.

$case = date(ymdHis);

//register into database
if (!empty($p1_firstname)) mysql_query ("INSERT INTO cases VALUES ('$case','$date_booked','$p1_firstname','$p1_lastname ''$city’)");

if (!empty($p2_firstname)) $register_case = mysql_query ("INSERT INTO cases VALUES ('$case','$date_booked','$p2_firstname','$p2_lastname','$city’)");

I have an update form which displays data for however many records there are for each "case". How can I use UPDATE to edit information in different rows when each row has the same identifier ($case)?


问:
authorize.net recurring billing
Need to integrate authorize.net payment gateway with my web application.

We need a Recurring billing subscription with single trial period (say 200$) and 10 monthly payments(100$). But there is a chance of having a different payment amount(say 125$) inbetween monthly payments and remaining installments may be or may not be changed. Current Update subscrition API allows us to update remaining payments but does not allows us to have a trial period in between. Kindly suggest me how to deal with this. Also heared of "Customer Profile" API ., will this help me?.

Use case Scenario:

assume an insurance policy worth 1200$ is purchased by an user. which will be charged from user like 200$ as downpayment(first payment/month) and remaining 1000$ in 10 installments (100$ per month). There is a chance where this policy can be endorsed in between payments by the user and the policy worth can increase or decrease (1200$ may turn up to 1500$ or may turn down to 1000$). In this case, on the month of endorsement there will be an downpayment (say 150$) to be charged and remaining payments may be updated to a constant amount(say 120$).

Thanks in advance,

Suresh babu R

答:
I got this back from Authorize.net Developer advocate.,

Hi @sureshrb3,

If you have the customer profiles feature turned on for your account, then when you create a subscription, you'll get in the response a customer profile ID and a payment profile ID. Then, if you want to charge the card associated with the subscription in between subscription payments, you can create a transaction using the profile information in place of the card information (as detailed in the Charge a Customer Profile documentation).

So in your use case, you would just do a one time charge of the customer profile for the new down payment, then update the subscription for the correct amount of the remaining transactions.
-Aaron

This can be useful.

Thanks,
Suersh Babu R

Title: authorize.net recurring billing


问:
Microsoft Visual Studio Tools for git push error
I'm trying to get used to the VS git plugin.
I'm using it with bitbuket and GitHub remote repositories.

Sometimes i get the following error :

```<code>An error was raised by libgit2. Category = Net (Error).
Chunked encoding upload is not supported on the HTTP/1.0 protocol.
</code>```

Is someone knowing how to avoid this error ?

答: In my case it was due to Fiddler monitoring requests. Once I've turned it off the problem disappeared.</p>

Body:
I'm trying to get used to the VS git plugin.
I'm using it with bitbuket and GitHub remote repositories.

Sometimes i get the following error :

An error was raised by libgit2. Category = Net (Error).
Chunked encoding upload is not supported on the HTTP/1.0 protocol.

Is someone knowing how to avoid this error ?


问:
How to extract the two elements in Selenium(python)?
I need to extract all the "snail"s and "hello world"s under class 'm' and 'n'.
m and n are repeated, but they have different "snail"s and "hello world"s.</p>

<p>[![below][1]][1] . </p>

答:
You can use most of the available find_element_by methods to locate and element, here is a list of them alongside with the docs.

You could, for example, find the elements by their link text, since they are  tags:

```<code>driver.find_element_by_link_text('snail')
driver.find_element_by_link_text('Re: hello world')
</code>```

or, since you mentioned XPaths, you could use .find_element_by_xpath.

Body:
I need to extract all the "snail"s and "hello world"s under class 'm' and 'n'.
m and n are repeated, but they have different "snail"s and "hello world"s.

[![below][1]][1] .

Body:
You can use most of the available find_element_by methods to locate and element, here is a list of them alongside with the docs.

You could, for example, find the elements by their link text, since they are <a> tags:

driver.find_element_by_link_text('snail')
driver.find_element_by_link_text('Re: hello world')

or, since you mentioned XPaths, you could use .find_element_by_xpath.


问:
How to avoid use of Thread.Sleep
I never gave the use of Thread.Sleep much thought, until I downloaded the latest version of Netbeans.  Netbeans now warns you not to use Thread.Sleep.  So I did some research on the topic and found people stating that you only need to use Thread.Sleep for debugging/testing purposes and that if you use it at any other time you have poorly written code.

So my question is how can I keep from using Thread.Sleep in the following situation.

I have written a server application that interfaces with another application.  The server has two threads:

Handles the data coming over the socket and sends back other information or just plain acknoledgements.

This is the main thread.  After kicking off the socket thread it going into an indefinite while loop.  Within this while loop I check to make sure the socket thread is still active and that the user hasn't asked to exit the application via a TrayIcon interface.  Then I sleep and continue this while loop.

With this application, the TrayIcon is the only UI.

Here is the snippet I'm referencing:

```<code>// continues running as long as the exitth file is not present and
// the tray icon is not in a safe to exit status.

while(doNotExit())
{

    if (getPrimaryThread() == null || !getPrimaryThread().isAlive())
        resetsThreadAndSocket();

    try
    {
        // check to see if the socket threads are still active, if not create new ones.
        if ((getPrimaryThread() == null || !getPrimaryThread().isAlive()))
            createSocketThread();

        // check right before sleeping that the user does not want to exit.
        if(getTrayIcon().isExiting())
            break;

        // puts the main Thread to sleep for 3 seconds
           Thread.sleep(3000);
    }
    catch(SQLException ex)
    {
        _log.error(ex.getMessage(), ex);
        restartDatabase();
    }
}
</code>```

答:
You should consider attaching an event listener to your tray icon instead of polling its state. That way you won't need an extra thread just for monitoring.

If you can't do that for some reason, you can still do away with the extra thread as the Timer class can do the waiting for you.

Title: How to avoid use of Thread.Sleep

Body:
I never gave the use of Thread.Sleep much thought, until I downloaded the latest version of Netbeans.  Netbeans now warns you not to use Thread.Sleep.  So I did some research on the topic and found people stating that you only need to use Thread.Sleep for debugging/testing purposes and that if you use it at any other time you have poorly written code.

So my question is how can I keep from using Thread.Sleep in the following situation.

I have written a server application that interfaces with another application.  The server has two threads:

Handles the data coming over the socket and sends back other information or just plain acknoledgements.

This is the main thread.  After kicking off the socket thread it going into an indefinite while loop.  Within this while loop I check to make sure the socket thread is still active and that the user hasn't asked to exit the application via a TrayIcon interface.  Then I sleep and continue this while loop.

With this application, the TrayIcon is the only UI.

Here is the snippet I'm referencing:

// continues running as long as the exitth file is not present and
// the tray icon is not in a safe to exit status.

while(doNotExit())
{

    if (getPrimaryThread() == null || !getPrimaryThread().isAlive())
        resetsThreadAndSocket();

    try
    {
        // check to see if the socket threads are still active, if not create new ones.
        if ((getPrimaryThread() == null || !getPrimaryThread().isAlive()))
            createSocketThread();

        // check right before sleeping that the user does not want to exit.
        if(getTrayIcon().isExiting())
            break;

        // puts the main Thread to sleep for 3 seconds
           Thread.sleep(3000);
    }
    catch(SQLException ex)
    {
        _log.error(ex.getMessage(), ex);
        restartDatabase();
    }
}


问:
Perl: Need assistance converting if-elsif-else to something simpler
I've been reading up on dispatch tables and I get the general idea of how they work, but I'm having some trouble taking what I see online and applying the concept to some code I originally wrote as an ugly mess of if-elsif-else statements.

I have options parsing configured by using GetOpt::Long, and in turn, those options set a value in the %OPTIONS hash, depending on the option used.

Taking the below code as an example... (UPDATED WITH MORE DETAIL)

```<code>use     5.008008;
use     strict;
use     warnings;
use     File::Basename qw(basename);
use     Getopt::Long qw(HelpMessage VersionMessage :config posix_default require_order no_ignore_case auto_version auto_help);

my $EMPTY      => q{};

sub usage
{
    my $PROG = basename($0);
    print {*STDERR} $_ for @_;
    print {*STDERR} "Try $PROG --help for more information.\n";
    exit(1);
}

sub process_args
{
    my %OPTIONS;

    $OPTIONS{host}              = $EMPTY;
    $OPTIONS{bash}              = 0;
    $OPTIONS{nic}               = 0;
    $OPTIONS{nicName}           = $EMPTY;
    $OPTIONS{console}           = 0;
    $OPTIONS{virtual}           = 0;
    $OPTIONS{cmdb}              = 0;
    $OPTIONS{policyid}          = 0;
    $OPTIONS{showcompliant}     = 0;
    $OPTIONS{backup}            = 0;
    $OPTIONS{backuphistory}     = 0;
    $OPTIONS{page}              = $EMPTY;

    GetOptions
      (
        'host|h=s'              => \$OPTIONS{host}               ,
        'use-bash-script'       => \$OPTIONS{bash}               ,
        'remote-console|r!'     => \$OPTIONS{console}            ,
        'virtual-console|v!'    => \$OPTIONS{virtual}            ,
        'nic|n!'                => \$OPTIONS{nic}                ,
        'nic-name|m=s'          => \$OPTIONS{nicName}            ,
        'cmdb|d!'               => \$OPTIONS{cmdb}               ,
        'policy|p=i'            => \$OPTIONS{policyid}           ,
        'show-compliant|c!'     => \$OPTIONS{showcompliant}      ,
        'backup|b!'             => \$OPTIONS{backup}             ,
        'backup-history|s!'     => \$OPTIONS{backuphistory}      ,
        'page|g=s'              => \$OPTIONS{page}               ,
        'help'                  => sub      { HelpMessage(-exitval => 0, -verbose ->1)     },
        'version'               => sub      { VersionMessage()  },
      ) or usage;

    if ($OPTIONS{host} eq $EMPTY)
    {
        print {*STDERR} "ERROR: Must specify a host with -h flag\n";
        HelpMessage;
    }

    sanity_check_options(\%OPTIONS);

    # Parse anything else on the command line and throw usage
    for (@ARGV)
    {
        warn "Unknown argument: $_\n";
        HelpMessage;
    }

    return {%OPTIONS};
}

sub sanity_check_options
{
    my $OPTIONS     = shift;

    if (($OPTIONS->{console}) and ($OPTIONS->{virtual}))
    {
        print "ERROR: Cannot use flags -r and -v together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -r and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -r and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -r and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{virtual}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -v and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -v and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -v and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{backup}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -b and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{backup}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -b and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{nic}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -n and -d together\n";
        HelpMessage;
    }

    if (($OPTIONS->{policyid} != 0) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -p without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{showcompliant}) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -c without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{backuphistory}) and not ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flag -s without also specifying -b\n";
        HelpMessage;
    }

    if (($OPTIONS->{nicName}) and not ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flag -m without also specifying -n\n";
        HelpMessage;
    }

    return %{$OPTIONS};
}
</code>```

I'd like to turn the above code into a dispatch table, but can't figure out how to do it.

Any help is appreciated.

答:
You shouldn't be using elsif here because multiple condition could be true. And since multiple conditions could be true, a dispatch table can't be used. Your code can still be simplified greatly.

```<code>my @errors;

push @errors, "ERROR: Host must be provided\n"
   if !defined($OPTIONS{host});

my @conflicting =
   map { my ($opt, $flag) = @$_; $OPTIONS->{$opt} ? $flag : () }
      [ 'console', '-r' ],
      [ 'virtual', '-v' ],
      [ 'cmdb',    '-d' ],
      [ 'backup',  '-b' ],
      [ 'nic',     '-n' ];

push @errors, "ERROR: Can only use one the following flags at a time: @conflicting\n"
   if @conflicting > 1;

push @errors, "ERROR: Can't use flag -p without also specifying -d\n"
   if defined($OPTIONS->{policyid}) && !$OPTIONS->{cmdb};

push @errors, "ERROR: Can't use flag -c without also specifying -d\n"
   if $OPTIONS->{showcompliant} && !$OPTIONS->{cmdb};

push @errors, "ERROR: Can't use flag -s without also specifying -b\n"
   if $OPTIONS->{backuphistory} && !$OPTIONS->{backup};

push @errors, "ERROR: Can't use flag -m without also specifying -n\n"
   if defined($OPTIONS->{nicName}) && !$OPTIONS->{nic};

push @errors, "ERROR: Incorrect number of arguments\n"
   if @ARGV;

usage(@errors) if @errors;
</code>```

Note that the above fixes numerous errors in your code.

Help vs Usage Error

--help should provide the requested help to STDOUT, and shouldn't result in an error exit code.

Usage errors should be printed to STDERR, and should result in an error exit code.

Calling HelpMessage indifferently in both situations is therefore incorrect.

Create the following sub named usage to use (without arguments) when GetOptions returns false, and with an error message when some other usage error occurs:

```<code>use File::Basename qw( basename );

sub usage {
   my $prog = basename($0);
   print STDERR $_ for @_;
   print STDERR "Try '$prog --help' for more information.\n";
   exit(1);
}
</code>```

Keep using HelpMessage in response to --help, but the defaults for the arguments are not appropriate for --help. You should use the following:

```<code>'help' => sub { HelpMessage( -exitval => 0, -verbose => 1 ) },
</code>```

Body:
I've been reading up on dispatch tables and I get the general idea of how they work, but I'm having some trouble taking what I see online and applying the concept to some code I originally wrote as an ugly mess of if-elsif-else statements.

I have options parsing configured by using GetOpt::Long, and in turn, those options set a value in the %OPTIONS hash, depending on the option used.

Taking the below code as an example... (UPDATED WITH MORE DETAIL)

use     5.008008;
use     strict;
use     warnings;
use     File::Basename qw(basename);
use     Getopt::Long qw(HelpMessage VersionMessage :config posix_default require_order no_ignore_case auto_version auto_help);

my $EMPTY      => q{};

sub usage
{
    my $PROG = basename($0);
    print {*STDERR} $_ for @_;
    print {*STDERR} "Try $PROG --help for more information.\n";
    exit(1);
}

sub process_args
{
    my %OPTIONS;

    $OPTIONS{host}              = $EMPTY;
    $OPTIONS{bash}              = 0;
    $OPTIONS{nic}               = 0;
    $OPTIONS{nicName}           = $EMPTY;
    $OPTIONS{console}           = 0;
    $OPTIONS{virtual}           = 0;
    $OPTIONS{cmdb}              = 0;
    $OPTIONS{policyid}          = 0;
    $OPTIONS{showcompliant}     = 0;
    $OPTIONS{backup}            = 0;
    $OPTIONS{backuphistory}     = 0;
    $OPTIONS{page}              = $EMPTY;

    GetOptions
      (
        'host|h=s'              => \$OPTIONS{host}               ,
        'use-bash-script'       => \$OPTIONS{bash}               ,
        'remote-console|r!'     => \$OPTIONS{console}            ,
        'virtual-console|v!'    => \$OPTIONS{virtual}            ,
        'nic|n!'                => \$OPTIONS{nic}                ,
        'nic-name|m=s'          => \$OPTIONS{nicName}            ,
        'cmdb|d!'               => \$OPTIONS{cmdb}               ,
        'policy|p=i'            => \$OPTIONS{policyid}           ,
        'show-compliant|c!'     => \$OPTIONS{showcompliant}      ,
        'backup|b!'             => \$OPTIONS{backup}             ,
        'backup-history|s!'     => \$OPTIONS{backuphistory}      ,
        'page|g=s'              => \$OPTIONS{page}               ,
        'help'                  => sub      { HelpMessage(-exitval => 0, -verbose ->1)     },
        'version'               => sub      { VersionMessage()  },
      ) or usage;

    if ($OPTIONS{host} eq $EMPTY)
    {
        print {*STDERR} "ERROR: Must specify a host with -h flag\n";
        HelpMessage;
    }

    sanity_check_options(\%OPTIONS);

    # Parse anything else on the command line and throw usage
    for (@ARGV)
    {
        warn "Unknown argument: $_\n";
        HelpMessage;
    }

    return {%OPTIONS};
}

sub sanity_check_options
{
    my $OPTIONS     = shift;

    if (($OPTIONS->{console}) and ($OPTIONS->{virtual}))
    {
        print "ERROR: Cannot use flags -r and -v together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -r and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -r and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -r and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{virtual}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -v and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -v and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -v and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{backup}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -b and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{backup}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -b and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{nic}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -n and -d together\n";
        HelpMessage;
    }

    if (($OPTIONS->{policyid} != 0) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -p without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{showcompliant}) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -c without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{backuphistory}) and not ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flag -s without also specifying -b\n";
        HelpMessage;
    }

    if (($OPTIONS->{nicName}) and not ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flag -m without also specifying -n\n";
        HelpMessage;
    }

    return %{$OPTIONS};
}

I'd like to turn the above code into a dispatch table, but can't figure out how to do it.

Any help is appreciated.

Body:
You shouldn't be using elsif here because multiple condition could be true. And since multiple conditions could be true, a dispatch table can't be used. Your code can still be simplified greatly.

my @errors;

push @errors, "ERROR: Host must be provided\n"
   if !defined($OPTIONS{host});

my @conflicting =
   map { my ($opt, $flag) = @$_; $OPTIONS->{$opt} ? $flag : () }
      [ 'console', '-r' ],
      [ 'virtual', '-v' ],
      [ 'cmdb',    '-d' ],
      [ 'backup',  '-b' ],
      [ 'nic',     '-n' ];

push @errors, "ERROR: Can only use one the following flags at a time: @conflicting\n"
   if @conflicting > 1;

push @errors, "ERROR: Can't use flag -p without also specifying -d\n"
   if defined($OPTIONS->{policyid}) && !$OPTIONS->{cmdb};

push @errors, "ERROR: Can't use flag -c without also specifying -d\n"
   if $OPTIONS->{showcompliant} && !$OPTIONS->{cmdb};

push @errors, "ERROR: Can't use flag -s without also specifying -b\n"
   if $OPTIONS->{backuphistory} && !$OPTIONS->{backup};

push @errors, "ERROR: Can't use flag -m without also specifying -n\n"
   if defined($OPTIONS->{nicName}) && !$OPTIONS->{nic};

push @errors, "ERROR: Incorrect number of arguments\n"
   if @ARGV;

usage(@errors) if @errors;

Note that the above fixes numerous errors in your code.

Help vs Usage Error

--help should provide the requested help to STDOUT, and shouldn't result in an error exit code.

Usage errors should be printed to STDERR, and should result in an error exit code.

Calling HelpMessage indifferently in both situations is therefore incorrect.

Create the following sub named usage to use (without arguments) when GetOptions returns false, and with an error message when some other usage error occurs:

use File::Basename qw( basename );

sub usage {
   my $prog = basename($0);
   print STDERR $_ for @_;
   print STDERR "Try '$prog --help' for more information.\n";
   exit(1);
}

Keep using HelpMessage in response to --help, but the defaults for the arguments are not appropriate for --help. You should use the following:

'help' => sub { HelpMessage( -exitval => 0, -verbose => 1 ) },


问:
I am getting Timeout expired error
System.Data; Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool.  This may have occurred because all pooled connections were in use and max pool size was reached.
this error will come only when i run service

i am using below code

```<code>try
{
    LogGenerator.WriteErrorLog("Conn opened before");
    if (con.State == System.Data.ConnectionState.Closed)
    con.Open();
    LogGenerator.WriteErrorLog("Conn opened");
    // Set up a command with the given query and associate
    // this with the current connection.
    SqlCommand cmd = new SqlCommand("Backup database " + DBName + " to disk='" + filePathExist + "'", con);
    cmd.ExecuteNonQuery();
    LogGenerator.WriteErrorLog("query executed");
}
catch(Exception ex)
{
    LogGenerator.WriteErrorLog("Error in Conn");
    LogGenerator.WriteErrorLog(ex);
}
finally
{
    con.Close();
    con.Dispose();
    SqlConnection.ClearPool(con);
}
</code>```

答:
As your trying take DB backup sometime it will take more than default connection time, so try to set timeout to your command.

```<code>try
{
    if (con.State == System.Data.ConnectionState.Closed)
      con.Open();
// Set up a command with the given query and associate
// this with the current connection.
   SqlCommand cmd = new SqlCommand("Backup database " + DBName + " to disk='" +
   filePathExist + "'", con);
   cmd.CommandTimeout = 60;
   cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
   //handle exception here
}
finally
{
    con.Close();
    con.Dispose();
    SqlConnection.ClearPool(con);
}
</code>```

for more information on timeout please refer here.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout(v=vs.110).aspx

https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-remote-login-timeout-server-configuration-option

Title: I am getting Timeout expired error

Body:
System.Data; Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool.  This may have occurred because all pooled connections were in use and max pool size was reached.
this error will come only when i run service

i am using below code

try
{
    LogGenerator.WriteErrorLog("Conn opened before");
    if (con.State == System.Data.ConnectionState.Closed)
    con.Open();
    LogGenerator.WriteErrorLog("Conn opened");
    // Set up a command with the given query and associate
    // this with the current connection.
    SqlCommand cmd = new SqlCommand("Backup database " + DBName + " to disk='" + filePathExist + "'", con);
    cmd.ExecuteNonQuery();
    LogGenerator.WriteErrorLog("query executed");
}
catch(Exception ex)
{
    LogGenerator.WriteErrorLog("Error in Conn");
    LogGenerator.WriteErrorLog(ex);
}
finally
{
    con.Close();
    con.Dispose();
    SqlConnection.ClearPool(con);
}

Body:
As your trying take DB backup sometime it will take more than default connection time, so try to set timeout to your command.

try
{
    if (con.State == System.Data.ConnectionState.Closed)
      con.Open();
// Set up a command with the given query and associate
// this with the current connection.
   SqlCommand cmd = new SqlCommand("Backup database " + DBName + " to disk='" +
   filePathExist + "'", con);
   cmd.CommandTimeout = 60;
   cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
   //handle exception here
}
finally
{
    con.Close();
    con.Dispose();
    SqlConnection.ClearPool(con);
}

for more information on timeout please refer here.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout(v=vs.110).aspx

https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-remote-login-timeout-server-configuration-option


问:
How to detect Y position of StackLayout
I am using mechanism to move Stacklayout with gestures.  Is there another event that detects StackLayout's Y position change?  Meaning that I would like to catch when the StackLayout position is being panned up or down.</p>

```<code>   <StackLayout x:Name="bottomDrawer" BackgroundColor="Olive" AbsoluteLayout.LayoutBounds="0.5,1.00,0.9,0.04" AbsoluteLayout.LayoutFlags="All">
        <StackLayout.GestureRecognizers>
            <PanGestureRecognizer PanUpdated="PanGestureHandler" />
        </StackLayout.GestureRecognizers>
</StackLayout>
</code>```

答:
There are PropertyChanging and PropertyChanged events on the BindableObject (which is a class within the StackLayout hierarchy).

So you could bind to change(s) on the Y, Height and/or LayoutBounds properties.

Example using events:

```<code>aStackLayoutObject.PropertyChanging += (sender, e) =>
{
    switch (e.PropertyName)
    {
        case "Y":
            Log.WriteLine($"{e.PropertyName} : {(sender as StackLayout).Y}");
            break;
        case "Height":
            Log.WriteLine($"{e.PropertyName} : {(sender as StackLayout).Height}");
            break;
        case "LayoutBounds":
            Log.WriteLine($"{e.PropertyName}";
            break;
};

aStackLayoutObject.PropertyChanged += (sender, e) =>
{
    switch (e.PropertyName)
    {
        case "Y":
            Log.WriteLine($"{e.PropertyName} : {(sender as StackLayout).Y}");
            break;
        case "Height":
            Log.WriteLine($"{e.PropertyName} : {(sender as StackLayout).Height}");
            break;
        case "LayoutBounds":
            Log.WriteLine($"{e.PropertyName}";
            break;
};
</code>```

Title: How to detect Y position of StackLayout

Body:
I am using mechanism to move Stacklayout with gestures.  Is there another event that detects StackLayout's Y position change?  Meaning that I would like to catch when the StackLayout position is being panned up or down.

   <StackLayout x:Name="bottomDrawer" BackgroundColor="Olive" AbsoluteLayout.LayoutBounds="0.5,1.00,0.9,0.04" AbsoluteLayout.LayoutFlags="All">
        <StackLayout.GestureRecognizers>
            <PanGestureRecognizer PanUpdated="PanGestureHandler" />
        </StackLayout.GestureRecognizers>
</StackLayout>

Body:
There are PropertyChanging and PropertyChanged events on the BindableObject (which is a class within the StackLayout hierarchy).

So you could bind to change(s) on the Y, Height and/or LayoutBounds properties.

Example using events:

aStackLayoutObject.PropertyChanging += (sender, e) =>
{
    switch (e.PropertyName)
    {
        case "Y":
            Log.WriteLine($"{e.PropertyName} : {(sender as StackLayout).Y}");
            break;
        case "Height":
            Log.WriteLine($"{e.PropertyName} : {(sender as StackLayout).Height}");
            break;
        case "LayoutBounds":
            Log.WriteLine($"{e.PropertyName}";
            break;
};

aStackLayoutObject.PropertyChanged += (sender, e) =>
{
    switch (e.PropertyName)
    {
        case "Y":
            Log.WriteLine($"{e.PropertyName} : {(sender as StackLayout).Y}");
            break;
        case "Height":
            Log.WriteLine($"{e.PropertyName} : {(sender as StackLayout).Height}");
            break;
        case "LayoutBounds":
            Log.WriteLine($"{e.PropertyName}";
            break;
};