i have the below code to read emails and check if the subject is matching with the expected message
Message[] messages = folder.getMessages();
String message="Thanks for contacting";
if(folder.getUnreadMessageCount()!=0)
{
for (Message mail : messages)
{
if(!mail.isSet(Flags.Flag.SEEN) && mail.getSubject().contains("Thanks"))//if mail is unread and the message matches
{
mail.setFlag(Flags.Flag.SEEN, true);
softAssert.assertTrue(true,"Email received ->");
Reporter.log("Email received ->" + mail.getSubject(), true);
break;
}
if(!mail.isSet(Flags.Flag.SEEN) && !mail.getSubject().contains("Thanks"))//if mail is unread and the message does not match
{
System.out.println(mail.getSubject() + "-> is not the email we are looking for");
}
}
}
else
{
softAssert.assertTrue(false,"Email not received");
Reporter.log("Email not received ->" + message, true);
}
The problem is I want to fail this test if both the conditions inside the for loop fail. if i put the else inside the for loop it prints not received for reach element in the loop. how do i go about this?
You can use boolean expression. See the below simple example,
boolean test = true;
boolean test2 = true;
for (int i = 0; i < 3; i++) {
if (!test) {
System.out.println("Test value is false.");
} else {
test = false;
}
if (!test2) {
System.out.println("Test2 value is false.");
} else {
test2 = false;
}
if(!test && !test2) {
System.out.println("Breaking loop.");
break;
}
}
Create two boolean variables and set their values as true incase if your if condition fails inside the loop then by using else block change the boolean value to false and do the same for your second if condition as well. In the last if condition if both statements fails then break the loop.
Related
I want to know how to write code which receives specific string.for example, this one OK , in this I only need "OK" string.
Another string is also like OK
I have written code in keil c51 for at89s52 microcontroller which works but I need more reliable code.
I'm using interrupt for rx data from rs232 serial.
void _esp8266_getch() interrupt 4 //UART Rx.{
if(TI){
TI=0;
xmit_bit=0;
return ;
}
else
{
count=0;
do
{
while(RI==0);
rx_buff=SBUF;
if(rx_buff==rx_data1) //rx_data1 = 0X0D /CR
{
RI=0;
while(RI==0);
rx_buff=SBUF;
if(rx_buff==rx_data2) // rx_data2 = 0x0A /LF
{
RI=0;
data_in_buffer=1;
if(loop_conti==1)
{
if(rec_bit_flag==1)
{
data_in_buffer=0;
loop_conti=0;
}
}
}
}
else
{
if(data_in_buffer==1)
{
received[count]=rx_buff; //my buffer in which storing string
rec_bit_flag=1;
count++;
loop_conti=1;
RI=0;
}
else
{
loop_conti=0;
rec_bit_flag=0;
RI=0;
}
}
}
while(loop_conti==1);
}
rx_buff=0;
}
This is one is just for reference, you need develop the logic further to your needs. Moreover, design is depends on what value is received, is there any specific pattern and many more parameter. And this is not a tested code, I tried to give my idea on design, with this disclaimer here is the sample..
//Assuming you get - "OK<CR><LF>" in which <CR><LF> indicates the end of string steam
int nCount =0;
int received[2][BUF_SIZE]; //used only 2 buffers, you can use more than 2, depending on how speed
//you receive and how fast you process it
int pingpong =0;
bool bRecFlag = FALSE;
int nNofbytes = 0;
void _esp8266_getch() interrupt 4 //UART Rx.
{
if(TI){
TI=0;
xmit_bit=0;
return ;
}
if(RI) // Rx interrupt
{
received[pingpong][nCount]=SBUF;
RI =0;
if(nCount > 0)
{
// check if you receive end of stream value
if(received[pingpong][nCount-1] == 0x0D) && (received[pingpong][nCount] == 0x0A))
{
bRecFlag = TRUE;
pingpong = (pingpong == 0);
nNofbytes = nCount;
nCount = 0;
return;
}
}
nCount++;
}
return;
}
int main()
{
// other stuff
while(1)
{
// other stuff
if(bRecFlag) //String is completely received
{
buftouse = pingpong ? 0 : 1; // when pingpong is 1, buff 0 will have last complete string
// when pingpong is 0, buff 1 will have last complete string
// copy to other buffer or do action on received[buftouse][]
bRecFlag = false;
}
// other stuff
}
}
I created a code in while loop in Orange HRM.
I am taking data for UID & Pwd from a text file.
But while Executing that it executes 1st line also, which is not necessary.
I want to skip the first line (UID, PWD) and proceed further.
I want the Solution with While as well as with For Loop.
I think It's simple but i am unable to do it immediately.
Please find my code written with while loop.
BufferedReader br = new BufferedReader(new FileReader("E:/WorkSpace/Test/InputData/uid.txt"));
String sCurrentLine;
while ((sCurrentLine = br.readLine())!= null)
{
String str[] = sCurrentLine.split(" ");
driver.findElement(By.id("txtUsername")).sendKeys(str[0]);
driver.findElement(By.id("txtPassword")).sendKeys(str[1]);
driver.findElement(By.id("btnLogin")).click();
Thread.sleep(3000);
if (driver.findElement(By.tagName("a")).getAttribute("id").contains("welcome"))
{
System.out.println("Login is Successful");
temp = true;
break;
}
else
{
System.out.println("Login Failed");
temp = false;
driver.navigate().to("http://opensource.demo.orangehrm.com/");
}
if (temp) {
break;
}
}
If you want to skip the first line, read it before the loop:
br.readLine()
while ((sCurrentLine = br.readLine())!= null)
{
...
Couldn't you just move the code you want executed only once, outside of the loop? Put it right before the loop, and it'll be executed, then go immediately into the loop.
Or you could have something like:
for(int i=0; i<length; i++) {
if (i == 0) {
//code you want executed
}
}
How can I modify UDPBasicApp to find duplicates in the messages recieved?
I made these changes to the class UDPBasicApp.cc to add an extra step to check recieved udp data packets like below, but I see no effect in .sca/.vec and does not even show bubbles.
Where could the error be?
void UDPBasicApp::handleMessageWhenUp(cMessage *msg)
{
if (msg->isSelfMessage()) {
ASSERT(msg == selfMsg);
switch (selfMsg->getKind()) {
case START:
processStart();
break;
case SEND:
processSend();
break;
case STOP:
processStop();
break;
default:
throw cRuntimeError("Invalid kind %d in self message", (int)selfMsg->getKind());
}
}
else if (msg->getKind() == UDP_I_DATA) {
// process incoming packet
//-----------------------------------------------------Added step
//std::string currentMsg= "" + msg->getTreeId();
std::string currentPacket= PK(msg)->getName();
if( BF->CheckBloom(currentPacket) == 1) {
numReplayed++;
getParentModule()->bubble("Replayed!!");
EV<<"----------------------WSNode "<<getParentModule()->getIndex() <<": REPLAYED! Dropping Packet\n";
delete msg;
return;
}
else
{
BF->AddToBloom(currentPacket);
numLegit++;
getParentModule()->bubble("Legit.");
EV<<"----------------------WSNode "<<getParentModule()->getIndex() <<":OK. Pass.\n";
}
//-----------------------------------------------------------------------------
processPacket(PK(msg));
}
else if (msg->getKind() == UDP_I_ERROR) {
EV_WARN << "Ignoring UDP error report\n";
delete msg;
}
else {
throw cRuntimeError("Unrecognized message (%s)%s", msg->getClassName(), msg->getName());
}
if (hasGUI()) {
char buf[40];
sprintf(buf, "rcvd: %d pks\nsent: %d pks", numReceived, numSent);
getDisplayString().setTagArg("t", 0, buf);
}
}
Since I don't have enough context about the entities participating in your overall system, I will provide the following idea:
You can add a unique ID to each message of your application by adding the following line to your applications *.msg:
int messageID = simulation.getUniqueNumber();
Now on the receiver side you can have an std::map<int, int> myMap where you store the <id,number-of-occurences>
Each time you receive a message you add the message to the std::map and increment the number-of-occurences
if(this->myMap.count(myMessage->getUniqueID) == 0) /* check whether this ID exists in the map */
{
this->myMap.insert(std::make_pair(myMessage->getUniqueID(), 1)); /* add this id to the map and set the counter to 1 */
}
else
{
this->myMap.at(myMessage->getUniqueID())++; /* add this id to the map and increment the counter */
}
This will allow you to track whether the same message has been forwarded twice, simply by doing:
if(this->myMap.at(myMessage->getUniqueID()) != 1 ) /* the counter is not 1, message has been "seen" more than once */
The tricky thing for you is how do you define whether a message has been seen twice (or more).
I'm trying to find the shortest path of finding friends. If person X wants to connect to person Y, I want to print out the shortest path of friends in order for X to get to Y. Everytime I run the code, I get null as a result.
public void shortest(String first, String target){
HashMap<String, String> prev = new HashMap<String, String>();
Queue<PersonNode> q = new LinkedList<PersonNode>();
PersonNode firstPerson = hash.get(first);
firstPerson.visited = true;
prev.put(first, first + " ");
q.add(firstPerson);
while(!q.isEmpty()){
PersonNode curr = q.remove();
if(!curr.visited){
curr.visited = true;
if(curr.equals(target)){
break;
}
else{
for(int i =0; i < curr.list.size(); i++){
if(curr.list.get(i).visited = false){
q.add(curr.list.get(i));
curr.list.get(i).visited = true;
prev.put(curr.list.get(i).name, prev.get(curr.list.get(i).name) + curr.list.get(i));
}
}
}
if(!curr.equals(target)){
System.out.println("They have no connections");
}
}
}
System.out.println(prev.get(target));
}
Try debugging your code. I see you set firstperson.visited to true outside of the loop. You then pop it from you queue and ignore it because it's true. It's the same inside your loop: you set all visited attributes to true which will cause them to be ignored when they get popped from the queue at runtime
I'm also thinking that the "they have no connections"-part should not be inside the while loop
I'm trying to figure out how to write a custom FindElement routine in Selenium 2.0 WebDriver. The idea would be something like this:
driver.FindElement(By.Method( (ISearchContext) => {
/* examine search context logic here... */ }));
The anonymous method would examine the ISearchContext and return True if it matches; False otherwise.
I'm digging through the Selenium code, and getting a bit lost. It looks like the actual By.* logic is carried out server-side, not client side. That seems to be complicating matters.
Any suggestions?
I do a multi-staged search. I have a method that performs a try catch and then a method that gets the element. In theory you could do a try catch until instead of this way but I like this way better because of my setup.
public bool CheckUntil(IWebDriver driver, string selectorType, string selectorInfo)
{
int Timer = 160;
bool itemFound = false;
for (int i = 0; i < Timer; i++)
if(itemFound)
{
i = 0
}
else
{
Thread.Sleep(500);
if(selectorType.ToLower() == "id" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.Id(selectorInfo).Displayed)
{
itemFound = true;
}
}
else if(selectorType.ToLower() == "tagname" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.TagName(selectorInfo).Displayed)
{
itemFound = true;
}
}
}
return itemFound;
}
Here's my try catch method you can add as many different types as you want id, cssselector, xpath, tagname, classname, etc.
public bool TryCatch(IWebDriver driver, string selectorType, string selectorInfo)
{
bool ElementFound = false;
try
{
switch(selectorType)
{
case "id":
driver.FindElement(By.Id(selectorInfo);
break;
case "tagname":
driver.FindElement(By.TagName(selectorInfo);
break;
}
ElementFound = truel
}
catch
{
ElementFound = false;
}
return ElementFound;
}
Ok, I figured out how to do this. I'm leveraging driver.ExecuteScript() to run custom js on the webdriver. It looks a bit like this:
function elementFound(elem) {
var nodeType = navigator.appName == ""Microsoft Internet
Explorer"" ? document.ELEMENT_NODE : Node.ELEMENT_NODE;
if(elem.nodeType == nodeType)
{
/* Element identification logic here */
}
else { return false; }
}
function traverseElement(elem) {
if (elementFound(elem) == true) {
return elem;
}
else {
for (var i = 0; i < elem.childNodes.length; i++) {
var ret = traverseElement(elem.childNodes[i]);
if(ret != null) { return ret; }
}
}
}
return traverseElement(document);