vendredi 30 septembre 2016

Javascript score target alert

New to JS, please be nice.

In creating a Javascript score for a browser canvas game, the code below increases by 1 for each second. For the variable score to equal 100, how would I go about this function displaying a window alert for when it reaches this value?

Attempts similar to if(score == 100), alert(score) have not worked for me.

Below code will not currently work in JSFiddle, output displays in browser tab.

var start = new Date().getTime(),
    score = '0.1';

window.setInterval(function() {
    var time = new Date().getTime() - start;
    score = Math.floor(time / 1000) ;
    if(Math.round(score) == score) 
        { score += '.0 Score'; }
    document.title = score;
}, 100);

Why my if statement ignoring string condition in java? [duplicate]

This question already has an answer here:

I'm simply sending lines using socket, and trying to stop printing messages when the line is "terminate". But, instead, when text = "terminate" it simply prints it and does not break!! Thanks in advance :)

Here is the condition code:

    String text = null;
      while (true) {

                    //Reading data received from the socket
                    text = input.readLine();
                    if (text == null || text == "terminate") {
                        break;
                    }

Average column by specific datetime associated values

I have one column with the time in format "dd/mm/yyyy hh:mm" and another with the temperature for that time point. I am looking to calculate the average temperature of the day and night of each month separately. I.e. average all temperatures between 06:00 and 18:00 in May and all temperature between 18:00 and 06:00 in May and then the same for March and so on.

    Time    Celsius(C)
06/05/2016 10:49    28
06/05/2016 11:49    29
06/05/2016 12:49    31
06/05/2016 13:49    27.5
06/05/2016 14:49    24
06/05/2016 15:49    25
06/05/2016 16:49    24.5
06/05/2016 17:49    23.5
06/05/2016 18:49    23
06/05/2016 19:49    22.5
06/05/2016 20:49    22.5

I am currently using the following formula:

=AVERAGEIFS(C2:C3643,B2:B3643,">=01/05/2016",B2:B3643,"<=31/05/2016",B2:B3643,">=01/05/2016 06:00",B2:B3643,"<=31/05/2016 18:00")

To try and calculate an average if the date is within May and during the day - however it doesn't appear to be working and when I change the hour periods it still spits out the same number (which is the average for the month).

Expression must have a class type(working with linked lists)

Have problems with this snippet of code. I keep getting error "expression must have a class type" on the third line.

if (users.find("I")!=string::npos)
        {
            int spot = atoi((users[3]).c_str());
            string pot = string(users.substr(2));
            stringstream spot(pot);
            string data;
            cin>>data;
            list.insertAfter(list.getNode(spot),data);
        }

how to check if the char in a string is the same as the previous char?

The problem asks to compare if the string has consecutive same letters and rewrite it as the number of the letter plus the letter, for example, AAAAA as in 5A. But when I use the if statement to make the comparison the output become some very long number instead of the desired result.

Here is a portion of the problem: Run-length encoding is a simple compression scheme best used when a dataset consists primarily of numerous, long runs of repeated characters. For example, AAAAAAAAAA is a run of 10 A’s. We could encode this run using a notation like *A10, where the * is a special flag character that indicates a run, A is the symbol in the run, and 10 is the length of the run.

Here is the code:

import java.util.Scanner;

public class RunLengthEncoding {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter input string: ");
    String s = input.nextLine();
    for (int a = 0; a < s.length(); a++) {
        if ((s.charAt(a) < 'A' || s.charAt(a) > 'Z')) {
            System.out.print("Bad input");
            System.exit(0);
        }
    }
    System.out.print("Enter flag character: ");
    char flag = input.nextLine().charAt(0);
    if (flag == '#' || flag == '$' || flag == '*' || flag == '&') {

        int count = 0;
        for (int i = 1; i < s.length(); i++) {
            if(s.charAt(i)=s.charAt(i-1));
            count++;

            if (count == 1)
                System.out.print(s.charAt(i));
            if (count == 2)
                System.out.print(s.charAt(i) + s.charAt(i));
            if (count == 3)
                System.out.print(s.charAt(i) + s.charAt(i) + s.charAt(i));
            else
                System.out.print(flag + s.charAt(i) + (count + 1));

        }

    } else
        System.out.print("Bad input");
}
}

Program Terminating when it Reaches my If Statement [duplicate]

This question already has an answer here:

My program is becoming terminated when it reaches the point of the if statement I am not sure why. All that I am doing before that point is taking user input. I don't seem to have any errors in the program either. The if statement doesn't have errors either. My question is, what is causing the termination of my program?

        if (animal == "cat"){

            food = ((10 * animal) + (6.25 * animalinch) - (5 * animalage) +5);
            System.out.print("your animal should eat this much" + calories);
        }else if (animal == "dog"){
            System.out.print("you have a dog");
        }


    }

Java IF Statement

I'm trying to write a Java program with a bunch of IF Statements. I'm confused about what it's actually supposed to look like. Could someone pleaaaase please give me an example with the question below, or something similar? Do IF Statements require a System.out.print for every variable in order for it to compile?

// Thank you soooo much!!!

Use a nested if to test the following conditions: If a boolean variable called sale is set to true, do the following: If the int variable price is less than 50, the double variable discount is set to 0.01. If the int variable price is 50 or greater, the double variable discount is set to 0.02.

This is the code I wrote for this, but I don't think it's correct....

boolean sale;
 int price;
 double discount;

 System.out.print("Please Enter Sale ");
  sale = keyboard.nextBoolean();

  if (sale == true)
    if  (price <= 50)
    discount = 0.01;

    else (price >= 50)
    discount = 0.02;

Excel If numbers end with '00'

Could you please help me write a IF formula so if a number end with '00' then output is A, else B. I wrote the following but it shows up as a #NAME?.

=IF((RIGHT(J3,2))="00",A,B)

Thanks in advance.

Ruby / Rails - Devise - before_action :authenticate_user! blocking else statement display

I would like to utilize my "plans" into a separate partial or perhaps a new file/location altogether. This page or partial should be accessed from a button on the landing page. Currently, my "plans" html is set to display conditionally on my home page if a user is not signed in. Due to the "before_action :authenticate_user!" I have on the home page, viewing the "else" (which contains the plans) can not be viewed. Should I separate the plans onto a separate page and remove the conditional statement? Or should I partial it out and render the view in my else statement?

Do I need to provide additional info?

Am I using correct terminology?


home.html.erb

<div class="row">
 <% if user_signed_in? %>

    <%= render 'users/home' %>

 <% else %>

 <!--Plans-->
 <div class="row">
    <div class="col-lg-3">
        <div class="well text-center">

            <!--Plan #1-->
            <%= link_to "REGISTER", new_user_registration_path(plan: @contributor_plan.id), class:'btn btn-info btn-block' %>

            <!--Plan #2-->
            <%= link_to "REGISTER", new_user_registration_path(plan: @elitecontributor_plan.id), class:'btn btn-warning btn-block' %>

            <!--Plan #3-->
            <%= link_to "REGISTER", new_user_registration_path(plan: @technician_plan.id), class:'btn btn-info btn-block' %>

            <!--Plan #4-->
            <%= link_to "REGISTER", new_user_registration_path(plan: @elitetechnician_plan.id), class:'btn btn-info btn-block' %>

            </div>
        </div>
    </div>

 <% end %>


pages_controller.rb

class PagesController < ApplicationController
before_action :authenticate_user!, except:  [:landing, :plans]

def landing

end

def plans
end

def home
    @contributor_plan = Plan.find(1)
    @elitecontributor_plan = Plan.find(2)
    @technician_plan = Plan.find(3)
    @elitetechnician_plan = Plan.find(4)
    @center_plan = Plan.find(5)
    @elitecenter_plan = Plan.find(6)
    @affair_plan = Plan.find(7)
    @eliteaffair_plan = Plan.find(8)
end

If else if statments not working after inspecting code

I have worked on this code for a week, as to not have to ask for assistance but i cannot find the problem with the code, so here goes I have a series of if and elseif statements that change two variable outputs $costs and $change. They are not working properly. i have attached the code.

<?php

header('Content-type: text/html; charset=utf-8');
ini_set('display_errors',"1");
ini_set('memory_limit','50000M');
require_once ('../db.php');
$conn = db_connect();
$today = date("Y-m-d");
$now = date("m/d/y h:i:s");
$rejectedSKU = array();
$lowestPrices = array();
$x=0;
$page=1;
$UseDate=date("Y-m-d", strtotime("-6 months",strtotime($today)));
$csvContent = "";
$i = 0;

$conn->query("update inventory set upload = 1 where quantity > 0 and ourPrice > 50 and ourPrice < 100 ");

$update = $conn->query("SELECT sku,i.isbn13,i.quantity,fillzPrice,ourPrice,cost,b.weight,b.title,i.quantity as qty,
book_condition.book_condition,taped.feature AS taped,i.date_created,
book_type.book_text,defect.defect,i.additional_note,i.additional_feature,feature.feature,water.feature AS water,note.note,
fixed,static,location,b.author,publisher,commission_level,follette_title.new_price,follette_title.usedbuying_price,bw.Price AS bwPrice,bw.NewPrice AS newPrice,bb.price AS bytePrice,ingram.price AS ingramPrice,
amtext.price AS aprice,nebraska.price AS nprice,tichenor.price AS tprice,s.price AS sterlingPrice,
feature.book_type_3,i.book_type_id,
buyer_type.buyer_type,source.source, i.source_date, note.book_type_2, i.csmt,i.cu, i.manual,i.taped_id,i.feature_id,
book_type.book_code,water.book_type_4 ,b.pub_date,b.binding
from inventory i
LEFT JOIN book b on i.isbn13 = b.isbn13
LEFT JOIN defect ON i.defect_id = defect.defect_id
LEFT JOIN book_condition ON defect.condition_id = book_condition.condition_id
LEFT JOIN feature ON i.feature_id = feature.feature_id
LEFT JOIN taped on i.taped_id = taped.taped_id
LEFT JOIN water on i.additional_feature = water.feature_id
LEFT JOIN note ON i.note_id = note.note_id
LEFT JOIN location ON i.location_id = location.location_id
LEFT JOIN source ON i.source_id = source.source_id
LEFT JOIN buyer_type ON source.buyer_type_id = buyer_type.buyer_type_id
LEFT JOIN book_type ON i.book_type_id = book_type.book_type_id
LEFT JOIN follette_title ON i.isbn13 = follette_title.isbn13
LEFT JOIN amtext ON i.isbn13 = amtext.isbn13
LEFT JOIN nebraska ON i.isbn13 = nebraska.isbn13
LEFT JOIN tichenor ON i.isbn13 = tichenor.isbn13
LEFT JOIN book_winner AS bw ON i.isbn13 = bw.isbn13
LEFT JOIN bookbyte AS bb ON i.isbn13 = bb.isbn
LEFT JOIN ingram ON i.isbn13 = ingram.isbn
LEFT JOIN sterling AS s ON i.isbn13 = s.isbn13
WHERE i.upload = 1 AND i.ourPrice > 50 and i.ourPrice < 100  AND i.location_id > 0");

while ($row = $update->fetch_assoc()) {
    $quantity1 = 0;
    $quantity2=$row['quantity'];
    $title = str_replace('"','',$row['title']);
    $created= $row['date_created'];
    $sku = $row['sku'];
    $isbn = $row['isbn13'];
    $weight = $row['weight'];
    $edition = $row['edition'];
    $fillz = $row['fillzPrice'];
    $ourPrice = $row['ourPrice'];
    $cond = $row['book_condition'];
    $State = $row['book_condition'];
    $damage=  $row['Damage'];
    $bookTypeId = $row['book_type_id'];
    $bookCode = $row['book_code'];
    $additional_note = $row['additional_note'];
    $feature_feature = $row['feature.feature'];
    $taped_feature = $row['taped'];
    $additional_feature = $row['additional_feature'];
    $location = $row['location'];
    $fixed = $row['fixed'];
    $static = $row['static'];
    $cost = $row['cost'];
    $cost2= $row['cost'];
    $comm = $row['commission_level'];
    $amtext = $row['aprice']; 
    $follett = $row['usedbuying_price'];
    $follettnew = $row['new_price'];
    $tich = $row['tprice'];
    $nebraska =$row['nprice'] ;
    $sterling = $row['sterlingPrice'];
    $ingram = $row['ingramPrice'];
    $bookbyte = $row['bytePrice'];
    $bookWin = $row['bwPrice'];
    $newPrice = $row['newPrice'];
    $junk=0;
    $exped = "y";
    $csmt = $row['csmt'];
    if($csmt == 1) {
        $csmt ="CSMT";
    } else {
        $csmt = "";
    }
    $cu = $row['cu'];
    if($cu ==1) {
        $cu="CU";
    } else {
        $cu="";
    }
    if (($row['cu']==1) && ($quantity2>0)) {
    if ($maxprice==null){
        $maxprice=0;
    }

    if($maxprice==0){
        $cu2=0;
    }
}
elseif (($row['cu']==0) && ($quantity2>0)) {
        if  ((($bookTypeId=="2") || ($bookTypeId=="5") || ($bookTypeId=="6") || ($bookTypeId=="7") || ($tpd == "TPD" )) &&
             (($row['book_type_4']!="WATER") || ($cond != "Poor"))){
            if ($maxprice2==null){
        $maxprice2=0;
    }
    if ($maxprice2>0){
        $cu2=1;
    }
}
elseif (($row['book_type_4']!="WATER") || ($cond != "Poor") || ($bookTypeId!="2") || ($bookTypeId!="5") || ($bookTypeId!="6") || ($bookTypeId!="7") || ($tpd != "TPD" )) {

        if ($maxprice==null){
        $maxprice=0;
    }
    if ($maxprice>0){
    $cu2=1;

    }

}
}
if ($cu2==1){
    $cu="CU";
}
    $manual = $row['manual'];
    if($manual == 1){
        $manual = "manual";
    } else {
        $manual = "";
    }
$tpd = $row['taped_id'];
$feature_id = $row['feature_id'];
if($tpd==34 || $tpd==35 || $feature_id==34 || $feature_id==35) {
    $tpd = "TPD";
}
if($static == 1){
    $static = "Static";
} else {
    $static = "";
}
    $water = $row['water'];

    $itemNote = $row['book_text'];
    $itemNote .=" " .$row['defect'];
    $itemNote .=" " .trim($row['additional_note']);
    $itemNote .=" " .$row['feature'];
    $itemNote .=" " .$row['taped'];
    $itemNote .=" " .$water;
    $itemNote .=" " .$row['note'];

    $source = $row['buyer_type'];
    $source .=$row['source'];
    $source .=$row['source_date'];
    $source .=$row['book_type_2'];
    $source .=$csmt;
    $source .=$cu;
    $source .=$manual;
    $source .=$row['book_code'];
    $source .=$row['book_type_4'];
    $source .=$tpd;
    $source .= $static;

    $createDate = new DateTime($created);

$strip = $createDate->format('Y-m-d');


if($weight<3.99) {
        $willShip = Y;
    } else {
        $willShip = N;
    }
if($weight>4.8 && (($ourPrice - $cost)<9)) {
    $exped = "n";
    }
    if($fillz == 0){
        if($ourPrice < 2.99 && ($weight >=2 && $weight<=2.99)) {
            $exped = "n";
        }
    } elseif (($fillz > 0 && $fillz <2.99) && ($weight >=2 && $weight<=2.99)) {
        $exped = "n";
    } elseif (($fillz >0 && $fillz <=4.99) && ($weight >=3 && $weight<=8.99)) {
        $exped = "n";
    } elseif (($fillz >0 && $fillz <=6.49) && ($weight >=9 )) {
        $exped = "n";
    }
$qty = $conn->query("SELECT quantity FROM qty_skus WHERE sku = $sku LIMIT 1");
$num_row = $qty->num_rows;
if($num_row>0) {
    $rows=$qty->fetch_assoc();
    $quantity = $rows['quantity'];
    $quantity1 = $rows['quantity'];
} else {
    $quantity = $row['quantity'];
}

if ($fixed == 1) {
    $fixed = "Fixed";
} else {
    $fixed = "";
}

$locations = $location;
$locations .= $fixed;



//SWITCH STATEMENT FOR CONDITION
    switch ($cond) {
                case "New":
                    $condition = 11;
                    break;
                case "Fine":
                    $condition = 1;
                    break;
                case "Very Good":
                    $condition = 2;
                    break;
                case "Good":
                   $condition = 3;
                    break;
                case "Poor":
                    $condition = 4;
                    break;
                default:
                    $condition = 0;
    }







    if ($strip > $UseDate){
        $check='yes';
    }
    elseif ($strip <= $UseDate){
        $check='no';
    }
    if ($strip <= $UseDate){

        if($row['commission_level'] == 1) {
        $maxprice3=max(($follettnew),($junk),($amtext*1.71),($newPrice),($sterling*1.71),($nebraska*1.2),($tich*1.25),($ingram*1.2),($bookbyte));

        if ($maxprice3>0){

        $costs=$maxprice3;
        $change="1";
        }
        elseif ($maxprice3==0) {
            $costs = 0;
            $change="2";
        } 
    }
        elseif (($bookTypeId=="1") || ($bookTypeId=="9")|| ($bookTypeId=="10")|| ($bookTypeId=="11")){
            $maxprice=max(($follett),($junk),($amtext*1.37),($nebraska*1.2),($tich*1.25),($sterling*1.37),($bookWin),($ingram*1.2),($bookbyte));
                if ($maxprice>0){

                            $costs = $maxprice;
                            $change=3;

                        }
                        elseif ($maxprice==0) {
                            $costs=$cost2;
                            $change=4;
                        }


    }


        if  (($bookTypeId=="2") || ($bookTypeId=="5") || ($bookTypeId=="6") || ($bookTypeId=="7") || ($tpd =="TPD" )){
                $maxprice2=max(($amtext*1.37),($junk),($sterling*1.37));    
                if ($maxprice2>0){

                            $costs = $maxprice2;
                            $change=1;
                                        }
                if ($maxprice2==0) {
                    $costs = 0;
                    $change=2;
                    }
            }

        if($damage=="DMG" || $damage=="WATER"|| $condition==3 || $bookTypeId==3 ) {
                $costs = 0;
                $change=3;
            }



    }

else {

    if($row['commission_level'] == 1) {
    $maxprice3=max(($follettnew),($junk),($amtext*1.71),($newPrice),($sterling*1.71),($nebraska*1.2),($tich*1.25),($ingram*1.2),($bookbyte));
        if ($maxprice3>0){

        $costs=$maxprice3;
        $change="1N";
        }
        elseif ($maxprice3==0) {
            $costs = $cost2;
            $change="2N";
        } 
    }
    elseif (($bookTypeId=="1") || ($bookTypeId=="9")|| ($bookTypeId=="10")|| ($bookTypeId=="11")){
            $maxprice=max(($follett),($junk),($amtext*1.37),($nebraska*1.2),($tich*1.25),($sterling*1.37),($bookWin),($ingram*1.2),($bookbyte));
                if ($maxprice>0){
                    if($cost<$maxprice){                    
                            $costs = $maxprice;
                            $change="15N";
                                        }
                elseif ($maxprice==0) {
                    $costs = $cost2;
                    $change="16N";
                    }
            }
    }

    if  (($bookTypeId=="2") || ($bookTypeId=="5") || ($bookTypeId=="6") || ($bookTypeId=="7") || ($tpd =="TPD" )){
                $maxprice2=max(($amtext*1.37),($junk),($sterling*1.37));        
                if ($maxprice2>0){
                    if($cost<$maxprice2){                   
                            $costs = $maxprice2;
                            $change="3N";
                                        }
                elseif ($maxprice2==0) {
                    $costs = $cost2;
                    $change="4N";
                    }
            }
    }

        if($damage=="DMG" || $damage=="WATER" || $condition==3 || $bookTypeId==3 ) {
                $costs = 0;
                $change="5N";
            }








else{
    $costs=$cost2;
}

}

if($condition==4) {
                $costs = 0;
                $change="25A";
            }



if($location == "FBA") {
    $place = "Amazon_NA";
} else {
    $place = "";
    }   

    if ($bookTypeId==8){
    $category='Custom';
}
elseif ($bookTypeId==1){
    $category='Book';
}
elseif ($bookTypeId==9){
    $category='DVD/CD';
}
else{
    $category='Special Edition';
}

$conn->query("UPDATE inventory SET cu=$cu2 WHERE sku= $sku");


$export[$x] = array('item-name' => $title,
            'sku' => $sku,
            'quantity' =>$quantity,
            'item-note' => $itemNote,
            'will-ship-internationally' =>$willShip,
            'product-id' => $isbn,
            'price' => number_format($ourPrice,2,'.',''),
            'expedited-shipping' =>$exped,
            'item-condition' =>$condition,
            'location' => $locations,
            'author' => stripslashes($row['author']),
            'publisher' => stripslashes($row['publisher']),
            'condition-id' => $condition,
            'Cost' => number_format($costs,2,'.',''),
            'Source' => $source,
            'pubdate' =>$row['pub_date'],
            'Media' => $row['binding'],
            'condition' => $cond,
            'fulfillment-center-id' => $place,
            'Original Cost'=>number_format($cost,2,'.',''),
            'Original Cost2'=>number_format($cost2,2,'.',''),
            'max new price'=>$maxprice,
            'max new price2'=>$maxprice2,
            'NEW MAXPRICE'=>$maxprice3,
            'created'=>$strip,
            'conditionCost'=>$conditionCost,
            'check'=>$check,
            'Commisi'=>$row['commission_level'],
            'Usedate'=>$UseDate,
            'Follett'=>$follett,
            'FolletNew'=> $follettnew,
            'Amtext'=>$amtext,
            'Nebraska' =>$nebraska,
            'tichenor' => $tich,
            'sterling'=>$sterling,
            'bookwinner' => $bookWin,
            'ingram'=> $ingram,
            'bookbyte'=>$bookbyte,
            'change'=>$change,
            'damage'=>$damage,
            'BookTypeID'=>$bookTypeId,
            );



    $x++;
    $conn->query("UPDATE inventory SET upload=0 WHERE sku= $sku");

    } //END OF WHILE STATEMENT

this runs through a while statement and collects anywhere from 20 to 1,200,000 records (it runs no problem but the change and the cost do not come out they way they should)

any help would be greatly appreciated

Turbo Pascal: check if string contains numbers

As its said in the tile im trying to check if a string contains a number for an if-statement. Here is what i got so far. Also if you can help me how to format that code here correctly would be awesome aswell :D

repeat writeln; writeln('Ok, geben Sie bitte ihre zuknftiges Passwort ein.'); writeln('Achtung: Der Text kann nach einer Verschlsselung mit PW'); writeln(' nur mit dem selben PW wieder entschlsselt werden.'); readln(PW); pwLength:= Length(PW); errornumlength:='123456789'; errorLength:= Length(errornumlength);

         repeat
         errorStelle:= errorStelle + 1;
         errornum:= pos(errornumlength[errorStelle],PW);
         until errorStelle=Length(errornumlength);
         error:= errornum;

                 if Length(PW)=0 then
                 begin
                 error:=1;
                 end;
                 if Length(PW)>25 then
                 begin
                 error:=1;
                 end;
                 if error>0 then
                 begin
                 writeln('ERROR: Deine PW muss mindestens 1-nen Buchstaben besitzen,');
                 writeln('       keine Zahlen enthalten und unter 25 Zeichen betragen!');
                 readln;
                 clrscr;
                 end;

until error=0;

Thx for the help

Throw and catch Java

The if statement in my throw is gives a bad input error message when using "#,$,&,*" and I can't figure out what is wrong with it. In addition, I need to able able to take up to 99 characters in the input but my code stops after around 15 and I don't know what I coded wrong

public static void main(String[] args) {

    int counter = 1;
    String last = "";
    String output = "";
    String addToOutput = "";


    Scanner s = new Scanner(System.in);

    System.out.print("Enter input string: ");
    String inputstring = s.nextLine();


    System.out.print("Enter flag character: ");
    String inputflag = s.nextLine();


    try{
    if(inputstring != "#" || inputstring != "$" || inputstring != "&" || inputstring != "*"){
            throw new IllegalArgumentException("Bad Input.");


    }
    else{
        System.out.print(output);
    }

    for (int i = 0; i<inputstring.length(); i++){



            if((""+inputstring.charAt(i)).equals(last)){
                counter ++;
    }
        else{
            if(counter>3)
            addToOutput = inputflag + last + counter;
            else{
                addToOutput = "";
                for(int j =0; j<counter; j++){
                    addToOutput = addToOutput + last;
                }

            }
            output = output + addToOutput;
        counter = 1;

    }


    last = "" + inputstring.charAt(i);


            }
        }

    catch(IllegalArgumentException e){
        System.out.println(e.getMessage());
    }

    }

    }

Stuck in Loop Collatz Conjecture Attempt in C

There is a logic flaw within my code that I can't seem to pass 2^31 − 1 as an input. Here is a fragment of my code.

#include <stdio.h>
int main() {
long input = 0;
long temp = 0;
int count = 0;
printf("Enter a positive integer ( or 0 to quit): ");
scanf("%ld", &input);
if(input == 0)
{
    printf("Quit.");
}
else
{
    temp = input;
    while (temp != 1)
    {
        if(temp %2 ==0)
        {
            temp = temp/2;
            count++;


        } else
        {
            temp = 3*temp + 1;
            count++;
        }

    }
return 0;
}

I have tried changing the size of my input to long => long long and it still get stuck within this area after Debugging it. Please provide some feedback Thanks!

Introductory Java math program returning 0

I'm trying to work on a program challenge that takes an input of Air, Water, or Steel, and shows the speed of sound traveled in feet in Java.

My driver code looks like this

import java.util.Scanner;

public class driver
{
public static void main(String[] args)
{
String type;
int distance;
int time = 0;

    Scanner keyboard = new Scanner(System.in);

System.out.print("Input one of the following- Air, water, or steel.");
        type = keyboard.nextLine();

System.out.print("Input distance in feet");
        distance = keyboard.nextInt();

        speedofsound sound = new speedofsound(distance);

        if (type.equals("Air"))
    time = sound.getSpeedInAir();
        System.out.println(time);
        if (type.equals("Water"))
    time = sound.getSpeedInWater();

        if (type.equals("Steel"))
    time = sound.getSpeedInSteel();

        System.out.println("The time it would take for"  + type + "to travel" + distance + "feet is" + time);
 }
}

and the Class looks like this

public class speedofsound {// class stating
private int distance;//distance integer
private int time;

public speedofsound (int d)
{
    distance = d; // from driver pass over dist in ft, 
}

public int getSpeedInAir()

{
return  (distance / 1100);

}
public int getSpeedInWater()

{
time = distance / 4900;
return time;
}
public int getSpeedInSteel()

{
time = distance / 16400;
return time;
 }
}

When I execute this in the console I get "Input one of the following- Air, water, or steel.Air Input distance in feet50 0 The time it would take forAirto travel50feet is0" No matter what I input, I keep getting 0. Whats up?

Boolean Required Here

The following logic gives me a Boolean Required Here error. Where am I going wrong?

{RV_Practitioner.IgnoreCertificationException} and
if ({RV_Practitioner_ID_Numbers.DocumentName} = ["NPI Number"])
then {RV_Practitioner_ID_Numbers.DocumentName} in ["NPI Number"]
else "No NPI"

If else if statments not working

I have worked on this code for a week, as to not have to ask for assistance but i cannot find the problem with the code, so here goes I have a series of if and elseif statements that change two variable outputs $costs and $change. They are not working properly. i have attached the code.

if ($strip <= $UseDate){
                
                if($row['commission_level'] == 1) {
                $maxprice3=max(($follettnew),($junk),($amtext*1.71),($newPrice),($sterling*1.71),($nebraska*1.2),($tich*1.25),($ingram*1.2),($bookbyte));
                
                if ($maxprice3>0){

                $costs=$maxprice3;
                $change="1";
                }
                elseif ($maxprice3==0) {
                        $costs = 0;
                        $change="2";
                } 
        }
                elseif (($bookTypeId=="1") || ($bookTypeId=="9")|| ($bookTypeId=="10")|| ($bookTypeId=="11")){
                        $maxprice=max(($follett),($junk),($amtext*1.37),($nebraska*1.2),($tich*1.25),($sterling*1.37),($bookWin),($ingram*1.2),($bookbyte));
                                if ($maxprice>0){
                                
                                                        $costs = $maxprice;
                                                        $change=3;
                                                
                                                }
                                                elseif ($maxprice==0) {
                                                        $costs=$cost2;
                                                        $change=4;
                                                }
                                
                                
        }

                
                if      (($bookTypeId=="2") || ($bookTypeId=="5") || ($bookTypeId=="6") || ($bookTypeId=="7") || ($tpd =="TPD" )){
                                $maxprice2=max(($amtext*1.37),($junk),($sterling*1.37));        
                                if ($maxprice2>0){
                                        
                                                        $costs = $maxprice2;
                                                        $change=1;
                                                                                }
                                if ($maxprice2==0) {
                                        $costs = 0;
                                        $change=2;
                                        }
                        }
                
                if($damage=="DMG" || $damage=="WATER"|| $condition==3 || $bookTypeId==3 ) {
                                $costs = 0;
                                $change=3;
                        }
                
        
        
        }

else {
        
        if($row['commission_level'] == 1) {
        $maxprice3=max(($follettnew),($junk),($amtext*1.71),($newPrice),($sterling*1.71),($nebraska*1.2),($tich*1.25),($ingram*1.2),($bookbyte));
                if ($maxprice3>0){

                $costs=$maxprice3;
                $change="1N";
                }
                elseif ($maxprice3==0) {
                        $costs = $cost2;
                        $change="2N";
                } 
        }
        elseif (($bookTypeId=="1") || ($bookTypeId=="9")|| ($bookTypeId=="10")|| ($bookTypeId=="11")){
                        $maxprice=max(($follett),($junk),($amtext*1.37),($nebraska*1.2),($tich*1.25),($sterling*1.37),($bookWin),($ingram*1.2),($bookbyte));
                                if ($maxprice>0){
                                        if($cost<$maxprice){                                 
                                                        $costs = $maxprice;
                                                        $change="15N";
                                                                                }
                                elseif ($maxprice==0) {
                                        $costs = $cost2;
                                        $change="16N";
                                        }
                        }
        }
        
        if      (($bookTypeId=="2") || ($bookTypeId=="5") || ($bookTypeId=="6") || ($bookTypeId=="7") || ($tpd =="TPD" )){
                                $maxprice2=max(($amtext*1.37),($junk),($sterling*1.37));                
                                if ($maxprice2>0){
                                        if($cost<$maxprice2){                                        
                                                        $costs = $maxprice2;
                                                        $change="3N";
                                                                                }
                                elseif ($maxprice2==0) {
                                        $costs = $cost2;
                                        $change="4N";
                                        }
                        }
        }
                
                if($damage=="DMG" || $damage=="WATER" || $condition==3 || $bookTypeId==3 ) {
                                $costs = 0;
                                $change="5N";
                        }
                
                        


        
                                
        }
        
else{
        $costs=$cost2;
}
        


if($condition==4) {
                                $costs = 0;
                                $change="25A";
                        }


        
if($location == "FBA") {
        $place = "Amazon_NA";
} else {
        $place = "";
        }       
        
        if ($bookTypeId==8){
        $category='Custom';
}
elseif ($bookTypeId==1){
        $category='Book';
}
elseif ($bookTypeId==9){
        $category='DVD/CD';
}
else{
        $category='Special Edition';
}

$conn->query("UPDATE inventory SET cu=$cu2 WHERE sku= $sku");


$export[$x] = array('item-name' => $title,
                    'sku' => $sku,
                    'quantity' =>$quantity,
                    'item-note' => $itemNote,
                    'will-ship-internationally' =>$willShip,
                    'product-id' => $isbn,
                    'price' => number_format($ourPrice,2,'.',''),
                    'expedited-shipping' =>$exped,
                    'item-condition' =>$condition,
                    'location' => $locations,
                    'author' => stripslashes($row['author']),
                    'publisher' => stripslashes($row['publisher']),
                    'condition-id' => $condition,
                    'Cost' => number_format($costs,2,'.',''),
                    'Source' => $source,
                    'pubdate' =>$row['pub_date'],
                    'Media' => $row['binding'],
                    'condition' => $cond,
                    'fulfillment-center-id' => $place,
                        'Original Cost'=>number_format($cost,2,'.',''),
                        'Original Cost2'=>number_format($cost2,2,'.',''),
                        'max new price'=>$maxprice,
                        'max new price2'=>$maxprice2,
                        'NEW MAXPRICE'=>$maxprice3,
                        'created'=>$strip,
                        'conditionCost'=>$conditionCost,
                        'check'=>$check,
                        'Commisi'=>$row['commission_level'],
                        'Usedate'=>$UseDate,
                        'Follett'=>$follett,
                        'FolletNew'=> $follettnew,
                        'Amtext'=>$amtext,
                        'Nebraska' =>$nebraska,
                        'tichenor' => $tich,
                        'sterling'=>$sterling,
                        'bookwinner' =>      $bookWin,
                        'ingram'=> $ingram,
                        'bookbyte'=>$bookbyte,
                        'change'=>$change,
                        'damage'=>$damage,
                        'BookTypeID'=>$bookTypeId,
                    );



        $x++;
        $conn->query("UPDATE inventory SET upload=0 WHERE sku= $sku");
        
        } //END OF WHILE STATEMENT

this runs through a while statement and collects anywhere from 20 to 1,200,000 records (it runs no problem but the change and the cost do not come out they way they should)

any help would be greatly appreciated

Int not incrementing or being checked properly

I am new to coding and am having a hard time trying to figure this out. I have an if/else loop that if matched will do things as well as increment the variable bbb. Then at the end it checks what the number of bbb is and acts on it depending on the if/else statement. The code is strange when I have the if(bbb==0) statement in, it will always resolve as true even when I know it shouldn't be. If the if(bbb == 0) statement is commented out it resolves with the correct number for count. Here is my full set of code. If I am not asking the correct questions please let me know. Thanks for your help.

        protected void jotti()
    {
        string input = TextBox1.Text;
        string file;
        file = "/C \"curl http://ift.tt/2dx1hPr" + input + " -o C:\\Windows\\Temp\\jotti.txt";
        System.Diagnostics.Process CMDprocess = new System.Diagnostics.Process();
        var StartProcessInfo = new System.Diagnostics.ProcessStartInfo();
        StartProcessInfo.FileName = "cmd.exe";
        StartProcessInfo.UseShellExecute = false;
        StartProcessInfo.CreateNoWindow = false;
        StartProcessInfo.Verb = "runas";
        StartProcessInfo.Arguments = file;
        CMDprocess.StartInfo = StartProcessInfo;
        CMDprocess.Start();
        CMDprocess.WaitForExit();
        jotti_Parser();
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    protected void jotti_Parser()
    {
        StringBuilder sb = new StringBuilder();
        string input = TextBox1.Text;
        int bbb = 0;
        var filename = @"C:\Windows\Temp\jotti.txt";
        var text = File.ReadAllText(filename);
        text = text.Replace("dataType:", "");
        File.WriteAllText(filename, text);
        string a = "<a href=http://ift.tt/2dx1hPr" + input + "> Hash Results </a> <br/> ";
        sb.Append(a);
        foreach (string line in File.ReadAllLines(filename))
        {
            if (line.Contains("Name:"))
            {
                string t = line.ToString() + " <br/> ";
                sb.Append(t);
                bbb++;
            }
            if (line.Contains("Size:"))
            {
                string y = line.ToString() + " <br/> ";
                sb.Append(y);
                bbb++;
            }
            if (line.Contains("Type:"))
            {
                string s = line.ToString() + " <br/> ";
                sb.Append(s);
                bbb++;
            }
            if (line.Contains("MD5:"))
            {
                string q = line.ToString() + " <br/> ";
                sb.Append(q);
                bbb++;
            }
            if (line.Contains("Status:"))
            {
                string u = line.ToString() + " <br/> ";
                sb.Append(u);
                bbb++;
            }
            File.WriteAllText(filename, sb.ToString());
            string text2 = File.ReadAllText(filename);
            text2 = text2.Replace("<td>", "");
            text2 = text2.Replace("</td>", "");
            text2 = text2.Replace("Status:<td id=\"statusText[hl5p2789za]\"", "Status:");
            text2 = text2.Replace("class=\"statusText\">Scan", "Scan");
            text2 = text2.Replace("Scan finished.", "Scan finished. <br/> ");
            text2 = text2.Replace(" <br/> ", " <br/> " + Environment.NewLine);
            File.WriteAllText(filename, text2);
            if (bbb == 0)
            {
                Label6.Visible = true;
                Label6.Text = text2.ToString() + bbb;
            }
            else
            {
                string v = "This hash has not been seen by this resource. <br/>";
                sb.Clear();
                Label6.Visible = true;
                Label6.Text = v + bbb;
                bbb++;
                return;
            }
        }
   }

(set was unexpected at this time

I've seen several articles about the error I'm getting, I just can't figure it out. If I answer 1-5 all works perfect. If I answer 6 or 7 it gives the error:(set was unexpected at this time Is it something wrong in my if statements?

:if
if %q1% == 1 (if %q2% == n (set sku=XG8ATCHUS) else set sku=XW8ATCHUS)
if %q1% == 2 (if %q2% == n (set sku=XG1ATCHUS) else set sku=XW1ATCHUS)
if %q1% == 3 (if %q2% == n (set sku=XG1BTCHUS) else set sku=XW1BTCHUS)
if %q1% == 4 (if %q2% == n (set sku=XG1CTCHUS) else set sku=XW1CTCHUS)
if %q1% == 5 (if %q2% == n (set sku=XG1DTCHUS) else set sku=XW1DTCHUS)
if %q1% == 6 set sku=XG21TCHUS
if %q1% == 7 set sku=XG23TCHUS
if %q3% == f set sku2=FullGuard
if %q3% == e set sku2=EnterpriseGuard

Outlook - Sorting Attachments by key phrase (VBA)

I am trying to run some VBA code to automatically save attachments based on a phrase in the attachment name to specific folders on my desktop.

   Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
     For Each objAtt In itm.Attachments
        If objAtt.SaveAsFile = "Test1" Then
            saveFolder = "P:\Desktop\Reports\Test1"
        If objAtt.SaveAsFile = "Test2" Then
            saveFolder = "P:\Desktop\Reports\Test2"
        If objAtt.SaveAsFile = "Test3" Then
            saveFolder = "P:\Desktop\Reports\Test3"
        If objAtt.SaveAsFile = "Test4" Then
            saveFolder = "P:\Desktop\Reports\Test4"
        If objAtt.SaveAsFile = "Test5" Then
            saveFolder = "P:\Desktop\Reports\Test5"
          objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
          Set objAtt = Nothing
     Next
End Sub

It is probably more long winded then it needs to be, but I am hoping you get the idea of what I am trying to do.

I am a complete VBA novice so any help would be appreciated

Chef if statement in recipe

I am trying to chef if the ubuntu platform is 14.04 or 16.04 and run the template based on that, but I am receiving errors.

Code:

   if node[:'platform_version'] == '14.04'
            template "/etc/apt/sources.list" do
                source "sources.list.erb"
                mode '0644'
                owner 'root'
                group 'root'
            end
    elseif node[:'platform_version'] == '16.04'
            template "/etc/apt/sources.list" do
                source "apt-sources.list.erb"
                mode '0644'
                owner 'root'
                group 'root'
            end
    end

Output:

[2016-09-30T10:52:55+02:00] WARN: Chef::Provider::AptRepository already exists!  Cannot create deprecation class for LWRP provider apt_repository from cookbook apt
[2016-09-30T10:52:55+02:00] WARN: AptRepository already exists!  Deprecation class overwrites Custom resource apt_repository from cookbook apt
Converging 0 resources

If statements in for loops

how do I run only one of those if statements in a for loop? For example i have an input of 5...and i just want it to print five...but whenever i run this code, it will execute all if statement..please help me

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    // Complete the code.
    int a;
    int b;

    cin >> a;

    for (a = 0; 0<a<10; a++)
        {
            if (a == 1)
                {
                    cout << "one";
            }
        if (a == 2)
                {
                    cout << "two";
            }
        if (a == 3)
                {
                    cout << "three";
            }
        if (a == 4)
                {
                    cout << "four";
            }
        if (a == 5)
                {
                    cout << "five";
            }
         if (a == 6)
                {
                    cout << "six";
            }
        if (a == 7)
                {
                    cout << "seven";
            }
         if (a == 8)
                {
                    cout << "eight";
            }
        if (a == 9)
                {
                    cout << "nine";
            }

        else if (a > 9 && a%2 == 0)
            {
                cout << "even";
        }
        else if (a > 9 && a&2 != 0)
            {
                cout << "odd";
        }
    }
    return 0;
}

Add query string to Image Source(img src) if it has a particular class or ID

I want this in either PHP or JS. Its like, if img has particular class them a query string will be appended to its source url. Lets assume, the particular class is 'hello' & query string is '?source=fb' So, if img has class 'hello' -

<img class="hello" src="http://ift.tt/2dcfTnw">

The PHP should check & append it to the img src.

Any function that can do this?

Change an icon using an 'if' statement in Google Maps

I'm writing a program for the oil and gas industry that allows you to see whether a pump-jack is on or off using a remote logic board at the site and relays the information via 4G internet. I'm trying to build it in a way that an icon on the map will be red or green depending of whether the alarm on the board is tripped. the file path can be reached via a static IP file path like for example:

http://ift.tt/2cPWJRL

this file path either gives a value of 1 or 0

how do i translate that value of 0 or 1 into an if statement that would change the icon depending on the value?

Here is my code for one of the icons:

 function initialize() {


        var map_canvas = document.getElementById('map_canvas');
        var map_options = {
          center: new google.maps.LatLng(50.242913, -111.195383),
          zoom: 14,
          mapTypeId: google.maps.MapTypeId.TERRAIN


        } 
        var map = new google.maps.Map(map_canvas, map_options);

        var point       =       new google.maps.LatLng(47.5, -100); 
        var derrick1    =       new google.maps.Marker ({
            position: new google.maps.LatLng(50.244915, -111.198540),    
            map: map,
            icon: 'on.png',
            size: new google.maps.Size(20, 32),
            title: '1' 

        })



        google.maps.event.addDomListener(window, 'load', initialize);
        

converting for loop to while loop/ or if loop

Program: loop through array and find the maximum count of a value that appear

I need to convert this to while or if loop can someone please show me

int max_len(int array[], int size)
    {
       int previous = array[0], count = 1, i = 0, maxCount = 1;

   for (i = 1; i < size; i++)
      (array[i] == previous)? count++: (previous = array[i],
              (maxCount < count)? maxCount = count : count = 1);
   return maxCount;
}enter code here

//I'm a bit new to this

jeudi 29 septembre 2016

When to use dereference operator for pointers C++

I'm currently studying C++. Not in school. Using books, tutorials and practice.

One thing that confuses me and I haven't been able to track down an answer is when to use the dereference operator (*) for pointers. For example, from C++ primer which I'm currently reading:

char *cp = get_string();
if (cp) /* ... */    // true if the pointer cp is not zero 

while (*cp) /*    ... */    // true if *cp is not the null character

I don't understand why in the if statement it is just cp without dereference operator and then in the while statement it uses the dereference operator. There is other examples like a mix of uses in a for loop but this is the latest example in the book that confuses me. Thanks in advance for your help.

PHP IF Statement - Two Variables Not Working

I have an IF statement and I need to check two variables, then execute the action if either of the variables are false.

I know I can use the OR (||) statement however for some reason it is not working. I am in the process of learning PHP so it's probably a syntax error on my behalf.

If I create the if statement with only one (either) variable, it works fine:

<?php if ($var1 == false) { do whatever...} ?>

However when I try to check two, neither of the variables seem to be checked. I have tried different syntax variations but nothing works:

<?php if (($var1 == false) || ($var2 == false)) { do whatever...} ?>
<?php if (($var1 == false) OR ($var2 == false)) { do whatever...} ?>
<?php if ($var1 == false || $var2 == false) { do whatever...} ?>
<?php if ($var1 == false OR $var2 == false) { do whatever...} ?>

Can someone please point out what my error is?

Thanks!

Image picker that displays both camera and photo library in swift 3 [duplicate]

First off this was the video tutorial I was trying to follow https://www.youtube.com/watch?v=YYS-LwvluL8. I have just recenlty installed the new Xcode update. So I am working with swift 3.

All this video has is a image picker, a camera, and a load photo gallery. I was able to load a photo from my saved album but I was not able to use the camera feature. If I had used the camera feature it gave me a sigabrt error. I also can't access my photo gallery anymore either within the app. All I am looking for is a exact replica of what the youtube videos tutorial represents. I have also put my view control code below. Thanks.

  import UIKit

class ViewController: UIViewController,    UINavigationControllerDelegate,      UIImagePickerControllerDelegate{

 @IBOutlet weak var x: UIImageView!
 override func viewDidLoad() {
  super.viewDidLoad()
   }


  @IBAction func camera(_ sender: AnyObject) {

let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
present(imagePicker, animated: true, completion: nil)
  }

 @IBAction func savedphotos(sender: AnyObject) {
 let imagePicker = UIImagePickerController()
 imagePicker.delegate = self
 imagePicker.sourceType =         UIImagePickerControllerSourceType.photoLibrary
present(imagePicker, animated: true, completion: nil)

}

d3js: adding multiple colors to each bars based on variables using if condition

I created a horizontal bar chart.

The width of each bar is based on object variable volume. Later I realized I need to make each bar a stack bar instead, the 2 categories object variables are vol1 & vol2, where vol1 + vol2 = volume.

I was wondering if there is a direct way to assign 2 colors to each bar based on vol1 & vol2 values instead of the usual stacked bar method where you need to (a) arrange data in arrays based on their categories, (b) define x, y, y0 (c) assign different colors to each array bars.

data structure:

var data = [
{ "merchant": "A",
  "volume": 100,
  "vol1": 48,
  "vol2": 52
},
{...},
{...}
];

The specific code to draw the chart is:

    var bar = d3.select(".mainGroup").selectAll(".bar")
            .data(data_merchantTop100Vol);

    bar.attr("x", 0)
        .attr("y", d => y(d.merchant))
        .attr("height", y.rangeBand())
        .transition().duration(50)
        .attr("width", d => x(d.volume));

    bar.enter().append("rect")
        .attr("class", "bar")
        .attr("x", 0)
        .attr("y", d => y(d.merchant))
        .attr("height", y.rangeBand())
        .transition().duration(50)
        .attr("width", d => x(d.volume))
        // THIS PART IS TO FILL 2 COLORS TO THE 2 SECTIONS OF EACH BAR
        // .style("fill", function(d) {
        //     if(d.Vol1) { return "blue"}
        //     else if (d.vol2) { return "red"};
        // })

In short, I want to create a horizontal stacked bar using if-condition coloring method instead of typical stacked bar method.

Current horizontal bar chart:
enter image description here

Desired outcome:
enter image description here

How can i simplify this condition in python?

Do you know a simpler way to achieve the same result as this?: I have this code:

color1 = input("Color 1: ")
color2 = input("Color 2: ")

if ((color1=="blue" and color2=="yellow") or (color1=="yellow" and color2=="blue")):
            print("{0} + {1} = Green".format(color1, color2))

I also tried with this:

if (color1 + color2 =="blueyellow" or color1 + color2 =="yellowblue")

R nested for multiple if loops to generate new vector

I have 20 workers doing 100 tasks each. I have generated the true answer for each task, which is 1 out of 5 answers by

answers <- c("liver", "blood", "lung", "brain", "heart")
truth <- sample(answers, no.tasks, replace = TRUE, prob = c(0.2, 0.2, 0.2, 0.2, 0.2))

My dataSet contains the columns workerID, taskID, truth. Now I need to generate another vector where I am simulating what the worker will answer based on a certain probability. For example, if my truth for task 1, worker 1 is "liver", I want the worker 1 to answer "liver" for task 1 with a high probability. Similarly for each of the five answers for all the 2000 tasks, I want the workers answers. For that I am using the following for and if loops.

for (i in nrow(dataSet)){
if (dataSet$truth[i] == "liver")
{
df <- (rep(sample(answers, no.tasks, prob = c(0.9, 0.02, 0.02, 0.02, 0.02), no.workers)))
} else if (dataSet$truth[i] == "blood")
{ 
df <-  (rep(sample(answers, no.tasks, prob = c(0.02, 0.9, 0.02, 0.02, 0.02), no.workers)))
} else if (dataSet$truth[i] == "lung")
{
df <- (rep(sample(answers, no.tasks, prob = c(0.02, 0.02, 0.9, 0.02, 0.02), no.workers)))
} else if (dataSet$truth[i] == "brain")
{
df <- (rep(sample(answers, no.tasks, prob = c(0.02, 0.02, 0.02, 0.9, 0.02), no.workers)))
} else if (dataSet$truth[i] == "heart")
{
df <-  (rep(sample(answers, no.tasks, prob = c(0.02, 0.02, 0.02, 0.02, 0.9), no.workers)))
} else {
df <- (rep(sample(answers, no.tasks, prob = c(0.2, 0.2, 0.2, 0.2, 0.2), no.workers)))
}
}

But, since my truth for task 1 is brain, the output vector df has a lot of answers which are "brain". Can some one please hint as to what is going wrong here?

condition statement executes when conditions are not met

I can not figure out where the bug is in the condition statement:

xo=130, y0=160, x=180, y=210
for(row = 0; row < 480; row++){
    for(col = 0; col < 640; col++){    
         if((col>xo) && (col<(xo+x)) && (row>=yo) && (row<(yo+y))){//do something;}
    }
}

In my particular situation, I want the if statement to execute only when I am withing the window defined by top left [xo+1,yo] and bottom right [x,y]. However, the statement executes even after col is greater then xo+x. I also tried single & operator but it did not help. Is something wrong with my condition statement?

Batch file with if exist statement not working

I have a small network with 3 groups of workstations. I use a batch file to push 3rd party updates by group (workstation names in text files by group) that I'm trying to recycle for this. I want to install an application, but only if Outlook 2016 is installed. Reading the help file for "if", I thought I could just add an "if exist 'filename' goto end", but it's not working. It seems to completely skip the "if exist" line and install the app with or without Outlook 2016. What am I missing?

@ECHO OFF
SET /P GroupName=
FOR /F %%A IN (\\server\share\admin\workingfolder\update\groups\%groupname%.txt) DO (
IF EXIST "\\%%A\c$\program files (x86)\Microsoft Office\Office16\Outlook.exe" GOTO END
xcopy /e /q "\\server\share\admin\software\application" "\\%%A\c$\temp\application\"
psexec cmd "\\%%A\temp\application\application.msi"
rmdir /s /q "\\%%A\c$\temp\application\"
)
exit
:END    
ECHO "Outlook 2016 was not detected, application not installed > "\\server\share\admin\software\application\install logs\%%a.txt" 
exit

Fill in the blank part of the java statement

Your friend is car shopping and wants either a white car with white interior or a black car that has any interior other than white. Fill in the blank below with an expression you can use to check that a car meets your friend’s criteria.
PROMPT for carColor READ carColor PROMPT for interiorColor READ interiorColor IF () THEN PRINT ‘This car meets the desired criteria!’ ENDIF

PHP/MySQL - Get results from specific date, but if more results exists from one day show different

I have the following code

        foreach ($dates as $dateS) {
                        // Check if subject contains error
    $queryCheck = mysqli_query($con, "SELECT Date, Subject, Sender, Checks.Check, Checks.Status, Checks.Color, Jobs.JobAutotaskID
FROM EmailHistory
JOIN Jobs ON EmailHistory.Subject LIKE CONCAT(  '%', Jobs.JobSubjectCheck,  '%' ) 
JOIN Checks ON EmailHistory.Subject LIKE CONCAT(  '%', Checks.Check,  '%' ) 
WHERE EmailHistory.Date between '$dateS 00:00:00' AND '$dateS 23:59:59'
ORDER BY DATE ASC
"); 

    if (mysqli_num_rows($queryCheck) == 0) {

        echo "<div class=\"col-md-1\">No Backup $dateS</div>";  
    }
    else
    {
        while ($rowCheck = mysqli_fetch_array($queryCheck)) {
        if (mysqli_num_rows($queryCheck) <= 1) {
        $RowCount = mysqli_num_rows($queryCheck);
        $EmailHistoryDate = $rowCheck["Date"];
        $EmailHistorySubject = $rowCheck["Subject"];
        $EmailHistorySender = $rowCheck["Sender"];
        $ChecksCheck = $rowCheck[03];
        $ChecksStatus = $rowCheck[04];
        $ChecksColor = $rowCheck[05];

        $EmailHistorySubjectFixed = htmlspecialchars($EmailHistorySubject); 
        if  ($ChecksStatus == "OK") { echo "<div class=\"col-md-1\"><button type=\"button\" class=\"btn btn-outline btn-success\" data-toggle=\"popover\" data-placement=\"top\" data-content=\"$EmailHistoryDate - $EmailHistorySender - $EmailHistorySubjectFixed)\">OK</button></div>"; }
        if  ($ChecksStatus == "Warning") { echo " <div class=\"col-md-1\"><button type=\"button\" class=\"btn btn-outline btn-warning\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"top\" data-content=\"$EmailHistoryDate - $EmailHistorySender - $EmailHistorySubjectFixed)\">Warning</button></div>"; }
        if  ($ChecksStatus == "Error") { echo "<div class=\"col-md-1\"><button type=\"button\" class=\"btn btn-outline btn-danger\" data-toggle=\"popover\" data-placement=\"top\" data-content=\"$EmailHistoryDate - $EmailHistorySender - $EmailHistorySubjectFixed)\">Error</button></div>"; }
        echo " ";
       } else { 
           // Show backups with more then 1 result
           echo "<div class=\"col-md-1\">$dateS </div>"; }

        }


    }
    }

That does the following (see image): backup view

What i also wants is that if i get a result where more then 1 job is returned(as the images shows for the date 2016-09-25), i only wants to show it one in the view(just like the other dates is), but i want to be able show all the results from that one, when i click on the OK/Warning/Error button.

How to get the output from a function and call it from a function inside an if statement

extremely new to python, or programming of any kind for that matter I'm working on a poker program, but have run into a couple issues.

1st - I would like for the cards to be based on the standard 52-card deck, right now when I run the program it will print out the set of 5 cards for each player, but there are times when several players can have the same card, which is obviously not accurate compared to a standard poker game.

2nd - I want to define the hand rankings (Ace high, pair, two pair, three of a kind, etc)...but I cannot figure out how to code (in English) - "If the result of the 'Dealem' function returns a pair, print 'player1 has a pair'. If the result for player 2 is QDiamondsm QClubs, QSpades, 2Heats, 5Spades, print 'player2 has Trips'....etc, etc...

Java can't figure out the this obstacle for ball animation

I have a task in which i have to make a app in JFrame form. Which contains 5 balls, which move randomly around the form, they can't exit the form and have to hit the borders. There's also an rectangle in the middle of the form, and that's the main problem, because i can't figure out how to make the ball's bounce off the rectangle. I already started doing something but the balls just bounce off at some random places in the form.

Task: Create JFrame (Done) Create 5 Balls, which move around and spawn in random positions (Done) Create a Rectangle in the middle of the form (Done) Make the balls bounce off the rectangle. (Need help)

Here is my code.

package lv.jak.viksna;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Main extends JPanel {

Random rn = new Random();
int blueX = rn.nextInt(650) + 1;
int blueY = rn.nextInt(650) + 1;

int redX = rn.nextInt(650) + 1;
int redY = rn.nextInt(650) + 1;

int yellowX = rn.nextInt(650) + 1;
int yellowY = rn.nextInt(650) + 1;

int greenX = rn.nextInt(650) + 1;
int greenY = rn.nextInt(650) + 1;

int magentaX = rn.nextInt(650) + 1;
int magentaY = rn.nextInt(650) + 1;

int blueAngleX = rn.nextInt(10) + 1;
int blueAngleY = rn.nextInt(20) + 1;

int redAngleX = rn.nextInt(10) + 1;
int redAngleY = rn.nextInt(50) + 1;

int yellowAngleX = rn.nextInt(40) + 1;
int yellowAngleY = rn.nextInt(50) + 1;

int greenAngleX = rn.nextInt(30) + 1;
int greenAngleY = rn.nextInt(20) + 1;

int magentaAngleX = rn.nextInt(20) + 1;
int magentaAngleY = rn.nextInt(50) + 1;

int rectX = 325, rectY = 325, rectW = 100, rectH = 100;

int speed = 5;

private void move() {

    rectContact();

    if (blueX + blueAngleX < 0) {
        blueAngleX = speed;
    } else if (blueX + blueAngleX > getWidth() - 30) {
        blueAngleX = -speed;
    } else if (blueY + blueAngleY < 0) {
        blueAngleY = speed;
    } else if (blueY + blueAngleY > getHeight() - 30) {
        blueAngleY = -speed;
    }

    blueX = blueX + blueAngleX;
    blueY = blueY + blueAngleY;

    ///////////////////////////////////////////////////////////////////////////////////////////

    if (redX + redAngleX < 0) {
        redAngleX = speed;
    } else if (redX + redAngleX > getWidth() - 30) {
        redAngleX = -speed;
    } else if (redY + redAngleY < 0) {
        redAngleY = speed;
    } else if (redY + redAngleY > getHeight() - 30) {
        redAngleY = -speed;
    }

    redX = redX + redAngleX;
    redY = redY + redAngleY;

    ///////////////////////////////////////////////////////////////////////////////////////////

    if (yellowX + yellowAngleX < 0) {
        yellowAngleX = speed;
    } else if (yellowX + yellowAngleX > getWidth() - 30) {
        yellowAngleX = -speed;
    } else if (yellowY + yellowAngleY < 0) {
        yellowAngleY = speed;
    } else if (yellowY + yellowAngleY > getHeight() - 30) {
        yellowAngleY = -speed;
    }

    yellowX = yellowX + yellowAngleX;
    yellowY = yellowY + yellowAngleY;

    ///////////////////////////////////////////////////////////////////////////////////////////

    if (greenX + greenAngleX < 0) {
        greenAngleX = speed;
    } else if (greenX + greenAngleX > getWidth() - 30) {
        greenAngleX = -speed;
    } else if (greenY + greenAngleY < 0) {
        greenAngleY = speed;
    } else if (greenY + greenAngleY > getHeight() - 30) {
        greenAngleY = -speed;
    }

    greenX = greenX + greenAngleX;
    greenY = greenY + greenAngleY;

    ///////////////////////////////////////////////////////////////////////////////////////////

    if (magentaX + magentaAngleX < 0) {
        magentaAngleX = speed;
    } else if (magentaX + magentaAngleX > getWidth() - 30) {
        magentaAngleX = -speed;
    } else if (magentaY + magentaAngleY < 0) {
        magentaAngleY = speed;
    } else if (magentaY + magentaAngleY > getHeight() - 30) {
        magentaAngleY = -speed;
    }

    magentaX = magentaX + magentaAngleX;
    magentaY = magentaY + magentaAngleY;

}

public void rectContact() {

    if (blueY + 30 >= rectY && (blueX >= rectX - 25 && blueX <= rectX)
            || (blueY >= rectY + 100 && (blueX >= rectX && blueX <= rectX + 100))) {
        blueAngleX = -speed;
    }
    if (blueX + 10 >= rectX && (blueY >= rectY && blueY <= rectY - 25)
            || (blueX >= rectX && (blueY >= rectY && blueY <= rectY))) {
        blueAngleY = -speed;
    }

}

@Override
public void paint(Graphics g) {
    super.paint(g);
    g.setColor(Color.BLUE);
    g.fillOval(blueX, blueY, 30, 30);

    g.setColor(Color.RED);
    g.fillOval(redX, redY, 30, 30);

    g.setColor(Color.YELLOW);
    g.fillOval(yellowX, yellowY, 30, 30);

    g.setColor(Color.GREEN);
    g.fillOval(greenX, greenY, 30, 30);

    g.setColor(Color.MAGENTA);
    g.fillOval(magentaX, magentaY, 30, 30);

    g.setColor(Color.RED);
    g.fillRect(rectX, rectY, rectW, rectH);
}

public static void main(String[] args) throws InterruptedException {

    JFrame frame = new JFrame("Moving Ball!");
    Main main = new Main();
    frame.add(main);
    frame.setBounds(300, 0, 750, 750);
    frame.setVisible(true);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    while (true) {
        main.move();
        main.repaint();
        Thread.sleep(10);
    }
}

}

Program won't run properly

So I wrote this program but for some reason my else statement won't work. If i input "e" for example my program will simply crash... when its actually supposed to return "Invalid Input" Can someone please help me?

=========================================================================

import java.util.Scanner;

public class AbsValue2 {
  public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  System.out.println("Enter a number:");
  String num = input.nextLine();
  Double num2 = new Double(Double.parseDouble(num));
  Double abs_val = new Double(Math.sqrt(num2 * num2));

  if (num.matches("[+-]?[\\d]+[.]*"))
    System.out.println("The absolute value of " + num + " is |" + abs_val + "|");
  else if (num.matches("[+-]?[\\d]*.[\\d]+"))
    System.out.println("The absolute value of " + num + " is |" + abs_val + "|");
  else
    System.out.println("Invalid input");

  }
}

how can I add a condition that will display an error if the username already taken or exist

how can I add a condition that will display an error if the username already taken or exist please help me :(

how can I add a condition that will display an error if the username already taken or exist please help me :(

how can I add a condition that will display an error if the username already taken or exist please help me :(

how can I add a condition that will display an error if the username already taken or exist please help me :(

This is my code

<?php
include '../connect.php';
?>

<?php
if(isset($_POST['register'])){

$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$email = $_POST['email'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$bday = $_POST['bday'];
$contact = $_POST['contact'];
$address = $_POST['address'];
$licenseno = $_POST['licenseno'];
$gender = $_POST['gender'];
$picture = $_POST['picture'];
$avail = $_POST['availability'];

if(empty($username)||empty($email)||empty($password)||empty($password2)||empty($fname)||empty($lname)||empty($bday)||empty($contact)||empty($address)||empty($licenseno)||empty($gender)){
    $msg="*PLEASE FILL IN REQUIRED FIELDS*";
    header('Location:RegisterT.php?msg='.$msg.'');
}
else{

     if($password != $password2){
         $msg="Password Mismatch!";
         header('Location:registerT.php?msg='.$msg.'');
         }
     else{

         mysql_query("INSERT INTO therapist (`id`, `username`, `email`, `password`, `fname`, `lname`, `bday`, `contact`, `address`, `licenseno`, `gender`, `picture`, `about`, `availability` )VALUES
         ('', '$username','$email','$password','$fname','$lname','$bday','$contact','$address','$licenseno','$gender','default.jpg','Currently no information to show','Available')");
         $msg="Registration Successful";
         header('Location:LoginT.php?msg='.$msg.'');

    }
}

}

?>

VBA script for if-else

My columns look like these for Column G, need a if else script: Column G Complete Complete In progress Not Started Complete

A script to Convert all Complete values to 'Y' otherwise 'N'

How to find the median of five user-input numbers without using array?

The title pretty much sums up my question. How do I find the median of five user-input numbers without using arrays?

The only way I can think of doing this is by using multiple if-statements. Even then, I wouldn't be quite sure where to start with that.

Any help or advice would be appreciated, thank you!

If statement to compare if lastName starts with letters A-L

function checkFirstLetterOfLastName() {
  if(lastname.startsWith (A-L)) {
  message.textContent `enter code here`= 'Go stand in first line.';
 } else message.textContent = 'Go stand in second line.'
}

I need help with this code.

AutoFilter via IF and multiple critera

This is my first post on this site so hoping to find an answer. I have an Excel form that users can fill out and click "Run Report". The report will grab data from a master tab and paste it on another tab. This is accomplished via an IF statement and auto filter. At the time, I had two fields and users could select either Field 1, Field 2, or both. Depending on the inputs, the formula would auto filter data appropriately.

Now, status codes have been incorporated to the form. I have created check boxes (form control, not activex) and linked the box to a cell. If the box is checked, the cell updates to "True", if it's not checked the cell shows "false".

I am looking to write an IF statement that auto filters the master data and pastes it onto a new sheet. Cell E9 and E13 (Sheet: Search Form) are drop downs (data validation). The check boxes are linked in Column S (S1-S23 - on Sheet: Search Form). I need the IF statement that auto filters the data (Sheet All Call Center Detail) in Column 6 by any value in E9, auto filter Column 7 by any value in E13, and auto filter Column 13 by any TRUE cells in S:S (Column S is on the Search Form sheet).

Please ask any questions as I know my explanation is a bit overwhelming. Here is the code:

Sub Add_Sheet()

Dim LastRow As Long
Dim Rng As Range
Dim Rng1 As Range
Dim Rng2 As Range
Dim i As Long, wsName As String, temp As String

Sheets("All Call Center Detail").Select
LastRow = Sheets("All Call Center Detail").Cells(Rows.Count, 1).End(xlUp).Row
Set Rng = Range("A1:BT" & LastRow)

Sheets("Search Form").Select
Set Rng1 = Range("E9")
Set Rng2 = Range("E13")

Sheets.Add After:=ActiveSheet
ActiveSheet.Name = ("Results")

Sheets("All Call Center Detail").Select

If Not Rng1 = "" And Not Rng2 = "" And Not Rng3 = "False" Then

    Sheets("All Call Center Detail").Select
    Rng.AutoFilter Field:=6, Criteria1:=Rng1
    Rng.AutoFilter Field:=7, Criteria1:=Rng2
    Rng.SpecialCells(xlCellTypeVisible).EntireRow.Copy Sheets("Results").Range("A1")

    ElseIf Rng1 = "" Then
    Sheets("All Call Center Detail").Select
    Rng.AutoFilter Field:=7, Criteria1:=Rng2
    Rng.SpecialCells(xlCellTypeVisible).EntireRow.Copy Sheets("Results").Range("A1")

    ElseIf Rng2 = "" Then
    Sheets("All Call Center Detail").Select
    Rng.AutoFilter Field:=6, Criteria1:=Rng1
    Rng.SpecialCells(xlCellTypeVisible).EntireRow.Copy Sheets("Results").Range("A1")

End If

Sheets("All Call Center Detail").Activate
Range("A1").Select
Application.CutCopyMode = False
Selection.AutoFilter

Sheets("Results").Activate
ActiveSheet.Columns.AutoFit
wsName = Format(Date, "mmddyy")

    If WorksheetExists(wsName) Then
    temp = Left(wsName, 6)
    i = 1
    wsName = temp & "_" & i
    Do While WorksheetExists(wsName)
    i = i + 1
    wsName = temp & "_" & i
    Loop
    End If

ActiveSheet.Name = wsName
Range("A1").Select

End Sub

Will `&&` always run before `if` on the same line in Ruby

Will every && run before if on the same line in Ruby?

For example:

@building.approved = params[:approved] if xyz && abc && mno...

Can an unlimited number of && be used on the right side of an if without using parentheses?

I'm inclined to use parentheses but I'd like to understand the default behaviour.

iMacro if/else in deleting photos

I'm trying to delete TONS of pictures per link (thousands) and I was wondering if there's a way for iMacros to delete the images without me having to extract each image form per page (as they would be too many) and if in case the page doesn't have the "Delete Photo" button (signifying all pictures have been deleted), it would close the tab and move on to the next tab.

Here's my code, when done normally:

VERSION BUILD=8970419 RECORDER=FX
TAB T=1
TAG POS=1 TYPE=BUTTON FORM=ID:image-form-493720 ATTR=NAME:delete
TAG POS=1 TYPE=BUTTON FORM=ID:image-form-493721 ATTR=NAME:delete
TAG POS=1 TYPE=BUTTON FORM=ID:image-form-493722 ATTR=NAME:delete
TAG POS=1 TYPE=BUTTON FORM=ID:image-form-493723 ATTR=NAME:delete
TAG POS=1 TYPE=BUTTON FORM=ID:image-form-493724 ATTR=NAME:delete
TAG POS=1 TYPE=BUTTON FORM=ID:image-form-493725 ATTR=NAME:delete
TAG POS=1 TYPE=BUTTON FORM=ID:image-form-493726 ATTR=NAME:delete

Any help would be greatly appreciated.

how to improve performance of my (if-statment) in matlab

I have the following code in my Matlab function which runs 8 million times. each line takes about two seconds. is there a way to improve this?

result = msum(row_end, col_end);
if row_start  ~= 1
    result = result - msum(row_start - 1, col_end);
end
if col_start  ~= 1
    result = result - msum(row_end, col_start - 1);
end
if row_start ~=1 && col_start ~= 1
    result = result + msum(row_start - 1, col_start - 1);
end

How does the ternary operator work internally?

I know that

int opening_time = (day == SUNDAY) ? 12 : 9;

is the same as

int opening_time;
if (day == SUNDAY){
    opening_time = 12;
}else{
    opening_time = 9;
}

but what is(written in c#)

if (new Random().NextDouble() >= 0.5 ? true : false)    {
}

the syntax sugar for? I know that the latter code is redundant but it's a question of understanding and i can't figure out in what other form it could be written. Thanks in advance.

Java: IDE indicates that my if else statement is redundant and I need an explanation to why

I am a beginner in programming. The Netbeans IDE is indicating that this if-else statement is redundant:

public boolean x = false;

private void add_labelMouseClicked(java.awt.event.MouseEvent evt) {                                       

    jPanel2.setVisible(x);
        if(x==false){
            x=true;
        }else
            x=false;
}         

And if I correct this if-else statement using the IDE it turns the code into this:

public boolean x = false;

private void add_labelMouseClicked(java.awt.event.MouseEvent evt) {                                       

    jPanel2.setVisible(x);
       x = x == false;
} 

I need a simple explanation on the second code and how come it has a similar function to the first code. Sorry for my bad English.

Optimize if -else statement

I am writing a query for searching records from db. I pass 3 values to the method . I want to write my query in such a way that condition for that column is appended in the query whose passed corresponding value is non-null. I have ended up with messy if else statements. Is there a way to optimize it.

if(StringUtils.isNotEmpty(projectId)){
      sql.append(" UPPER(CIRC.PROJECT_ID) like ?");
  }

    if(StringUtils.isNotEmpty(circuitId)){
      if(StringUtils.isNotEmpty(projectId)){
          sql.append(" AND");
      }
      sql.append("  UPPER(CIRC.CIRCUIT_ID) like ?");
  }

    if(StringUtils.isNotEmpty(orderRef)){
      if(StringUtils.isNotEmpty(projectId) || StringUtils.isNotEmpty(circuitId) ){
        sql.append(" AND");
    }
      sql.append("  UPPER(CIRC.ORDERID) like ?");
  }

    JSONArray jsonArray = new JSONArray();
    ResultSet rs = null;
    SimpleDateFormat sdf = new  SimpleDateFormat("dd-MM-yyyy");

    PreparedStatement ps = null;
    try {
        if (connection != null) {
            ps = connection.prepareStatement(sql.toString());
            if(StringUtils.isNotEmpty(projectId)){
                ps.setString(1, "%" + projectId.toUpperCase() + "%");
            }

            if(StringUtils.isNotEmpty(circuitId)) {
              if(StringUtils.isEmpty(projectId)) {
                ps.setString(1, "%" + circuitId.toUpperCase() + "%");
              } else {
               ps.setString(2, "%" + circuitId.toUpperCase() + "%");
              }
           } 

            if(StringUtils.isNotEmpty(orderRef)) {
              if(StringUtils.isEmpty(projectId) && StringUtils.isEmpty(circuitId)) {
                ps.setString(1, "%" + orderRef.toUpperCase() + "%");
              } else if (StringUtils.isEmpty(projectId) || StringUtils.isEmpty(circuitId)){
               ps.setString(2, "%" + orderRef.toUpperCase() + "%");
              } else {
                ps.setString(3, "%" + orderRef.toUpperCase() + "%");
               }
           } 

Note: This question is not a subject of orm/jdbc. Also please ignore hard coding.

Is there an advantage of non cuddled else (Stroustrup style) over cuddled else (1TBS style)?

I searched all the discussions and can't find what is the advantage of using this:

if (x < 0) {
    puts("Negative");
    negative(x);
}
else {
    puts("Non-negative");
    nonnegative(x);
}

over this:

if (x < 0) {
    puts("Negative");
    negative(x);
} else {
    puts("Non-negative");
    nonnegative(x);
}

Why isn't the second variant considered superior to the first? What are the advantages compared to the disadvantage of having 1 more line? Why is the 1st variant used in code, where you don't have to stick with 1st variant coding style?

I am uniform with my coding style, but this (and cuddled catch) is the last remaining problem for me in that area.

If condition is not evaluated

When running, it does not match the condition.
It skips it and runs the "else" block.

Could you help me?

public class LoginActivity extends AppCompatActivity {

private EditText usern;
private EditText passw;
private Button logButton;

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

    usern = (EditText) findViewById(R.id.userNameText);
    passw = (EditText) findViewById(R.id.passwordText);
    logButton = (Button) findViewById(R.id.loginButton);

    logButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if(usern.getText().toString().equals("demo") && passw.getText().equals("demo")){
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                Toast.makeText(getApplicationContext(), "Login...", Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(getApplicationContext(), "Username or password incorrect", Toast.LENGTH_SHORT).show();
            }
        }
    });
}
}

mercredi 28 septembre 2016

How to improve the code quality to see if a string matches either one of the regex's Java

in one of my projects i need to compare the URI with several regex patterns(15+ regex patterns). Currently i have used a if ladder to see if either one of them gets matched and there onward the logical part of the code is executed.

Glimpse of the code now

         if (uri.matches(Constants.GET_ALL_APIS_STORE_REGEX)) {    
            long lastUpdatedTime = InBoundETagManager.apisGet(null, null, tenantDomain, null);
            String eTag = ETagGenerator.getETag(lastUpdatedTime);
            if (eTag.equals(ifNoneMatch)) {
                message.getExchange().put("ETag", eTag);
                generate304NotModifiedResponse(message);
            }
            message.getExchange().put("ETag", eTag);
        } else if (uri.matches(Constants.GET_API_FOR_ID_REGEX)) {   //        /apis/{apiId}
            apiId = UUIDList.get(0);
            String requestedTenantDomain = RestApiUtil.getRequestedTenantDomain(tenantDomain);
            long lastUpdatedTime = InBoundETagManager.apisApiIdGet(apiId, requestedTenantDomain, uri);
            String eTag = ETagGenerator.getETag(lastUpdatedTime);
            handleInterceptorResponse(message, ifNoneMatch, eTag);
        } else if (uri.matches(Constants.GET_SWAGGER_FOR_API_ID_REGEX)) {   //  /apis/{apiId}/swagger
            apiId = UUIDList.get(0);
            long lastUpdatedTime = InBoundETagManager.apisApiIdSwaggerGet(apiId, tenantDomain); 
            String eTag = ETagGenerator.getETag(lastUpdatedTime);
            if (lastUpdatedTime == 0L) {
                log.info("No last updated time available for the desired API swagger json file");
            }
            handleInterceptorResponse(message, ifNoneMatch, eTag);
        }........

can someone please introduce me with a more neat and clever way to doing this regex matching thing?? Any help would be much appreciated!!! thanks in advance

How can I simplify my if condition in python?

i want to know if there is a simpler way to write the condition of the if statement, something like item1, item2 == "wood":, something like that i have this code:

item1 = input("item1: ")
item2 = input("item2: ")

if item1 == "wood" and item2 == "wood":
    print("You created a stick")

How can i re-write these arrays, and vars?

I have a dropdown with three values "Divi,Extra,theme3" User selects a value, and that value is tied into this hook, which passes it on to another program. What i have below may work, however i would like to try a different way to re-write it using all the info below.

if($vars["params"]["customfields"]["theme"] === "divi") { $contentid = "4a661d4vtym88go44cwo444c0";
} else if($vars["params"]["customfields"]["theme"] === "extra") { $contentid = "cdnjaxaosao0cwko8ww08skgc"; } else if($vars["params"]["customfields"]["theme"] === "theme3") { $contentid = "2jspn9z2tkw0gcgg0wccks0c0"; } else { return; }

Checking input with an if statement (bash)

I am trying to write a file that mimics the cat -n bash command. It is supposed to accept a filename as input and if no input is given print a usage statement.

This is what I have so far but I am not sure what I am doing wrong:

#!/bin/bash
echo "OK"
read filename
if [ $filename -eq 0 ]
then 
    echo "Usage: cat-n.sh file"
else
    cat -n $filename
fi

WP - displaying posts in a category easier way to code

Hi I would like to find an easier way to code my block below. I am doing if statements on categories based on post type, then spitting out posts including titles/featured image /content. Wondering if there is an easier way with a for loop - looping through an array or similar?

Currently it is:

        if(in_category('hoses-posts')){
            $args = array( 'post_type' => 'hoses_posts' , 'category_name' => 'hoses-posts' , 'order' => 'ASC', 'posts_per_page'  => 30);
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();?>
            <?php get_template_part('templates/loop-product');?>
            <?php
            endwhile;

        } elseif(in_category('hoses-isobaric')){

            $args = array( 'post_type' => 'hoses_posts' , 'category_name' => 'hoses-isobaric' , 'order' => 'ASC','posts_per_page'  => 30);
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();?>
            <?php get_template_part('templates/loop-product');?>
            <?php
            endwhile;

        } elseif(in_category('hoses-braid')){

            $args = array( 'post_type' => 'hoses_posts' , 'category_name' => 'hoses-braid' , 'order' => 'ASC','posts_per_page'  => 30);
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();?>
            <?php get_template_part('templates/loop-product');?>
            <?php
            endwhile;

        } elseif(in_category('hoses-spiral')){

            $args = array( 'post_type' => 'hoses_posts' , 'category_name' => 'hoses-spiral' , 'order' => 'ASC','posts_per_page'  => 30);
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();?>
            <?php get_template_part('templates/loop-product');?>
            <?php
            endwhile;

        } elseif(in_category('hoses-speciality')){
          and so on....
        }

If/else with blood types

Beginner here. I am supposed to write a program that takes as input his blood type, and the blood type of his prey and outputs whether they are safe to consume. From the chart: http://ift.tt/2dALkUs The vampire is the recipient and the prey is the donor.

If/else statements are the first thing that came to mind. I am unsure how to determine the two blood types in an if else after i determined that the blood type at least had A,B,O in it. If someone could explain to me the steps, I would appreciate it a bunch.

import java.util.Scanner; 



public class Hw2pr6 {

public static void main(String[] args)
{

    String vampBlood, bloodEat;


    Scanner keyboard = new Scanner (System.in);

    System.out.print("\tWhat is the vampire's blood type? ");
    vampBlood = keyboard.nextLine();

    System.out.print("\tWhich blood type is on the menu today? ");
    bloodEat = keyboard.nextLine();


    if (bloodEat.contains("A") || bloodEat.contains("O") || bloodEat.contains("B")) {

        if (vampBlood == "AB+"){

            System.out.print ("Safe to consume!");

        }

        if (vampBlood == "AB-"){

            System.out.print ("Safe to consume!");

        }

        if (vampBlood == "A+"){

            System.out.print ("Safe to consume!");

        }

        if (vampBlood == "A-"){

            System.out.print ("Safe to consume!");

        }



    }

    else 

    {
        System.out.print ("That is not a valid blood type.\n");
    }

}

}

How do I fix an if statement saying it's false when it's true?

So what happens is when the app goes to the background it goes to a link and copies it's HTML contents. After that it keeps checking that page until the contents are not true. Although what happens is it says it's false even though it's not. I used some break points to check and the two values are indeed the same. I'm not sure why it's not working. Here's the code.

- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
NSURL *urll = [NSURL URLWithString:@"http://ift.tt/2daMPug"];
NSString *content1 = [NSString stringWithContentsOfURL:urll encoding: NSStringEncodingConversionAllowLossy error:nil];

while (_GO == true)
{
    NSURL *urlll = [NSURL URLWithString:@"http://ift.tt/2daMPug"];
    NSString *content = [NSString stringWithContentsOfURL:urlll encoding: NSStringEncodingConversionAllowLossy error:nil];
    sleep(3);
    if (content1 != content) {
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        localNotification.fireDate = [[NSDate alloc]initWithTimeIntervalSinceNow:1];
        localNotification.alertBody = @"New Little Hoot To Read!";
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
        _GO = false;
    }
}}

How to test whether a variable is equal to one of five Array Values

I am storing five values in an array and I need to check whether a variable I've set up is equal to one of those values. Here is what I mean:

var x = e.clientX, // horizontal mouse position
myArray = []; // I have another function that stores five values in this array

if(x == /*one of the five array values*/){
    //do something
}

Thanks...

someone gave me a code can someone please explain it to me [on hold]

someone gave me this code and it worked with me but I didn't understand the code very well

the z1 ,z2 and z3 are pictures (I don't want an explanation for the them) i just want an explanation for the job of (if statement) and the variable here how did he use them, what is there job?

var firstClick = true;

$('.button').click(function() {
    if (firstClick){
        $('.z1').replaceWith($z2);
        firstClick = false;

    }else{
        $('.z2').replaceWith($z3);    
        firstClick = true;

    }
});

Excel multiple If(Isnumber (search)

Can you do multiple =IF(ISNUMBER(SEARCH)) in Excel? I would like a single formula to look at several text strings and give a result if one of various words are in that string.

For example if I had below items on the left - I would want an equation to give the results on the right. I used =IF(ISNUMBER(SEARCH("1pc",A1)),"1 Pc","") and it pulled the 1 Pc I was looking for but how do I pull the other items like 2 Pc or Set?

Floral 1pc                         1 Pc
Floral 1pc                         1 Pc
1pc w/bow                          1 Pc
Pink Heart  Set                        Set
Pink Heart  Set                        Set
Multi Mini Heart 2pc w/bow         2 Pc
Multi Mini Heart 2pc w/bow         2 Pc

I am trying to build a basic calculator using if statements

I am trying to make a basic calculator for class I came up with the code below but all it does it addition. even if I use -, *, or /. Any tips?

Scanner input = new Scanner(System.in); String num1, num2, operation, function;

    System.out.println("Enter a simple equation: ");
    function = input.nextLine();
    int firstspace = function.indexOf(" ");
    num1 = (function.substring(0,firstspace));
    int lastspace = function.lastIndexOf(" ");
    operation = (function.substring(firstspace,lastspace));
    num2= (function.substring(lastspace+1,function.length()));
    double n1 = Double.parseDouble(num1);
    double n2 = Double.parseDouble(num2);



    if (operation.equals(" + "));
    {
        System.out.println("your answer is " + (n1 + n2));
    }
    if  (operation.equals(" - "))
    {
        System.out.println("your answer is " + (n1 - n2));
    }

    if (operation.equals(" / "))
    {
        System.out.println("your answer is " + (n1 / n2));
    }
    if (operation.equals(" * "))
    {
        System.out.println("your answer is " + ( n1*n2));
    }

}

}

Nested IF...THEN...ELSE in GW-BASIC

I use following block of code to test some conditions in gw-basic program.

IF Average >= 80 AND Average <= 100 THEN Grade$ = "A"
IF Average >= 70 AND Average <= 79 THEN Grade$ = "B"
IF Average >= 60 AND Average <= 69 THEN Grade$ = "C"
IF Average >= 50 AND Average <= 59 THEN Grade$ = "D"
IF Average >= 40 AND Average <= 49 THEN Grade$ = "E" ELSE Grade$ = "F"  
PRINT "Average is: ", Average
PRINT "Grade is: ", Grade$

It always prints Grade is: F whatever is the value of Àverage.

What is the error in this gw-basic program?

Change last digit of a number

I'm learning C# and one of my assignments is to aks for a number, then ask for a single digit and let the program see if the single digit is the last digit of the previously given number (eg number 1647, last digit 7) Then the program has to display the original number but with the last digit either red if the digit given is incorrect, green if the digit entered is correct. So;

number: 1647 digit: 7 1647(7 is green)

number: 1647 digit: 3 1647(7 is red)

So how do I only get the last digit to change color?

if statement producing gibberish output

I have a java assignment that is asking for a code that tells the user to enter a point (row and column or x and y) and the program outputs all possible moves for the chess' knight.

package datastructureass1;
import java.util.Scanner;

public class DataStructureAss1 {

    public static void main(String[] args) {
       Scanner cin = new Scanner (System.in);
        
        int knight[][]= new int [7][7];
            
                     System.out.println("Please enter the knight's position starting with rows followed by columns");
                       int i=cin.nextInt();      
                       int j=cin.nextInt();
                        
                        i=i+2;
                        j=j+1;
                        if (i<=8&&j<=8)
                     
                           System.out.println( "{"+knight[i]+","+knight[j]+"}");
                       
                        i= i+2;
                        j=j-1;
                        if (i<=8&&j<=8);
                            System.out.println( "{"+knight[i]+","+knight[j]+"}");
                            
                        i= i-2;
                        j=j+1;
                        if (i<=8&&j<=8);
                            System.out.println( "{"+knight[i]+","+knight[j]+"}");
                        i= i-2;
                        j=j-1;
                        if (i<=8&&j<=8);
                            System.out.println( "{"+knight[i]+","+knight[j]+"}");   
                            
                        i= i+1;
                        j=j+2;
                        if (i<=8&&j<=8);
                            System.out.println( "{"+knight[i]+","+knight[j]+"}");
                        i= i+1;
                        j=j-2;
                        if (i<=8&&j<=8);
                            System.out.println( "{"+knight[i]+","+knight[j]+"}");
                        i= i-1;
                        j=j+2;
                        if (i<=8&&j<=8);
                            System.out.println( "{"+knight[i]+","+knight[j]+"}");    
                        i= i-1;
                        j=j-2;
                        if (i<=8&&j<=8);
                            System.out.println( "{"+knight[i]+","+knight[j]+"}");
                         
    }
                            
                 }
                 
            
        
       

when i run this in netbeans it gives me this kind of output: {[I@6ac1abcf,[I@6ac1abcf}

{[I@50f6d9ca,[I@7e54864c}

{[I@6ac1abcf,[I@6ac1abcf}

{[I@5f3d285f,[I@7e54864c}

{[I@7e54864c,[I@2825a5d2}

{[I@6ac1abcf,[I@7e54864c}

{[I@7e54864c,[I@2825a5d2}

it doesnt make sense and i dont know what i did wrong in my code!

Nested if in While loop

I am having some trouble getting my while loop to reiterate when executed. The if statements work as expected but the char value returned from the scanner isn't getting to my while loop. Anyone know what I did wrong or a better solution to my program?

Thanks for any help!

package classWork;
import java.util.Scanner;

public class project_2 {
    public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        int choice = 0;
        double celsius, fahrenheit, inches, centimeters;
        char doAgain = 'y';

        while (doAgain == 'y' || doAgain == 'Y')
        {

        System.out.print(" Main Menu \n 1. Celsius to Fahrenheit \n 2. Inches to Centimeters \n"
                + "Please select either 1 or 2 \nThen press enter to continue");
        choice = input.nextInt();


        if (choice == 1)
        {
            System.out.println("This program will convert a celsius value into a fahrenheit one. \n");

            System.out.println("Please enter the tempature for conversion: ");
            celsius = input.nextInt();

            fahrenheit = 1.8 * celsius + 32.0;

            System.out.println(celsius + " degree(s) in celcius" + " is " + fahrenheit + 
                    " in fahrenheit. \n");

            System.out.println("Do you want to continue?\n: " +
                       "enter a \'y \' for another round\n " +
                      " enter a\'n\'   to end the program\n");

            doAgain = input.next().charAt(0);

            input.close();
            return;
        }

        if (choice == 2)
        {
            System.out.println("This program will convert inches to centimeters. \n");


            System.out.println("Please enter the length for conversion: ");
            inches = input.nextInt();


            centimeters = 2.54 * inches;


            System.out.println(inches + " inches is " + centimeters + " centimeters. \n");

            System.out.println("Do you want to continue?\n: " +
                       "enter a \'y \' for another round\n " +
                      " enter a\'n\'   to end the program\n");

            doAgain = input.next().charAt(0);

            input.close();
            return;
        }

        else
        {
            System.out.println("That is not a valid option. Please restart and try again");
            input.close();
            }
        }
    }
}