lundi 29 février 2016

display child posts based on category terms

I have a custom post type named city guide . The child post articles are displayed within the parent page.Child posts has custom category named as newyork and paris.

<div class="container">
<?php while( have_posts() ): the_post();  ?>
<div class="row main-content-wrap">
  <div class="col-md-12 long-post-sections-wrapper">
<?php while( $city_guide->have_posts() ): $city_guide->the_post(); 
$terms = get_the_terms( $post->ID , 'city-guide-cities-category' );
 // Loop over each item since it's an array
 if ( $terms != null ){
 foreach( $terms as $term ) {
 // Print the name method from $term which is an OBJECT
 print $term->name ;

} }
 ?> 

<div <?php post_class('city-guide-row row' . classes_related($wp_query->current_post) ); ?>>
    <div class="col-sm-8">
        <h3 id="<?php echo esc_attr( get_post()->post_name ); ?>"><?php the_title(); ?></h3>

        <?php the_post_thumbnail(); ?>
        <div class="img-caption"><?php echo get_post(get_post_thumbnail_id())->post_excerpt; ?></div>
        <?php the_content(); ?>
    </div>

    <div class="col-sm-4 map-container">

        <!-- google map -->
        <div class="map-wrapper">
            <div class="mobile-map-overlay" onClick="style.pointerEvents='none'"></div>
            <iframe frameborder="0" scrolling="no" marginheight="0" marginwidth="0"width="100%" height="260" src="http://ift.tt/1TjDj7E echo get_field('address',get_the_ID()); ?>&ie=UTF8&t=roadmap&z=6&iwloc=B&output=embed&z=16"></iframe>
        </div>

        <h5>Address</h5>
        <?php echo get_field('address'); ?><br/>
        <?php echo get_field('address_2'); ?>

        <h5>Contact</h5>
        <?php if(get_field('contact_number')): 
            echo '<a href="tel:' . get_field('contact_number') . '">' . get_field('contact_number') . '</a>';
        endif; ?><br/>
        <?php if(get_field('website')): 
            echo '<a href="' . get_field('website') . '" target="_blank">' . get_field('website') . '</a>';
        endif; ?><br/>
        <?php if(get_field('email')): 
            echo '<a href="mailto:' . get_field('email') . '">' . get_field('email') . '</a>';
        endif; ?>

    </div>
    <div class="clearfix"></div>
<hr class="city-row-separator"/>
<?php endwhile; ?>
</div>
</div>
<?php endwhile; ?>

I have printed print $term->name ; inside while so each child article is showing its own categories.

What i want to achieve is display newyork posts first and then paris.

if ( $term->name == 'newyork'){

}
elseif ( $term->name == 'paris'){

}

did not result what i expected.how can I achieve ?Please help

javascript clarification for handling null values

Ok i have little section of javascript syntax and i am very confuse how null behaves. There is a lot of discussion about null values but i cant seem to figure out the problem! Please help me. Here is the script.

var jsonData = '<?php echo $jsonData;?>';


    if (jsonData)
    {           
        console.log('jsonData is '+ jsonData);// null or not this section is always executed! why?
    }else{
        ini(jsonData);
    }

I tried using '===', '!' operators but still not working as expected

If statement to check if variable landed on 2 numbers out of 10

I tried this code, but I'm getting an error. What is an alternative to this?

int chance = rand.Next(1, 11);

if (chance == 1 || 10)
{
    string win = "lose";
}

This is in C#

VBA IF Then statements using string variables

I am working out an problem for my programming class and was wondering if I could get some help. The code below is supposed to do calculate a discount for specific model numbers (AX1 and SD2) at 10% off. All other inputs are to be discounted at 5%. What happens now with the code is just a flat message box with the original entered price.

Private Sub DiscountCalc_Click()

Dim strModelNum As String
Dim curOrigPrice As Currency
Dim sngRate As Long
Dim curDiscount As Long
Dim curNewPrice As Currency


strModelNum = InputBox("Enter desired model number", "Price Lookup")
strModelNum = UCase(strModelNum)

curOrigPrice = InputBox("Enter the original Price", "Price Lookup")
sngRate = 0.1
curDiscount = 0.05


If strModelNum = "AX1" Then
  curNewPrice = curOrigPrice - (curOrigPrice * sngRate)
Else
If strModelNum = "SD2" Then
  curNewPrice = curOrigPrice - (curOrigPrice * sngRate)
Else
    curNewPrice = curOrigPrice - (curOrigPrice * curDiscount)
End If
End If

   MsgBox curNewPrice



End Sub

Thank you!

I cannot get my if statement to loop correctly

I am trying to prompt the user if the information they entered is correct and the program just proceeds anyway instead of re-prompting the user. I think i need to change how I loop this do some type of do-while loop, but I don't quite know what to do.

{

    //Here we will set up our method of data entry and decimal format
    Scanner keyboard = new Scanner(System.in);
    DecimalFormat eNotation1 = new DecimalFormat("00.00");

    //Let's introduce our program to the user
    System.out.println("Hi, This is a program to calculate quarterly interest growth");

    //Here we will prompt the user to enter the amount of quarters
    System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
    int quarterNumber = keyboard.nextInt();
    if (quarterNumber > 10 || quarterNumber < 0)
    {
    System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 0 and 10 (number can include 10)");
    System.exit(0);
    }

    //Here we will prompt the user for the starting balance.
    System.out.println("What is the starting balance of this account?");
    double startingBalance = keyboard.nextDouble();

    //Here we will prompt the user for the interest rate
    System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
    double interestRate = keyboard.nextDouble();
    if (interestRate < 1 || interestRate > 20)
    {
    System.out.println("You entered a number outside of the boundrys. Please run the program again and choose a number between 1 and 20 (can include 1 and 20)");
    System.exit(0);
    }

    //Here we will double check with the user that the info is correct.
    System.out.println("The amount of quarters you would like displayed is " + quarterNumber);
    System.out.println("The starting balance you would like to work with is " + startingBalance);
    System.out.println("The interest rate in your area is " + interestRate);
    System.out.println("Is this information correct?");
    keyboard.nextLine();
    String answer = keyboard.nextLine();
    System.out.println("");

    //We will have them enter the information again if the answer is no or No
    if (answer == "no" || answer == "No")
    {
    //Here we will prompt the user to enter the amount of quarters
    System.out.println("How many quarters would you like to display? Please pick a number greater than zero and less than or equal to 10");
    keyboard.nextInt();
    quarterNumber = keyboard.nextInt();

    //Here we will prompt the user for the starting balance.
    System.out.println("What is the starting balance of this account?");
    keyboard.nextDouble();
    startingBalance = keyboard.nextDouble();

    //Here we will prompt the user for the interest rate
    System.out.println("What is the interest rate (in percent) in your area? Please pick a number from 1 - 20.");
    keyboard.nextDouble();
    interestRate = keyboard.nextDouble();
    }

    //Next we will proceed with the calculation if the information is indeed correct
    double endingBalance = startingBalance + (startingBalance * (interestRate / 100 * .25));
    double interestEarned = endingBalance - startingBalance;

    //Now we will output the information
    for (int qn = 1; qn < (quarterNumber + 1); qn++ , startingBalance = startingBalance + interestEarned , endingBalance =startingBalance + (startingBalance * (interestRate / 100 * .25)), interestEarned = endingBalance - startingBalance )
    {
    System.out.println("Quarter Number                      Starting Balance                      Interest Earned                           Ending Balance   ");
    System.out.println(qn + "                                   " + eNotation1.format(startingBalance) + "                                " + eNotation1.format(interestEarned) + "                                      " + eNotation1.format(endingBalance) + "   ");                
    }   


 }

}

Panel using stored procedure - Code not reacting as expected

I have hit a small issue and hoping someone might be able to assist. I am using a panel - On the page load, it should list all the products as no category has been selected as per stored procedure (this works perfectly).

When a user clicks on a specific category, it should only show the products that have the specific CategoryID. When I run the code in SQL, it works a dream for this part too, so assume the stored procedure is ok.

At "CategoryID = CategoryID" in GetProducts, I get "Warning: Assignment made to same variable; did you mean to assign something else?", however I am following a tutorial video and this works fine. Is there another silly error that is preventing it from working?

I think I have included all the required code - sorry if its a bit overkill!!

Thanks as ever in advance - Jack

pnlCategories

           <asp:Panel ID="pnlCategories" runat="server" ScrollBars="Auto" Height="550px" BorderColor="Black"
                                            BorderStyle="Inset" BorderWidth="1px">
                                            <asp:DataList ID="dlCategories" runat="server" BackColor="White" BorderColor="#CCCCCC"
                                                BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal"
                                                Width="252px">
                                                <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
                                                <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
                                                <ItemTemplate>
                                                    <asp:LinkButton ID="lblbtnCategory" runat="server" Text='<%# Eval("CategoryName") %>'
                                                        OnClick ="lblbtnCategory_Click" CommandArgument='<%# Eval("CategoryID") %>'></asp:LinkButton>
                                                </ItemTemplate>
                                                <SelectedItemStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
                                            </asp:DataList>
                                        </asp:Panel>        

Coding Behind pnlCategories

    private void GetProducts(int CategoryID)
    {
        ShoppingCart k = new ShoppingCart();
        {
            CategoryID = CategoryID;
        };

        dlProducts.DataSource = null;
        dlProducts.DataSource = k.GetProdcuts();
        dlProducts.DataBind();
    }

    protected void lblbtnCategory_Click(object sender, EventArgs e)
    {
        pnlBasket.Visible = false;
        pnlProducts.Visible = true;
        int CategoryID = Convert.ToInt16((((LinkButton)sender).CommandArgument));
        GetProducts(CategoryID);
    }


    public DataTable GetProdcuts()
    {
        SqlParameter[] parameters = new SqlParameter[1];
        parameters[0] = DataAccess.AddParamater("@CategoryID", CategoryID, System.Data.SqlDbType.Int, 20);
        DataTable dt = DataAccess.ExecuteDTByProcedure("mj350.GetProducts", parameters);
        return dt;
    }

ShoppingCart

    public DataTable GetProdcuts()
    {
        SqlParameter[] parameters = new SqlParameter[1];
        parameters[0] = DataAccess.AddParamater("@CategoryID", CategoryID, System.Data.SqlDbType.Int, 20);
        DataTable dt = DataAccess.ExecuteDTByProcedure("mj350.GetProducts", parameters);
        return dt;
    }

Stored Procedure - GetProducts

    IF( @CategoryID <> 0 )
        BEGIN
            SELECT * FROM    
                           (SELECT 
                           Prod.ProductID,
                           Prod.ProductName,
                           Prod.CategoryID,
                           Prod.ProductPrice,
                           Prod.ProductImageUrl,
                           Prod.ProductStock,
            -- Sum of all the products purchased
             ISNULL(Sum(SBI.ShoppingBasketItemQuantity), 0) AS ProductSold,
                           (Prod.ProductStock - ISNULL(Sum(SBI.ShoppingBasketItemQuantity), 0) ) AS AvailableStock

                    FROM   Product Prod
                           -- Join gets all the specific products which has the specifed category ID
                           INNER JOIN Category Cat ON Cat.CategoryID = Prod.CategoryID
                           LEFT JOIN ShoppingBasketItem SBI ON SBI.ProductID = Prod.ProductID

                           GROUP  BY Prod.ProductID,
                              Prod.ProductName,
                              Prod.CategoryID,
                              Prod.ProductPrice,
                              Prod.ProductImageUrl,
                              Prod.ProductStock) ProductStockTable

           --The important line of code where it specific's the ID of the products it should list        
           WHERE  AvailableStock > 0 AND CategoryID = @CategoryID

        END

      ELSE
        --If no specific Category ID has been selected, it should list for all and therfore trigger the else method as category ID is equal to 0
        BEGIN
            SELECT * FROM    
                           (SELECT 
                           Prod.ProductID,
                           Prod.ProductName,
                           Prod.CategoryID,
                           Prod.ProductPrice,
                           Prod.ProductImageUrl,
                           Prod.ProductStock,
            -- Sum of all the products purchased
             ISNULL(Sum(SBI.ShoppingBasketItemQuantity), 0) AS ProductSold,

                           (Prod.ProductStock - ISNULL(Sum(SBI.ShoppingBasketItemQuantity), 0) ) AS AvailableStock

                    FROM   Product Prod

                           INNER JOIN Category Cat ON Cat.CategoryID = Prod.CategoryID
                           LEFT JOIN ShoppingBasketItem SBI ON SBI.ProductID = Prod.ProductID


                    GROUP  BY Prod.ProductID,
                              Prod.ProductName,
                              Prod.CategoryID,
                              Prod.ProductPrice,
                              Prod.ProductImageUrl,
                              Prod.ProductStock) ProductStockTable

            WHERE  AvailableStock > 0
        END

Add an increment based on alert notification

I'm writing a TicTacToe game and I'm having trouble adding the Win Count to track how many games the X player wins and how many games the O player wins. Right now, I have the JS code with an if statement. If alert = Winner is X, then xWinCount++ but I'm not sure this is the correct way. Thanks for any and all help, I really appreciate it.

HTML Code:

<head>
<meta charset="UTF-8">
<title>Tic Tac Toe</title>
<link rel="stylesheet" href="http://ift.tt/1jAc5cP">
<link rel="stylesheet" href="http://ift.tt/1QgFFRj">
<link rel="stylesheet" href="css/altTicTacToe.css">
</head>

<body>

<div class="container">
  <div class="col-md-12 header">
  <h1 class="banner">Previous Games</h1>

  <h1 class="banner">Rules</h1>     

  <h1 class="banner-right">List of Wins</h1>
  </div>
<div class="row">
  <div class="col-md-4 nine hidden-xs red"></div><!--previous game-->

  <div class="col-md-4 hidden-xs green-bg"><!--rules + who's turn is it -->
    <p>Classic Tic-Tac-Toe game.</br></br>  Match three X's or three O's in a line vertically, horizontally or diagonally to win!</p></div>
  <div class="col-md-4 hidden-xs blue"> <!-- List of wins -->
<div class="win-chart">
 <p class="win-chart">X has won:</p><p id="xWinCount" class="xWinCount win-chart">0</p><p class="win-chart">time(s)</p></br>
 <p class="win-chart">O has won:</p><p id="oWinCount" class="xWinCount win-chart">0</p><p class="win-chart">time(s)</p>
      </div>
</div>
<div class="row">
  <div class="col-md-4 nine hidden-xs red"></div>
  <div class="col-md-4 nine" id="board">
    <div class="col-md-4 innerNine empty borderBottom col-xs-4"></div>
    <div class="col-md-4 innerNine empty borderBottom borderLeftAndRight col-xs-4"></div>
    <div class="col-md-4 innerNine empty borderBottom col-xs-4"></div>
    <div class="col-md-4 innerNine empty col-xs-4"></div>
    <div class="col-md-4 innerNine empty borderLeftAndRight col-xs-4"></div>
    <div class="col-md-4 innerNine empty col-xs-4"></div>
    <div class="col-md-4 innerNine empty borderTop col-xs-4"></div>
    <div class="col-md-4 innerNine empty borderTop borderLeftAndRight col-xs-4"></div>
    <div class="col-md-4 innerNine empty borderTop col-xs-4"></div>
  </div>
  <div class="col-md-4 hidden-xs"></div> <!--blue not needed -->
</div>
<div class="row">
  <div class="col-md-4 nine red"></div>
  <div class="col-md-4">
    <button id="newGame" class="btn btn-success btn-lg" type="button"><span class="glyphicon glyphicon-repeat"></span>Restart Game </button>
      <a href=" " button id="newGame" class="btn btn-primary btn-lg" type="button"><span class="glyphicon glyphicon-repeat"></span>Reset Scores</button></a>
  </div>
  <div class="col-md-4"> </div> <!--blue not needed -->
  </div>
  </div>
  <script src="http://ift.tt/1LdO4RA"></script>
  <script src="http://ift.tt/1jAc4pg"> 
</script>
<script src="js/altTicTacToe.js"></script>
</body>

</html>

CSS Code:

.row {
margin-top: 5px;
}
.nine, .col-md-4 {
height: 300px;
text-align: center;
}
.innerNine {
height: 100px;
text-align: center;
}
.o {
font-size: 100px;
text-align: center;
vertical-align: middle;
line-height: 100px;
padding-bottom: 10px;
}
.x {
font-size: 100px;
text-align: center;
vertical-align: middle;
line-height: 100px;
padding-bottom: 10px;
}
.green {
color: green;
}
.allBorders {
border: 1px black solid;
}
.borderBottom {
border-bottom: 1px black solid;
}
.borderTop {
border-top: 1px black solid;
}
.borderLeftAndRight {
border-left: 1px black solid;
border-right: 1px black solid;
}

/*Added classes */
p{
font-size: 24px;
}
.header{
width: 100%;
}
.banner {
display: inline;
margin-right: 225px;
}
.banner-right{
display: inline;
}
.blue {
background-color: blue;
}
.red{
background-color: red;
}

.green-bg{
background-color: green;
}

.win-chart{
display: inline;
}

JS Code:

$(document).ready(function() {

  var circleOrEx = "o"; // who gets first turn, right now circle goes first
  var isGameInProgress = true; // when the document loads, the tictactoe board is an active game
  var winningCombos = { // the game board is a series of nine square boxes, but since this is an array, the values for earch box is 0 to 8.  these values outline the winning combinations starting from each possible square on the board.  the board is writen out like this:

      // 0 | 1 | 2  
      // ---------  
      // 3 | 4 | 5
      // ---------
      // 6 | 7 | 8

    0: [ //0 is key (winning combinations starting from the top left square)
      [1, 2], //if the user enters in three of the same values across the top three squares, they win
      [3, 6], //if the user enters in three of the same values down the far left column, they win
      [4, 8]  //if the user enters in three of the same values  diagonally from the top left to bottom                       right, they win
    ],
    1: [ //(winning combinations starting from the top middle square)
      [0, 2], //if the user enters in three of the same values across the top three squares, they win
      [4, 7]  //if the user enters in three of the same values down the middle column, they win

    ],        //there are no diagonal winning combinations for values 1, 3, 5, 7 

    2: [ //(winning combinations starting from the top right square)
      [0, 1], //if the user enters in three of the same values across the top three squares, they win
      [5, 8],  //if the user enters in three of the same values down the far right column, they win
      [4, 6]   //if the user enters in three of the same values  diagonally from the top right to bottom                       left, they win
    ],
    3: [ //(winning combinations starting at the middle square on the far left column )
      [0, 6], //if the user enters in three of the same values down the far left column, they win
      [4, 5] //if the user enters in three of the same values across the middle row, they win
    ],
    4: [ //(winning combinations starting at the center square)
      [1, 8], //BUG IN THE CODE, this should not be a winning combination
      [2, 6], //if the user enters in three of the same values  diagonally from the top right to bottom                       left, they win
      [1, 7], //if the user enters in three of the same values down the middle column, they win
      [3, 5] // if the user enters in three of the same values across the middle row, they win
    ],
    5: [ //(winning combinations starting from the middle square in the far right column)
      [2, 8], //if the user enters in three of the same values down the far right column, they win
      [3, 4] // if the user enters in three of the same values across the middle row, they win
    ],
    6: [ //(winning combinations starting from the bottom left square)
      [0, 3], //if the user enters in three of the same values down the far left column, they win
      [2, 4], //if the user enters in three of the same values  diagonally from the top left to bottom                       right, they win
      [7, 8] //if the user enters in three of the same values across the bottom three squares, they win
    ],
    7: [   //(winning combinations starting from the bottom middle square)
      [1, 4],//if the user enters in three of the same values down the middle column, they win
      [6, 8] //if the user enters in three of the same values across the bottom three squares, they win
    ],
    8: [  //(winning combinations starting from the bottom right square)
      [0, 4], //if the user enters in three of the same values  diagonally from the bottom right to the top               left, they win
      [2, 5], //if the user enters in three of the same values down the far right column, they win
      [6, 7] //if the user enters in three of the same values across the bottom three squares, they win
    ]
  };

  // when the user clicks on the board, the function runs, and the game is in progress
  $("#board").find("div").on("click", function() {

    if (isGameInProgress && $(this).hasClass("empty")) { /// within the #board remove the empty class and add either an X or an O value to the square when it is is clicked
      $(this).removeClass("empty").append("<span class='" + circleOrEx + "'>" + circleOrEx + "</span"); //allows user to input X or O value in the square

      checkIfWon($(this).index(), circleOrEx); //function determines the turn cycle of the game 

      if (circleOrEx === "o") { // if O has played their turn, run code on line 68
        circleOrEx = "x"; // now it is X's turn
      } else {
        circleOrEx = "o"; // X has played their turn, now it is circle's turn
      }
    }

  });

  // once you click the button with the 'newGame' id, run the function
  $("#newGame").on("click", function() {

    var boardSquares = $("#board").find("div"); //boardSquares now becomes every div element within #board, which is each of the nine blank squares that make up the tic tac toe game
    var firstEmptyMemorySquare = $(".container").find(".nine").filter(function() { //returns a value for firstEmptyMemorySquare if the function passes these requirements place the #board within the class nine that is in the containter. (once the game clicking the refresh button, place the previous board in an empty section of the page)
      return $.trim($(this).text()) === "" && $(this).children().length === 0;
    }).not("#board").first();

    if (firstEmptyMemorySquare.length == 1) { //placing a previously played game in an EmptyMemorySquare
      firstEmptyMemorySquare.html($("#board").html());
    } else {
      $(".container").find(".nine").not("#board").empty();
      $(".container").find(".nine").first().html($("#board").html());
    }

    //deletes anything in the empty class to games that are in progress, which allows user to enter X's or O's in the boardSquares
    boardSquares.each(function() {
      $(this).addClass("empty").empty();
    })
    isGameInProgress = true;
  })

  //checks if a player won. chosenSquare is the final value in a winning combination; the possible values for the  chosenSquare parameter is [0] - [8] 
  function checkIfWon(chosenSquare) {

    var mulitArr = winningCombos[chosenSquare];
    var playerWon;

    for (var i = 0; i < mulitArr.length; i++) { //the nested loop provides the length of the multidimensional array
      playerWon = true;
      for (var j = 0; j < mulitArr[i].length; j++) { //value of j starts at zero so the user must enter three values within a winning combination.  If j initially starts at 1 user only needs to match two of the same values within a winning combination.  If j => 2 the user only needs to match one value of a winning combination (which would be any square on the board) 
        if (!$("#board").find("div").eq(mulitArr[i][j]).find("span").hasClass(circleOrEx)) { //Explain this condition
          playerWon = false;
        }
      }

      if (playerWon) { //remaining lines affect the board when a player enters a winning combination

        for (var j = 0; j < mulitArr[i].length; j++) {
          $("#board").find("div").eq(mulitArr[i][j]).find("." + circleOrEx).addClass("green"); //makes the first two inputs of the winning comination the color green
        }
        $("#board").find("div").eq(chosenSquare).find("." + circleOrEx).addClass("green"); //makes the last         input of the winning combination (chosenSquare) the color green
        alert("Winner is " + circleOrEx.toUpperCase() + "!"); //alert "Winner is X" or "Winner is O"
 var xWinCount = 0;
    var xWinCount = 0;
      if (playerWon = Ex){
          document.getElementById('xWinCount');
          var xWin = xWinCount.innerHTML;
          xWinin++;
          xWinCount.innerHTML = x-win;
          }
      else{
      document.getElementById('oWinCount');
      var oWin = oWinCount.innerHTML;
      oWin++;
      oWinCount.innerHTML = o-win;
      }
        isGameInProgress = false; //since a player has won, the game is no longer in progress
        return false; //this exits the loop
      }
    }


  }
})

check for URL Canonicalization inconsistent

I am trying to check for URL Canonicalization. It is working fine for some page while it is not working on some pages.

My code:

function getRedirect($webpage)
{
    $curlInit = curl_init($webpage);
    curl_setopt($curlInit, CURLOPT_CONNECTTIMEOUT, 20);
    curl_setopt($curlInit, CURLOPT_HEADER, true);
    curl_setopt($curlInit, CURLOPT_NOBODY, true);
    curl_setopt($curlInit, CURLOPT_RETURNTRANSFER, true);
    $response      = curl_exec($curlInit);
    $response_time = curl_getinfo($curlInit);
    curl_close($curlInit);
    return $response_time['redirect_url'];
}

function get_root_domain($url)
{
    $pattern = '/\w+\..{2,3}(?:\..{2,3})?(?:$|(?=\/))/i';

    if (preg_match($pattern, $url, $matches) === 1) {
        return $matches[0];
    }
}

function getDomain($url)
{
    $url = Trim($url);
    $url = preg_replace("/^(http:\/\/)*/is", "", $url);
    $url = preg_replace("/^(https:\/\/)*/is", "", $url);
    $url = preg_replace("/\/.*$/is", "", $url);
    return $url;
}

Main function:

$parsedUrl = get_root_domain($url);
$url_WWW = 'www.' . $parsedUrl;
$getRedirect = getRedirect($parsedUrl);
if ($getRedirect == null)
{
    // echo with or without www resolve to the same url
}
else
{
    $parsedRedirect = getDomain($getRedirect);
    if ($parsedRedirect == $parsedUrl)
    {
        // echo with or without www resolve to the same url
    }
    elseif ($parsedRedirect == $url_WWW)
    {
        // echo with or without www resolve to the same url
    }
    else
    {
        // echo with or without www DOES NOT resolve to the same url.
    }
}

I have tried modifying the first if statement to this:

if ($get_redirect == null)
{
    $get_redirect_url = get_redirect($url_WWW);
    $get_redirect_url = getDomain($get_redirect_url);
    if ($get_redirect_url == $url_WWW)
    {
        // echo with or without www DOES NOT resolve to the same url.
    }
    else
    {
        // echo with or without www resolve to the same url
    }
}

but I get the same inconsistent result.

If statements combined with lookups and corresponding calculations

Ok, so I am wanting to create a spreadsheet that allows me to calculate food macros automatically once I input the food and serving size. I have a table that has the food list and then the corresponding, proteins, carbs, fats, cals and then the serving size. What I want to happen is once I provide the food and the serving size, a function will look up and food from the table and calculate the individual macros based on what corresponds to the correct food.

Basically, if the value I enter in A2 is found in H2, divide the serving size that corresponds to h2 by the serving size corresponding to a2 and then multiply it by the macro value corresponding to h2. I have attached a picture so to hopefully show what I am attempting to do. Thank you for any help you can provide!!!

enter image description here

Scanner input == null?

I am trying to say if you enter a character it will do this; else if scanner input == null do this instead. I'm not getting any syntax errors, I just need to know how to word this so that if you don't enter any characters and hit ENTER then it will go to my default settings. Here is what I have so far.

Shape sq = new Square(10);
                System.out.println("Choose character to fill your shape. A-Z, a-z, ! # $ % & ( ) * + Press ENTER.");
                characterChoiceSquare = input.next();
                if(characterChoiceSquare == input.next())
                {
                    for(int m = 0; m < shapeChars.length; m++)
                    }
                    {
                        if(characterChoiceSquare.equals(shapeChars[m]));
                        {
                            char[] c1 = characterChoiceSquare.toCharArray();
                            char[] shapeCharacter = new char[sq.getSizeInt()];
                            for(int i = 0; i < sq.getSizeInt(); i++) 
                            {
                                shapeCharacter[i] = c1[0]; // repeat the char input to fit shapeString
                            }
                            string = String.valueOf(shapeCharacter); //assign the value of the arraylist to shapeString

                            shapeString += string + "\n";

                            System.out.print(shapeString);
                        }
                    }
                }
                else if(characterChoiceSquare == null)
                {
                    System.out.print(sq.displayCharacters());
                }

SQL UPDATE using an IF statement

I have a table that has a unique identifier of "name" and two fields that are both Boolean statements. The two fields are titled "sentbirth" and "senthire".

What I am trying to do is to see if the value is already true for senthire or sentbirth. If so I want to leave it as true. But if it is false then I want it to update with the @SentBirth or @SentHire value that is being produced from my web application.

What I have so far is:

SELECT [name],[sentbirth],[senthire]
FROM [table]
WHERE name = @Name

IF [sentbirth] = '1'
    BEGIN
    UPDATE [CCRAuction].[dbo].[cardsUser]
        SET [sentbirth] = '1'
    END 
 ELSE
    BEGIN
     UPDATE [CCRAuction].[dbo].[cardsUser]
        SET [sentbirth] = @SentBirth
    END

IF [senthire] = '1'
    BEGIN
    UPDATE [CCRAuction].[dbo].[cardsUser]
        SET [senthire] = '1'
    END
 ELSE
    BEGIN
     UPDATE [CCRAuction].[dbo].[cardsUser]
        SET [senthire] = @SentHire
    END

With this code as is I am receiving the error message that 'sentbirth' and 'senthire' are invalid column names.

How do I write this code properly in Microsoft SQL Server Management Studio?

How to combine different conditionals in R?

this is my reproducible example:

SMTscenes.ACC SMTscenes.RESP TrialType 
0             4              Old
0             3              Old
0             r              New
0             2              New
0             1              New
0             r              Old
0             3              Old
0             4              New

I started by using the following command to get rid of the "r" so that the next conditionals abide by numbers, then applying the conditional:

levels(df$SMTscenes.RESP)[levels(df$SMTscenes.RESP)=="r"] <- "5" df$SMTscenes.ACC <- ifelse(df$SMTscenes.RESP >= '3' & df$TrialType == 'Old', '1', '0') df[is.na(df)] <- 1 levels(df$SMTscenes.RESP)[levels(df$SMTscenes.RESP)=="5"] <- "r"

This yields

SMTscenes.ACC SMTscenes.RESP TrialType 
1             4              Old
1             3              Old
0             r              New
0             2              New
0             1              New
1             r              Old
1             3              Old
0             4              New

Here comes the tricky part: If I try to use the following (For 'New' now):

levels(df$SMTscenes.RESP)[levels(df$SMTscenes.RESP)=="r"] <- "5" df$SMTscenes.ACC <- ifelse(df$SMTscenes.RESP <= '2' & df$TrialType == 'New', '1', '0') df[is.na(df)] <- 1 levels(df$SMTscenes.RESP)[levels(df$SMTscenes.RESP)=="5"] <- "r"

then what happens is it reverses the previous step, obviously. Now, I've tried tweaking it in various ways, like mixing the conditionals, all to no avail. What I want the end result to be is this:

 SMTscenes.ACC SMTscenes.RESP TrialType 
1             4              Old
1             3              Old
0             r              New
1             2              New
1             1              New
1             r              Old
1             3              Old
0             4              New

So, any pointers on how to achieve this? I'd do it manually but there are thousands of rows of data... All help is appreciated.

variables compared tcl script annouce

what is wrong here?

i have the variable $type various words,but only one. I want only a msg when not Animation or Scriped is

    if {$sec == "Dir"} {
        } else {
            if [{$type != "Animation"} {$type != "Scripted"}]  {
            putquick "privmsg #test :$type"

    }
    }

how can help me?

How to determine determine largest/smallest number

I have 6 int variables and I need to determine the the smallest one and the largest, also I have only learned for/while loops, switches, and if statements. Im fairly new to c.

for visualization, the totals are the 6 integers i need to find the smallest/largest of. Also the driest and wettest is where ill be printing largest/smallest number.

http://ift.tt/1oTi0gu

return more rhan one value in multiple choice in Android

I have list view with multiple choice items, I want whenever user check more than one item, return all his checked values

SparseBooleanArray checked = lv.getCheckedItemPositions();
            ArrayList<String> selectedItems = new ArrayList<String>();

            for (int i = 0; i < checked.size(); i++) {
             int position = checked.keyAt(i);
             if (checked.valueAt(i))
             selectedItems.add(String.valueOf(ard.getItem(position)));
             }

         String[] outputStrArr = new String[selectedItems.size()];

          for (int i = 0; i < selectedItems.size(); i++) {
              outputStrArr[i] = selectedItems.get(i);
              Pushbots.sharedInstance().setAlias(outputStrArr[i]);

              }



        }
    });

in this case, only last checked value is took ...

Is it possible to use an IF statement in PHP along with different sql queries?

Basically I want to update a value in the table if the date field is equal to todays date, otherwise I'd like to insert a new row into the table if the date is not equal to today. Say for example something like (I know syntax is wrong here) -

if($date == $today){
   $sql = $con->query("UPDATE table SET field= 'field+$value', field2='field2 + $value2' WHERE id=2")
}else{
     $sql = $con->query("INSERT INTO table (field1, field2,field3)VALUES('{$value1}', '{$value2}', '{$value3}')");
}

How would I go about doing something like this? is using an if statement like this in php/SQL queries possible? or is there a different way that it has to be done? Cheers.

if block being performed even when comparison values of Int are not equal (Swift)

func audioControllerDidFinishLoadingAudioForKey(key: Int) {

    print("current line position")
    print(scriptTableView.currentLinePosition)
    print("key")
    print(key)

    if scriptTableView.currentLinePosition == key && pausedPlayback == false {

        playbackRecordingWithKey(key)

        dispatch_async(dispatch_get_main_queue(), { () -> Void in

            if self.recordLines == true {
                self.setToolbarState(.RecordMode)
            } else {
                self.setToolbarState(.Playing)
            }

        })
    }
}

I am having some very strange behaviour with this if-statement.

The above function always performs the if block, even if the key is a different value to the currentLinePosition (both are Ints). The print output shows for example:

current line position
25
key
27
playbackRecordingWithKey

But "playbackRecordingWithKey" is still being called (there is a print function there as well)

Does anybody know why this might be happening or how to debug this? I'm a bit stumped here.

python defining with Pandas for DataFrame building

I have a sample inputfile.txt:

chr1    34870071    34899867    pi-Fam168b.1    -
chr11   98724946    98764609    pi-Wipf2.1  +
chr11   105898192   105920636   pi-Dcaf7.1  +
chr11   120486441   120495268   pi-Mafg.1   -
chr12   3891106 3914443 pi-Dnmt3a.1 +
chr12   82815946    82882157    pi-Map3k9.1 -

Column1=chromosome_number

Column2=start

Column3=end

Column4=gene

Column5=strand (either + or -)

This is the code that I have:

import pandas as pd
df1=pd.read_csv('filename.txt',names= ['chr','start','stop','gene','strand'], delimiter=r'\s+')
count =0
c = 0
for i in df1.index:
    for y in df1.index:
        if abs(df1.loc[i,"start"]- df1.loc[y,"stop"]) < 201:
            if i != y:
                index 
                c +=1
print(c)

I keep on getting this error that the index is not defined:

File "./filename.py", line 25, in <module>
index 
NameError: name 'index' is not defined

I have Python 2.7.10 Any feedback much appreciated. Thanks

How can I make an if statement that recognizes whether or not my input appears in a list?

That is what I have so far and it doesn't work, I am new to Python so sorry if there is a really obvious mistake that I don't see :)

Quotes = ['Iron and Blood' , 'No Quote Available' ]   
Blood=Quotes[0]
Else=Quotes[1]

Name = raw_input('Who do you want this humble AI to quote?')
if Name == Bismark:
    print(Blood)

Which order does the else statement follow?

I wanted to be sure about something,

When i have multiple if/else conditions and if does not imply an else condition for one of those if conditions; does the next else statement goes for the last if statement?

For example:

if(condition1)
{
//operation1
}

if(condition2)
{
//operation2
}

else
{
//operation3.  
}

Like above example, if i don't use an else for the first if statement, which if statement does this else work for? Would this cause a problem for me, if i don't specify the else for each if?

I made some tests but wanted to be sure about how does this works actually.

If/Else nested in while loop issue

I'm a beginner at Java, and I thought a great way to learn was to build a simple basketball game.

The point of the basketball game is press 1 to shoot and 2 to pass. It will use random numbers 1-20 to determine the distance in feet you are from the basketball. Random numbers 21-24 are for you get fouled or turn the ball over.

For some reason, it seems like once the if statements begin, the program breaks down. Also, I'm not sure if I'm using the Random and Scanner correctly.Can you help me out with the code?

import java.util.Random;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        System.out.println("Welcome to the basketball game!");
        System.out.println("How to play: If you want to shoot, press 1. Then choose the strength of your shot. Your" +
                " shooting strength is a percentage of how hard you want to shoot. Or you can pass the ball by pressing 2.");
        System.out.println("Get ready, it's time for tip-off!");
        int possession = 10;
        int score = 0;

        while (possession > 0) {
            Random distance = new Random();
            int Low = 1;
            int High = 25;
            int Result = distance.nextInt(High - Low) + Low;
            Scanner input = new Scanner(System.in);
            int choose = input.nextInt();

            System.out.println("Your team has the ball.");


            if (Result == 21) {
                System.out.println("You were fouled. You shoot two free throws, but only MADE 1 out of 2.");
                possession--;
                score++;
                System.out.println("SCORE: " + score + "-");
            } else if (Result == 22) {
                System.out.println("You were fouled. You shoot two free throws and you made 2 out of 2!");
                possession--;
                score = score + 2;
                System.out.println("SCORE: " + score + "-");
            } else if (Result == 23) {
                System.out.println("You were fouled. You shoot two free throws and you MISSED both!");
                possession--;
                System.out.println("SCORE: " + score + "-");
            } else if (Result == 24) {
                System.out.println("Your opponent stole the ball from you. TURNOVER.");
                possession--;
                System.out.println("SCORE: " + score + "-");
            } else {
                System.out.println("Your team has the ball. You are " + Result + " feet from the basketball.");
                System.out.println("What do you want to do? Press 1 to shoot or press 2 to pass:" + choose);
            }


        }
    }
}

In Java, Does adding an else statement (after an already used if) take longer to execute?

Since an if statement is already evaluated anyway, does adding an else statement have any effect on performance?

A practical example:

if(updateTime >= updateIncrement)
{
    update();
    updateTime = 0;
}
else
    updateTime+=deltaTime;

vs:

if(updateTime >= updateIncrement)
{
    update();
    updateTime = -deltaTime;
}
updateTime+=deltaTime;

Comparing multiple criteria in excel

Query Photo. Sl. No. Invoice No. AWB No. Dispatch Date Reason for delay 1 A1 BD123 02/02/2016 On Time 2 A1 BD123 02/02/2016 Delay

In above example, i want the following done:

If i have same invoice No. and AWB No., if the dispatch date entered are different, it should highlight it. Also, for same condition, if there are multiple reasons, it should highlight it.

In example above, the same invoice number dispatched against same AWB no. can either be On time or Delayed and thus having two different reasons for same entries should get highlighted.

Thank you very much in advance. Saurabh Singh

dimanche 28 février 2016

Program not going into tthe IF condition. Involve struct

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

    struct BBQ
    {
       int BBQNumber;  // Pit Number
       string cal_date; // calendar date
       bool available; // status of pit - true if available for booking
    };

    const int SIZE = 3;
    BBQ pits[365][SIZE]; //2-D array that store the pits information for    the year

    void initialize();
    void display();
    BBQ findBBQ(string);


    int main()
    {
        string choice = "-";

        initialize();
        display();
        while (choice != "e")
        {
            cout << "Enter Reservation Date: ";
            cin >> choice;

            findBBQ(choice);
        }
    }

    void initialize()
    {

        BBQ pt[3];
        pt[0].BBQNumber = 10;
        pt[0].available = 1;
        pt[0].cal_date = "jan";

        pt[1].BBQNumber = 11;
        pt[1].available = 1;
        pt[1].cal_date = "feb";

        pt[2].BBQNumber = 12;
        pt[2].available = 1;
        pt[2].cal_date = "mar";

       for (int i = 0; i < 3; i++)
       {
           for (int j = 0; j < SIZE; j++)
           {
                pits[i][j] = pt[i];
           }
       }
    }

    BBQ findBBQ(string date)
    {
          for (int i = 0; i < 3; i++)
          {
              for (int j = 0; j < SIZE; j++)
              {
                  if (pits[i][j].cal_date == date)
                  {
                      cout << "Avail" << endl;
                      return pits[i][j];
                  }
                  else
                  {
                      cout << "Unavail" << endl;
                      return pits[i][j];
                  }
              }
          }
     }

     void display()
     {
         for (int i = 0; i < 3; i++)
         {
              for (int j = 0; j < SIZE; j++)
              {
              cout << pits[i][0].BBQNumber << endl;
              cout << pits[i][j].cal_date << endl;
             }
             cout << endl;
         }
     }

My problem lies in the findBBQ() function. I am trying to enter a date, and have the program run through the array and print if such a date is available. For some reason, the program only prints 'avail' when i asked it to search for 'jan' but 'unavail' when i ask for the other 2 months despite having all 3 months in the array as i have initialised.

ng-if in ng-repeat recreating elements on click events

I wanted to replace anchor tag by img when user clicked on it. My Sample code is like

<div ng-repeat="postpart in currentPost.parts ">

 <div ng-if = "postpart.type == 'MEDIA'">

   <div ng-if = "!postpart.isclicked">
          <img ng-src="{{imgurl}}" ng-click="iclicked(postpart)"/>
   </div>

   <div ng-if = "postpart.isclicked">
       <a ng-href="{{postpart.description}}" ng-init="init()"></a>
   </div>

 </div>

</div>

iclicked function just make isclicked to true.

It worked perfectly for one part. But When there are 2 parts it is showing 2 images. When i click on first it replaces by one anchor element.

But in case of 2nd image click it replaces with 2 anchor tags.

How can i able to make it? is there any solution to replace image element by anchor in ng-repeat?

How can I tell a for loop in R to regenerate a sample if the sample contains a certain pair of species?

I am creating 1000 random communities (vectors) from a species pool of 128 with certain operations applied to the community and stored in a new vector. For simplicity, I have been practicing writing code using 10 random communities from a species pool of 20. The problem is that there are a couple of pairs of species such that if one of the pairs is generated in the random community, I need that community to be thrown out and a new one regenerated. I have been able to code that if the pair is found in a community for that community(vector) to be labeled NA. I also know how to tell the loop to skip that vector using the "next" command. But with both of these options, I do not get all of the communities that I needing.

Here is my code using the NA option, but again that ends up shorting me communities.

C<-c(1:20)
D<-numeric(10)
X<- numeric(5)
for(i in 1:10){
  X<-sample(C, size=5, replace = FALSE)
  if("10" %in% X & "11" %in% X) X=NA else X=X
  if("1" %in% X & "2" %in% X) X=NA else X=X
  print(X)
  D[i]<-sum(X)
  }
print(D)

This is what my result looks like.

[1]  5  1  7  3 14
[1] 20  8  3 18 17
[1] NA
[1] NA
[1] 4 7 1 5 3
[1] 16  1 11  3 12
[1] 14  3  8 10 15
[1]  7  6 18  3 17
[1]  6  5  7  3 20
[1] 16 14 17  7  9
> print(D)
 [1] 30 66 NA NA 20 43 50 51 41 63

Thanks so much!

Counter not working in jQuery

I am trying to run my counter for 3 times. once I reach 3 tries the button is supposed to be disabled. I tried couple variations of this solution to no avail. the issue is right on my rollItAgain function. I have my counter starting at 3, and a for loop with an if statement inside. I am also running my randomFunction() inside my if statement, not sure if this is good practice. As of now, I only click reroll once and it gets disabled. I would like it to run at least 3 times.

// 'use strict';
var array = [];

var random = Math.ceil(Math.random() * 9);
var newStars = "<div class='star'><img src='http://ift.tt/21Cq5Eh'></div>";

$(document).ready(init);

function init(){
        for (var i = 0; i < random; i++){
                $('#starbox').append(newStars);
                //Create Event Handler for selectNumbers Function               
        }
        $('.numbers').click(selectNumbers);
        $('#checked').click(confirm);
        $('.numbers').click(toggleButton);
        $('#playagain').click(playItAgain);
        $('#reroll').click(rollItAgain);

}

function randomFunction(){
        $('#starbox').empty();
        random = Math.ceil(Math.random() * 9);
        for (var i = 0; i < random; i++){
                $('#starbox').append(newStars);
        }
}       

//selectNumbers function
function selectNumbers(){
        var num  = $(this).text();
        // $(this).css('background-color', 'red');
        array.push(num);
        // console.log(array);
        sum = array.reduce(function(a, b){
                return Number(a) + Number(b);
        });
        console.log(sum);
        //Check if numbers has select class
        console.log(num);
}


function toggleButton(){
 
        $(this).toggleClass('select');

}

function confirm(){
        if (sum === random){
                $('#displayResult').append("Correct!");
                // $('.select').css('display', 'none');
        } else {
                $('#displayResult').append("Wrong, try again!!");
        }

        $('.select').remove();
}

function rollItAgain(){
        // debugger;
        var counter = 3;
        // debugger;
        for (var j = 0; j < counter; j++){
                if(j === counter){
                        
                        randomFunction();
                        counter++;
                        
                } else {
                        $('#reroll').attr('disabled', 'disabled');
                }
        }       
}

function playItAgain(){

        location.reload();
}
#numberbox {
        width: 400px;
        height: 100px;
        border: 2px solid green ;
}

.numbers {
        height: 100px;
    width: 100px;
    background-color:transparent;
    border: 2px solid #000;
    margin: 5px;
    line-height: 100px;
    display: inline-block;
    border-radius: 50%;
    text-align: center;
    border: 2px solid #000;
    font-size: 30px;


}

#starbox {

        min-height: 300px;
    min-width: 400px;
    background-color:transparent;
    border: 2px solid #000;
    margin:100px 100px;

    
}

.star {
    display: inline-block;
}

.select {
    background-color: red;
}
<script src="http://ift.tt/1oMJErh"></script>
<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="UTF-8">
        <title>Mathgame1</title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="http://ift.tt/1L6zqzP"></script>
        <script src="main.js"></script>
</head>

<body>
<div id="starbox"></div>
<p id="displayResult"></p>

<table id="numberbox" >
<button id="playagain">Play it Again</button>
<button id="checked">checked</button>
<button id="reroll">reroll</button>
        <tr >
                <td class="numbers">1</td>
                <td class="numbers">2</td>
                <td class="numbers">3</td>
        </tr>
        <tr >
                <td class="numbers">4</td>
                <td class="numbers">5</td>
                <td class="numbers">6</td>
        </tr>
        <tr >
                <td class="numbers">7</td>
                <td class="numbers">8</td>
                <td class="numbers">9</td>
        </tr>
</table>
</body>
</html>

Calculating Mass Index and For loop?

Please bear with me all, as this is my first programming class. So what I'm trying to do is to calculate BMI based on an input of height and weight, and to determine whether the weight is overweight or obese based on the BMI calculated. I'm also required to include this for loop what would run the function four times, but I can't even get it to run properly once. I'm not sure if it's because I'm using the wrong type of returnType or if my formula for calculating BMI is off. Please help!

#include <stdio.h>
FILE *csis;

int calculateBMI(double height,double weight);

int main(void) {
int i;
double BMI, height, weight;

csis = fopen("csis.txt", "w");
for (i = 1; i <= 4; ++i); {
    int calculateBMI(double height, double weight);
}

printf("Enter your height (in inches) and weight (in pounds):\n");
fprintf(csis,"Enter your height (in inches) and weight (in pounds):\n");
scanf("%d %d", &height, &weight);
printf("Your BMI is: %.2f\n", BMI);
fprintf(csis,"Your BMI is: %.2f\n", BMI);
return BMI;


if (BMI < 18.5) {
    printf("The calculated Body Mass Index is Underweight.\n");
    fprintf(csis,"The calculated Body Mass Index is Underweight.\n");
}
else if (BMI < 25.0) {
    printf("The calculated Body Mass Index is Normal.\n");
    fprintf(csis,"The calculated Body Mass Index is Normal.\n");
}
else if (BMI < 30.0) {
    printf("The calculated Body Mass Index is Overweight.\n");
    fprintf(csis,"The calculated Body Mass Index is Overweight.\n");
}
else {
    printf("The calculated Body Mass Index is Obese.\n");
    fprintf(csis,"The calculated Body Mass Index is Obese.\n");

    fclose(csis);
    return BMI;
}
}

// Calculates BMI given the weight and height.
// Returns the Body Mass Index

int calculateBMI(double height, double weight) {
    double BMI;

    BMI = (weight * 703) / (height * height);
return BMI;
}

if Statements calling on random array

This is the code i have made so far. I have two words, red and black. when the red button is pressed i want an if statement that tells the user if they are wrong or right. The code picks randomly either red or black but i can't seem to figure how to match the if statement with word that is randomly picked.

@IBAction func red(sender: AnyObject) {

    let array = ["Red", "Black"]
    let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
    print(array[randomIndex])


    if array == Int("Red") {

        colorLabel.text = "You're right"


    } else {

        colorLabel.text = "Wrong! It was a Black"
    }



}

Removal confirm with a pop-up message (jQuery)

I have a button with class .delete When I click it I want to run a jQuery code.
First of all I want to do this:
$('.pop-up-alert').addClass('clicked');

Then I need to run a function with if/else if/else statments.

  1. If .no-btn is clicked, I want to do this:
    $('.pop-up-alert').removeClass('clicked');

  2. Else if .yes-btn clicked, I want to do this:
    $(.delete).parent().remove(); // actually I need to delete only parent with .delete class child that was clicked (I need to use this somehow, but I don't know how)

  3. Else, I'm apllying this code again:
    $('.pop-up-alert').removeClass('clicked');

The point is, if user clicks the delete button, he gets a pop-up with the ability to confirm deleting. If he clicks YES, jQuery will delete the .delete parent. If NO, pop-up will be hidden (with .clicked class in CSS). But if he clicks anywhere else, pop-up will be hidden anyway.

If I understand it right, the code should be something like that:

$('.delete').click(function() {
    $('.pop-up-alert').addClass('clicked');
    function() {
        if ($('.no-btn').click()) {
            $('.pop-up-alert').removeClass('clicked');
        } else if ($('.yes-btn').click()) {
            $(.delete).parent().remove();
        } else {
            $('.pop-up-alert').removeClass('clicked');          
        };
    };
});

But it doesn't work. Please, help

Excel lookup data IF-statement

I got a problem where I have data inform of numbers with a certain date related to them.

My problem is that I want to summaries the monthly values that belong to the certain month. Someone before me is using : =IF(References!$M6,IF(HLOOKUP($C63,Elec_data, ROW(Q3),FALSE),HLOOKUP((DATE(YEAR($C63),MONTH($C63)+COLUMN(B1)-1,DAY($C63))),Elec_data,ROW(Q3),FALSE),""),"")

Where Elec_data is the saved name of that table to extract the data from. M6 is the month, C63 is also the month. I don't understand what COLUMN(B1)-1 has to be -1 also?

The function works but if there is no value in the column it still takes the next value in the column. It takes the wrong value to the cell for the month.

Thanks.

If statement inside a case statement c seems to ignore condition and just do else

I am using cmd to launch my program and it reads through arguments typed in cmd and the if statement doesnt seem to work it just goes to else and executes. its supposed to read if the 4th argument typed in is = (in this case) "something" then execute the code.. anyone has any idea ?

int main(int inputn, char* inputs) 
{ 
switch (inputn)
{
case 6:
if(input[4] == "something") 
{
//code
break;
}
else        
{
//code   
break;
}
.
.
.
default:

//code break; } }

Countdown Timer and If Command

I want to create a if command in Countdowntimer. When the Countdown reached the specific number It will say "Yeee Congrats Blalbalba." How Can I do this ?

I looked so many pages but I didn't see anything about it.

Function to return a list - issue with filtering the output

I try to output only articles if authorsid = authorid.

Beside that the whole function works exactly as I want, here it is:

The general idea is to limit access to only own articles.

So, my question is: how do I limit the results to show only articles written by the owner of the page we are on (authorsid = authorid).

function ArticlesListReturn(returned) {
    xml = returned.documentElement;
    var rel = document.getElementById('related_category_articles');
    rel.options.length = 0;
    var status = getXMLData('status');
    var title = '';
    var id = '';
    var authorid = '';


    if (status == 0) {
      alert("%%LNG_jsArticleListError%%" + errormsg);
    } else {
      var authorid = document.getElementById("authorid").value; // Serge

      //    authorsid = getNextXMLData('authors',x);
      for (var x = 0; x < xml.getElementsByTagName('titles').length; x++) {


        title = getNextXMLData('titles', x);
        id = getNextXMLData('ids', x);
        authorsid = getNextXMLData('authors', x);

        alert(authorsid) // authors of each article - it returns the proper values
        alert(authorid) // author of the page we are on - it returns the proper value

        rel.options
        var count = 0;

        rel.options[x] = new Option(title, id, authorid); // lign that returns results

        title = '';
        id = '';
        authorid = '';

      }

if( fn1(args) || fn2(args){ "Add the elements into the list" ;}

I have a doubt of how this if loop is going to work. if fn1 evaluates to be true, will it still go for checking fn2 or will it go into the if loop and add the elements into the list?

No responds after using if-elseif function

I have a project due in 5 days. I am trying to create a tool using macro so that when few criteria are selected, a certain rating will be shown. There are three criteria that need to be filtered before getting the result. For example, if the "agriculture industry" is selected, followed by selection of "Indonesia", followed by selection of certain ratio (e.g.2.5), a rating from 1 to 6 will be given (in this case, 3). I tried the following code but nothing appears under my rating column. Can someone please help me out. Codes are shown below.

>

Private Sub CommandButton1_Click() Dim Value As Double If Range("V4").Value = "A.Agriculture,forestry and fishing" Then

If Range("W4").Value = All Or ID Or SG Then

    If Range("D4").Value <= 0 Then
        Range("X4").Value = 6
    ElseIf Range("M4").Value > 4 Then
        Range("X4").Value = 5
    ElseIf Range("M4").Value <= 4 And Value > 2 Then
        Range("X4").Value = 4
    ElseIf Range("M4").Value <= 2 And Value > 1 Then
        Range("X4").Value = 3
    ElseIf Range("M4").Value <= 1 And Value > 0 Then
        Range("X4").Value = 2
    ElseIf Range("M4").Value <= 0 Then
        Range("X4").Value = 1
    End If

ElseIf Range("W4").Value = MY Or TH Then

    If Range("D4").Value <= 0 Then
        Range("X4").Value = 6
    ElseIf Range("M4").Value > 4.5 Then
        Range("X4").Value = 5
    ElseIf Range("M4").Value <= 4.5 And Value > 2 Then
        Range("X4").Value = 4
    ElseIf Range("M4").Value <= 2 And Value > 1 Then
        Range("X4").Value = 3
    ElseIf Range("M4").Value <= 1 And Value > 0 Then
        Range("X4").Value = 2
    ElseIf Range("M4").Value <= 0 Then
        Range("X4").Value = 1
    End If

Else: Range("X4").Value = ""
End If

ElseIf Range("V4").Value = "B.Mining and quarrying" Then

If Range("W4").Value = All Or ID Or MY Or SG Or TH Then

    If Range("D4").Value <= 0 Then
        Range("X4").Value = 6
    ElseIf Range("M4").Value > 3.5 Then
        Range("X4").Value = 5
    ElseIf Range("M4").Value <= 3.5 And Value > 2 Then
        Range("X4").Value = 4
    ElseIf Range("M4").Value <= 2 And Value > 1 Then
        Range("X4").Value = 3
    ElseIf Range("M4").Value <= 1 And Value > 0 Then
        Range("X4").Value = 2
    ElseIf Range("M4").Value <= 0 Then
        Range("X4").Value = 1
    End If

Else: Range("X4").Value = ""
End If

End If End Sub

How will the condition work in JOptionPane?

I'm trying to make quiz program with two category: Java or C++ using JOptionPane and I'm trying to make a question with 4 options but I don't know how the condition will work and how will the score will be store.

import javax.swing.JOptionPane;

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

    int score = 0;
    JOptionPane.showMessageDialog(null,"WELCOME");
    String name = JOptionPane.showInputDialog(null,"Enter Your Name: ");

    String [] Intro = new String [] {"JAVA","C++"};
    int option = JOptionPane.showOptionDialog(null, "Choose a Category","Menu",JOptionPane.YES_NO_OPTION,
    JOptionPane.PLAIN_MESSAGE, null, Intro, Intro[0]);


    if (option == JOptionPane.YES_OPTION) // I just make YES or NO option since there are 2 choices
    {
        JOptionPane.showMessageDialog(null, "Hello "+ name + "\n Welcome to Java Quiz!");
        JOptionPane.showMessageDialog(null, "1. Please read the questions carefully \n 2. Answer all the question \n 3. Scores will be computed after the quiz \n 4. No Cheating!","RULES",JOptionPane.WARNING_MESSAGE);
        JOptionPane.showMessageDialog(null, "This Quiz consist of \n 1. Multiple Choice \n 2.Enumeration \n 3. True/False");
        JOptionPane.showMessageDialog(null,"Quiz #1: Enter the correct letter of the answer");

        // STRING OF QUESTIONS
        String[] quesJava = new String [] {"1) The JDK command to compile a class in the file Test.java is", "2)    Java was developed by_____."};


        String[] answers1 = new String[] {"A) java Test.java", "B) java Test","C) javac Test","D) javac Test.java"};
        int answer1 = JOptionPane.showOptionDialog(null, quesJava[0], "JAVA", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, answer1, answer1[0]);

            if (answer1== ???????????) // the answer is letter "D" but I don't know what will I put in here
            {
                score++;
            }

        String[] answer2 = new String[] {"A) IBM ", "B) Microsoft ","C) Sun Microsystem ","D) Oracle"};
        int answer2 = JOptionPane.showOptionDialog(null, quesJava[1], "JAVA", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, answer2, answer2[0]);
        {
            if (answer2== )
            {
                score++;
            }
        }

        JOptionPane.showMessageDialog(null,"your score is"+score);
    }


}

}

samedi 27 février 2016

Executing a while method in an if statement? [duplicate]

This question already has an answer here:

Hello I am building a version of Craps where it randomly rolls two dice and stores the information in two different rolls, where how many times it rolled a 7 and how many times it rolled an 11 in 100 rolls. I have managed to get it where I can output how many rolls I got for each and how many wins altogether, but now when I prompt the user if they want to play again I cant see to get it to execute the while method I created for the rolling loop. Is there a way I can get it to re-execute that in the last if statement and if so what would I put in that if statement to achieve this or is there some other kind of method I should be doing here instead?

import java.util.Random;
import java.util.Scanner;

public class Craps_ws7
{
    public static void main(String args[])
    {
        Scanner keyboard1 = new Scanner(System.in);
        System.out.println("Welcome to my Craps Game!");
        boolean stop = false;
        int sevenRoll = 0;
        int elevenRoll = 0;
        int totalWins = 0;
        int gameCount = 0;
        while(gameCount <= 100)
        {
            gameCount = gameCount + 1;
            Random generator = new Random();
            int die1 = generator.nextInt(6) + 1;
            int die2 = generator.nextInt(6) + 1;
            int dieTotal = die1 + die2;

             if (dieTotal == 7)
             {
                System.out.println("You rolled: " + dieTotal);
                System.out.println("You Win!");
                sevenRoll++;
                totalWins++;
             }
             else if(dieTotal == 11)
             {
                System.out.println("You rolled: " + dieTotal);
                System.out.println("You Win!");
                elevenRoll++;
                totalWins++;
             }
             else
             {
                System.out.println("You rolled: " + dieTotal);
                System.out.println("You lose!");
             }
        }
    System.out.println("You rolled a total of " + sevenRoll + "  sevens and " + elevenRoll + " elevens for a total of " + totalWins + " wins out of 100!" );
    System,out.println("Would you like to play again? [y/n]");
    string ans = keyboard1.nextLine();
    if (ans = "y" || ans = "Y")
    {

    }
    else 
    {
        System.out.println("Thank you for playing, Good Bye!");
    }
    }
}

Developing a general code that calculates the Future value for each cateogory and also one other future value

Here is the code:

import xlrd
import numpy

fileWorkspace = 'C://Users/jod/Desktop/'

wb1 = xlrd.open_workbook(fileWorkspace + 'assign.xls')
sh1 = wb1.sheet_by_index(0)

time,amount,category = [],[],[]            
for a in range(2,sh1.nrows):
    time.append(int(sh1.cell(a,0).value))        # Pulling time from excel (column A)
    amount.append(float(sh1.cell(a,1).value))    # Pulling amount from excel (column B)
    category.append(str(sh1.cell(a,2).value))    # Pulling category from excel (column C)
#print(time)
#print(amount)
#print(category)
print('\n')

p_p2 = str(sh1.cell(0,1))
p_p1 = p_p2.replace("text:'","")
pp = p_p1.replace("'","")
print(pp)                            # Printing the type of pay period (Row 1, col B)
c_p2 = str(sh1.cell(1,1))
c_p1 = c_p2.replace("text:'","")
cp = c_p1.replace("'","")
print(cp)                            # Printing the type of compound period (Row 2, col B)

netflow = 0
outflow = 0
inflow = 0
flow = 0

cat = ["Sales", "Salvage", "Subsidy", "Redeemable", "Utility", "Labor", 
       "Testing", "Marketing", "Materials", "Logistics"]

if pp == "Years" and cp == "Years":   # if pay period and compound period are both in years

    IRR = numpy.irr(amount) * 100            # Calculates the internal rate of return (IRR)
    print ("IRR:", round(IRR, 2), '%', '\n') # prints (IRR)

    for i in category:              # for every value in time array
        if cat[5] in category:  # if "Labor" for cat array is in category array or not

            # calculates the present values using all the amount values (col B) instead of 
            # just using the ones that has "Labor" category label beside them
            # Need to make every other value 0, such as beside "Redeemable" and "Salvage"
            flow = amount[i] / numpy.power((1 + (IRR/100)), time[i])
            if flow>0:                      
                inflow = inflow + flow      
            if flow<0:                      
                outflow = outflow + flow  

            print ('Present Value (P) is:', round(flow,0), '\n')

    netflow = outflow + inflow
    print("In 2016")
    print("-------")
    print ('Outflow is: ', round(outflow,0))
    print ('Inflow is: ', round(inflow,0))
    print ('Netflow is: ', round(netflow,0), '\n')

    outflow2 = (round(outflow,0))*(1+(IRR/100))**(9)
    inflow2 = (round(inflow,0))*(1+(IRR/100))**(9)
    netflow2 = outflow2 + inflow2

    print("In 2025")
    print("-------")
    print ('Outflow is: ', round(outflow2,0))
    print ('Inflow is: ', round(inflow2,0))
    print ('Netflow is: ', round(netflow2,0), '\n')

I have commented important lines of code for clarification. Here is the original question:

illustrate the breakdown of major project revenues and expenses by category as a percentage of that project’s future value in year 9. The illustration must also clearly indicate the total future value of the project in year 9 as well as the IRR.

There will be a total of 10 revenue and cost categories that a project may be composed of. The categories are: Sales, salvage, subsidy, redeemable, utility, labor, testing, marketing, materials and logistics. All revenues and expenses will fall in one of these ten categories. The project pay period and compound period will be identified at the top of the Excel sheet. Pay period and compound period may be designated as any of the following: years, quarters, months.

I am getting confused because I am not able to pull the only values from beside the "Labor", "Redeemable", or "Salvage". I just don't know where I am making a mistake, or there is something that is incomplete. There is a lot of work to be done in the code.

Different conditions in different excel files will exist such as the following: 1) Having different compound period and pay period. There are 9 possible combinations. With that being, the IRR module that calculates IRR, how to use that?

2) There will be different categories in different excel files and also more or less than 10 years.

This code needs to be a general code. It should be able to do what we to do with any excel file. It just seems to be really difficult.

The answer for IRR is 6.29% and the net present worth is $1.64

Below is the excel file image:

Excel Image

C++ if statement issue in tokenizer

I am writing a tokenizer for a small language called jack in c++ for class. The problem isn't tokenizing itself, but one of the if statements is acting up. In the code below, the line if(jack.characters == "/*") will return false even when jack.characters holds "/*". Is this an error with c++ commenting?

char checkch = ' ';

do
{
    checkch = getc(in_file);     //get next character and add it to token
    jack.characters += checkch;

    if(jack.characters == "")
    {
        jack.characters = checkch;
    }

    if(jack.characters == "//")    //handle comments 
    {
        fgets(ignore, INT_MAX, in_file);  //ignore rest of line when comment is encountered
        jack.characters = getc(in_file);  //set jack.characters to first character of next line
    }

    if(jack.characters == "/*")   //handle multi-line comments
    {
        while(true)               //continue ignoring until end of comment is found
        {
            checkch = getc(in_file);
            if(checkch == '*')
            {
                checkch = getc(in_file);
                if(checkch == '/')
                {
                    checkch = getc(in_file);
                    jack.characters = "";    //reset jack.characters
                    break;
                }
                break;
            }
            break;
        }
    }

List item

List item

HTML- and PHP-code inside an PHP 'if statement'

What if I want to have HTML code inside my 'if' statement, and then php code in the 'else' part? What do I do? I have tried this, but with no luck..

<?php

session_start();

if ($_SESSION['bnavn']) : ?>

   'HTML-code'

<?php else : ?>

    'PHP-code'
    
<?php endif: ?>

I have also tried this, but also with no luck:

<?php

    session_start();

    if ($_SESSION['bnavn']) : ?>

       'HTML-code'

    <?php else : ?>

        <?php 'PHP-code' ?>
        
    <?php endif: ?>

Invalid Syntax error on relatively simple if statement

I'm pretty new to Python and am taking a CS 170 course in it for my degree. I'm encountering an error in my code that I can't seem to resolve and my professor has been all but helpful. Any tips would be greatly appreciated!

When I run my program, I get an invalid syntax error that highlights the colon of my if statement, I'm attaching the code around the error so that ya'll can see it and maybe be able to help. Let me know if you need anything more. Thanks in advance!

float(year)
y = int(float(year))
float(month)
m = int(float(month))
float(day)
d = int(float(day)

if get_valid_date(y, m, d):

        day_number = zeller(year, month, day):
        print_date(day_number)

else:

    print('The date is invalid')

For Loop result doesn't make sense to me

So I had the following code snippet on a quiz:

int a = 120;
int b = 90;
int n1 = Math.abs(a);
int n2 = Math.abs(b);
int result = 1;

for (int k = 1; k <= n1 && k <= n2; k++) 
{
   if (n1 % k == 0 && n2 % k == 0) 
   {
      result = k;
   }
}
System.out.println(result);

The output is 30 and I'm not sure why. As far as I can see, wouldn't the loop keep running until the counter broke 90 (90 being the absolute value of n2)? That would make result = 90. Or is there just something I'm not quite understanding?

C programming, skipped a scanf function unexpectedly

I'm coding on Visual Studio 2015. When I execute below C program, during the execution program skips else part's character scanf function and displays "You entered an invalid character." directly. What is the problem?

    double grade1, grade2, avarage;
    char yes_no;            //character variable for (Y/N) statement
    int std;            //index for students
    int std_num;        //number of students
    printf("Enter how many students will be determined: ");
    scanf("%d", &std_num);
    for (std = 1; std <= std_num; std++);       //loop statement
    {//curly brace for loop

        printf("Enter two grades: ");       //display for inputs
        scanf("%lf %lf", &grade1, &grade2);     //input statement

        avarage = (grade1 + grade2) / 2;

        if (avarage >= 50)
            printf("Successful.\n");
        else
        {
            printf("Did the student take this exam before?(Y/N): ");
            scanf("%c", &yes_no);

            if (yes_no == 'Y' || yes_no == 'y')
                printf("Unsuccessful, and has no other chance.\n");
            else if (yes_no == 'N' || yes_no == 'n')
                printf("Unsuccessful, but has one more chance.\n");
            else
                printf("You entered an invalid character.\n");
        }
    }//curly brace for end of the loop
return 0;
}

PHP Conditional logic troubles row 2 won't work without row 1

I'm working on a project that I grew frustrated with because I think I may have been a little to happy with conditional logics. The website is eqcalendar.com and it's for a private entity.

My objective is to make this user friendly so anyone in this group can access a .txt file, edit the variables, and they show up appropriately.

I was trying to make it that if a variable was left blank that no characters would show up but that if the variables are filled, they will show up.

I want to repeat this for 1 day a week spanning out to three months. As I finished day 1, I went onto day 2 but day 2 will not work unless all variables are defined in day 1.

I was also making it possible to turn the day off if the date was not filled, it would add a css inline display: none;. It was working but now it won't. I found the more if statements I add, the less seems to be cooperative.

I've noticed the same thing with the jQuery toggle. The more I add, then no other month will work.

This is supposed to be a simple web app for mobile devices. I have the following elements that I've included:

Above the DOCTYPE, I have the PHP calling in the .txt file

<?php
$title = "EQ Calendar";
include 'planner.txt'; ?>

The planner.txt file looks like the following:

/*** MONTH 1 ***/
$month1 = "February";

    /** WEEK 1 **/
        $m1w1_Day               =   "07";
        $m1w1_Chapter           =   "4";
        $m1w1_Chapter_Header    =   "Test";
        $m1w1_Chapter_Link      =   "Testing";
        $m1w1_Conf_Header       =   "Tester";
        $m1w1_Conf_Speaker      =   "Dieter";
        $m1w1_Conf_Link         =   "http://www.google.com";
        $m1w1_Teacher           =   "Steven Scott";
        $m1w1_Other             =   "Presidency Message";

    /** WEEK 2 **/
        $m1w2_Day               =   "14";
        $m1w2_Chapter           =   "";
        $m1w2_Chapter_Header    =   "";
        $m1w2_Chapter_Link      =   "";
        $m1w2_Teacher           =   "";
        $m1w2_Other             =   "Stake Conference";

    /** WEEK 3 **/
        $m1w3_Day               =   "21";
        $m1w3_Chapter           =   "2";
        $m1w3_Chapter_Header    =   "My Peace I Give unto You";
        $m1w3_Chapter_Link      =   "";
        $m1w3_Teacher           =   "Joshua Hayes";
        $m1w3_Other             =   "";

    /** WEEK 4 **/
        $m1w4_Day               =   "28";
        $m1w4_Chapter           =   "";
        $m1w4_Chapter_Header    =   "";
        $m1w4_Chapter_Link      =   "";
        $m1w4_Conf_Header       =   "Be Not Afraid, Only Believe by Dieter F. Uchtdorf";
        $m1w4_Conf_Speaker      =   "Dieter F. Uchtdorf";
        $m1w4_Conf_Link         =   "";
        $m1w4_Teacher           =   "Jory Wahlen";
        $m1w4_Other             =   "";

    /** WEEK 5 **/
        $m1w5_Day               =   "";
        $m1w5_Chapter           =   "";
        $m1w5_Chapter_Header    =   "";
        $m1w5_Chapter_Link      =   "";
        $m1w5_Conf_Header       =   "";
        $m1w5_Conf_Speaker      =   "";
        $m1w5_Conf_Link         =   "";
        $m1w5_Teacher           =   "";
        $m1w5_Other             =   "";

The PHP code within the index.php is as follows:

<div class="top-header">
                <h1><?php echo $month1 ?> <span><i class="fa fa-close month1"></i></span></h1>
            </div>
            <div class="col-md-2 col-sm-2"></div>
            <div class="col-md-8 col-sm-8">
                <p <?php if (empty($m1w1_Day)) { echo "style='display:none;'"; } ?>><strong><?php echo $m1w1_Day ?></strong> <i class="fa fa-ellipsis-v"></i>
                <?php
                    if ($m1w1_Chapter !== "") {
                        if (empty($m1w1_Chapter)) {
                            return null;
                        } else {
                            echo "Ch. $m1w1_Chapter &ndash;";
                        }
                        if (empty($m1w1_Chapter_Header)) {
                            return null;
                        } elseif ($m1w1_Chapter_Link == "") {
                            echo " $m1w1_Chapter_Header";
                            if (empty($m1w1_Teacher)) { return null; } else { echo " &ndash; $m1w1_Teacher"; }
                        } else {
                            echo " <a href='$m1w1_Chapter_Link'>$m1w1_Chapter_Header</a>";
                            if (empty($m1w1_Teacher)) { return null; } else { echo " &ndash; $m1w1_Teacher"; }
                        }
                    } elseif ($m1w1_Conf_Header !== "") {
                        if (empty($m1w1_Conf_Header)) {
                            return null;
                        } elseif ($m1w1_Conf_Link == "") {
                            echo " $m1w1_Conf_Header";
                        } else {
                            echo " <a href='$m1w1_Conf_Link'>$m1w1_Conf_Header</a>";
                        }
                        if (empty($m1w1_Conf_Speaker)) {
                            return null;
                        } else {
                            echo " by $m1w1_Conf_Speaker";
                            if (empty($m1w1_Teacher)) { return null; } else { echo " &ndash; $m1w1_Teacher"; } 
                        }
                    } else {
                        echo "$m1w1_Other";
                        if (empty($m1w1_Teacher)) { return null; } else { echo " &ndash; $m1w1_Teacher"; }
                    }
                ?></p>
            </div>

My goal is to be able to repeat this code weekly and monthly. Am I missing any elements that is preventing me from isolating the if conditional to a single variable that is interfering with the other ifs?

Calculate the future value for only one category using the IRR (Python)

import xlrd
import numpy

fileWorkspace = 'C://Users/jod/Desktop/'

wb1 = xlrd.open_workbook(fileWorkspace + 'assign2.xls')
sh1 = wb1.sheet_by_index(0)

time,amount,category = [],[],[]            
for a in range(2,sh1.nrows):
    time.append(int(sh1.cell(a,0).value))        # Pulling time from excel (column A)
    amount.append(float(sh1.cell(a,1).value))    # Pulling amount from excel (column B)
    category.append(str(sh1.cell(a,2).value))    # Pulling category from excel (column C)
#print(time)
#print(amount)
#print(category)
print('\n')

p_p2 = str(sh1.cell(0,1))
p_p1 = p_p2.replace("text:'","")
pp = p_p1.replace("'","")
print(pp)                            # Printing the type of pay period (Row 1, col B)
c_p2 = str(sh1.cell(1,1))
c_p1 = c_p2.replace("text:'","")
cp = c_p1.replace("'","")
print(cp)                            # Printing the type of compound period (Row 2, col B)

netflow = 0
outflow = 0
inflow = 0
flow = 0

cat = ["Sales", "Salvage", "Subsidy", "Redeemable", "Utility", "Labor", 
       "Testing", "Marketing", "Materials", "Logistics"]

if pp == "Years" and cp == "Years":   # if pay period and compound period are both in years

    IRR = numpy.irr(amount) * 100            # Calculates the internal rate of return (IRR)
    print ("IRR:", round(IRR, 2), '%', '\n') # prints (IRR)

    for i in time:              # for every value in time array
        if cat[5] in category:  # if "Labor" for cat array is in category array or not

            # calculates the present values using all the amount values (col B) instead of 
            # just using the ones that has "Labor" category label beside them
            # Need to make every other value 0, such as beside "Redeemable" and "Salvage"
            flow = amount[i] / numpy.power((1 + (IRR/100)), time[i])
            if flow>0:                      
                inflow = inflow + flow      
            if flow<0:                      
                outflow = outflow + flow  

            print ('Present Value (P) is:', round(flow,0), '\n')

    netflow = outflow + inflow
    print("In year 0 or current year")
    print("-------")
    print ('Outflow is: ', round(outflow,0))
    print ('Inflow is: ', round(inflow,0))
    print ('Netflow is: ', round(netflow,0), '\n')

    outflow2 = (round(outflow,0))*(1+(IRR/100))**(9)
    inflow2 = (round(inflow,0))*(1+(IRR/100))**(9)
    netflow2 = outflow2 + inflow2

    print("In year 9")
    print("-------")
    print ('Outflow is: ', round(outflow2,0))
    print ('Inflow is: ', round(inflow2,0))
    print ('Netflow is: ', round(netflow2,0), '\n')

I have commented important lines of code for clarification. Here is the original question:

illustrate the breakdown of major project revenues and expenses by category as a percentage of that project’s future value in year 9. The illustration must also clearly indicate the total future value of the project in year 9 as well as the IRR.

There will be a total of 10 revenue and cost categories that a project may be composed of. The categories are: Sales, salvage, subsidy, redeemable, utility, labor, testing, marketing, materials and logistics. All revenues and expenses will fall in one of these ten categories. The project pay period and compound period will be identified at the top of the Excel sheet. Pay period and compound period may be designated as any of the following: years, quarters, months.

There will be a total of 10 revenue and cost categories that a project may be composed of. The categories are: Sales, salvage, subsidy, redeemable, utility, labor, testing, marketing, materials and logistics. All revenues and expenses will fall in one of these ten categories. The project pay period and compound period will be identified at the top of the Excel sheet. Pay period and compound period may be designated as any of the following: years, quarters, months.


I am getting confused because I am not able to pull the only values from beside the "Labor", "Redeemable", or "Salvage". I just don't know where I am making a mistake, or there is something that is incomplete. Below is the excel file image:

Program subtracting 1 from only even value output

So I cant figure out why this is happening. This program asks the user for an input integer and either doubles the digits or triples the digits depending on whether it is an even or odd number respectively. The problem is that for only the even integer loop it subtracts the first digit by 1 for each loop iteration. The loop for the odd integers is exactly the same as the even integers with the exception tripling the digits instead of doubling and it works just fine. Any ideas?

Ex:

Input: 12
Expected output: 1122
Actual output: 1121

Input: 13
Expected output: 111333
Actual output: 111333

//This program asks the user to enter an integer and depending on whether the integer is even or odd, doubles or triples
//each digit in the integer respectively. It then reads out the result and asks the user if they would like to enter
//another integer and run the program again.
int main()
{
    string restart;
    int integer, remainder;

    while (restart != "n" && restart !="N")
    {
        cout << "Enter an integer: ";
        cin >> integer;
        cout << endl;

        //Creates variable "temp" and "mycount" and divides "integer" by 10 until remainder is 0 and counts number of
        //steps to do this to count the number of significant digits of the integer
        int temp = integer, mycount = 0;
        while (temp != 0)
        {
            temp = temp / 10;
            mycount++;
        }

        //Computes if the integer is even or odd by determining the remainder: 0 remainder = even, Non-0 remainder = odd
        //Creates two integer variables "exponent" and "sum" and sets them to 0
        //Assigns variable "temp" to the integer value
        remainder = integer % 2;
        int exponent = 0;
        int sum = 0;
        temp = integer;

        //If integer is even, doubles each significant digit
        if (remainder == 0)
        {
            //Begins for loop which runs for the number of times equal to the number of significant digits stored in "mycount"
            for (int i = mycount; i > 0; i--)
            {
                //Stores current significant digit in "digit"
                //Removes current significant digit by dividing by 10
                //Multiplies current significant digit by 11 and stores it in "timesTwo"
                //Multiplies current significant digit by 10^exponent then adds it to other modified digits
                //Adds 2 to current exponent to increase digit multiplier by 100
                int digit = temp % 10;
                temp = temp / 10;
                int timesTwo = digit * 11;
                sum = (timesTwo * pow(10, exponent)) + sum;
                exponent = exponent + 2;
                cout << sum << endl;
                cout << endl;
            }

            cout << "Number is even, doubling each digit in the integer ..." << endl;
            cout << sum << endl;
        }

        //If integer is odd this runs the same as the above function except it triples the digit and adds 3 to the multiplier
        else
        {
            for (int i = mycount; i > 0; i--)
            {
                int digit = temp % 10;
                temp = temp / 10;
                int timesThree = digit * 111;
                sum = (timesThree * pow(10, exponent)) + sum;
                exponent = exponent + 3;
                cout << sum << endl;
            }
            cout << "Number is odd, tripling each digit in the integer ..." << endl;
            cout << "Result: " << sum << endl;
        }

        cout << "Would you like to enter another integer? (y/n): ";
        cin >> restart;
    }

    return 0;
}

VBA Input Box and If Statement - Catching user misspellings

I'm practicing some VBA code, and I'm trying to write a code that will display the appropriate price in a message box for various types of seat locations that have their assigned price. I also want to make sure I use an If statement for this code.

Seat Location:

Box $75

Pavilion $30

Lawn $21

What I have so far is an input box that asks the user to enter the seat location, and a message box will come up with the assigned price. My problem is figuring out how to display the appropriate price when the user inadvertently misspells the seat location. The code I have right now works if everything is spelled correctly, but how do I make it work even if the user misspelled the seat location ex. Instead of Pavilion they enter Pavillion.

Here is the code I have so far.

    Option Explicit
    Public Sub ConcertPricing()
    'declare variables
    Dim strSeat As String
    Dim curTicketPrice As Currency

    'ask user for desired seat location
    strSeat = InputBox("Enter seat location", "Seat Location")
   'if statement that assigns appropriate pricing according to seat selection
   If strSeat = "Box" Then
    curTicketPrice = 75
    Else
       If strSeat = "Pavilion" Then
       curTicketPrice = 30
       Else
          If strSeat = "Lawn" Then
          curTicketPrice = 21
          Else
             If strSeat = "Other" Then
             curTicketPrice = 0
             End If
          End If
       End If
    End If

    'pricing results based on seat selection
    MsgBox ("The ticket price for a seat in the " & strSeat & " location is:    " & Format(curTicketPrice, "$0.00"))

    End Sub

Thank you!

Return button text after toggle

I have the following React component:

var $ = require('jquery');

module.exports = {
    trigger: '.form-trigger',
    form: '.financial-form',
    init: function() {
        $(this.trigger).click(this.toggleForm.bind(this));
    },
    toggleForm: function(e) {
        // define currentTarget
        var currentTarget = $(event.currentTarget);
        // define current Text
        var currentText = currentTarget.html();
        // Prevent anchor click default
        e.preventDefault();
        // Remove any active classes
        currentTarget.next(form).slideToggle("fast");
        // console.log(currentText);
        if ($(this.form).is(":visible")){
            // $(element).is(":visible")
            currentTarget.html("Close Form");
        } else {
            currentTarget.html(currentText);
        }
    }
};

There are multiple 'triggers' on the page which open up their adjacent forms. Inside the toggleForm function, the 'if' statement determines the text of the button. I store the buttons current Text so that if the form is open, I can change to "Close Form" or else return the button to its original text. However the currentText variable is storing the "Close Form" Text as it becomes the currentTarget. How can I make sure the button's text returns to its original state?

What can be used to replace the if statement in this bit of code written in C?

The following is my attempt to scan a file to search and see if an entered username is taken already. The code doesn't work because of the if statement.

     for(x=0;x<100;x++)/*for loop allows the user to keep entering usernames until they come up with an unused username.*/
        {
            FILE *userlist;/*The userlist file holds all the taken usernames*/

            userlist=fopen("userlist.txt","r");
            fseek(userlist, x, SEEK_SET);/* This starts the search at the place x, which is incremented each time.*/
            fscanf(userlist," %s", &username_ext);/*This scans the file contents after x and stores it in the username_ext variable*/

            if(strcmp(username,username_ext)==0)/*If the username entered and the strings after the x are the same, the loop terminates.
            {
                printf("\nThe username is already taken.");
                break;
            }
            fclose(userlist);
        }

Thanks!

Python if else statement

My if statement works but else doesn't can anyone help me? this is my code. Btw if anyone knows how to ask for a retry after one time would be awesome!

import random

print('choose a number between 1 and 10,if you guess right you get 10 points if you guess wrong you lose 15points')

answer = input()

randint = random.randint(0,2)

print('the answer is ',randint)

if [answer == randint]:

 print('gratz! you win 10points!')

else:

 print('you lose 15points!')

Pull column B (amount) based on the column C (category) from excel and compute in python

import xlrd
import numpy

fileWorkspace = 'C://Users/doj/Desktop/'

wb1 = xlrd.open_workbook(fileWorkspace + 'assignment.xls')
sh1 = wb1.sheet_by_index(0)

time,amount,category = [],[],[]
for a in range(2,sh1.nrows):
    time.append(int(sh1.cell(a,0).value))
    amount.append(float(sh1.cell(a,1).value))
    category.append(str(sh1.cell(a,2).value))
#print(time)
#print(amount)
print(category)
print('\n')

p_p2 = str(sh1.cell(0,1))
p_p1 = p_p2.replace("text:'","")
pp = p_p1.replace("'","")
print(pp)
c_p2 = str(sh1.cell(1,1))
c_p1 = c_p2.replace("text:'","")
cp = c_p1.replace("'","")
print(cp)

netflow = 0
outflow = 0
inflow = 0
flow = 0

a = []
category = ["'Sales'", "'Salvage'", "'Subsidy'", "'Redeemable'", "'Utility'", "'Labor'", 
            "Testing", "Marketing", "Materials", "Logistics"]

if pp == "Years" and cp == "Years":

    IRR = numpy.irr(amount) * 100
    print ("IRR:", round(IRR, 2), '%', '\n')

    for i in category:
        if category == [5]:
            flow = amount[i] / numpy.power((1 + (IRR/100)), time[i])
            if flow>0:                      
                inflow = inflow + flow      
            if flow<0:                      
                outflow = outflow + flow  

            a.append(flow)
            print(a)
            print ('Present Value (P) is:', round(flow,0), '\n')

I need to illustrate the breakdown of major project revenues and expenses by category as a percentage of that project’s future value in 2025. The illustration must also clearly indicate the total future value of the project in year 2025 as well as the IRR.

I am totally confused what I am doing wrong with my code. I understand what to do, but I just can't code it.

Below is the image of the Excel File I have:

Excel File