问:
Insert Mutiple Record into Database Using Php Mysql
I am running a forecast.This forecast has been successfully implemented and i want to run summary report based on the forecast. To achieve this, i had to allow the user to click a button "Summary Report". Upon clicking the button, it will insert the record into the Database and immediately fetch and analyze the data into summary as required. Question now is that the record are much like 1200 records. This records are not inserted into the DB,perhaps because it is too much. But when i reduce the period of the forecast such that the record is like 100, it will insert the data  and analyze it as required. What should i do for the record of says 5000 to be inserted into the Database. Or is there a better way to achieve multiple insertion to the database?
See below the insertion code:</p>

```<code>if(isset($_POST['exportBtn'])){
        foreach($_POST['sj'] as $key => $value) {
         $eflt = $_POST['sflt'][$key];
         $emodel = $_POST['smodel'][$key];
         $eengine =$_POST['sengine'][$key];
         $eloc = $_POST['sloc'][$key];
         $estye = $_POST['sstye'][$key];
         $ensvr = $_POST['snsvr'][$key];
         $eehd = $_POST['sehd'][$key];
              $inExp = mysqli_query($link,"INSERT INTO table_name(fltno,model,engine,loc,serviceType,nextSvr,usageHr)VALUES('$eflt','$emodel','$eengine','$eloc','$estye','$ensvr','$eehd')");
        }//End for-each loop
</code>```

答:
First of all change your database engine to "InnoDB" if its different as it's provide Row level locking that improves data operation faster in table.

Second, instead of inserting one by one row in to MySQL table, prepare string with all rows and insert it in one go as assembling one INSERT statement with multiple rows is much faster in MySQL than one INSERT statement per row.

EX.

```<code>$arrData = array();
foreach( $result as $row ) {
    $arrData[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['id'].')';
}
mysql_query('INSERT INTO table (text, id) VALUES '.implode(',', $arrData));
</code>```

Above query will insert all data in one go. Also you can divide $arrData variable if you have to insert thousands of data. In my case, I had successfully inserted 4200 data having 10 columns data.

Body:
I am running a forecast.This forecast has been successfully implemented and i want to run summary report based on the forecast. To achieve this, i had to allow the user to click a button "Summary Report". Upon clicking the button, it will insert the record into the Database and immediately fetch and analyze the data into summary as required. Question now is that the record are much like 1200 records. This records are not inserted into the DB,perhaps because it is too much. But when i reduce the period of the forecast such that the record is like 100, it will insert the data  and analyze it as required. What should i do for the record of says 5000 to be inserted into the Database. Or is there a better way to achieve multiple insertion to the database?
See below the insertion code:

if(isset($_POST['exportBtn'])){
        foreach($_POST['sj'] as $key => $value) {
         $eflt = $_POST['sflt'][$key];
         $emodel = $_POST['smodel'][$key];
         $eengine =$_POST['sengine'][$key];
         $eloc = $_POST['sloc'][$key];
         $estye = $_POST['sstye'][$key];
         $ensvr = $_POST['snsvr'][$key];
         $eehd = $_POST['sehd'][$key];
              $inExp = mysqli_query($link,"INSERT INTO table_name(fltno,model,engine,loc,serviceType,nextSvr,usageHr)VALUES('$eflt','$emodel','$eengine','$eloc','$estye','$ensvr','$eehd')");
        }//End for-each loop

Body:
First of all change your database engine to "InnoDB" if its different as it's provide Row level locking that improves data operation faster in table.

Second, instead of inserting one by one row in to MySQL table, prepare string with all rows and insert it in one go as assembling one INSERT statement with multiple rows is much faster in MySQL than one INSERT statement per row.

EX.

$arrData = array();
foreach( $result as $row ) {
    $arrData[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['id'].')';
}
mysql_query('INSERT INTO table (text, id) VALUES '.implode(',', $arrData));

Above query will insert all data in one go. Also you can divide $arrData variable if you have to insert thousands of data. In my case, I had successfully inserted 4200 data having 10 columns data.


来源: stackexchange

问:
Check if text field in collectionView is empty

I have a collection view (CollectionViewController) with 3 cells (each cell has it's own class). In the first cell (TextCell) I have a text field and a button (nextButton). When I press the button I want to check if the text field is empty or not. If it's not empty, I want to switch to the second cell.

CollectionViewController:

```<code>let textCell = TextCell()

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath)

    // TextCell
    if indexPath.item == 0 {

        let tCell = collectionView.dequeueReusableCell(withReuseIdentifier: textCellId, for: indexPath)
            let nextButton = textCell.nextButton
                nextButton.addTarget(self, action: #selector(handleNextButton), for: .touchUpInside)
        return tCell
    }
    return cell
}

//Handle Action

@objc func handleNextButton() {
    let text = textCell.TextField.text

    if text?.isEmpty == false {
        scrollToIndex(menuIndex: 1)
    } else {
        print("Text field is empty.")
    }
}
</code>```

The problem is that every time i check if the text field is empty or not, it say's it is empty although it's not.

答:
To identify whether the UITextField inside UICollectionViewCell is empty or not, you need to pass index position when button is clicked. To pass index position you can use tag. By using tag you can get clicked index position. After getting position, you can access elements from current index position by using  cellForItemAtIndexPath . You can find the particular index position UITextField is empty or not using the fetched cell reference

In Your  cellForItemAt

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

      if indexPath.item  == 0{
         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YOUR_CELL_IDENTIFIER", for: indexPath) as!  YOUR_UICOLLECTIONVIEW_CELL
                    cell.nextBtn.tag = indexPath.item
                    cell.nextBtn.addTarget(self, action: #selector(handleNextButton(_:)), for: .touchUpInside)

          return cell
       } else {
              ///use your other cells here
       }
}
</code>```

In your ViewController

```<code>func handleNextButton(_ sender:UIButton){
  let indexPath = IndexPath(item:sender.tag,section:0)
  let cell = YOUR_COLLECTIONVIEW.cellForItem(at: indexPath) as! YOUR_UICOLLECTIONVIEW_CELL
  if cell.txtFld.text == "" {
    print("TextField is empty")
   } else {
   print("TextField not empty")
  }
}
</code>```

Hope this will help you

ContentLicense: CC BY-SA 3.0

Body:
I have a collection view (CollectionViewController) with 3 cells (each cell has it's own class). In the first cell (TextCell) I have a text field and a button (nextButton). When I press the button I want to check if the text field is empty or not. If it's not empty, I want to switch to the second cell.

CollectionViewController:

let textCell = TextCell()

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath)

    // TextCell
    if indexPath.item == 0 {

        let tCell = collectionView.dequeueReusableCell(withReuseIdentifier: textCellId, for: indexPath)
            let nextButton = textCell.nextButton
                nextButton.addTarget(self, action: #selector(handleNextButton), for: .touchUpInside)
        return tCell
    }
    return cell
}

//Handle Action

@objc func handleNextButton() {
    let text = textCell.TextField.text

    if text?.isEmpty == false {
        scrollToIndex(menuIndex: 1)
    } else {
        print("Text field is empty.")
    }
}

The problem is that every time i check if the text field is empty or not, it say's it is empty although it's not.

Body:
To identify whether the UITextField inside UICollectionViewCell is empty or not, you need to pass index position when button is clicked. To pass index position you can use tag. By using tag you can get clicked index position. After getting position, you can access elements from current index position by using  cellForItemAtIndexPath . You can find the particular index position UITextField is empty or not using the fetched cell reference

In Your  cellForItemAt

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

      if indexPath.item  == 0{
         let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YOUR_CELL_IDENTIFIER", for: indexPath) as!  YOUR_UICOLLECTIONVIEW_CELL
                    cell.nextBtn.tag = indexPath.item
                    cell.nextBtn.addTarget(self, action: #selector(handleNextButton(_:)), for: .touchUpInside)

          return cell
       } else {
              ///use your other cells here
       }
}

In your ViewController

func handleNextButton(_ sender:UIButton){
  let indexPath = IndexPath(item:sender.tag,section:0)
  let cell = YOUR_COLLECTIONVIEW.cellForItem(at: indexPath) as! YOUR_UICOLLECTIONVIEW_CELL
  if cell.txtFld.text == "" {
    print("TextField is empty")
   } else {
   print("TextField not empty")
  }
}

Hope this will help you


问:
Generating URL for Controller action in Spring
How can I dynamically create an URL for a Controller action?

Consider the following case:

```<code>@Controller
@RequestMapping("controller")
public class Controller {
    @RequestMapping("url")
    public String method() {
        return "Whatever"
    }
}
</code>```

What I'd like to do is get the base URL and concat controller/url to it.
For this behavior, Laravel for example provides the URL helper (action() method). Is there something similar in Spring Boot?

答:
I think using @PathVariable will help you </p>

```<code>@Controller
@RequestMapping(value="/controller")
public class Controller {
    @RequestMapping(value="/url/{id}", method=RequestMethod.GET)
    public String method(@PathVariable("id") String id) {
         System.out.println("the url value : "+id );
        return "Whatever"
    }
}
</code>```

<p>then you can call the method using /controller/url/{here the value}
example /controller/url/www.google.com </p>

Body:
How can I dynamically create an URL for a Controller action?

Consider the following case:

@Controller
@RequestMapping("controller")
public class Controller {
    @RequestMapping("url")
    public String method() {
        return "Whatever"
    }
}

What I'd like to do is get the base URL and concat controller/url to it.
For this behavior, Laravel for example provides the URL helper (action() method). Is there something similar in Spring Boot?

Body:
I think using @PathVariable will help you

@Controller
@RequestMapping(value="/controller")
public class Controller {
    @RequestMapping(value="/url/{id}", method=RequestMethod.GET)
    public String method(@PathVariable("id") String id) {
         System.out.println("the url value : "+id );
        return "Whatever"
    }
}

then you can call the method using /controller/url/{here the value}
example /controller/url/www.google.com


问:
How to sort a list by my order for several times?
I have just started coding with python recently.
I am trying to sort my list as a dictionary which I've made.
this is the dictionary:

```<code>X={'Si':6,'La':5,'Sol':4,'Fa':3,'Mi':2,'Re':1,'Do':0}
</code>```

And I have a list like this:

```<code>A=[['Do', 'Do'], ['Re', 'Do'], ['Do', 'Mi'], ['Si', 'Do'], ['Fa', 'Fa'], ['Mi', 'Fa'], ['Sol', 'Si']]
</code>```

I intend to sort this list into:

```<code>[['Do', 'Do'], ['Do', 'Mi'], ['Re', 'Do'], ['Mi', 'Fa'], ['Fa', 'Fa'], ['Sol', 'Si'], ['Si', 'Do']]
</code>```

I mean sorting this list by sorting first element then the second element and third and ...

I have tried to fulfill this by using this code:

```<code>A.sort(key=lambda val: X[val[0]])
</code>```

Therefore, I could sort the list by the first item, but for the second or third(if the inner lists contain more items) I cannot sort them.
I'm not a Groovy coder so thanks for the help in advance.

Body:
I have just started coding with python recently.
I am trying to sort my list as a dictionary which I've made.
this is the dictionary:

X={'Si':6,'La':5,'Sol':4,'Fa':3,'Mi':2,'Re':1,'Do':0}

And I have a list like this:

A=[['Do', 'Do'], ['Re', 'Do'], ['Do', 'Mi'], ['Si', 'Do'], ['Fa', 'Fa'], ['Mi', 'Fa'], ['Sol', 'Si']]

I intend to sort this list into:

[['Do', 'Do'], ['Do', 'Mi'], ['Re', 'Do'], ['Mi', 'Fa'], ['Fa', 'Fa'], ['Sol', 'Si'], ['Si', 'Do']]

I mean sorting this list by sorting first element then the second element and third and ...

I have tried to fulfill this by using this code:

A.sort(key=lambda val: X[val[0]])

Therefore, I could sort the list by the first item, but for the second or third(if the inner lists contain more items) I cannot sort them.
I'm not a Groovy coder so thanks for the help in advance.

Body:
Sorting by multiple "fields":

X = {'Si':6,'La':5,'Sol':4,'Fa':3,'Mi':2,'Re':1,'Do':0}
A = [['Do', 'Do'], ['Re', 'Do'], ['Do', 'Mi'], ['Si', 'Do'], ['Fa', 'Fa'], ['Mi', 'Fa'], ['Sol', 'Si']]
result = sorted(A, key=lambda lst: tuple(X[i] for i in lst))

print(result)

The output:

[['Do', 'Do'], ['Do', 'Mi'], ['Re', 'Do'], ['Mi', 'Fa'], ['Fa', 'Fa'], ['Sol', 'Si'], ['Si', 'Do']]


问:
How to break a loop for getting an integer array in c++
How can I break a loop when I define an integer array with a number and I want to finish the loop by pressing the ENTER.
I test '\n' and '\r' and '\0' and char(13) and NULL but didn't work !
for example ( in this code i try to stop the loop with ascii code of ENTER) :

```<code>#include <iostream>
using namespace std;
int main()
{
    int n[100];
    for (int i = 0; i < 100 && n[i]!=char(13); i++)
    {
        cin >> n[i];
    }
    return 0;
}
</code>```

答:
The behaviour of your code is undefined: you read an element from n before writing it: int n[100] = {}; is a fix for that.

Your specific problem here is that you need to check the error state of cin if an int is not readable from the stream: use something like std::cin.fail().

Also, don't hardcode character values (presumably that's what char(13) is doing?), as then you're not writing portable code. Use '\r' &c. instead.

Body:
How can I break a loop when I define an integer array with a number and I want to finish the loop by pressing the ENTER.
I test '\n' and '\r' and '\0' and char(13) and NULL but didn't work !
for example ( in this code i try to stop the loop with ascii code of ENTER) :

#include <iostream>
using namespace std;
int main()
{
    int n[100];
    for (int i = 0; i < 100 && n[i]!=char(13); i++)
    {
        cin >> n[i];
    }
    return 0;
}


问:
Jquery radio button starts endless loop?
I want to get an answer from the php file if I click on one of the radio buttons, but if I use the radio button, the alert appers in an endless loop. Why? And how do I get the alert only once?

I try it with only a „normal“ button, then it works:
If I click on the button, the ajax responds the values in the alert once.

Thank you

<!doctype html>

    <title>test</title>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

      <button type="button" class="btn btn-dark" id="go">Go</button>

            <input type="radio"  name="aktionswahl" value="alles" checked autocomplete="off"> Alles

            <input type="radio"  name="aktionswahl" value="blue" autocomplete="off"> blue

            <input type="radio"  name="aktionswahl" value="red" autocomplete="off"> red

```

答:
Try this, your code is right just need one change...
write return false; immediately after alert.
means...function(data) { alert(data); return false; }</p>


问:
In pathfinding, what is the difference between DFS and Dijkstra?
I'm studying about DFS and Dijkstra.
In my simple test cases, most of them shows that DFS is faster.
Passing every nodes costs the same in my test cases.
But most people prefer Dijkstra to DFS in pathfinding because Dijkstra is so accurate.

So, what's the difference between DFS and Dijkstra?
Also, what are the pros and cons of each algorithm?

答:
DFS keeps jumping along nodes until it finds a path, While Dijkstra is more similar to a BFS except it keeps track of weights (not all paths have equal cost) and will keep checking the shortest path not already checked until it gets to the target.

In general DFS is (usually) the fastest way to find a path and can be implemented very easily with recursion, but Dijkstra's algorithm is the fastest general way to find the shortest possible path.

In a less general case there is A*, which is Dijkstra's algorithm with some extra heuristics on top to guess which paths might be better to check first.  This will also find the shortest possible path, but may do so faster if your heuristic is good.

EDIT:

I should add, that if you want a "pretty good" path in a hurry and heuristics are available, that DFS with heuristics can often be a good choice if your graph doesn't have too many dead ends.  This is called Greedy Best First Search and is a good, underutilized path finding algorithm for use in e.g. games, where you can design your maps to have few dead ends, or road maps where A* is prohibitively expensive.


问:
Vertically align elements in one layout with elements in another to be at same level?
I have horizontal linear layout with two vertical linear layouts in it. Each vertical layout contains 5 TextViews and looks like this:

As you see the 5 textviews from the first layout are at the same vertical  level with the 5 textviews from the second layout. But when I change the elements of the second layout to be EditTexts it starts looking like that:

What can I do to align TextViews with their corresponding EditTexts to be at the exact same vertical level? I can change the margin top and bottom to all TextViews. But it's a lot of work and after that they are not at the exact same level. I'm using Xamarin.Android.

答:
Try below code.I think it will help you.
<img src="https://i.stack.imgur.com/x9Kfe.png" alt="enter image description here"> </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:padding="10dp"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:weightSum="10"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:text="TextView1"
            android:layout_weight="2"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:text="TextView1"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:text="TextView1"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:text="TextView1"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:text="TextView1"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:weightSum="10"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <EditText
            android:layout_weight="2"
            android:hint="edittext"
            android:layout_width="match_parent"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <EditText
            android:layout_width="match_parent"
            android:layout_weight="2"
            android:hint="edittext"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <EditText
            android:layout_width="match_parent"
            android:gravity="bottom|center"
            android:layout_weight="2"
            android:hint="edittext"
            android:layout_height="wrap_content" />
        <EditText
            android:layout_width="match_parent"
            android:hint="edittext"
            android:gravity="bottom|center"
            android:layout_weight="2"
            android:layout_height="wrap_content" />
        <EditText
            android:layout_width="match_parent"
            android:hint="edittext"
            android:layout_weight="2"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />

    </LinearLayout>
</LinearLayout>
</code>```

Body:
Try below code.I think it will help you.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:padding="10dp"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:weightSum="10"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:text="TextView1"
            android:layout_weight="2"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:text="TextView1"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:text="TextView1"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:text="TextView1"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:text="TextView1"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:weightSum="10"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <EditText
            android:layout_weight="2"
            android:hint="edittext"
            android:layout_width="match_parent"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <EditText
            android:layout_width="match_parent"
            android:layout_weight="2"
            android:hint="edittext"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />
        <EditText
            android:layout_width="match_parent"
            android:gravity="bottom|center"
            android:layout_weight="2"
            android:hint="edittext"
            android:layout_height="wrap_content" />
        <EditText
            android:layout_width="match_parent"
            android:hint="edittext"
            android:gravity="bottom|center"
            android:layout_weight="2"
            android:layout_height="wrap_content" />
        <EditText
            android:layout_width="match_parent"
            android:hint="edittext"
            android:layout_weight="2"
            android:gravity="bottom|center"
            android:layout_height="wrap_content" />

    </LinearLayout>
</LinearLayout>


问:
Way to not use goto loops in vba msgbox
I am trying to find a way to avoid using GoTo loops in VBA as i understand they can lead to serious confusion and issues. I have a  user InputBox, where the user defines a variables, currently on the if statement there are 3 options, if = Y ElseIf = N and else GoTo Start.

However this works great for the case where the user mistypes the variable i.e Y# etc, but i currently run into issues when the user wants to close the input box i.e clicks cancel or the cross.

So i was wondering if there is a more elligent solution to this or am I stuck with this hicup?

My code is below, this is only a test set used to test this new feature i am adding to my main code.

```<code>Sub MsgBox_Test ()

Dim TestVariable As String

VariableEntrey: TestVariable = InputBox(" Y or N")
If TestVariable = "Y" Or TestVariable = "y" Then
    MsgBox ("Yeyy")
ElseIf TestVariable = "N" Or TestVariable = "n" Then
    MsgBox ("Awww")
Else: GoTo VariableEntrey
End If

End Sub
</code>```

Thanks for any help you are able to provide

答:
You could try with Do .... Loop here:

Edit: plus limitation for single character or empty input

```<code>Dim TestVariable As String
TestVariable = InputBox(" Y or N")

Do While (TestVariable = "N" Or TestVariable = "n" or Len(TestVariable) > 1)
    MsgBox ("Awww")
    TestVariable = InputBox(" Y or N")

Loop

If TestVariable = "Y" Or TestVariable = "y" Then
    MsgBox ("Yeyy")
End if
</code>```

Title: Way to not use goto loops in vba msgbox

Body:
I am trying to find a way to avoid using GoTo loops in VBA as i understand they can lead to serious confusion and issues. I have a  user InputBox, where the user defines a variables, currently on the if statement there are 3 options, if = Y ElseIf = N and else GoTo Start.

However this works great for the case where the user mistypes the variable i.e Y# etc, but i currently run into issues when the user wants to close the input box i.e clicks cancel or the cross.

So i was wondering if there is a more elligent solution to this or am I stuck with this hicup?

My code is below, this is only a test set used to test this new feature i am adding to my main code.

Sub MsgBox_Test ()

Dim TestVariable As String

VariableEntrey: TestVariable = InputBox(" Y or N")
If TestVariable = "Y" Or TestVariable = "y" Then
    MsgBox ("Yeyy")
ElseIf TestVariable = "N" Or TestVariable = "n" Then
    MsgBox ("Awww")
Else: GoTo VariableEntrey
End If

End Sub

Thanks for any help you are able to provide

Body:
You could try with Do .... Loop here:

Edit: plus limitation for single character or empty input

Dim TestVariable As String
TestVariable = InputBox(" Y or N")

Do While (TestVariable = "N" Or TestVariable = "n" or Len(TestVariable) > 1)
    MsgBox ("Awww")
    TestVariable = InputBox(" Y or N")

Loop

If TestVariable = "Y" Or TestVariable = "y" Then
    MsgBox ("Yeyy")
End if


问:
PerfMon Metrics Collector - Error in JMeter
Need to know the reason for the below mentioned error, while runnig the recorded script in JMeter to calculate the hosted server's CPU, RAM utilization & performance result. Before running the test script I started the Server Agent in my hosted server to calculate the CPU & RAM utilization of hosted server's machine.

When I connect my local machine using LAN connection and start running the JMeter script, I can get my CPU & RAM utilization status as mentioned in below image-1.

And when I connect my local machine using WIFI connection and start running the JMeter script, I cannot track my CPU & RAM utilization status and java.net.ConnectException:Connection timed out: connect error message displays as mentioned in below image-2.

Please let me know the solution for this issue.

答:
Most probably your WiFi Connection resides in the different subnet therefore JMeter cannot establish connection with the server agent.

Check subnet masks on JMeter and ServerAgent hosts, if it is not the same - most likely you won't be able to connect without specific IP routing settings. You can talk to your network administrator to resolve it.

If you won't be able to connect to port 4444 of the host where the ServerAgent is running using telnet command (or equivalent) - JMeter's Perfmon Metrics Collector listener will not be able to fetch the data as well.

According to What’s the Max Number of Users You Can Test on JMeter? article you should not be running the load test over WiFi so I would strongly recommend reconsidering your approach and switching back to LAN for tests execution. If you need to see how your application behaves when it is being accessed over WiFi - you can simulate slower connections by controlling JMeter's bandwidth


答:
You can try a Do... Loop Until construct that just repeats until you get an acceptable answer. For example:

```<code>Sub GetAnswer()

    Dim strAnswer As String

    Do
        strAnswer = InputBox("Y or N")
    Loop Until strAnswer Like "[YyNn]"

    MsgBox "Thanks for your answer of: " & strAnswer

End Sub
</code>```

See the docs on the Like operator to prevent having to check individually for y, Y, n and N.

Title: Way to not use goto loops in vba msgbox

Body:
You can try a Do... Loop Until construct that just repeats until you get an acceptable answer. For example:

Sub GetAnswer()

    Dim strAnswer As String

    Do
        strAnswer = InputBox("Y or N")
    Loop Until strAnswer Like "[YyNn]"

    MsgBox "Thanks for your answer of: " & strAnswer

End Sub

See the docs on the Like operator to prevent having to check individually for y, Y, n and N.


问:
What does mean this return
1 What does mean this return;? If p<0 what does this set method give me back?

```<code>-(void)setSomething:(int)p{
   if (p<0)
      return;
   _p=p
}
</code>```

2 And whats the difference with?

```<code>-(void)setSomething:(int)p{
   if (p>=0){
      _p=p
   }else{
      return;
   }
}
</code>```

3 If I omit the else statement above, what does happen?

答:
You got 3 ways to write a function which are effectively doing the same thing. They are all assigning _p with the value of p if the value of p is not negative.

(void) in your function says that it is not going to return anything.
Therefore the return; is not doing anything but exiting from the function.

& 3. For a function with return type void, you don't need an explicit return statement at the end of the function body.

ie.

```<code>-(void)setSomething:(int)p{
  <code>
  return;
}
</code>```

and

```<code>-(void)setSomething:(int)p{
  <code>
}
</code>```

are effectively same.

There are no other lines which will get executed after the return statement in else case of 2. Even if you have the else block or not, the program will exit from the function there.

Title: What does mean this return

Body:
1 What does mean this return;? If p<0 what does this set method give me back?

-(void)setSomething:(int)p{
   if (p<0)
      return;
   _p=p
}

2 And whats the difference with?

-(void)setSomething:(int)p{
   if (p>=0){
      _p=p
   }else{
      return;
   }
}

3 If I omit the else statement above, what does happen?

Body:
You got 3 ways to write a function which are effectively doing the same thing. They are all assigning _p with the value of p if the value of p is not negative.

(void) in your function says that it is not going to return anything.
Therefore the return; is not doing anything but exiting from the function.

& 3. For a function with return type void, you don't need an explicit return statement at the end of the function body.

ie.

-(void)setSomething:(int)p{
  <code>
  return;
}

and

-(void)setSomething:(int)p{
  <code>
}

are effectively same.

There are no other lines which will get executed after the return statement in else case of 2. Even if you have the else block or not, the program will exit from the function there.


问:
Ansible-Playbook - Save output to a remote server
I'm new to all the Ansible stuff. So most of the time I'm in "Trial and Error"-Mode.

Now I'm facing a challenge with a playbook and I do not know to look further.

The main task of this playbook should be to get a "Show run" from a Cisco Device and save this in a text file on a backup server (which is a remote server).

The only task, which is not working, is the Backup Task.

Here is my playbook:

```<code>- hosts: IOSGATEWAY
  gather_facts: no
  connection: local
  tasks:
  - name: GET CREDENTIALS
    include_vars: path/to/all/all.yml

  - name: DEFINE CONNECTION TO GW
    set_fact:
       connection:
          host: "{{ inventory_hostname }}"
          username: "{{ creds['username'] }}"
          password: "{{ creds['password'] }}"

  - name: GET SHOW RUN
    ios_command:
      provider: "{{ connection }}"
      commands:
         - show run
    register: show_run

  - name: SAVE TO BACKUP SERVER
    copy:
      content: "{{ show_run.stdout[0] }}"
      dest: "path/to/Directory/{{ inventory_hostname }}.txt"
    delegate_to: BACKUPSERVER
</code>```

Can someone hint me in the right direction?

答:
You set connection: local for the playbook, so everything you do is executed locally (which is correct for ios_... modules, but not what you actually want for copy module).

I'd recommend to define ansible_connection variable in your inventory per group of hosts/devices, so Ansible will use local connection for your ios devices, and ssh for backup-server.

Body:
I'm new to all the Ansible stuff. So most of the time I'm in "Trial and Error"-Mode.

Now I'm facing a challenge with a playbook and I do not know to look further.

The main task of this playbook should be to get a "Show run" from a Cisco Device and save this in a text file on a backup server (which is a remote server).

The only task, which is not working, is the Backup Task.

Here is my playbook:

- hosts: IOSGATEWAY
  gather_facts: no
  connection: local
  tasks:
  - name: GET CREDENTIALS
    include_vars: path/to/all/all.yml

  - name: DEFINE CONNECTION TO GW
    set_fact:
       connection:
          host: "{{ inventory_hostname }}"
          username: "{{ creds['username'] }}"
          password: "{{ creds['password'] }}"

  - name: GET SHOW RUN
    ios_command:
      provider: "{{ connection }}"
      commands:
         - show run
    register: show_run

  - name: SAVE TO BACKUP SERVER
    copy:
      content: "{{ show_run.stdout[0] }}"
      dest: "path/to/Directory/{{ inventory_hostname }}.txt"
    delegate_to: BACKUPSERVER

Can someone hint me in the right direction?


问:
Jersey java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer
I'm trying to make a web-service with Tomcat and Eclipse using jersey library.
This is my service class:

```<code>package com.gontuseries.university;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/university")
public class UniversityRestWs {

    @GET
    @Produces(MediaType.TEXT_HTML)
    public String getHtmlUniversityInfo(){
        return "<html><body>test</body></html>";
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getTextUniversityInfo(){
        return "test";
    }
}
</code>```

And this is file web.xml

```<code> <servlet>
 <servlet-name>Jersey REST Service</servlet-name>
 <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
 <init-param>
 <param-name>com.sun.jersey.config.property.packages</param-name>
 <param-value>com.gontuseries.university</param-value>
 </init-param>
 </servlet>
 <servlet-mapping>
 <servlet-name>Jersey REST Service</servlet-name>
 <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>
</code>```

When i test my service i get java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer
I downloaded jersey from https://jersey.java.net/download.html

Can someone help me?
Thanks

答: Above provided solutions are correct but even after making these changes i was getting this error. So what I did was removed all the maven downloaded Jersey jars and update Project again with new maven dependency and that resolved my issue </p>

Body:
I'm trying to make a web-service with Tomcat and Eclipse using jersey library.
This is my service class:

package com.gontuseries.university;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/university")
public class UniversityRestWs {

    @GET
    @Produces(MediaType.TEXT_HTML)
    public String getHtmlUniversityInfo(){
        return "test";
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getTextUniversityInfo(){
        return "test";
    }
}

And this is file web.xml

 <servlet>
 <servlet-name>Jersey REST Service</servlet-name>
 <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
 <init-param>
 <param-name>com.sun.jersey.config.property.packages</param-name>
 <param-value>com.gontuseries.university</param-value>
 </init-param>
 </servlet>
 <servlet-mapping>
 <servlet-name>Jersey REST Service</servlet-name>
 <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>

When i test my service i get java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer
I downloaded jersey from https://jersey.java.net/download.html

Can someone help me?
Thanks


问:
z value for output in async reset register - verilog
i want to make a register with synce load and asynce reset

it's my module

```<code>module register32bit(indata,load,reset,clk,outdate);
input [31:0]indata;
input load;
input clk;
input reset;
output [31:0] outdate;
wire [31:0] indata;
reg [31:0] outdata;
wire clk;
wire load;
wire reset;

always @(posedge clk or reset) begin
if(reset) begin
 outdata <= 0;
end
else if(load) begin
 outdata <= indata;
end
end
endmodule
</code>```

now the problem is in my tb
how can i test the module???
here's my tb

i dont know why the outdate haz 'z' value and dont know that this way of using tb is logical or not

```<code>module tb1();
reg [31:0]indata;
reg load;
reg clk = 0;
reg reset;
wire [31:0]outdata;
initial begin
#0 indata = 32'haef27c80;
#10 load = 1;
#3 clk = 1;
#0 clk = 0;
#10 $finish;
end

register32bit reg32b(
.indata(indata),
.load(load),
.reset(reset),
.clk(clk),
.outdate(outdate)
);

initial begin
$monitor("indata:%b\nclk:%b\nload:%b\nreset:%b\noutdata:%b\n------------",
indata,clk,load,reset,outdate,);
end
endmodule
</code>```

and this is the result

```<code># indata:10101110111100100111110010000000
# clk:0
# load:x
# reset:x
# outdata:z
# ------------
# indata:10101110111100100111110010000000
# clk:0
# load:1
# reset:x
# outdata:z
# ------------
# indata:10101110111100100111110010000000
# clk:0
# load:1
# reset:x
# outdata:zhere
</code>```

please make a tb for me and if the register module has some problems , tell them to me
thanks a lot

答: You're not driving your output outdata in module register32bit. You're not driving the wire outdata in your testbench. This is presumably because the typo outdate appears throughout your code.

Body:
i want to make a register with synce load and asynce reset

it's my module

module register32bit(indata,load,reset,clk,outdate);
input [31:0]indata;
input load;
input clk;
input reset;
output [31:0] outdate;
wire [31:0] indata;
reg [31:0] outdata;
wire clk;
wire load;
wire reset;

always @(posedge clk or reset) begin
if(reset) begin
 outdata <= 0;
end
else if(load) begin
 outdata <= indata;
end
end
endmodule

now the problem is in my tb
how can i test the module???
here's my tb

i dont know why the outdate haz 'z' value and dont know that this way of using tb is logical or not

module tb1();
reg [31:0]indata;
reg load;
reg clk = 0;
reg reset;
wire [31:0]outdata;
initial begin
#0 indata = 32'haef27c80;
#10 load = 1;
#3 clk = 1;
#0 clk = 0;
#10 $finish;
end

register32bit reg32b(
.indata(indata),
.load(load),
.reset(reset),
.clk(clk),
.outdate(outdate)
);

initial begin
$monitor("indata:%b\nclk:%b\nload:%b\nreset:%b\noutdata:%b\n------------",
indata,clk,load,reset,outdate,);
end
endmodule

and this is the result

# indata:10101110111100100111110010000000
# clk:0
# load:x
# reset:x
# outdata:z
# ------------
# indata:10101110111100100111110010000000
# clk:0
# load:1
# reset:x
# outdata:z
# ------------
# indata:10101110111100100111110010000000
# clk:0
# load:1
# reset:x
# outdata:zhere

please make a tb for me and if the register module has some problems , tell them to me
thanks a lot


问:
Error 'rm: missing operand' when using along with 'find' command
I see that this question is getting popular.
I answered my own question below.
What says Inian is correct and it helped me to analyze my source code better.

My problem was in the FIND and not in the RM. My answer gives a block of code, which I am currently using, to avoid problems when FIND finds nothing but still would pass arguments to RM, causing the error mentioned above.

OLD QUESTION BELOW

I'm writing many and many different version of the same command.
All, are executed but with an error/info:

```<code>rm: missing operand
Try 'rm --help' for more information.
</code>```

These are the commands I'm using:

```<code>#!/bin/bash
BDIR=/home/user/backup
find ${BDIR} -type d -mtime +180 -print -exec rm -rf {} \;
find ${BDIR} -type d -mtime +180 -print -exec rm -rf {} +
find "$BDIR" -type d -mtime +180 -print -exec rm -rf {} \;
find "$BDIR" -depth -type d -mtime +180 -print -exec rm -rf {} \;
find ${BDIR} -depth -type d -mtime +180 -print -exec rm -rf {} +

find $BDIR -type d -mtime +180 -print0 | xargs -0 rm -rf

DEL=$(FIND $BDIR -type d -mtime +180 -print)
rm -rf $DEL
</code>```

I'm sure all of them are correct (because they all do their job), and if I run them manually I do not get that message back, but while in a .sh script I do.

EDIT: since I have many of these RM's, the problem could be somewhere else. I'm checking all of them. All of the above codes works but the best answer is the one marked ;)

答:
After researches, the command I'm comfortable using is:

```<code>HOME=/home/user
FDEL=$HOME/foldersToDelete
BDIR=/backup/my_old_folders
FLOG=/var/log/delete_old_backup.log
find ${BDIR} -mindepth 1 -daystart -type d -mtime +180 -printf "%f\n" > ${FDEL}
if [[ $? -eq 0 && $(wc -l < ${FDEL}) -gt 0 ]]; then
    cd ${BDIR}
    xargs -d '\n' -a ${FDEL} rm -rf
  LOG=" - Folders older than 180 were deleted"
else
  LOG=" - There aren't folders older than 180 days to delete"
fi
echo ${LOG} >> ${FLOG}
</code>```

Why? I search all the old folders I want to delete and print them all into a file, regardless for their naming with or without space. If the file is bigger than 0 byte this means that there are folder I want no more.

If your 'FIND' fails with a 'rm: missing operand', it probably isn't to search in the RM rather in the FIND itself.
A good way of removing the file using FIND, is the one I felt to share with you.

Body:
I see that this question is getting popular.
I answered my own question below.
What says Inian is correct and it helped me to analyze my source code better.

My problem was in the FIND and not in the RM. My answer gives a block of code, which I am currently using, to avoid problems when FIND finds nothing but still would pass arguments to RM, causing the error mentioned above.

OLD QUESTION BELOW

I'm writing many and many different version of the same command.
All, are executed but with an error/info:

rm: missing operand
Try 'rm --help' for more information.

These are the commands I'm using:

#!/bin/bash
BDIR=/home/user/backup
find ${BDIR} -type d -mtime +180 -print -exec rm -rf {} \;
find ${BDIR} -type d -mtime +180 -print -exec rm -rf {} +
find "$BDIR" -type d -mtime +180 -print -exec rm -rf {} \;
find "$BDIR" -depth -type d -mtime +180 -print -exec rm -rf {} \;
find ${BDIR} -depth -type d -mtime +180 -print -exec rm -rf {} +

find $BDIR -type d -mtime +180 -print0 | xargs -0 rm -rf

DEL=$(FIND $BDIR -type d -mtime +180 -print)
rm -rf $DEL

I'm sure all of them are correct (because they all do their job), and if I run them manually I do not get that message back, but while in a .sh script I do.

EDIT: since I have many of these RM's, the problem could be somewhere else. I'm checking all of them. All of the above codes works but the best answer is the one marked ;)

Body:
After researches, the command I'm comfortable using is:

HOME=/home/user
FDEL=$HOME/foldersToDelete
BDIR=/backup/my_old_folders
FLOG=/var/log/delete_old_backup.log
find ${BDIR} -mindepth 1 -daystart -type d -mtime +180 -printf "%f\n" > ${FDEL}
if [[ $? -eq 0 && $(wc -l < ${FDEL}) -gt 0 ]]; then
    cd ${BDIR}
    xargs -d '\n' -a ${FDEL} rm -rf
  LOG=" - Folders older than 180 were deleted"
else
  LOG=" - There aren't folders older than 180 days to delete"
fi
echo ${LOG} >> ${FLOG}

Why? I search all the old folders I want to delete and print them all into a file, regardless for their naming with or without space. If the file is bigger than 0 byte this means that there are folder I want no more.

If your 'FIND' fails with a 'rm: missing operand', it probably isn't to search in the RM rather in the FIND itself.
A good way of removing the file using FIND, is the one I felt to share with you.


问:
Is it posible to use django_select2 widgets with a Wagtail ParentalManyToManyField
I need a complex selection widget because there are a lot of options in a multiple select widget. But I see HeavySelect2MultipleWidget needs views and urls to use it. I think there is not possible it in Wagtail by default.

This is the code:

```<code>class Resource(Page):
authors  = ParentalManyToManyField('Authors', blank=True)

content_panels = Page.content_panels + [
    FieldPanel('authors',  widget=forms.CheckboxSelectMultiple)
]
</code>```

It would be nice to use

```<code> FieldPanel('authors',  widget=HeavySelect2MultipleWidget)
</code>```

but it raises a

You must ether specify "data_view" or "data_url".

答:
According to the Django-Select2 documentation you have to initiate (call) the widget with the attributes first.

As the error says - data_url or data_view has not been provided to the widget.

It will be up to you to generate that view or url specific to your use case. You could override the serve method of your page model to serve the data and provide the appropriate url pattern or simply create a different view altogether as documented here (see Heavy Components section).

For example:

```<code>FieldPanel(
    'authors',
    widget=HeavySelect2MultipleWidget(
        data_url='url/to/json/resonse'
    )
)
</code>```

HeavySelect2MultipleWidget extends HeavySelect2Widget - see docs for more detail:
http://django-select2.readthedocs.io/en/latest/django_select2.html#django_select2.forms.HeavySelect2Widget

I have not used this specific widget but have used Django-Select2 in Wagtail in a similar set up and it has worked well.

Body:
I need a complex selection widget because there are a lot of options in a multiple select widget. But I see HeavySelect2MultipleWidget needs views and urls to use it. I think there is not possible it in Wagtail by default.

This is the code:

class Resource(Page):
authors  = ParentalManyToManyField('Authors', blank=True)

content_panels = Page.content_panels + [
    FieldPanel('authors',  widget=forms.CheckboxSelectMultiple)
]

It would be nice to use

 FieldPanel('authors',  widget=HeavySelect2MultipleWidget)

but it raises a

You must ether specify "data_view" or "data_url".

Body:
According to the Django-Select2 documentation you have to initiate (call) the widget with the attributes first.

As the error says - data_url or data_view has not been provided to the widget.

It will be up to you to generate that view or url specific to your use case. You could override the serve method of your page model to serve the data and provide the appropriate url pattern or simply create a different view altogether as documented here (see Heavy Components section).

For example:

FieldPanel(
    'authors',
    widget=HeavySelect2MultipleWidget(
        data_url='url/to/json/resonse'
    )
)

HeavySelect2MultipleWidget extends HeavySelect2Widget - see docs for more detail:
http://django-select2.readthedocs.io/en/latest/django_select2.html#django_select2.forms.HeavySelect2Widget

I have not used this specific widget but have used Django-Select2 in Wagtail in a similar set up and it has worked well.


问:
Why {} is used in this statement for instantiation, Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Please explain why {} used in

```<code>Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
</code>```

This is from Gson documentation link to documentation

答:
It's creating a new anonymous type. This is a workaround for type erasure, because you can get the Collection<Integer> reflectively via Class.getGenericSuperclass() and Class.getGenericInterfaces() if the class is not generic (*).

This code basically implements the same functionality Ideone demo:

```<code>abstract class TypeToken<T> {
  Type getType() {
    ParameterizedType t = (ParameterizedType) getClass().getGenericSuperclass();
    return t.getActualTypeArguments()[0];
  }
}

public static void main (String[] args) {
    Collection<Integer> list = new ArrayList<>();
    System.out.println(list.getClass().getGenericInterfaces()[0]);

    TypeToken<Collection<Integer>> tt = new TypeToken<Collection<Integer>>() {};

    System.out.println(tt.getClass().getGenericSuperclass());
    System.out.println(tt.getType());
}
</code>```

Output:

```<code>java.util.List<E>
Ideone.Ideone$TypeToken<java.util.Collection<java.lang.Integer>>
java.util.Collection<java.lang.Integer>
</code>```

You can see that the "Integer"-ness of the Collection is lost; but it's still present in the TypeToken, so you can get it via the getType() method.

(*) An important point here is that you can't (correctly) create a TypeToken in a generic method. For example:

```<code><T> TypeToken<T> getGenericToken() {
  return new TypeToken<T>() {};
}
</code>```

won't work like you might expect Ideone demo.

```<code>TypeToken<Collection<String>> t = getGenericToken();
System.out.println(t.getType()); // T, not Collection<String>.
</code>```

Body:
Please explain why {} used in

Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();

This is from Gson documentation link to documentation

Body:
It's creating a new anonymous type. This is a workaround for type erasure, because you can get the Collection<Integer> reflectively via Class.getGenericSuperclass() and Class.getGenericInterfaces() if the class is not generic (*).

This code basically implements the same functionality Ideone demo:

abstract class TypeToken<T> {
  Type getType() {
    ParameterizedType t = (ParameterizedType) getClass().getGenericSuperclass();
    return t.getActualTypeArguments()[0];
  }
}

public static void main (String[] args) {
    Collection<Integer> list = new ArrayList<>();
    System.out.println(list.getClass().getGenericInterfaces()[0]);

    TypeToken<Collection<Integer>> tt = new TypeToken<Collection<Integer>>() {};

    System.out.println(tt.getClass().getGenericSuperclass());
    System.out.println(tt.getType());
}

Output:

java.util.List<E>
Ideone.Ideone$TypeToken<java.util.Collection<java.lang.Integer>>
java.util.Collection<java.lang.Integer>

You can see that the "Integer"-ness of the Collection is lost; but it's still present in the TypeToken, so you can get it via the getType() method.

(*) An important point here is that you can't (correctly) create a TypeToken in a generic method. For example:

<T> TypeToken<T> getGenericToken() {
  return new TypeToken<T>() {};
}

won't work like you might expect Ideone demo.

TypeToken<Collection<String>> t = getGenericToken();
System.out.println(t.getType()); // T, not Collection<String>.


问:
Finding screen elements in appium(iOS) using contains
I am doing QA and recently started using appium and cucumber to automate some tests and am still new to this.

I succeeded in what I wanted to automate using some functions like this one.

```<code>def function(element_name)
    find_element(:xpath,
                 '//XCUIElementTypeOther[@name="' + element_name + '"]'
                ).click
end
</code>```

This works for what I want, but now I am trying to redo the same functions but using contains. Something like this

```<code>def function(element_name)
  find_element(:xpath,
               '//*[contains(text(), element_name)]'
              ).click
end
</code>```

What I'm getting is

An element could not be located on the page using the given search parameters.

I think I am just not using contains the right way but I am really not sure.

答:
the way you are using contains is correct, the only problem is its not finding the element.
If XPATH is not working , why dont you try with relative path e.g. below</p>

```<code>def function(element_name)
  //tbody//td[contains(text(),element_name)]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am doing QA and recently started using appium and cucumber to automate some tests and am still new to this.

I succeeded in what I wanted to automate using some functions like this one.

def function(element_name)
    find_element(:xpath,
                 '//XCUIElementTypeOther[@name="' + element_name + '"]'
                ).click
end

This works for what I want, but now I am trying to redo the same functions but using contains. Something like this

def function(element_name)
  find_element(:xpath,
               '//*[contains(text(), element_name)]'
              ).click
end

What I'm getting is

An element could not be located on the page using the given search parameters.

I think I am just not using contains the right way but I am really not sure.

Body:
the way you are using contains is correct, the only problem is its not finding the element.
If XPATH is not working , why dont you try with relative path e.g. below

def function(element_name)
  //tbody//td[contains(text(),element_name)]


问:
Radio button text to top of the button programmatically
Is there any way to align the text of radio button to the top like below programmatically.

i used the below code for creating radio group

```<code>  final RadioButton[] rb = new RadioButton[5];
            RadioGroup rg = new RadioGroup(getActivity()); //create the RadioGroup
            rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL
            rg.setLayoutParams(radioparams);

            for (int i = 0; i < 5; i++) {
                rb[i] = new RadioButton(getActivity());
                rb[i].setText("Radiobtn " + i);
                rb[i].setId(i + 100);
                rg.addView(rb[i]);

            }
            layout.addView(rg);
</code>```

but i get the text to the right side of each button.

答:
Try this way you can do a trick

make your layout like this

```<code><LinearLayout
    android:id="@+id/lnrView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="80dp"
    android:orientation="horizontal">

</LinearLayout>
</code>```

than add programatically RadioButton like this

```<code>    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            LinearLayout layout = new LinearLayout(MainActivity.this);

            layout.setOrientation(LinearLayout.HORIZONTAL);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);

            LinearLayout layout2 = new LinearLayout(MainActivity.this);
            layout2.setOrientation(LinearLayout.VERTICAL);
            LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);

            final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            final TextView textView = new TextView(MainActivity.this);
            int id = 0;
            textView.setId(id);
            textView.setTextSize(14);
            textView.setTextColor(Color.rgb(0, 0, 0));
            textView.setMaxEms(2);
            textView.setText("NIlu");
            layout2.addView(textView);

            RadioButton radioButton = new RadioButton(MainActivity.this);
            layout2.addView(radioButton);
            layout.setLayoutParams(lp);

            lnrView.addView(layout2);

        }
    });
</code>```

Body:
Is there any way to align the text of radio button to the top like below programmatically.

i used the below code for creating radio group

  final RadioButton[] rb = new RadioButton[5];
            RadioGroup rg = new RadioGroup(getActivity()); //create the RadioGroup
            rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL
            rg.setLayoutParams(radioparams);

            for (int i = 0; i < 5; i++) {
                rb[i] = new RadioButton(getActivity());
                rb[i].setText("Radiobtn " + i);
                rb[i].setId(i + 100);
                rg.addView(rb[i]);

            }
            layout.addView(rg);

but i get the text to the right side of each button.

Body:
Try this way you can do a trick

make your layout like this

<LinearLayout
    android:id="@+id/lnrView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="80dp"
    android:orientation="horizontal">

</LinearLayout>

than add programatically RadioButton like this

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            LinearLayout layout = new LinearLayout(MainActivity.this);

            layout.setOrientation(LinearLayout.HORIZONTAL);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);

            LinearLayout layout2 = new LinearLayout(MainActivity.this);
            layout2.setOrientation(LinearLayout.VERTICAL);
            LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);

            final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            final TextView textView = new TextView(MainActivity.this);
            int id = 0;
            textView.setId(id);
            textView.setTextSize(14);
            textView.setTextColor(Color.rgb(0, 0, 0));
            textView.setMaxEms(2);
            textView.setText("NIlu");
            layout2.addView(textView);

            RadioButton radioButton = new RadioButton(MainActivity.this);
            layout2.addView(radioButton);
            layout.setLayoutParams(lp);

            lnrView.addView(layout2);

        }
    });


问:
validating login form in angular 2
I have successfully implemented Http post request with my rest micro service .

Implemented the login application with the post request.

But i am unable to set validation to my login form.If the entered credentials are not correct the form should display me a message "invalid username/password.

Below shown is my code

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeaderComponent } from "./header.component";
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';

import { GetService } from './home/get.service';
import { PostService } from './login/post.service';

import { routing } from "./app.routing";
import { RouterModule, Routes} from '@angular/router';

import { FormsModule ,ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

@NgModule({

  declarations: [AppComponent,HeaderComponent,LoginComponent,HomeComponent],

  imports: [RouterModule,BrowserModule, HttpModule , routing, FormsModule ,ReactiveFormsModule ],

  providers: [GetService,PostService],

  bootstrap: [AppComponent]

})

export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}
</code>```

app.component.html

```<code><div style="text-align:justify-all;">
  <h1>
    {{title}}
  </h1>

 <div class="container">
<router-outlet></router-outlet>
</div>
</code>```

app.routing.ts

```<code>import { Routes, RouterModule } from "@angular/router";
import { LoginComponent } from "./login/login.component";
import { HomeComponent } from "./home/home.component";

const APP_ROUTES: Routes = [
{ path: '' , redirectTo: '/homepage', pathMatch: 'full' },
{ path: 'homepage', component: LoginComponent },
{ path: 'homepage/home', component: HomeComponent }
];

export const routing = RouterModule.forRoot(APP_ROUTES);
</code>```

header.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
})
export class HeaderComponent {}
</code>```

header.component.html

```<code><div class="row">
<div class="col-xs-12"><ul class="nav nav-pills">
<li routerLinkActive="active"><a [routerLink]="['/homepage/home']">
<strong>Home</strong></a></li>
<li><a [routerLink]="['/homepage']"><strong>Logout</strong></a></li>
</ul></div>
</div>
</code>```

Here is my login component where i have implemented the post request

login.component.ts

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})

export class LoginComponent {
  data:any;

  constructor(private router:Router ,private MyService: PostService){ }

 checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password)
      .subscribe(users => {
           if(users)
              this.router.navigate(['homepage/home']);
           else
              this.router.navigate(['homepage']);
           }   );
                }}
</code>```

login.component.html

```<code><div class="container formWidth" style="text-align:center;">
  <h1> eSpace Login</h1><hr>
<br/>
     <h2>Login</h2>
    <form role="form">
      <div ng-control-group="credentials">
        <label for="username">Username</label>
        <input
          type="text"
          #username
          id="username"
          ng-control="username"
          required>
<br/>
        <label for="password">Password</label>
        <input
          type="password"
          #password
          id="password"
          ng-control="password"
          required>
      </div>
      <button type="button" (click)="checkByCredential(username.value,password.value)">Login</button>
    </form>
</div>
</code>```

post.service.ts

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PostService {
constructor(private http:Http) { }

 checkByCredential(username: string, password: string) {
 const user = { username: username, password: password };
 return this.http
    .post('http://localhost:8080/checkByCredential', user)
    .map(result => result.json());
  } }
</code>```

Here is my home component in which i implemented get request

home.component.ts

```<code>import { Component} from '@angular/core';
import { GetService } from './get.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent{
title :string;
data:any;

constructor(private MyService: GetService){
this.title="Angular Service";
}

onClickToLoadUsers(e: any): void {
this.loadUsers()
e.preventDefault()
}

loadUsers() {
this.MyService.GetUsers().subscribe(users => this.data = users);
}
}
</code>```

home.component.html

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}
</code>```0

get.service.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}
</code>```1

when i submit my form with the username and password which is not in my database,it should display me a message "invalid username and password".

can anybody please help in implementing a reactive form with my application.

答:
Kindly check the below code and compare with your code, where I am mentioned by ** symbol in the below code and do those changes in your code.

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})

export class LoginComponent {
  data:any;
 **IsLoggined:boolean = true;**

  constructor(private router:Router ,private MyService: PostService){**this.IsLoggined = true;** }

 checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password)
      .subscribe(users => {
           if(users)
              this.router.navigate(['homepage/home']);
           else
              **this.IsLoggined=false;
               return false;**
           }   );
                }}
</code>```

login.component.html

```<code>    <div class="container formWidth" style="text-align:center;">
      <h1> eSpace Login</h1><hr>
    <br/>
         <h2>Login</h2>
        <form role="form">
  **<div [hidden]='IsLoggined'  style="background-color:red;color:white"> invalid username and password </div>**
          <div ng-control-group="credentials">
            <label for="username">Username</label>
            <input
              type="text"
              #username
              id="username"
              ng-control="username"
              required>
    <br/>
            <label for="password">Password</label>
            <input
              type="password"
              #password
              id="password"
              ng-control="password"
              required>
          </div>
          <button type="button" (click)="checkByCredential(username.value,password.value)">Login</button>
        </form>
    </div>
</code>```

Title: validating login form in angular 2

Body:
I have successfully implemented Http post request with my rest micro service .

Implemented the login application with the post request.

But i am unable to set validation to my login form.If the entered credentials are not correct the form should display me a message "invalid username/password.

Below shown is my code

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeaderComponent } from "./header.component";
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';

import { GetService } from './home/get.service';
import { PostService } from './login/post.service';

import { routing } from "./app.routing";
import { RouterModule, Routes} from '@angular/router';

import { FormsModule ,ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

@NgModule({

  declarations: [AppComponent,HeaderComponent,LoginComponent,HomeComponent],

  imports: [RouterModule,BrowserModule, HttpModule , routing, FormsModule ,ReactiveFormsModule ],

  providers: [GetService,PostService],

  bootstrap: [AppComponent]

})

export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}

app.component.html

    {{title}}

<router-outlet></router-outlet>

app.routing.ts

import { Routes, RouterModule } from "@angular/router";
import { LoginComponent } from "./login/login.component";
import { HomeComponent } from "./home/home.component";

const APP_ROUTES: Routes = [
{ path: '' , redirectTo: '/homepage', pathMatch: 'full' },
{ path: 'homepage', component: LoginComponent },
{ path: 'homepage/home', component: HomeComponent }
];

export const routing = RouterModule.forRoot(APP_ROUTES);

header.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
})
export class HeaderComponent {}

header.component.html

Home

Logout

Here is my login component where i have implemented the post request

login.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})

export class LoginComponent {
  data:any;

  constructor(private router:Router ,private MyService: PostService){ }

 checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password)
      .subscribe(users => {
           if(users)
              this.router.navigate(['homepage/home']);
           else
              this.router.navigate(['homepage']);
           }   );
                }}

login.component.html

 eSpace Login

Login

    <form role="form">

        Username
        <input
          type="text"
          #username
          id="username"
          ng-control="username"
          required>

        Password
        <input
          type="password"
          #password
          id="password"
          ng-control="password"
          required>

      <button type="button" (click)="checkByCredential(username.value,password.value)">Login</button>
    </form>

post.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PostService {
constructor(private http:Http) { }

 checkByCredential(username: string, password: string) {
 const user = { username: username, password: password };
 return this.http
    .post('http://localhost:8080/checkByCredential', user)
    .map(result => result.json());
  } }

Here is my home component in which i implemented get request

home.component.ts

import { Component} from '@angular/core';
import { GetService } from './get.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent{
title :string;
data:any;

constructor(private MyService: GetService){
this.title="Angular Service";
}

onClickToLoadUsers(e: any): void {
this.loadUsers()
e.preventDefault()
}

loadUsers() {
this.MyService.GetUsers().subscribe(users => this.data = users);
}
}

home.component.html

    <app-header></app-header>

  Welcome to eSpace Home

Angular GET service

    <button (click)="onClickToLoadUsers($event)">Load user</button>

Username	  Password

             {{ item.username }}	  {{ item.password }}

get.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class GetService {
constructor(private http:Http) { }

GetUsers(){
  return this.http.get('http://localhost:8080/checkUsers')
    .map(result => result.json());
           }
 }

when i submit my form with the username and password which is not in my database,it should display me a message "invalid username and password".

can anybody please help in implementing a reactive form with my application.

Body:
Kindly check the below code and compare with your code, where I am mentioned by ** symbol in the below code and do those changes in your code.

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})

export class LoginComponent {
  data:any;
 **IsLoggined:boolean = true;**

  constructor(private router:Router ,private MyService: PostService){**this.IsLoggined = true;** }

 checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password)
      .subscribe(users => {
           if(users)
              this.router.navigate(['homepage/home']);
           else
              **this.IsLoggined=false;
               return false;**
           }   );
                }}

login.component.html

    <div class="container formWidth" style="text-align:center;">
      <h1> eSpace Login</h1><hr>
    <br/>
         <h2>Login</h2>
        <form role="form">
  **<div [hidden]='IsLoggined'  style="background-color:red;color:white"> invalid username and password </div>**
          <div ng-control-group="credentials">
            <label for="username">Username</label>
            <input
              type="text"
              #username
              id="username"
              ng-control="username"
              required>
    <br/>
            <label for="password">Password</label>
            <input
              type="password"
              #password
              id="password"
              ng-control="password"
              required>
          </div>
          <button type="button" (click)="checkByCredential(username.value,password.value)">Login</button>
        </form>
    </div>


问:
Disable Cell Highlighting in a datagridview
How to disable Cell Highlighting in a datagridview,
Highlighting should not happen even if I click on the cell.

Any thoughts please

答:
The ForeColor/BackColor kludge wasn't working for me, because I had cells of different colors.  So for anyone in the same spot, I found a solution more akin to actually disabling the ability.

Set the SelectionChanged event to call a method that runs ClearSelection

```<code>private void datagridview_SelectionChanged(object sender, EventArgs e)
{
    this.datagridview.ClearSelection();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The ForeColor/BackColor kludge wasn't working for me, because I had cells of different colors.  So for anyone in the same spot, I found a solution more akin to actually disabling the ability.

Set the SelectionChanged event to call a method that runs ClearSelection

private void datagridview_SelectionChanged(object sender, EventArgs e)
{
    this.datagridview.ClearSelection();
}


问:
how to insert multiple rows into sqlite android
I have a method to insert values into sqlite in a class. And in the main activity i am parsing json values and trying to insert the values into sqlite in a loop as i have got to insert more than one row. But only one row is getting added into database.

Method to add multiple rows is as below:

```<code>public void addSession(String sessionname,String start_time,String end_time,String id) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            db.beginTransaction();
            String sql = "Insert into session (id, sessionname,start_time, end_time) values(?,?,?,?)";
            SQLiteStatement insert = db.compileStatement(sql);
            insert.bindString(1, id);
            insert.bindString(2, sessionname);
            insert.bindString(3, start_time);
            insert.bindString(4, end_time);
            insert.execute();
            db.setTransactionSuccessful();
        } catch (Exception e) {
            Log.w("Appet8:",e );
        } finally {
         db.endTransaction();
        }
    }
</code>```

In the below for loop i am trying to add values into sqlite table:

```<code>JSONObject jsonObject = new JSONObject(response);
JSONArray foodsessions = jsonObject.getJSONArray("foodsessions");
for(int i=0;i<foodsessions.length();i++) {
                   JSONObject session_object = foodsessions.getJSONObject(i);
                   String session = session_object.getString("sessionname");
                   String start_time = session_object.getString("start_time");
                   String end_time = session_object.getString("end_time");
                   String session_id = session_object.getString("id");
 db.addSession(session,start_time,end_time,session_id);
                       }
</code>```

Body:
I have a method to insert values into sqlite in a class. And in the main activity i am parsing json values and trying to insert the values into sqlite in a loop as i have got to insert more than one row. But only one row is getting added into database.

Method to add multiple rows is as below:

public void addSession(String sessionname,String start_time,String end_time,String id) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            db.beginTransaction();
            String sql = "Insert into session (id, sessionname,start_time, end_time) values(?,?,?,?)";
            SQLiteStatement insert = db.compileStatement(sql);
            insert.bindString(1, id);
            insert.bindString(2, sessionname);
            insert.bindString(3, start_time);
            insert.bindString(4, end_time);
            insert.execute();
            db.setTransactionSuccessful();
        } catch (Exception e) {
            Log.w("Appet8:",e );
        } finally {
         db.endTransaction();
        }
    }

In the below for loop i am trying to add values into sqlite table:

JSONObject jsonObject = new JSONObject(response);
JSONArray foodsessions = jsonObject.getJSONArray("foodsessions");
for(int i=0;i<foodsessions.length();i++) {
                   JSONObject session_object = foodsessions.getJSONObject(i);
                   String session = session_object.getString("sessionname");
                   String start_time = session_object.getString("start_time");
                   String end_time = session_object.getString("end_time");
                   String session_id = session_object.getString("id");
 db.addSession(session,start_time,end_time,session_id);
                       }

Body:
this is simpler:

INSERT INTO tb_units (sort, name, isdef) VALUES
(1, "عدد",1),
(2, "کیلوگرم",1),
(3, "گرم",1),
(4, "کیلومتر",1),
(5, "متر",1),
(6, "متراژ",1),
(7, "مگابایت",1),
(8, "کیلوبایت",1),
(9, "مثقال",1),
(10, "شاخه",1),
(11, "صفحه",1),
(12, "رول",1),
(13, "بسته",1),
(14, "کارتن",1),
(15, "دستگاه",1),
(16, "پاکت",1),
(17, "مورد",1),
(18, "جعبه",1),
(19, "تن",1),
(20, "قطعه",1),
(21, "حلقه",1),
(22, "تخته",1),
(23, "جلد",1),
(24, "لیتر",1),
(25, "مترمکعب",1),
(26, "مترمربع",1),
(27, "دست",1),
(28, "جین",1),
(29, "اشتراک",1),
(30, "سری",1),
(31, "گیگابایت",1),
(32, "جلسه",1),
(33, "جفت",1),
(34, "قراض",1),
(35, "ساعت",1),
(36, "تن",1);

and us query with db.execSQL


问:
Help in jxls reader
HI

I am new to jxls. I read the articles regarding it, but seems not so good examples there. I am reading a xls file through java.
Please find the simple attached xls file for the same.

1)

```<code>public class Employee {

    private String rollno;
    private String name;
    private String percentage;
</code>```

2)

```<code><worksheet name="Sheet1">
  <section endRow="1" startRow="0"/>
  <loop endRow="4" items="employee" startRow="3" var="emp" varType="com.Employee">
    <section endRow="4" startRow="3">
      <mapping col="0" row="3">emp.rollno</mapping>
      <mapping col="1" row="3">emp.name</mapping>
      <mapping col="2" row="3">emp.percentage</mapping>
    </section>
  </loop>
</worksheet>
</code>```

3)

```<code>public class Client {
    public static void main(String[] args) throws IOException, SAXException {
          InputStream inputXML = new BufferedInputStream(new FileInputStream("C:\\NewFile1.xml"));
          XLSReader mainReader = ReaderBuilder.buildFromXML( inputXML );
          InputStream inputXLS = new BufferedInputStream(new FileInputStream("c:\\Book1.xls"));

         Employee employee = new Employee();

         System.out.println("Is Null inputXML:"+inputXML==null);
         System.out.println("Is Null inputXLS:"+inputXLS==null);

         Map beans = new HashMap();
         beans.put("employee", employee);
         XLSReadStatus readStatus = mainReader.read( inputXLS, beans);
         readStatus.toString();
    }
}
</code>```

I am getting a exception as

```<code>Feb 21, 2011 3:59:17 PM net.sf.jxls.reader.XLSReaderImpl readSheet
INFO: Processing sheet Sheet1
Exception in thread "main" java.lang.NullPointerException
    at net.sf.jxls.reader.XLSForEachBlockReaderImpl.read(XLSForEachBlockReaderImpl.java:45)
    at net.sf.jxls.reader.XLSSheetReaderImpl.read(XLSSheetReaderImpl.java:25)
    at net.sf.jxls.reader.XLSReaderImpl.readSheet(XLSReaderImpl.java:45)
    at net.sf.jxls.reader.XLSReaderImpl.read(XLSReaderImpl.java:31)
    at com.GetTheData.main(GetTheData.java:41)
</code>```

Please help in solving this prob.

Thank you

答:
Client.java this line : beans.put("employee", employee);
change to :
 beans.put("employee", new ArrayList() );

works for me.

Title: Help in jxls reader

Body:
HI

I am new to jxls. I read the articles regarding it, but seems not so good examples there. I am reading a xls file through java.
Please find the simple attached xls file for the same.

1)

public class Employee {

    private String rollno;
    private String name;
    private String percentage;

2)

<worksheet name="Sheet1">

  <loop endRow="4" items="employee" startRow="3" var="emp" varType="com.Employee">

      <mapping col="0" row="3">emp.rollno</mapping>
      <mapping col="1" row="3">emp.name</mapping>
      <mapping col="2" row="3">emp.percentage</mapping>

  </loop>
</worksheet>

3)

public class Client {
    public static void main(String[] args) throws IOException, SAXException {
          InputStream inputXML = new BufferedInputStream(new FileInputStream("C:\\NewFile1.xml"));
          XLSReader mainReader = ReaderBuilder.buildFromXML( inputXML );
          InputStream inputXLS = new BufferedInputStream(new FileInputStream("c:\\Book1.xls"));

         Employee employee = new Employee();

         System.out.println("Is Null inputXML:"+inputXML==null);
         System.out.println("Is Null inputXLS:"+inputXLS==null);

         Map beans = new HashMap();
         beans.put("employee", employee);
         XLSReadStatus readStatus = mainReader.read( inputXLS, beans);
         readStatus.toString();
    }
}

I am getting a exception as

Feb 21, 2011 3:59:17 PM net.sf.jxls.reader.XLSReaderImpl readSheet
INFO: Processing sheet Sheet1
Exception in thread "main" java.lang.NullPointerException
    at net.sf.jxls.reader.XLSForEachBlockReaderImpl.read(XLSForEachBlockReaderImpl.java:45)
    at net.sf.jxls.reader.XLSSheetReaderImpl.read(XLSSheetReaderImpl.java:25)
    at net.sf.jxls.reader.XLSReaderImpl.readSheet(XLSReaderImpl.java:45)
    at net.sf.jxls.reader.XLSReaderImpl.read(XLSReaderImpl.java:31)
    at com.GetTheData.main(GetTheData.java:41)

Please help in solving this prob.

Thank you


问:
How can I do a self-join in Laravel?
Here is my code:

```<code>$role_id = Auth::user()->role_id;

$related = Page::where('path', $request->path())->where('method', $_SERVER["REQUEST_METHOD"])->first()->related;
$pages   = Page::where('related', $related)->get();

foreach ($pages as $page){
    $accessGiven = page_role::where('role_id', $role_id)->where('page_id', $page->id)->first();
    if ( sizeof($accessGiven) > 0 ) {
        return $next($request);
    }
}

return redirect('/');
</code>```

It works well logically, but it is a little slow for huge dataset. You know, it's actually a middleware and will be executed before most of requests.

Anyway, I guess I can combine line 2 and line 3 and make one query of them. Any idea how can I do that?

答:
Look in this example (I didn't test it):</p>

```<code>$requestPath = $request->path();
$serverMethod = $_SERVER["REQUEST_METHOD"];
$pages = Page::where('related', function($query) use($requestPath,$serverMethod) {
    $query->where('path', $requestPath )->where('method',
    $serverMethod)->first()->related; }
)->get()
</code>```

Title: How can I do a self-join in Laravel?

Body:
Here is my code:

$role_id = Auth::user()->role_id;

$related = Page::where('path', $request->path())->where('method', $_SERVER["REQUEST_METHOD"])->first()->related;
$pages   = Page::where('related', $related)->get();

foreach ($pages as $page){
    $accessGiven = page_role::where('role_id', $role_id)->where('page_id', $page->id)->first();
    if ( sizeof($accessGiven) > 0 ) {
        return $next($request);
    }
}

return redirect('/');

It works well logically, but it is a little slow for huge dataset. You know, it's actually a middleware and will be executed before most of requests.

Anyway, I guess I can combine line 2 and line 3 and make one query of them. Any idea how can I do that?

Body:
Look in this example (I didn't test it):

$requestPath = $request->path();
$serverMethod = $_SERVER["REQUEST_METHOD"];
$pages = Page::where('related', function($query) use($requestPath,$serverMethod) {
    $query->where('path', $requestPath )->where('method',
    $serverMethod)->first()->related; }
)->get()


问:
How do I add python3 kernel to jupyter (IPython)
My Jupyter notebooks installed with python 2 kernel. I do not understand why. I might have messed something up when I did the install. I already have python 3  installed. How can I add it to Jupyter?
Here's a screenshot of what the default Jupyter insalled with python3 -m install jupyter and opened in the browser with jupyter notebooklooks like:

答:
When you use conda managing your python envs, follow these two steps:

activate py3 (on Windows or source activate py3 on Linux)

conda install notebook ipykernel or just use conda install jupyter


问:
Java: Get last element after split
I am using the String split method and I want to have the last element.
The size of the Array can change.

Example:

```<code>String one = "Düsseldorf - Zentrum - Günnewig Uebachs"
String two = "Düsseldorf - Madison"
</code>```

I want to split the above Strings and get the last item:

```<code>lastone = one.split("-")[here the last item] // <- how?
lasttwo = two.split("-")[here the last item] // <- how?
</code>```

I don't know the sizes of the arrays at runtime :(

答:
I guess you want to do this in i line. It is possible (a bit of juggling though  =^)

```<code>new StringBuilder(new StringBuilder("Düsseldorf - Zentrum - Günnewig Uebachs").reverse().toString().split(" - ")[0]).reverse()
</code>```

tadaa, one line -> the result you want (if you split on " - " (space minus space) instead of only "-" (minus) you will loose the annoying space before the partition too =^) so "Günnewig Uebachs" instead of " Günnewig Uebachs" (with a space as first character)

Nice extra -> no need for extra JAR files in the lib folder so you can keep your application light weight.

Title: Java: Get last element after split

Body:
I am using the String split method and I want to have the last element.
The size of the Array can change.

Example:

String one = "Düsseldorf - Zentrum - Günnewig Uebachs"
String two = "Düsseldorf - Madison"

I want to split the above Strings and get the last item:

lastone = one.split("-")[here the last item] // <- how?
lasttwo = two.split("-")[here the last item] // <- how?

I don't know the sizes of the arrays at runtime :(

Body:
I guess you want to do this in i line. It is possible (a bit of juggling though  =^)

new StringBuilder(new StringBuilder("Düsseldorf - Zentrum - Günnewig Uebachs").reverse().toString().split(" - ")[0]).reverse()

tadaa, one line -> the result you want (if you split on " - " (space minus space) instead of only "-" (minus) you will loose the annoying space before the partition too =^) so "Günnewig Uebachs" instead of " Günnewig Uebachs" (with a space as first character)

Nice extra -> no need for extra JAR files in the lib folder so you can keep your application light weight.


问:
Replacing string values in cell array with numbers
I have a cell array which contains some descriptions, namely my_des.

```<code> my_des = [{'FRD'} {'1'}; {'UNFRD'} {'2'}; {'OTH'} {'3'};];
</code>```

I also have an approximately 5000x1 cell array. The elements in this array are either 'FRD', 'UNFRD' or 'OTH'.

What I want to do is replace these text values with the corresponding numeric values in my_des.

Currently my only idea (which I think isn't that great) is to loop through my_des and do a string replacement.

Example:

So say my current vector looks like this:

```<code>FRD
FRD
OTH
UNFRD
OTH
FRD
</code>```

Then my desired output would be this:

```<code>1
1
3
2
3
1
</code>```

The numbers come from the my_des array

答:
Do you want to use the characters '1', '2', '3' or just the numbers 1, 2, 3? The distinction is the difference between a 1 line answer and a 2 line answer!

Based on your example, let's use the following data:

```<code>arr = {'FRD'; 'FRD'; 'OTH'; 'UNFRD'; 'OTH'; 'FRD'};
</code>```

Get the row index within my_des of each element in arr, and use that to get the corresponding 2nd column values...

```<code>% If you just want the *number* then this is all you need
[~, idx] = ismember(arr, my_des);
% idx is the row within column 1 of my_des where the value in arr is found
% >> idx = [1; 1; 3; 2; 3; 1]

% If you want to get the values my_des then use idx as a row index
out = mydes(idx, 2);
% out is the corresponding values from the 2nd column of my_des, whatever they may be.
% >> out = {'1'; '1'; '3'; '2'; '3'; '1'};
</code>```

Aside: why are you declaring a cell array by concatenating 1-element cell arrays for my_des? Instead, you can just do this:

```<code>my_des = {'FRD',   '1';
          'UNFRD', '2';
          'OTH',   '3'};
</code>```

Body:
I have a cell array which contains some descriptions, namely my_des.

 my_des = [{'FRD'} {'1'}; {'UNFRD'} {'2'}; {'OTH'} {'3'};];

I also have an approximately 5000x1 cell array. The elements in this array are either 'FRD', 'UNFRD' or 'OTH'.

What I want to do is replace these text values with the corresponding numeric values in my_des.

Currently my only idea (which I think isn't that great) is to loop through my_des and do a string replacement.

Example:

So say my current vector looks like this:

FRD
FRD
OTH
UNFRD
OTH
FRD

Then my desired output would be this:

1
1
3
2
3
1

The numbers come from the my_des array

Body:
Do you want to use the characters '1', '2', '3' or just the numbers 1, 2, 3? The distinction is the difference between a 1 line answer and a 2 line answer!

Based on your example, let's use the following data:

arr = {'FRD'; 'FRD'; 'OTH'; 'UNFRD'; 'OTH'; 'FRD'};

Get the row index within my_des of each element in arr, and use that to get the corresponding 2nd column values...

% If you just want the *number* then this is all you need
[~, idx] = ismember(arr, my_des);
% idx is the row within column 1 of my_des where the value in arr is found
% >> idx = [1; 1; 3; 2; 3; 1]

% If you want to get the values my_des then use idx as a row index
out = mydes(idx, 2);
% out is the corresponding values from the 2nd column of my_des, whatever they may be.
% >> out = {'1'; '1'; '3'; '2'; '3'; '1'};

Aside: why are you declaring a cell array by concatenating 1-element cell arrays for my_des? Instead, you can just do this:

my_des = {'FRD',   '1';
          'UNFRD', '2';
          'OTH',   '3'};


问:
Quick successful exit from C++ with lots of objects allocated
I'm looking for a way to quickly exit a C++ that has allocated a lot of structures in memory using C++ classes.  The program finishes correctly, but after the final "return" in the program, all of the auto-destructors kick in.  The problem is the program has allocated about 15GB of memory through lots of C++ class structures, and this auto-destruct process takes about 1 more hour itself to complete as it walks through all of the structures - even though I don't care about the results.  The program only took 1 hour to complete the task up to this point.  I would like to just return to the OS and let it do its normal wholesale process allocation deletion - which is very quick.  I've been doing this by manually killing the process during the cleanup stage - but am looking for a better programic solution.

I would like to return a success to the OS, but don't care to keep any of the memory content.  The program does perform a lot of dynamic allocation/deallocation during the normal processing, so it's not just simple heap management.

Any opinions?

答: As Naveen says, this can't be a matter of memory deallocation. I've written neural network simulations with evolutionary algorithms that where allocating and freed lots of memory in small and large chunks and this was never a major issue.</p>


问:
Query Check Status from other table
I have following query

```<code>select * from user_profile
</code>```

Now i want to add where condition check user status from other table (users)

```<code>select * from user_profile,users where users.status!=0
</code>```

Please Do Not Recommend Join  i following old join query

Thanks

答:
If you want every column from both tables in your query, you can use:

```<code>SELECT * from user_profile, users WHERE user_profile.user_id = users.id AND users.status! = 0
</code>```

Where I assumed you have some column(like user_id - user_profile
and id - users in my example) that links both tables together.

Title: Query Check Status from other table

Body:
I have following query

select * from user_profile

Now i want to add where condition check user status from other table (users)

select * from user_profile,users where users.status!=0

Please Do Not Recommend Join  i following old join query

Thanks

Body:
If you want every column from both tables in your query, you can use:

SELECT * from user_profile, users WHERE user_profile.user_id = users.id AND users.status! = 0

Where I assumed you have some column(like user_id - user_profile
and id - users in my example) that links both tables together.


问:
Update multiple columns based on a single condition in kdb
I have a table -

```<code>q)t
a b  c
--------
1 10 100
3 20 200
2 30 300
1 40 400
2 50 500
</code>```

I wish to update column b and c values based on a single 'if' condition on column a. For example -

```<code>t:update b:0 from t where a=1
t:update c:0 from t where a=1
</code>```

I could use vector conditional but don't want to as it would evaluate the condition twice for each row and my table has large number of rows.

```<code>update b:?[a=1;0;b], c:?[a=1;0;c] from t
</code>```

Is there any way I can do it in so that 'a=1' condition is evaluated only once for each row?

Edit : I earlier missed mentioning that I want 'b' and 'c' to take some other values in 'else' condition and not just retain their original values -

```<code>update b:?[a=1;0;-1], c:?[a=1;0;-1] from t
</code>```

答:
```<code>update b:0, c:0 from t where a=1
</code>```

Body:
I have a table -

q)t
a b  c
--------
1 10 100
3 20 200
2 30 300
1 40 400
2 50 500

I wish to update column b and c values based on a single 'if' condition on column a. For example -

t:update b:0 from t where a=1
t:update c:0 from t where a=1

I could use vector conditional but don't want to as it would evaluate the condition twice for each row and my table has large number of rows.

update b:?[a=1;0;b], c:?[a=1;0;c] from t

Is there any way I can do it in so that 'a=1' condition is evaluated only once for each row?

Edit : I earlier missed mentioning that I want 'b' and 'c' to take some other values in 'else' condition and not just retain their original values -

update b:?[a=1;0;-1], c:?[a=1;0;-1] from t

Body: update b:0, c:0 from t where a=1


问:
Bootstrap, I created a dropdown menu, how can I highlight choices on hover?
I created a dropdown menu that opens when you click on a text box, and then when you chose a string for that dropdown list, it puts it in the text box.

I would like to make that when you hover your mouse on the strings in the dropdown, they get slightly highlighted!  how can I achieve this?

```<code><div class="row">
    <div class="col-xs-12 max300" uib-dropdown is-open="vm.descriptionDropdownOpen">
         <textarea name="remarks" class="form-control" ng-model="vm.presence.description" ng-click="vm.toggleDescriptionDropdown()" autofocus></textarea>
         <ul id="descriptionDropdown" uib-dropdown-menu>
             <li ng-repeat="descr in vm.loadedDescriptions" ng-click="vm.presence.description = descr.text; vm.descriptionDropdownOpen = false;">
                 {{descr.text}}
             </li>
         </ul>
</code>```

and the css to keep the dropdown aligned with the textbox:

```<code>#descriptionDropdown {
    width: 100%;
    line-height: 150%;
    padding-left: 8px;
    position: relative;
}
</code>```

thank you very much

答:
You could add this css :</p>

```<code>li:hover {
  background-color: blue;
}
</code>```

Body:
I created a dropdown menu that opens when you click on a text box, and then when you chose a string for that dropdown list, it puts it in the text box.

I would like to make that when you hover your mouse on the strings in the dropdown, they get slightly highlighted!  how can I achieve this?

         <textarea name="remarks" class="form-control" ng-model="vm.presence.description" ng-click="vm.toggleDescriptionDropdown()" autofocus></textarea>

                 {{descr.text}}

and the css to keep the dropdown aligned with the textbox:

#descriptionDropdown {
    width: 100%;
    line-height: 150%;
    padding-left: 8px;
    position: relative;
}

thank you very much

Body:
You could add this css :

li:hover {
  background-color: blue;
}