mercredi 31 août 2016

bash automatically select specific variable from while

Is there a way to call a variable through the $i in a while loop? To access a specific variable automatically?

This is a scaled down version of what i'm trying to do:

i=1;

while [ $i -lt 4 ]; do
    let card$i=1;
    let i++;
done

let i=1;

while [[ $i -lt 4 ]]; do

    if [ "$card$i" = "1" ]; then 
        let card$i++;
    fi

    let i++;
done

Is there a way to make this work?

(I'm trying to do this with +50 variables. This is just scaled down)

Thanks.

CASE Statement with conditions

Iam trying to write two CASE Statements. The First CASE statement just sees if a field is empty, if empty it shows the value of another field. The CASE statement is below:

CASE 
When commercial_logi_freight.cust_shipmentdate_awb Is Null Or 
commercial_logi_freight.cust_shipmentdate_awb = '' Then
 commercial_logi_freight.comp_shipdate_awb
    Else commercial_logi_freight.cust_shipmentdate_awb End AS shipment_date

Now i need one more CASE statement which should check if shipment_date which is the result of the above CASE statement is NULL or not, if NULL or EMPTY it should show 'Pending" or else 'Completed'. Something like this. But its wrong.

Case When shipment_date Is Null Or shipment_date = '' Then 'Pending' Else 'Completed' End AS 
shipment_status

Not getting required result from if else in helper method

I'm calling the helper method from view like this -

%th{:class => weekend_class_top(date)}= date.strftime("%d")

helper method which has been called -

def weekend_class_top(date)
    if (date == date.end_of_month)
      'weekend_color5'
    elsif (date.to_s(:weekend) == 'Sun')  
      'weekend_color3'
    elsif @holidays.any?
      @holidays.map.each do |holiday|
        if (date == holiday)
          'timesheet_holiday_color'
        end
      end
    elsif @user_leaves.any?
      @user_leaves.flatten.map.each do |leave|
        if (date == leave)
          'timesheet_leave_color'
        end
      end
    end
  end

I want to show different background color for holidays and leaves, but the code that I have written, I'm getting background color only for holidays not leaves.

Why is my if statement an error?

This code is supposed to stop an object from passing through it, ans if an object hits it, make it so it has to wait 1 second before it can be interacted with again. I thought the best place to but the timer would be after the keylistener, but when I tried to put an if statement down, it just came up as an error, even though it seems to be complete.

What can I do to fix this, and is there a better way to do this?

I put the problem statement towards the middle, and added comment lines at the start and end of the if statement. Thank you for your help.

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;

public class Imject {

int x = 30;
int y = 30;
int xa = 0;
int ya = 0;
private CrcGame Game;

public void keyPressed(KeyEvent e) {

    if (e.getKeyCode() == KeyEvent.VK_W)
        if (collision()){
            ya = 0;
            y =- y;
        }
        else {ya = 1;
        }
    if (e.getKeyCode() == KeyEvent.VK_S)
        if (collision()){
            ya = 0;
        }
        else {ya = -1;
        }
    if (e.getKeyCode() == KeyEvent.VK_A)
        if (collision()){
            xa = 0;
        }
        else {xa = 1;
        }
    if (e.getKeyCode() == KeyEvent.VK_D)
        if (collision()){
            xa = 0;
        }
        else {xa = -1;
        }
}

public void keyReleased(KeyEvent e) {
    ya = 0;
    xa = 0;
}

//Starts
if (collision()){

}
//Ends

void move() {
    if (x + xa > 0)
        x = x + xa;
    if (y + ya > 0)
        y = y + ya;
}

public Imject(CrcGame Game) {
    this.Game= Game;
}

private boolean collision() {
    return Game.player.getBounds().intersects(getBounds());
}

public void paint(Graphics2D g) {
    g.fillRect(x, y, 100, 20);
}

public Rectangle getBounds() {
    return new Rectangle(x, y, 100, 20);
}

}

(HELP) How to reference a variable outside of scope in C#

I'm learning C#, and my professor asked us to create a program that takes in a user's height and weight, and then calculate bmi. I decided to take it a little further and added in some "input validation" logic. This means that if someone inputs "cat" for their weight, it let the user know that "cat" is not a valid weight.

class MainClass
{
    public static void Main ()
    {
        float userWeight;
        float userHeight;           
        bool weight = true;
        Console.Write ("Weight:  ");
        while (weight) 
        {               
            var inputWeight = (Console.ReadLine ());
            if (!float.TryParse (inputWeight, out userWeight)) {
                Console.WriteLine ("Invalid input");
                Console.Write ("Please try again: ");
            } 
            else 
            {
                weight = false;
            }
        }
        bool height = true;
        Console.Write ("Height:  ");
        while (height) 
        {
            var inputHeight = (Console.ReadLine ());
            if (!float.TryParse (inputHeight, out userHeight)) {
                Console.WriteLine ("Invalid input");
                Console.Write ("Please try again: ");
            } 
            else 
            {
                height = false;
            }
        }
        float bmiHeight = userHeight * userHeight; // error for userHeight
        float bmi = userWeight / bmiHeight * 703;  // error for userWeight
        Console.WriteLine ("You BMI is " + bmi);
    }           
}

The error I get is "use of unassigned local variable..". I know that I am assigning the user variables within IF statements, and that they only persist until the end of that IF statement. My question is, how do I generate a variable in an if statement, and then reference that variable outside of that statement? Certainly I don't have to nest them all, because that seems tedious....

#NAME errors in nested IF function

I am trying to create a simple formula for deadlines. After several hours I cannot figure out why it won't work. Any help would be greatly appreciated!

   =IF(NOT(ISBLANK(G2)),IF(G2>TODAY(),“Due in “&G2-TODAY()&” days”,IF(G2=TODAY(),“Due today”,IF(G2<H2,“Late filed”,“Timely filed”))),IF(NOT(ISBLANK(F2)),IF(F2>TODAY(),“Due in “&F2-TODAY()&” days”,IF(F2=TODAY(), “Due today”,IF(F2<H2,“Late filed”,“Timely filed”))),IF(NOT(ISBLANK(E2)),IF(G2>TODAY(),“Due in “&G2-TODAY()&” days”,IF(E2=TODAY(),“Due today”,IF(E2<H2,“Late filed”,“Timely filed”))))))

chart with 5 columns: 1 deadline 2 extension 3 extension 4 date of filing 5 status

If else statements in Java / calling other class

I need to create a driver program that says if I can fight a ticket or just pay it off. My problem is calling in another class called ticket to create an if else statement. I created an if else statement that will only say to fight the ticket on the last ticket...

(here is the problem im stuck on) **The problem: You are receiving speeding tickets which are automatically generated by a camera. You can FIGHT the ticket if any of the following are true:

• Your recorded speed is <= 11 mph over the limit

what am i doing wrong?

          import java.util.*; //scanner
           public class MinilabUsingClasses

         {
            public static void main (String [] args)
         {
    Scanner kb = new Scanner(System.in);  //creating new instance of scanner
    int numTickets;  //variable for number of tickets
    String name; //variable for name


    System.out.print("How many tickets do you have? " );         //ask user for numtickets
    numTickets = kb.nextInt();

    System.out.print("\nWhat is your name? " );         //ask user for name
    name = kb.next();
    System.out.println("\n");

    for (int i= 1; i <= numTickets; i++)  // use for loop to bring in random ticket info

        {
        Ticket currentTicket = new Ticket(name);
        System.out.println(currentTicket.toString());
        }

    int newSpeed = 0;

    if (newSpeed <= 11)
    {
        System.out.println ("Fight!");
    }
    else if (newSpeed > 11)
    {
        System.out.println("Pay :(");
    }






}

}

      //This class will describe a theoretical "speed camera ticket"

         import java.util.*;     //for random number generator

     public class Ticket
       {
//constant
private final int LIMIT = 55;

//data
private String name;
//private int limit;
private int speed;
private String cameraID;
private String location;

//default constructor - creates a ticket with the name "Bill Gates"
public Ticket()
{
    this("Bill Gates");     //just turns around and calls constructor with single arg
}

//parameterized constructor - this will set all values.  limit and location
//will be constant and the rest will have some randomness built in
public Ticket(String theName)
{
    //random number generator
    Random generator = new Random();

    //local variables
    int rand, len;
    char randomChar;

    //set the name data value
    name = theName;

    //name will have some randomness
    for (int i=0; i<name.length(); i++)
    {
        rand = generator.nextInt(10);     //random int from 0-9
        if (rand < 3)        //3/10 of the time change lowercase <-> uppercase
            if (name.charAt(i) >= 'a' && name.charAt(i) <= 'z')
            {
                //lowercase -> uppercase
                name = name.substring(0,i) + (char)(name.charAt(i)-32) + name.substring(i+1);
            }
            else if (name.charAt(i) >= 'a' && name.charAt(i) <= 'z')
            {
                //uppercase -> lowercase
                name = name.substring(0,i) + (char)(name.charAt(i)+32) + name.substring(i+1);
            }

        rand = generator.nextInt(21);     //random int from 0-20
        if (rand < 1 && name.charAt(i) != ' ')        //1/20 of the time put in a typo (but not for blanks)
        {
            randomChar = (char)(generator.nextInt(94)+33);          //get a randomChar in the ASCII table (33-126)
            name = name.substring(0,i) + randomChar + name.substring(i+1);  //put it in
        }
    }

    //it is programmed for constant location and speed limit
    location = "I-10 and 48th Street";

    //generate pseudorandom "cameraID"
    rand = generator.nextInt(10);     //int between 0-9
    if (rand < 2)
        cameraID = "A";       //starts with A 2/10 of the time
    else
        cameraID = "B";

    //middle digits of varying length
    len = generator.nextInt(4)+4;   //length this part of the ID (3-7 digits)
    for (int i=0; i<len; i++)
        cameraID = cameraID + (char)(generator.nextInt(10)+48);   //concatenate a random digit

    //ends with 35 2/10 of the time
    rand = generator.nextInt(10);
    if (rand < 2)
        cameraID = cameraID + "35";   //concatenate

    //speed is a random number between 6 - 20 mph over the limit
    rand = (int)(Math.random()*20);
    speed = LIMIT + 6 + rand;
}

//getLimit - returns the speed limit the camera was set at
public int getLimit()
{
    return LIMIT;
}

//getSpeed - returns the driver's speed
public int getSpeed()
{
    return speed;
}

//setSpeed - sets the speed to whatever is passed in
public void setSpeed(int newSpeed)
{
    speed = newSpeed;
}


//getName - returns the driver's name
public String getName()
{
    return name;
}

//get getCameraID - returns the cameraNumber
public String getCameraID()
{
    return cameraID;
}

//setCameraID - sets it to whatever is passed in
public void setCameraID(String newID)
{
    cameraID = newID;
}

//toString - returns its representation as a String
public String toString()
{
    String str = "\nName: " + name + "\nLimit: " + LIMIT;
    str += "\nSpeed: " + speed + "\nCamera: " + cameraID;
    str += "\nLocation: " + location;

    return str;
}

}

Bash IF exit code redirect errors

I'm writing a bash script right now that has a statement to check if a directory contains stuff.

Right now, the code is

if [ "$(ls -A $APPLICATIONS)"  ]; then
    do something
else
    do something else
fi

However, when the folder is indeed empty, I would like the error from ls to be suppressed. Normally, it would say "No such file or directory," but I want to redirect that to /dev/null.

I've tried doing

if [ "$(ls -A $APPLICATIONS &> /dev/null)"  ]; then

That does redirect everything to /dev/null like I wanted, but it also causes the directory to not be found (essentially causing exit code 1).

What would be the right way to do this?

If statement followed by more statements

Is the code below a valid C/C++ code? If yes what is the behavior?

void abc()
{
 ....
}

..
..
void xyz()
 {
   if( "some condition" )
   {
     ...
    ...
   }abc();
 }

Specifically if it is valid, would abc() be executed only when the conditions true?

ARMv7-M assembly ITEE usage

  • Problem:

I'm trying to get the ITEE EQ ie 'If-Then-Else-Else Equal' block to work when R6==0, with THEN branching into the END label but the assembler called out an error on the line: BEQ END

  • Program info:

I'm doing a program that is in pertinence with Optimization. I'm using a Gradient Descent to converge to the point where gradient is 0 to find the solution x* that minimises some function f(x). I'm using C language to call an assembly function which is this program here.

Here is my program where the error is:

        CMP R6, #0          @ Compare f'(x) with 0
        ITEE EQ             @ If R6 == 0, Then-Else-Else
        BEQ END             @ Calls END label if equal
        SUBNE R0, R6        @ Change R0(x) in the opp direction of gradient to get lower value of f(x) if not equal
        BNE optimize        @ Branch to optimize if not equal

This is my first assembly program using the NXP LPC1769 for a school assignment. Do let me know what I'm missing or I have done wrong. Thank you!

Here is my whole program:

.syntax unified
.cpu cortex-m3
.thumb
.align 2
.global optimize
.thumb_func

optimize:
@  Write optimization function in assembly language here

        MOV R5, INLAMBDA    @ R5 holds value of inverse lambda(10) ie to eliminate floating point
        LDR R6, #2          @ Load R6 with value '2' ie constant of f'(x)
        MUL R6, R1, R6      @ Multiply R6(2) with R1(a) & store to R6(results)
        MLA R6, R6, R0, R2  @ Multiply R6(results) with R0(x) & sum with R2(b) to get f'(x). Store & update results to R6
        SDIV R6, R5         @ Divide R6(results) by R5(1/lambda) to get f'(x) * lambda

        CMP R6, #0          @ Compare f'(x) with 0
        ITEE EQ             @ If R6 == 0, Then-Else-Else
        BEQ END             @ Calls END label if equal
        SUBNE R0, R6        @ Change R0(x) in the opp direction of gradient to get lower value of f(x) if not equal
        BNE optimize        @ Branch to optimize if not equal

@  End label
END:

BX LR

@ Define constant values
CONST: .word 123
INLAMBDA: .word 10      @ Inverse lambda 1 / lambda(0.1) is 10

MS Excel- Populate cell with a percentage based on number of cells coloured?

I'm looking to populate a cell value with a number based on how many cells have the colour green.

example 1:

A1 B1 C1 D1 (E1- Answer '15%' will appear here)
G  NG NG NG (G= Green, NG= Not Green)

Another example:

A1 B1 C1 D1 (E1- Answer '30%' will appear here)
G  G  NG NG (G= Green, NG= Not Green)

=IF(GetFillColor(A1)=4,"1",AND IF(GetFillColor(A1:B1)=4,"2"), AND IF(GetFillColor(A1:C1)=4,"3"), AND IF(GetFillColor(A1:C1)=4,"4", "0"))

GetFillColour:

 Function GetFillColor(Rng As Range) As Long
    GetFillColor = Rng.Interior.ColorIndex
 End Function

Any help would be much appreciated, Thanks!

Using case instead of IF ELSE to change WHERE clause in SQL

I am trying to build a query in which where clause slightly changes depending on an external variable and I came up with the below script

IF(@threshold='N')

  select  min_price
  ,       s.customization_type
  ,       gii.brand
  ,       gii.item_flag
  from   item_info gii
  ,      style s
  ,      categories gpc  
  where  isnull(@ordered,getdate()) between gpc.start_date and isnull(gpc.end_date, dateadd(day, 1, getdate()))
  and    gii.segment1 = s.style_number   
  and    gpc.line_of_business_category = 'AAA'
  and    gii.inventory_item_id = @v_item_id;

ELSE 
      select  min_price
  ,       s.customization_type
  ,       gii.brand
  ,       gii.item_flag
  from   item_info gii
  ,      style s
  ,      categories gpc  
  where  isnull(@ordered,getdate()) between gpc.start_date and isnull(gpc.end_date, dateadd(day, 1, getdate()))
  and    gii.segment1 = s.style_number   
  and    gpc.line_of_business_category = 'BBB'
  and    gii.inventory_item_id = @v_item_id;

But, I feel like the above query is not clean though it gives the desired results. Is there a better way I can optimized this query like using CASE WHEN?

PHP is that possible to add if statements when calling objects obj->sub1({if(foo==true) return foo; else return bar})

Im trying to create if statement inside $soap object, while typing its params. my need is like that: $soap->add($name,$something,$foo,$optionalarg,$optionalarg2);

this itself isnt too bad, but I need to change "optionalarg" for something else (to be precise "brak" ("none" in polish) ) making lots of cases dosent seem like good idea in that situation (it would be ton of that, and its not proper way to do that, I guess)

I know I could in theory prepare if for each optional arg before $soap, but Im looking for alternatives.

I tried googling, I tried doing random-ish things (sometimes stuff just works but not in this case), like

$soap->add($name,$something,$foo,{if($enabled==true) $optarg else "brak"})

$soap->add($name,$something,$foo,{if($enabled==true) return $optarg else return "brak"})

$soap->add($name,$something,$foo,if($enabled==true) $optarg else "brak")

everything was throwing errors, so I gave up.

conditional includetext and empty tocs

I need to display several sections of my document only in specific situations based on data stored in DocProperties. Currently I am doing this using the following nested field statements:

{IF {DOCPROPERTY var}="true" {INCLUDETEXT "include.docx"} ""}

This works as excepted but if there is a section headline within include.docx there will be a empty TOC entry before the actual section header. However, if I remove the if-statement and use only the plain INCLUDETEXT field the empty headline vanishes.

Example for strange includetext behaviour

I guess this is a bug so do you guys know any workaround?

Word 2016, Version 16.0.7167.2040 (most recent version available today)

if condition fails while checking json array values

i have a simple json array. in which i have two objects. now i am checking it for some specific values , if found do some thing , if not found do another thing. But i dont know why if condition runs both blocks. true and false both blocks are executed. please help.

$jsonstring = '{"like":[{"username":"abc","password":"abc"},{"username":"def","password":"def"}]}';
$jsonarr = json_decode($jsonstring);
$count = count($jsonarr->like);
for ($r = 0; $r < $count; $r++) 
{
    if ($jsonarr->like[$r]->username == 'abc' && $jsonarr->like[$r]->password == 'abc') 
    { 
         echo 'Match';
    }else
    {
        echo 'No Match';
    }
}

is it not like regular if condition ?

Update a link every few hours from external URL

I am trying to create a download link on my website which changes every few hours. The URL is stored in a file on another server.

When a user visits the website a script will need to run that does the following: -

  • checks to see if current time is greater or equal to expiring time in the file.
  • If current time is less than expire time then the stored URL will display
  • else it needs to read the latest URL from the API and store it in the variable/file
  • then add a new expiring time of expiring time plus 3 hours

How do I write this script? What does the time format need to be in?

Also does the file that the data is stored in need to be txt or XML?

The first file will be manually created and contains the download URL and an expiring time of current time plus 3 hours.

Help :(

Double IIF Statement in Python

I have an SQL code that has a double IIF statement in it, that is, the if true part is another IIF statement and I m trying to recreate this in python using np.where

the SQL code is:

IIF ([STATE] Is Null, IIF ([COUNTRY] Is Null,'No Country',[COUNTRY]), [STATE])

I've tried this:

DF['NewCol'] = np.where(DF['STATE'].isnull(),(np.where(DF['COUNTRY'].isnull(),'No Country','DF['COUNTRY']'),DF['STATE']))

any help appreciated

Second conditional statement is not triggering -

By default all of the checkboxes are checked, and has a parent child relation. When all the checkboxes are unchecked I want to add a class.But The second else if statement is not working -

if($('#treelist :checkbox:not(:checked)').length == 0){ 
   $('.row.cd-feed-wrapper').addClass('visible');
 } else if($('#treelist :checkbox:checked').length == 0){
  $('.row.cd-feed-wrapper').addClass('hidden');
}

The first one when the page loads.

codepen setup : http://ift.tt/2c3LDam

<ul id="treeList">
  <li>
    <input type="checkbox" name="selectedRole" checked> mCRC
  <ul>
  <li>
    <input type="checkbox" name="selectedRole" checked> STIVARGA Efficacy
    <ul>
      <li>
        <input type="checkbox" name="selectedRole" checked> Long-Term Responders
      </li>
      <li>
        <input type="checkbox" name="selectedRole" checked> STIVARGA in Clinical Practice
      </li>
    </ul>
  </li>
  <li>
    <input type="checkbox" name="selectedRole" checked> STIVARGA AE Management
  </li>

  <li>
    <input type="checkbox" name="selectedRole" checked> Dosing
  </li>
  <li>
    <input type="checkbox" name="selectedRole" checked> Patient Communication
  </li>
  <li>
    <input type="checkbox" name="selectedRole" checked> Case Studies
  </li>
</ul>

<li>
  <input type="checkbox" name="selectedRole" checked> GIST
</li>

MS access if condition doesn't work

I used to have one query that does a bunch of things, one of them is tell me about the salary increase for each employee. Is it due? is it overdue? is it too early for one?

The query kept asking me to enter parameters and after asking this question removing "enter parameter value" in query MS access I broke the one query into a bunch, each query builds on the other until the last one that has the if condition. Everything worked exactly the way I want it to, except for the if condition (that used to work fine before!!!)

This is my if condition

Eligibility: IIf([MonthsSinceLastIncrease]<24,IIf([MonthsSinceLastIncrease]>=18 And [LastOfRatings]<=2,"OVERDUE",IIf([MonthsSinceLastIncrease]>=15 And [LastOfRatings]=1,"OVERDUE",IIf([MonthsSinceLastIncrease]>=9 And [MonthsSinceLastIncrease]<15 And [LastOfRatings]=1,"Eligible",IIf([MonthsSinceLastIncrease]>=12 And [MonthsSinceLastIncrease]<18 And [LastOfRatings]=2,"Eligible","ok")))),"OVERDUE")

The rule for salary increases are as follows:

  • If the employee's rating is 3, he gets an increase after 24 months of his last one
  • If the employee's rating is 2, he gets one in 12-18 months
  • If the employee's rating is 1, he gets one in 9-15 months

What happens now, is that for some of the employees, I get only one record and it's correct, but for some employees, I get two records, one of them is correct an the other is not. Now instead of 48 records (what I used to get when the condition worked fine), I get 58.

This is the code for the whole query

SELECT IIf([MonthsSinceLastIncrease]<24,IIf([MonthsSinceLastIncrease]>=18 And [LastOfRatings]<=2,"OVERDUE",IIf([MonthsSinceLastIncrease]>=15 And [LastOfRatings]=1,"OVERDUE",IIf([MonthsSinceLastIncrease]>=9 And [MonthsSinceLastIncrease]<15 And [LastOfRatings]=1,"Eligible",IIf([MonthsSinceLastIncrease]>=12 And [MonthsSinceLastIncrease]<18 And [LastOfRatings]=2,"Eligible","ok")))),"OVERDUE") AS Eligibility, MonthsSinceLastUpdateQ.LocalID, MonthsSinceLastUpdateQ.LastOfRatings, MonthsSinceLastUpdateQ.MaxOfDateOfUpdate, MonthsSinceLastUpdateQ.MonthsSinceLastIncrease
FROM MonthsSinceLastUpdateQ, DateOfUpdateQ
GROUP BY IIf([MonthsSinceLastIncrease]<24,IIf([MonthsSinceLastIncrease]>=18 And [LastOfRatings]<=2,"OVERDUE",IIf([MonthsSinceLastIncrease]>=15 And [LastOfRatings]=1,"OVERDUE",IIf([MonthsSinceLastIncrease]>=9 And [MonthsSinceLastIncrease]<15 And [LastOfRatings]=1,"Eligible",IIf([MonthsSinceLastIncrease]>=12 And [MonthsSinceLastIncrease]<18 And [LastOfRatings]=2,"Eligible","ok")))),"OVERDUE"), MonthsSinceLastUpdateQ.LocalID, MonthsSinceLastUpdateQ.LastOfRatings, MonthsSinceLastUpdateQ.MaxOfDateOfUpdate, MonthsSinceLastUpdateQ.MonthsSinceLastIncrease;

Your help is much appreciated, please note that I barely know coding and have only been learning MS Access as I go, thank you!

mardi 30 août 2016

How do I get a function to be in effect every time something is typed in an input?

I am trying to compare the values of two input boxes, then change the border of the boxes when the value of the two boxes are not equal. The problem I am having is in the if statement where I compare the two values of the input boxes, it will never compare equal, except at the beginning where they are both blank, even if they are. I run the function through itself, I run a setTimeout on my function so it checks it every 500 milliseconds. Any help would be appreciated, and I most likely will look at the answers when I wake up in the morn.

var passContext = $('#pass').val();
var pass2Context = $('#pass2').val();

      function checkMatch() {
    if (passContext == pass2Context) {
      if($('#passCont').css({borderWidth: 1})) {
        $('#passCont').animate({
        borderWidth: 0
      }, 400)
      }
      //Add button animation
    } else {
      $('#passCont').css({
        border: '0 solid red'
      }).animate({
        borderWidth: 1
      }, 400)
      setTimeout(checkMatch, 2000);
    }
  }

  checkMatch();

Full code: http://ift.tt/2bZfUc0

Excel IF statement, true value equals value in another cell

In Excel I'm trying to make a IF statement that logically sounds like this: If a cell in this range contain "TS" Look up the value in the Same column in Row 4 and make it hat value.

Essentially : =IF(COUNTIF(AC5:BC5,"TS"),( the same column as the one that contains TS but the value Row 4,"")

enter image description here

Anyone have any ideas?

Assigning part of an if statement to a variable

Is it possible to assign

get_theme_mod('dds) !=='false';

to a variable and include it in an if statement instead of typing the whole thing?

This is the if statement I am dealing with:

$DDS = get_theme_mod('dds')!=='false';

if(is_category() && $DDS :
    //output some css style
endif;

I get an error: Parse error: syntax error, unexpected ':'

How to go back to the first for loop from a nested for loop in MATLAB?

I have 2 for loops in a code, and I want to go back to the first loop in the second loop (in a certain condition). How should I do that? The following code is what I use.

function func(x)
for i=1:9
   for j = 2:10
       differences = abs(x(j)-x(i));
       if differences >= 0.5
       max_num = x(j);
       %%  From here go back to the second line and start from i+1
       else
       continue; 
   end
end
end
end   

Result of double postincrementation - in if statement and its body

Could someone explain me why this short line of code is returning 1?

int i = 0;
if(i++) i++;
printf("%d", i);

I mean when checking the if statement i has to be incremented otherwise the result would not be 1. But then as it is incremented is should be incremented once again resulting in 2.

And even better, why this line of code is resulting 2?

int i = 0;
if(++i || i++) i++;

Also this

int i = 0;
if(++i && i++) i++;

Returns 3.

Why PHP is not showing my HTML code inside an "if" statement? [on hold]

I'm trying to create a forgot password page and I have echoed some HTML into my PHP code but the HTML part is not showing

code:

if(!$_GET['code']) {
  echo "
    <form action='forgot_pass.php' method='POST'>
      Enter your username<br><input type='text' name='username'><p>
      Enter your email<br><input type='text' name='email'><p>
      <input type='submit' value='Submit' name='submit'>
    </form>
  ";
}

Python - If, elif statements

I've not long started with python and I've looked over a lot of posts on here but just cant seem to work out whats wrong with my code... If the user types in N or n then surely my elif would kick in but it still plays the sound and prints out "sound played". Can anyone help please? Thank you.

test2 = raw_input("Would you like to test the sound? Y\N or exit? ")
if test2 == "Y" or "y":
    winsound.PlaySound('C:/Windows/Media/tada.wav', winsound.SND_FILENAME)
    print ("Sound Played")
elif test2 == "N" or "n":
    print ("Test skipped")
elif test2 == "exit":
    print ("Test exit")
else:
    print ("Please choose an option")

vlookup if matches row and column

I'm creating a schedule and want to fill in who is scheduled at a certain dates and store.

If nothing is currently scheduled, then the space will read open.

See picture for desired results.

Thank you.

enter image description here

VLOOKUP and IF in Excel

an excel cell:

=VLOOKUP(A11;datax;17;0) 

Function returns a integer -- But then if a try:

=IF(VLOOKUP(A10;datax;17;0) > 0; VLOOKUP(A10;datax;18;0) ;  VLOOKUP(A10;datax;17;0) )

It returns #REF!

Why?

Visual Basic: Else-Ifs with For loops stopping after first For loop

I have a series of If, Then, ElseIfs checking through rows in this worksheet. It looks to see if the entire is not zero, but looking for the sum of cells to not be zero, then checks for any other zeroes in the row. Essentially in each row, if there any values, I want to make sure that ALL values are filled in. What I have for now is this:

ElseIf Application.WorksheetFunction.Sum(CashL1) <> 0 Then Dim i As Integer For i = 2 To 10 If Cells(8, i).Value = 0 Then Cancel = True MsgBox ("Values missing in *this section* at " & Chr$(i + 64) & 8) End If Next i MsgBox "CashL1: Good"

This works great once, however I have another block of the same kind immediately following it with:

'******************************************************************************

ElseIf Application.WorksheetFunction.Sum(CashL2) <> 0 Then Dim j As Integer For j = 2 To 10 If Cells(9, j).Value = 0 Then Cancel = True MsgBox ("Values missing in *this other section* at " & Chr$(j + 64) & 9) End If Next j MsgBox "CashL2: Good"

I added the MsgBox saying "CashL(1/2): Good" so I could see what it was doing. It appears to only be going through the first one successfully and then showing the MsgBox, unfortunately after that, it ends. It never even makes it to the next section: CashL2. Am I overlooking something somewhere? I am still a VB beginner obviously, so I'm still trying to figure out how to correct myself.

I need a if-statement for drag and drop

I need a if-statement for my drag and drop code:

If the user drag the item into a empty box, all is okay. The item will show in the empty box (this can do my code below).

But, if the user drag the item into a non-empty-box, the item in the non-empty-box will exchange with the drag item. My code drag the item in the box also the box is not empty :-(

And my second Problem: If the user drag the item anywhere on the screen, the item disappear :-(

@Override
public boolean onDrag(View v, DragEvent event) {
    switch (event.getAction()) {
        case DragEvent.ACTION_DRAG_STARTED:
            // Do nothing
            break;
        case DragEvent.ACTION_DRAG_ENTERED:
            v.setBackground(enterShape);
            break;
        case DragEvent.ACTION_DRAG_EXITED:
            v.setBackground(normalShape);
            break;
        case DragEvent.ACTION_DROP:
            // view dropped, reassign the view to the new ViewGroup
            View view = (View) event.getLocalState();
            ViewGroup owner = (ViewGroup) view.getParent();
            owner.removeView(view);
            LinearLayout container = (LinearLayout) v;
            container.addView(view);
            view.setVisibility(View.VISIBLE);
            break;
        case DragEvent.ACTION_DRAG_ENDED:
            v.setBackground(normalShape);
        default:
            break;
    }
    return true;
}

Greater than issue

I am trying to create a function that asks the user to input the size of a drive and if the drive size is greater then 100 then ask the user to input it again. My script just keeps saying "Cannot ask for more then 100gb" even if the user inputs 50.

Here is my script param ( [string]$MaxC = "100" )

function cDrive {

$C_DiskGB = Read-Host "C: Drive - Disk Size in GB"
    if ($C_DiskGB -gt $MaxC) {

            Write-Host "Cannot ask for more then 100gb of disk space.  Please re-enter how much disk space you need for the c: drive" 
            cDrive 

         }
    else {

        Write-Host "C: Drive is $C_DiskGB GB" 

         } 

}

The output when i put anything less is: C: Drive - Disk Size in GB: 50 Cannot ask for more then 100gb of disk space. Please re-enter how much disk space you need for the c: drive C: Drive - Disk Size in GB:

Any help is greatly appreciated. Thanks!

PHP Boolean true/false issue in 'if' statement [duplicate]

The following code

$status = true;

if($status == 'all') {
  echo "Hello!";
} else {
  echo "Bye!";
}

outputs "Hello" when $status = true, but "Bye" when $status = false. Why is that the case?

PHP action when more than one checkbox was selected

I've got a POST form with its action on the same page. The form has many checkboxes and I'd like run some PHP line when the user has checked more than one checkbox (PHP should run after submitting the form).

So basically I'd need following in PHP:

If checked checkboxes of #FormXY > 1
...do something...
else (which means 0 or 1 checked checbox)
...do something else

Thanks in advance, Tom

if-else condition not being checked, FixedUpdate method Unity3D

void FixedUpdate () {

        Vector3 pos = GameObject.FindWithTag("Player").transform.position;
        Vector3 newPos = GameObject.FindWithTag("Player").transform.position;

        moveDirection = Vector3.zero;

        if(pos.x == 0f){
            if (Input.GetKey (KeyCode.A)) {
                newPos.x = -1.3f;
                transform.position = Vector3.Slerp (pos, newPos, movespeed);
            } 
            else if (Input.GetKey (KeyCode.D)) {
                newPos.x = 1.3f;
                transform.position = Vector3.Slerp (pos, newPos, movespeed);
            }
        }
        else if(pos.x == 1.3f){
            if(Input.GetKey(KeyCode.A)){
                newPos.x = 0f;
                transform.position = Vector3.Slerp (pos, newPos, movespeed);
            }
        }
        else if(pos.x == -1.3f){
            if(Input.GetKey(KeyCode.D)){
                newPos.x = 0f;
                transform.position = Vector3.Slerp (pos, newPos, movespeed);
            }
        }

        moveDirection.z = movespeed;    
        controller.Move (moveDirection * Time.deltaTime);
    }

i am using this code to move my player between three lanes. the game starts at the middle lane which is at 0 position of x, the right lane is at 1.3 of x and the left lane is at -1.3 of x. when the game starts it gets pos.x == 0f to be true and the A and D controls work and moves the player to the left or the right lanes according to input but once the player is at 1.3 or -1.3 the other two else-if conditions are not being checked i guess so i can't go back to the middle lane. i don't know why its happening. this code gives no error and it should work. any idea?

Java if statement. user input

i am using scanner to take user input.

    Scanner scanner = new Scanner(System.in);

    Int choice = scanner.nextInt();

    if(choice==1) {
    System.out.println(" you chosed number 1!")
    }

    if(choice==2) {
    System.out.println(" you chosed number 2!")
    }

    if(choice==3) {
    System.out.println(" you chosed number 3!")
    }

    if(choice==q) {
    System.out.println("the game will end now!");
    }

so when you enter the game you have a meny that poops up. you can chose between 1, 2, 3 or q. if you press any of the numbers the game will take you to those sections. but if you press q the game will end.

i dont know how to fix so that i can enter q and game ends. help please

If and or statement

I have a nested logic statement below that is frustrating me, the logic inside the OR statement should be evaluating as true however when I evaluate the formula it is showing as false even though the values met the criteria.

The second and third if statements are all functioning as expected as this if statement is in use in different part of the workbook.

I12 is a value based of an Vlookup could this be causing the issue? Googling this is makes it unclear, changing the values of I12 to text didn't have an affect.

 =IF(AND(OR(I12="In Assesment",I12="New Project"),IF(N$11>=$H12,N$11<=$I12)),"Yellow",IF((AND(N$11>=$H12,N$11<=$I12)),"Yes","No"))

Pandas conditional creation of a new dataframe column

This question is an extension of question. If we had this dataframe:

    Col1       Col2
1    A          Z
2    B          Z           
3    B          X
4    C          Y
5    C          W

and we wanted to do the equivalent of:

if Col2 in ('Z','X') then Col3 = 'J' 
else if Col2 = 'Y' then Col3 = 'K'
else Col3 = {value of Col1}

How could I do that?

Create a new column depending on different values in other columns R

I have a big data set that in its short version looks like this:

> df
Stimulus    TimeDiff
S102        10332.4
S 66        1095.4
S103        2987.8
S 77        551.4
S112        3015.2
S 66        566.6
S114        5999.8
S 88        403.8
S104        4679.4
S 88        655.2

I want to create a new column df$Accuracy where I need to assign correct, incorrect responses, and misses depending on certain values (only S 88, S 66, S 77) in the df$Stimulus and in df$TimeDiff. For example, if S 88 is preceded by S114 or S104 and df$TimeDiff for that row is less than 710 then assign "incorrect" in df$Accuracy. So the data set would look like this:

> df
Stimulus    TimeDiff     Accuracy
S102        10332.4      NA 
S 66        1095.4       NA
S103        2987.8       NA
S 77        551.4        NA
S112        3015.2       NA
S 66        566.6        NA
S114        5999.8       NA
S 88        403.8        incorrect
S104        4679.4       NA
S 88        655.2        incorrect 

What is the best way to do it?

How to use foreach and if statement within array of arrays?

I'm developing a WordPress plugin and using Tareq's WordPress Settings API to develop my settings page.

With the API, I am displaying checkbox items. However, I want to show additional checkboxes using the foreach and if statement.

  • foreach: this will display additional checkboxes for every field in the wp_get_user_contact_methods()
  • if: this will display an extra set of checkboxes if another plugin is activated

This is what I have right now going off of my own logic:

$settings_fields = array( // Parent array
    'dsbl_basics' => array( // Child array
        array( // Child's child array
            'name' => 'text_val',
            'label' => __( 'Text Input', 'dsbl' ),
            'type' => 'text',
            'default' => 'Title',
            'sanitize_callback' => 'intval'
        )
    ),
    'dsbl_profile' => array( // Child array
        array( // Child's child array
            'name' => 'name',
            'label' => __( 'Name', 'dsbl' ),
            'type' => 'multicheck',
            'options' => array(
                'first_name' => 'First Name',
                'last_name' => 'Last Name'
            )
        ),
        array( // Child's child array
            'name' => 'contact_info',
            'label' => __( 'Contact Info', 'dsbl' ),
            'type' => 'multicheck',
            'options' => array(
                'url' => 'Website',
                foreach ( wp_get_user_contact_methods() as $value => $label ) { // Additional contact fields
                    $value => $label
                }
            )
        ),
        if ( is_plugin_active( 'wordpress-seo/wp-seo.php' ) ) { // If plugin exists
            array( // Child's child array
                'name' => 'yoast_seo',
                'label' => __( 'Yoast SEO', 'dsbl' ),
                'type' => 'multicheck',
                'options' => array(
                    'wpseo_author_title' => 'Title to use for Author page',
                    'wpseo_author_metadesc' => 'Meta description to use for Author page'
                )
            ),
        }
    )
);

I know that my syntax is off which is giving me these errors:

Parse error: syntax error, unexpected foreach (T_FOREACH), expecting )

Parse error: syntax error, unexpected if (T_IF), expecting )

What is the proper approach to this?

How to add a break if product title is less than a certain amount of charaters

I am trying to get more of a consistent grid layout on my shop loop.

The product title spans over 1 or 2 lines depending on the string length, therefore if the string length is below the amount which forces it to overlap to the next line I want to add a break '
' so that it doesn't affect the overall spacing of the shop loop page

This is what i have at the moment

<?php
    echo "test";
    $title = get_the_title();
    if (strlen($title) <29 )
    {
    echo '<br>';
    }
?>

I have tried putting it in content-product.php but its not working Is my code correct?

Any help would be greatly appreciated

Ending script with if statement

I'm very new to Python and want to know how to end a program with an if statement that prints a message, as this does not appear to be happening with my 'stand' variable when it is under < 5000. The if statement bolded ** ** is the code I'm having trouble with and it still prints the message I want, however, the program does not stop with that message but continue going to the next code (countdown variable). Ignore 'countdown'.

Here is a part of my code.

   while stand <= 0 or mission > 10000: 
        try: 
            stand = int(input("Enter a VALID distance in metres: ")) 
        except ValueError: 
            print("Please enter a valid distance E.g 6000: ") 
    **if stand > 0 or stand < 5000: 
        print("ERROR, ERROR") 
        print("Launch cannot begin, the Mission Control and spectator stands are dangerously close at a distance of {}m.".format(mission)) 
        print("This launch site sucks! It must be demolished and rebuilt!") 
        print("Launch delayed.")**                   

    if stand >= 5000: 
        print("Fortunately the mission control and viewing stands are situated far enough.")              
    while countdown == 0 or countdown == "": 
        print("We need a person to countdown.")
        try:
            countdown = int(input("How many seconds would you like the countdown to be?: "))
        except ValueError:

Is it ok to call the method again from inside the method?

Is this ok, I feel like its not right, like im doing a "GOTO", is this ok?

private void myCopySpecial()
{
    TSMUI.Picker myPicker1 = new TSMUI.Picker();
    Component c1 = myPicker1.PickObject(TSMUI.Picker.PickObjectEnum.PICK_ONE_OBJECT) as Component;

    TSMUI.Picker myPicker2 = new TSMUI.Picker();
    Beam fromBeam = myPicker2.PickObject(TSMUI.Picker.PickObjectEnum.PICK_ONE_PART) as Beam;

    if (c1 == null)
    {
        MessageBox.Show("That's not a component? Try again.");
        //User selected something other than a component, start again.
        myCopySpecial();
    }

BASH - Change information in columns 2 by 2 using for loop and If statements

I have the following tab-separated file:

A1    A1    0       0       1       1       0 0     0 0     2 2     1 2
A2    A2    0       0       1       1       1 1     1 1     0 0     1 2
A3    A3    0       0       1       2       1 1     1 1     0 0     2 2
A4    A4    0       0       1       1       1 1     0 0     0 0     1 2

The idea is to modify the information between column 7 (included) and the end in the way that, for every row, if column 7 and 8:

  • equal “0 0”: don’t modify

  • equal “1 1”: don’t modify

  • equal “1 2” or “2 1”: change to “2 2”

  • equal “2 2”: don’t modify

And the same for the following columns (9 and 10, then 11 and 12, 13 and 14, and so on..).

I started to extract the columns I want to work on using the command:

awk '{for (i = 7; i <= NF; i++) printf $i " "; print ""}' test.ped > tmp_test.txt

Then I was thinking to use a for loop with If statements, with this general format:

for i between 7 and the end (for (i = 7; i <= NF)):
       if i and i+1 == “1 2”:
        replace by “2 2”
    elif i and i+1 == “2 1”:
        replace by “2 2”
    else
        pass
    i=i+2 (increase i to do the same for the next double columns)

But I am stuck here. Is the general format logical or is there a faster way to do the same? Am I going in the right direction?

The expected output (after merging the first 6 columns from the initial file and the ones that I subsetted and modified) is:

A1    A1    0       0       1       1       0 0     0 0     2 2     2 2
A2    A2    0       0       1       1       1 1     1 1     0 0     2 2
A3    A3    0       0       1       2       1 1     1 1     0 0     2 2
A4    A4    0       0       1       1       1 1     0 0     0 0     2 2

Thank you for your help!

If statement not being picked up

I'm working on my first program that is supposed to simulate launch procedures, but my if statement isn't being picked up, which is supposed to end the program, and instead it immediately proceeds to the next part of the code.

Any help will be greatly appreciated as this is the last problem I can find in my program. Sorry for the non-pythonic language

   while mission <= 0 or mission > 1000: 
        try: 
            mission = int(input("Enter a VALID distance in metres: ")) 
        except ValueError: 
            print("Please enter a valid distance E.g 100: ") 
    if mission > 0 or mission < 100: 
        print("ERROR, ERROR")            

    if mission >= 5000: 
        print("The viewing stands are situated far enough.")              
    while people == 0 or people == "":  
        print("We need to know how many people are spectating.")
        try:
            people = int(input("How many people are there watching?: "))
        except ValueError:
            print("Please enter a valid number: ")

lundi 29 août 2016

R: Improving Nested ifelse Statements & Multiple Patterns

I am continuing to work on some data cleaning practice with some animal shelter data. My goal here is to shrink down the number of breed categories.

I am using each breed category as a partial pattern match against the outgoing$Single.Breed data frame column. So, there are cases where the breed will just be Chihuahua, but it may also be Long Hair Chihuahua. (Hence, my use of grepl.) Thus, anything containing a breed category would be represented in a different column by said category. Furthermore, I also need to add the cat breed categories...making for an even messier bunch of code.

The code below is my "solution", but it's quite clunky. Is there a better, slicker and/or more efficient way to accomplish this?

BreedCategories <- ifelse(outgoing$New.Type == "Dog",
           ifelse(grepl("Chihuahua",outgoing$Single.Breed, ignore.case = TRUE), "Chihuahua",
           ifelse(grepl("Pit Bull",outgoing$Single.Breed, ignore.case = TRUE), "Pit Bull",
           ifelse(grepl("Terrier",outgoing$Single.Breed, ignore.case = TRUE), "Terrier",
           ifelse(grepl("Shepherd",outgoing$Single.Breed, ignore.case = TRUE), "Shepherd",
           ifelse(grepl("Poodle",outgoing$Single.Breed, ignore.case = TRUE), "Poodle",
           ifelse(grepl("Labrador|Retriever",outgoing$Single.Breed, ignore.case = TRUE),"Labrador",
           "Other")))))),"Cat")

Optimizing an if statement with over 50 OR's ( || )

Okay, so I'm doing some stuff involving keyboard input. I now have a giant function like this:

return key == BB_KEY_SPACE || key == BB_KEY_ZERO || key == BB_KEY_ONE || key == BB_KEY_TWO || key == BB_KEY_THREE || key == BB_KEY_FOUR || key == BB_KEY_FIVE || key == BB_KEY_SIX || key == BB_KEY_SEVEN || key == BB_KEY_EIGHT || key == BB_KEY_NINE || key == BB_KEY_A || key == BB_KEY_B || key == BB_KEY_C || key == BB_KEY_D || key == BB_KEY_E || key == BB_KEY_F || key == BB_KEY_G || key == BB_KEY_H || key == BB_KEY_I || key == BB_KEY_J || key == BB_KEY_K || key == BB_KEY_L || key == BB_KEY_M || key == BB_KEY_N || key == BB_KEY_O || key == BB_KEY_P || key == BB_KEY_Q || key == BB_KEY_R || key == BB_KEY_S || key == BB_KEY_T || key == BB_KEY_U || key == BB_KEY_V || key == BB_KEY_W || key == BB_KEY_X || key == BB_KEY_Y || key == BB_KEY_Z || key == BB_KEY_NUMPAD0 || key == BB_KEY_NUMPAD1 || key == BB_KEY_NUMPAD2 || key == BB_KEY_NUMPAD3 || key == BB_KEY_NUMPAD4 || key == BB_KEY_NUMPAD5 || key == BB_KEY_NUMPAD6 || key == BB_KEY_NUMPAD7 || key == BB_KEY_NUMPAD8 || key == BB_KEY_NUMPAD9 || key == BB_KEY_MULTIPLY || key == BB_KEY_PLUS || key == BB_KEY_SEPERATOR || key == BB_KEY_MINUS || key == BB_KEY_DECIMAL || key == BB_KEY_DIVIDE || key == BB_KEY_OEM1 || key == BB_KEY_OEMPLUS || key == BB_KEY_OEMCOMMA || key == BB_KEY_OEMMINUS || key == BB_KEY_OEMPERIOD || key == BB_KEY_OEM2 || key == BB_KEY_OEM3 || key == BB_KEY_OEM4 || key == BB_KEY_OEM5 || key == BB_KEY_OEM6 || key == BB_KEY_OEM7 || key == BB_KEY_OEM8 || key == BB_KEY_OEM102;

Is there a good way to optimize this? I am assuming it takes a bit of processing power to verify all of this if-statement stuff. When looking at diagnostics it seems it's taking up a bit of time too. I'm wondering if there is a smarter way of doing this..

javascript, combining AND, OR in an if starement

I would like my code to be able to do the following;

IF (value1 is less than -1 AND variable2 does not equal either 6 or 5) then...

so far I can get a single if and to work as follows;

  if( (value < -1 && (day !== 6)) )  sendEmail(value)

but as soon as I add in the second or it falls over. What am I doing wrong? I have tried it in a few different ways but below are a couple of examples that did not work.

  if( (value < -1 && (day !== 6 || 5)) )  sendEmail(value)

  if( (value < -1 && (day !== 6 || day !== 5)) )  sendEmail(value)

apply function with a conditional statement using two dataframe

I have two data frame x and y.

x<-data.frame("j"=c("A","B","C"),"k"=c(1,90,14))
  x j  k
  1 A  1
  2 B 90
  3 C 14

y<-data.frame("A"=c(1,0,0,1,1),"B"=c(0,1,0,0,1),"C"=c(1,1,1,0,0))
  A B C
1 1 0 1
2 0 1 1
3 0 0 1
4 1 0 0
5 1 1 0

I need a function with a conditional statement where if in the data set y there is a 0 a replace by -1 or 1 replace by 1 in the column A and so on to get this result.

z<-data.frame("A"=c(1,-1,-1,1,1),"B"=c(-90,90,-90,-90,90),"C"=c(14,14,14,-14,-14))
   A   B   C
1  1 -90  14
2 -1  90  14
3 -1 -90  14
4  1 -90 -14
5  1  90 -14

i3 - executing multiple commands but only if instances don't yet exist

I am using i3 window manager and am trying to configure my desktop so that key combination Win+o would open Viber, Skype and Whatsapp. So this is what I put in ~/.config/i3/config file:

bindsym $mod+o exec "viber & chromium --app=http://ift.tt/1Dt3Tno & chromium --app=http://ift.tt/1BsJicG"

This works fine and all three windows open up fine, but if I close only Skype and again press Win+o I will have one instance of Skype and two instances of Viber / Whatsapp.

So I need to somehow first check if any instance of the programs is already running and prevent the ones that do to reload. I had an idea to start xprop and click on all of the windows to get their details which look like it is shown below.

Whatsapp:

WM_STATE(WM_STATE):
                window state: Normal
                icon window: 0x0
_NET_WM_DESKTOP(CARDINAL) = 1
_NET_WM_USER_TIME(CARDINAL) = 6425123
WM_NORMAL_HINTS(WM_SIZE_HINTS):
                program specified location: 0, 18
WM_NAME(UTF8_STRING) = "WhatsApp"
_NET_WM_NAME(UTF8_STRING) = "WhatsApp"
XdndAware(ATOM) = BITMAP
_MOTIF_WM_HINTS(_MOTIF_WM_HINTS) = 0x2, 0x0, 0x1, 0x0, 0x0
_NET_WM_ICON(CARDINAL) =        Icon (16 x 16):

               ░░       
            ░░▒▒▒▒░░    
           ░▒▒▒▒▒▒▒▒░   
          ░▒░ ▒▒▒▒▒▒▒░  
          ░▒  ░▒▒▒▒▒▒▒  
          ▒▒   ▒▒▒▒▒▒▒  
         ░▒▒  ░▒▒▒▒▒▒▒░ 
         ░▒▒░  ▒▒▒▒▒▒▒░ 
          ▒▒▒░  ░  ░▒▒  
          ▒▒▒▒░     ▒▒  
          ░▒▒▒▒▒░  ░▒░  
          ░▒▒▒▒▒▒▒▒▒░   
          ░░░░▒▒▒▒▒░    
               ░░       


        Icon (16 x 16):

               ░░       
            ░░▒▒▒▒░░    
           ░▒▒▒▒▒▒▒▒░   
          ░▒░ ▒▒▒▒▒▒▒░  
          ░▒  ░▒▒▒▒▒▒▒  
          ▒▒   ▒▒▒▒▒▒▒  
         ░▒▒  ░▒▒▒▒▒▒▒░ 
         ░▒▒░  ▒▒▒▒▒▒▒░ 
          ▒▒▒░  ░  ░▒▒  
          ▒▒▒▒░     ▒▒  
          ░▒▒▒▒▒░  ░▒░  
          ░▒▒▒▒▒▒▒▒▒░   
          ░░░░▒▒▒▒▒░    
               ░░       



WM_WINDOW_ROLE(STRING) = "pop-up"
WM_CLASS(STRING) = "web.whatsapp.com", "chromium"
_NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_NORMAL
_NET_WM_PID(CARDINAL) = 6987
WM_LOCALE_NAME(STRING) = "en_US.utf8"
WM_CLIENT_MACHINE(STRING) = "ziga-laptop"
WM_PROTOCOLS(ATOM): protocols  WM_DELETE_WINDOW, _NET_WM_PING

Skype:

_NET_WM_DESKTOP(CARDINAL) = 1
WM_STATE(WM_STATE):
                window state: Normal
                icon window: 0x0
_NET_WM_USER_TIME(CARDINAL) = 6297395
WM_NORMAL_HINTS(WM_SIZE_HINTS):
                program specified location: 962, 18
WM_NAME(UTF8_STRING) = "Skype"
_NET_WM_NAME(UTF8_STRING) = "Skype"
XdndAware(ATOM) = BITMAP
_MOTIF_WM_HINTS(_MOTIF_WM_HINTS) = 0x2, 0x0, 0x1, 0x0, 0x0
_NET_WM_ICON(CARDINAL) =        Icon (64 x 64):



                                 ░░▒▒▒▒▒▒▒▒▒▒░░                         
                              ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░                      
                           ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░                   
                         ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░                 
                        ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░                
                      ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░              
                     ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░             
                    ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░            
                   ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░           
                  ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░          
                 ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░         
                ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░        
                ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒        
               ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒       
              ░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░      
              ░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░      
             ░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░         ░░░░░░░░░░░░░░░░░░░░░      
             ░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░             ░░░░░░░░░░░░░░░░░░░░     
            ░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒░      ░░░░      ░░░░░░░░░░░░░░░░░░░     
            ░░░░░░░▒▒▒▒▒▒▒▒▒▒▒░    ░░░░░░░░░░    ░░░░░░░░░░░░░░░░░░     
            ░░░░░░░░▒▒▒▒▒▒▒▒▒░    ░░░░░░░░░░░░    ░░░░░░░░░░░░░░░░░░    
           ░░░░░░░░░▒▒▒▒▒▒▒▒▒   ░░░░░░░░░░░░░░░░   ░░░░░░░░░░░░░░░░░    
           ░░░░░░░░░░▒▒▒▒▒▒▒    ░░░░░░░░░░░░░░░░    ░░░░░░░░░░░░░░░░    
           ░░░░░░░░░░▒▒▒▒▒▒▒   ░░░░░░░░░░░░░░░░░░   ░░░░░░░░░░░░░░░░    
           ░░░░░░░░░░░▒▒▒▒▒░  ░░░░░░░░░░░░░░░░░░░░   ░░░░░░░░░░░░       
           ░░░░░░░░░░░▒▒▒▒▒   ░░░░░░░░░░░░░░░░░░░░   ░░░░░░             
           ░░░░░░░░░░░░▒▒▒▒   ░░░░░░░░░░░░░░░░░░░░    ░                 
           ░░░░░░░░░░░░░▒▒░  ░░░░░░░░░░░░░░░░░░░░░░                     
           ░░░░░░░░░░░░░▒▒░  ░░░░░░░░░░░░░░░░░░░░░░                 ░   
           ░░░░░░░░░░░░░░▒░  ░░░░░░░░░░░░░░░░░░░░░░                 ░   
           ░░░░░░░░░░░░░░▒░  ░░░░░░░░░░░░░░░░░░░░░░                 ░   
           ░░░░░░░░░░░░░░░▒   ░░░░░░░░░░░░░░░░░░░░                 ░░   
           ░░░░░░░░░░░░░░░░   ░░░░░░░░░░░░░░░░░░░░                 ░░   
           ░░░░░░░░░░░░░░░░░  ░░░░░░░░░░░░░░░░░░░░                ░░░   
           ░░░░░░░░░░░░░░░░░   ░░░░░░░░░░░░░░░░░░                ░░░    
           ░░░░░░░░░░░░░░░░░    ░░░░░░░░░░░░░░░░                 ░░░    
           ░░░░░░░░░░░░░░░░░░   ░░░░░░░░░░░░░░░░   ░            ░░░░    
            ░░░░░░░░░░░░░░░░░░    ░░░░░░░░░░░░                  ░░░░    
            ░░░░░░░░░░░░░░░░░░░    ░░░░░░░░░░    ░             ░░░░     
            ░░░░░░░░░░░░░░░░░░░░      ░░░░      ░░            ░░░░░     
             ░░░░░░░░░░░░░░░░░░░░              ░░            ░░░░░      
             ░░░░░░░░░░░░░░░░░░░░░░          ░░░             ░░░░░      
              ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░            ░░░░░░      
              ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░            ░░░░░░       
               ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░           ░░░░░░        
                ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░           ░░░░░░░        
                ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░          ░░░░░░░         
                 ░░░░░░░░░░░░░░░░░░░░░░░░░░░░          ░░░░░░░          
                  ░░░░░░░░░░░░░░░░░░░░░░░░░░          ░░░░░░░           
                   ░░░░░░░░░░░░░░░░░░░░░░░░░        ░░░░░░░░            
                    ░░░░░░░░░░░░░░░░░░░░░░░        ░░░░░░░░             
                     ░░░░░░░░░░░░░░░░░░░░░░       ░░░░░░░░              
                      ░░░░░░░░░░░░░░░░░░░░      ░░░░░░░░░               
                        ░░░░░░░░░░░░░░░░░░     ░░░░░░░░                 
                         ░░░░░░░░░░░░░░░░    ░░░░░░░░░                  
                           ░░░░░░░░░░░░░   ░░░░░░░░░                    
                             ░░░░░░░░░░░ ░░░░░░░░                       
                                ░░░░░░░░░░░░░                           





WM_WINDOW_ROLE(STRING) = "pop-up"
WM_CLASS(STRING) = "web.skype.com__en", "chromium"
_NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_NORMAL
_NET_WM_PID(CARDINAL) = 6987
WM_LOCALE_NAME(STRING) = "en_US.utf8"
WM_CLIENT_MACHINE(STRING) = "ziga-laptop"
WM_PROTOCOLS(ATOM): protocols  WM_DELETE_WINDOW, _NET_WM_PING

Viber:

WM_STATE(WM_STATE):
                window state: Normal
                icon window: 0x0
_NET_WM_DESKTOP(CARDINAL) = 1
_NET_WM_ICON(CARDINAL) = 
XdndAware(ATOM) = BITMAP
WM_NAME(STRING) = "Viber +38631790976"
_NET_WM_NAME(UTF8_STRING) = "Viber +38631790976"
_MOTIF_WM_HINTS(_MOTIF_WM_HINTS) = 0x3, 0x3e, 0x7e, 0x0, 0x0
_NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_NORMAL
_XEMBED_INFO(_XEMBED_INFO) = 0x0, 0x1
WM_CLIENT_LEADER(WINDOW): window id # 0x800008
WM_HINTS(WM_HINTS):
                Client accepts input or input focus: True
                Initial state is Normal State.
_NET_WM_PID(CARDINAL) = 28603
WM_CLASS(STRING) = "Viber", "ViberPC"
WM_PROTOCOLS(ATOM): protocols  WM_DELETE_WINDOW, WM_TAKE_FOCUS, _NET_WM_PING
WM_NORMAL_HINTS(WM_SIZE_HINTS):
                user specified location: -1, 20
                user specified size: 1921 by 1036
                program specified minimum size: 785 by 550
                window gravity: Static

Can anyone help me on how to check if these instances are already running?

Bash Automatically while loop variable

Is there a way to call a variable through the $i in a while loop? To access a variable automatically?

This is what i mean:

i=1;
card1=1;
card2=1;
card3=1;

while [[ $i -lt 4 ]]; do

    if [ "$card$i" = "1" ]; then 
        let card$i++;
    fi

    let i++;
done

Is there a way to make this work?

Thanks.

IF statement picking first option in currency converter (python)

print "Pound Sterling converter"
print "You can convert pounds to either dollars, euros or yen"

print

dollar = 0
euro = 0
yen = 0

convert_to = input ("What currency do you want to convert to? ")
amount = input("How much would you like to convert? ")

print

if convert_to == dollar:
    amount = amount * 1.3
elif convert_to == euro:
     amount = amount * 1.17
elif convert_to == yen:
    amount = amount * 133.66
else:
    print "You must pick either dollar, euro or yen."

print amount

I'm a beginner in Python, as you can probably tell. All I want this program to do is have the user choose a currency (convert_to) and then choose how much they want to convert (amount) and then the program will convert it for them.

When I run the program, the if statement does not work correctly. Instead of seeing what convert_to is, it goes through the convert_to == dollar part regardless of if you type euro or yen. The numbers they are being multiplied by are simply the conversion rates from pounds.

also, a side note but less important one, the final else part does not work. The program brings up a "input not defined" error instead of printing "You must pick either dollar, euro or yen."

Thanks in advance

if statement inside a for statement runs only once in R

I have a dataframe which contains the following text:

df$Position 

[1] "START"  "MIDDLE" "MIDDLE" "START"  "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START"  "START"  "START"  "MIDDLE" "MIDDLE" "MIDDLE" "START" 

[22] "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" [43] "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE"

I would like to replace the "MIDDLE" text before the previous "START" text with "END" to mark the correct position.

So i am basically iterating through the positions in the frame and if the condition is met then replace the text.

for(i in 2:i)
{    
# iterate through the frame
if (df$Position[i]=="START" && df$Position[i-1]=="MIDDLE")

{
df$Position[i-1] <- "END"
}
}

This appears to work once only. I end up with the following output:

[1] "START"  "MIDDLE" "END"    "START"  "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START"  "START"  "START"  "MIDDLE" "MIDDLE" "MIDDLE" "START" 

[22] "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" [43] "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE"

I'm wondering what i am doing wrong here and if there is a better approach (maybe a custom function??) to complete this task.

Regards Jonathan

multiple or conditions in if else statements best way oracle pl sql

I have below scenario where i have to check multiple or conditions to check if local varibale should not be equal to A, B, C, D and so on. Obviously real values are different than I refered here. I want to know which one is the best from below or any other possible way:

IF(condition1 AND (myLocalVAr NOT IN ('A','B','C','D','E','F') ) ) THEN
----
--
END IF;

or

IF(condition1 AND (myLocalVAr <> 'A' OR myLocalVAr <> 'B' OR myLocalVAr <> 'C'--'D'--'E'--'F' --so on) ) ) THEN
----
--
END IF; 

Mysql query with certain IF ELSE If ELSE Conditions

Iam trying to write a mysql query with certain if conditions.

My DB Structure is

Currency (Table)

++++++++++++++++++++++++++
id | currency | rate
++++++++++++++++++++++++++
1      USD       1
2      INR       67.10043
3      GBP       0.761203
4      EUR       0.89295
++++++++++++++++++++++++++

com_payments (Table)
++++++++++++++++++++++++++
id | amt_curr | amt_paid
++++++++++++++++++++++++++
1      EUR        300.89
2      GBP        390.90
3      USD        600.00
++++++++++++++++++++++++++

The query i am looking for is if

if (amt_curr=='USD') {
    $totalinr = (amt_paid * rate); (rate it should take from currency table where currency='USD' from currency table)
} else if ($currency1=='GBP'){
    totalinr = ((select currency, rate from Currency where currency=INR / 0.761203 (GBP value from currency table)) * amt_paid);
} else if ($currency1=='EUR'){
    totalinr = ((select currency, rate from Currency where currency=INR / 0.89295 (EUR value from currency table)) * amt_paid); 
}

Iam trying to achieve this with mysql query: I tried something like this but its not working:

CASE WHEN (amt_curr=='USD') THEN (amt_paid * rate) (rate it should take from currency table where currency='USD' from currency table)
     WHEN ($currency1=='GBP') THEN ((select currency, rate from Currency where currency=INR / 0.761203 (GBP value from currency table)) * amt_paid) 
     WHEN ($currency1=='EUR') THEN ((select currency, rate from Currency where currency=INR / 0.89295 (EUR value from currency table)) * amt_paid)
END AS totalinr

if-statement: how to rewrite in matlab

I newby in Matlab. I have took the work code with complex if-statement condition and need to rewrite it. This code should prepare some initial data to solve an optimization task. This if-statement condition looks like:

x=[784.8 959.2 468 572 279 341 139.5 170.5 76.5 93.5 45 55];
a=combntns(x,6); % all possible combinations from 6 elements of x
n=length(a);
q=[];

 for i=1:n

if( ((a(i,1)==x(1)) & (a(i,2)==x(2))) | 
    ((a(i,1)==x(3)) & (a(i,2)==x(4))) | 
    ((a(i,1)==x(5)) & (a(i,2)==x(6))) |  
    ((a(i,1)==x(7)) & (a(i,2)==x(8))) |
    ((a(i,2)==x(3)) & (a(i,3)==x(4))) |  
    ((a(i,2)==x(5)) & (a(i,3)==x(6))) | 
    ((a(i,2)==x(7)) & (a(i,3)==x(8))) |  
    ((a(i,3)==x(3)) & (a(i,4)==x(4))) |  
    ((a(i,3)==x(5)) & (a(i,4)==x(6))) |  
    ((a(i,3)==x(7)) & (a(i,4)==x(8))) |  
    ((a(i,3)==x(9)) & (a(i,4)==x(10)))|  
    ((a(i,4)==x(5)) & (a(i,5)==x(6))) |  
    ((a(i,4)==x(7)) & (a(i,5)==x(8))) |  
    ((a(i,4)==x(9)) & (a(i,5)==x(10)))|  
    ((a(i,5)==x(5)) & (a(i,6)==x(6))) |  
    ((a(i,5)==x(7)) & (a(i,6)==x(8))) |  
    ((a(i,5)==x(9)) & (a(i,6)==x(10)) | 
    ((a(i,5)==x(11)) & (a(i,6)==x(12)))))
   q(i,:)=a(i,:);
end;
end;
q;
R1=a-q;
R1(~any(R1,2),:) = [];
R1(:, ~any(R1)) = [];

Here x and is a 12-size vector of real numbers, a is 924-by-6 matrix: a=combntns(x,6)

Question: Could anyone give an idea how to rewrite if-statement to improve readability of code?

Update. After the Andras Deak's comments and the Mingjing Zhang's answer I have tried to rewrite the code:

x=[784.8 959.2 468 572 279 341 139.5 170.5 76.5 93.5 45 55];
a = nchoosek(1:length(x), 6); %  all possible combinations from 6 indeces of x

success = any (mod(a(:,1:end-1), 2) & diff(a,1,2)==1);

n=length(a);
q=[];

for i=1:n
if()  
    q(i,:)=a(i,:);
end;
end;
q;
R1=a-q;

The all success(i) is true and I couldn't figure out how to use this logic in the if-statement. I have tried to write

for i=1:n
if(success(i))  
    q(i,:)=a(i,:);
end;
end;

but later I couldn't to use R1=a-q; because the the a and q sizes aren't equal.

dimanche 28 août 2016

Issues with if-statement adding players with `is-inactive` class to input

Problem

The maximum number of players for each position is:

  • 2 out of 4 goalies
  • 6 out of 15 defencemen
  • 12 out of 31 forwards

I've gotten to the point where I'll click on a hockey player and that name gets added to a input field in a form, but if you already have two goalies selected, ie has a class of is-active and then click on one of the other two unselected players with the default is-inactive class, that name will still be added into an input when there should only be two goalies max. And unfortunately, this is also the case with the defencemen and the forwards too.

Goal

When starredGoaltenders === maxGoaltenders or starredDefencemen === maxDefencemen or starredForwards === maxFowards the names of players that do not have not been selected of that specific position and do not have an is-active class should not be added to any input in the form.

scripts.js

    function countSelected() {
        $(".player").on("click", function(){

            // Checks if the maximum number of players have been selected
            // If so, return false and then do nothing
            // If not, the class will toggle from `is-inactive` to `is-active`
            if ($(this).find(".picked.is-inactive.full").length > 0) return false;
            $(this).find(".picked").toggleClass("is-inactive is-active");
            $(".player").removeClass("not-picked");
            $(".player").not(":has(.is-active)").addClass("not-picked");

            // Count the number of players with stars
            var starredGoaltenders = $(".player--goalie").find(".picked.is-active").length;
            var starredDefencemen = $(".player--defencemen").find(".picked.is-active").length;
            var starredForwards = $(".player--forward").find(".picked.is-active").length;

            console.log(starredGoaltenders, starredDefencemen, starredForwards);

            // The number of starred players for each position cannot exceed the following numbers
            var maxGoaltenders = 2;
            var maxDefencemen = 6;
            var maxFowards = 12;

            // If the number of starred players hits its max, a class of `is-completed` is adding to the corresponding checkmark to indicate that the task has been completed
            if (starredGoaltenders === maxGoaltenders) {
                $(".checkmark--goalie").addClass("is-completed");
                $(".player--goalie").find(".picked").addClass("full");
            } else {
                $(".checkmark--goalie").removeClass("is-completed");
                $(".player--goalie").find(".picked.is-inactive").removeClass('full');
            }

            if (starredDefencemen === maxDefencemen) {
                $(".checkmark--defencemen").addClass("is-completed");
                $(".player--defencemen").find(".picked").addClass("full");
            } else {
                $(".checkmark--defencemen").removeClass("is-completed");
                $(".player--defencemen").find(".picked.is-inactive").removeClass('full');
            }

            if (starredForwards === maxFowards) {
                $(".checkmark--forward").addClass("is-completed");
                $(".player--forward").find(".picked").addClass("full");
            } else {
                $(".checkmark--forward").removeClass("is-completed");
                $(".player--forward").find(".picked.is-inactive").removeClass('full');
            }

            // If all the conditions are met show the submit vote button
            if (starredGoaltenders === maxGoaltenders && starredDefencemen === maxDefencemen && starredForwards === maxFowards) {
                $(".btn--submit").show();
                $(".btn--submit").addClass("slideLeft");
            } else{
                $(".btn--submit").hide();
                $(".btn--submit").removeClass("slideLeft");
            }
        });
} countSelected();


// Every time a player is clicked, note the name of the player
$(".player").on("click", function(){
    var playerNames = [];
    $("input:text").each(function(i, t) { playerNames.push(t.value) });

    if ($(this).find("picked.is-active")) {
        var playerName = $(this).find(".player__name").html();
        var index = playerNames.indexOf(playerName);

        if (index == -1) // Add player
            $("input:text:eq(" + playerNames.indexOf("") + ")").val(playerName);
        else // Remove player
            $("input:text:eq(" + index + ")").val("");
    } else {
        $("input").val("");
    }
});

index.html - Snippet includes form and one out of the 60 available players to be clicked on

   <form id="form">
        <input type="text" name="p1"  id="p1">
        <input type="text" name="p2"  id="p2">
        <input type="text" name="p3"  id="p3">
        <input type="text" name="p4"  id="p4">
        <input type="text" name="p5"  id="p5">
        <input type="text" name="p6"  id="p6">
        <input type="text" name="p7"  id="p7">
        <input type="text" name="p8"  id="p8">
        <input type="text" name="p9"  id="p9">
        <input type="text" name="p10" id="p10">
        <input type="text" name="p11" id="p11">
        <input type="text" name="p12" id="p12">
        <input type="text" name="p13" id="p13">
        <input type="text" name="p14" id="p14">
        <input type="text" name="p15" id="p15">
        <input type="text" name="p16" id="p16">
        <input type="text" name="p17" id="p17">
        <input type="text" name="p18" id="p18">
        <input type="text" name="p19" id="p19">
        <input type="text" name="p20" id="p20">

        <button class="btn btn--submit" type="submit"><img src="src/img/ballot-alt.png" class="image--ballot">Submit Vote</button>
    </form>

<div class="player player--forward year--2000 year--2010">
            <div class="tooltip">
                <p class="tooltip__name">Mark Stone</p>
                <p class="tooltip__hometown"><span>Hometown:</span> Winnipeg, Man.</p>
                <p class="tooltip__years"><span>Years Played:</span> 2008-2012</p>
                <div class="tooltip__stats--inline">

                    <div class="stats__group stats--games">
                        <p class="stats__header">GP</p>
                        <p class="stats__number stats__number--games">232</p>
                    </div>

                    <div class="stats__group stats--goals">
                        <p class="stats__header">G</p>
                        <p class="stats__number stats__number--goals">106</p>
                    </div>

                    <div class="stats__group stats--assists">
                        <p class="stats__header">A</p>
                        <p class="stats__number stats__number--assists">190</p>
                    </div>

                    <div class="stats__group stats--points">
                        <p class="stats__header">Pts</p>
                        <p class="stats__number stats__number--points">296</p>
                    </div>

                    <div class="stats__group stats--penalties">
                        <p class="stats__header">Pim</p>
                        <p class="stats__number stats__number--penalties">102</p>
                    </div>
                </div>
            </div>
            <div class="player__headshot player--mstone">
                <div class="picked is-inactive"><i class="fa fa-star" aria-hidden="true"></i></div>
            </div>
            <p class="player__name">Mark Stone</p>
            <p class="player__position">Forward</p>
        </div>

Swift - How to check to see if sprite is assigned to certain image

Currently, in my code, I have an SKSpriteNode named ball which randomly changes texture when it makes contact with anything. There are 4 different textures each with a different colored ball. I want to use an if else statement to check to see if the ball is equal to a specific texture so it can do an action.

I have this code so far, but it does not work

func didBeginContact(contact: SKPhysicsContact) {

    if ball.texture == SKTexture(imageNamed: "ball2") {

        print("Color Matched")

    } else {

        print("Color does not match")
    }


}

The if ball.texture == .... line is not working

How can I test an IF statement in MySQL?

How can I test an IF statement in MySQL ?

I need to know, what happens when a query is into a IF statement and it returns nothing (0 row selected) ?

In other word, what a SELECT query returns when the no row is selected? Will it return NULL? If yes, so will this throw an error? IF ( NULL ) THEN ...? Or in this case just the statement of that IF won't execute?


In reality, I have a code like this:

IF ( SELECT banned FROM users WHERE id=new.user_id ) THEN 
// do stuff

Note: banned column contains either 0 or 1.

All I want to know, is my code safe when that query doesn't return any row? I mean will it throw an error or nothing happens (just that IF statement doesn't execute) ?


Noted that I wanted to test it myselft, but I don't know how can I test a IF statement in MySQL. For example, I wanted to test it by this code:

BEGIN
    IF ( SELECT banned FROM users WHERE id=new.user_id ) THEN 
       SELECT 'test';
    ENDIF;
END

But code above doesn't even run. That's why I've asked this question.

Can't compare NSDates in if statement

I am fetching data from iCloud and would like to compare it if it's more recent than the data on the device. However, my if statement evaluates to true even if the iCloud data is older.

Here is my code:

if ([fetchedRemindersRecord objectForKey:@"reminders"] && ([fetchedRemindersRecord.modificationDate compare:userDefaultsModificationDate] == NSOrderedDescending)){

            [self createReminders:[NSKeyedUnarchiver unarchiveObjectWithData:[fetchedRemindersRecord objectForKey:@"reminders"]]];

            NSLog(@"user defaults date: %@",userDefaultsModificationDate);
            NSLog(@"icloud fetch date : %@",fetchedRemindersRecord.modificationDate);
        }

Console:

user defaults date: 2016-08-28 21:45:24 +0000
icloud fetch date : 2016-08-28 21:34:49 +0000

As you can see clearly, iCloud data is older, however the if statement still evaluates to true. I even checked to make sure that both dates are not nil before comparing. Changing it to NSOrderedAscending doesn't work either..

I have been struggling with this for an hour, can't seem to figure out what's going on.. probably some obvious thing which I am overlooking.

Thanks in advance!

Eliminating long switch

I have an object that keeps weather measurements for a single factory.

public class FactoryWeather { 

    // each measurement consists of min, max and average observations.
    private Measurement temperature;
    private Measurement humidity;
    private Measurement ...

    public constructor,setters/getters...

}

Measurement types are defined as enum like below :

public enum WeatherMeasurementEnum {
    // min and max range of single measurement
    TEMPERATURE(-50,50),
    HUMIDITY(0,100),
    ...

    // validity check for measurements
    public boolean isValid(int average) {
        return average >= minimum && average <= maximum;
    }
}

Finally, I update each measurement using following method :

public void updateWeatherMeasurement(String type, Measurement measurement, FactoryWeather factory) {
    WeatherMeasurementEnum m = WeatherMeasurementEnum(type.toUpperCase());
    if(!m.isValid(measurement.getAverage())
        throw new AppException("Invalid measurement!");

    switch(m) {
    case TEMPERATURE: factory.setTemperature(measurement);break;
    case HUMIDITY: factory.setHumidity(measurement);break;
    ...
    }

}

Although the switch statement might look fine, type of measurements can grow in future. Taking this into consideration and the sake of best practice, is it possible to eliminate this kind of long switch or if/else statements ?

how to ask for input again c++

First of all im sorry if the code look weird here but i dont know how to set it up good. But my question is how i ask the user if he/she wants to input again. ex. do you want to calculate again? yes or no.

}int main()

{

int a;
cout << endl << "Write 1 for addition and 0 for substraction:" << endl;
cin >> a;

// addition
if (a == 1) {
    cout << "You are now about to add two number together, ";
    cout << "enter a number: " << endl;
    int b;
    cin >> b;
    cout << "one more: " << endl;
    int c;
    cin >> c;
    cout << b + c;
}
//Substraction
else if (a == 0) {
    cout << "enter a number: " << endl;
    int b;
    cin >> b;
    cout << "one more: " << endl;
    int c;
    cin >> c;
    cout << b - c;
}
//If not 1 or 0 was called
else {
    cout << " da fuck " << endl;

}

return 0;

}

Stuck with the "binary operator expected" message

Stuck with the "binary operator expected" message when I run this command :

for variable in "ebooks" "movies" "games" "softwares" "music" "series" "tvreplay"
do
    if [ -d /in/recep/downloader_ftp*/${variable} ]
    then
        mv /in/recep/downloader_ftp*/${variable}/* /in/arch/${variable}/ 
    else
        echo "no files type ${variable}"
    fi
done

I know this is because the command find 2 directories starting with the pattern "downloader_ftp*" in the recep directory, but I can't figure good way to do it.

C# How to CLONE a DataSet inside if/else statement

i would like to know (if its posible) how to CLONE a DataSet inside an if/else statement, i mean, i want to trigger a query search using a button, then pour that data into the cloned Dataset (that has the exact structure i want, table relations included) to correctly show search data in form. Here is the code:

    private void btn_Click(object sender, EventArgs e)
{

    OdbcConnection conn = new OdbcConnection(); // A connection string...

    if (whatever)
    {
      whatever
    }
    else
    {
        OdbcDataAdapter SearchData = new OdbcDataAdapter(); //Query string...

        //now i need to clone a existing DataSet

        DataSet cloneSet = dataSet.Clone();

        //Then fill it with dat from query

        SearchData.Fill(cloneSet);
    }
} // end of button click event

Is there a way to accomplish this? Thanks in Advance.

can not break the statement twice

i have a problem with my code,as you can see there's a break statement and a function that can re-loop(i guess)the code,my problem is,if i try to break the statement using the "e" button for the second time it's still looping,help pls?!

class forwarding(): def forward(self): print("you've moved forward!")

class jumping(): def jump(self): print("you've jump!")

class moving(forwarding, jumping): pass

moves = moving()

def Game_on(): while True: move = input("Press 'D' to move forward or 'W' to jump\n") if move is "d": moves.forward() print("You fell and DIE!!!") retry = input("Press 'R' to retry or 'E' to exit the game\n") if retry is "r": Game_on() elif retry is "e": print("You've exit the game") break elif move is "w": moves.jump() print("You just got hit by a plane and DIE!!!") retry = input("Press 'R' to retry or 'E' to exit the game\n") if retry is "r": Game_on() elif retry is "e": print("You've exit the game") break else: print("Make sure to type the moves that are available")

Game_on()

what is mysql stored procedure if statement structure

CREATE PROCEDURE PROCEDURENAME() BEGIN IF ((CONDITION),SELECT 0, SELECT 1)); //not working IF condition THEN statement END IF; //not working IF condition statement //not working END

How should I properly write the if statement structure? Anyone have a working example? Please help me.

Condition on a function

I'm trying to create a condition on the following function, but can't figure out a way.

"mods" can be from level 1 to 15, and a mod level can be checked with ".level"

I need that if a set of mods(can be 2 or 4 pieces) has a non level 15 mod, then it calls for allsets[2] and if all mods on a set are level 15 then it calls for allsets[3]

var allSets = {
"Health": [2, "HP%", 5, 10], //0
"Offense": [4, "OFF%", 5, 10], //1
"Crit Chance": [2, "CRate", 2.5, 5], //2
"Crit Damage": [4, "CDmg", 15, 30], //3
"Speed": [4, "SPD%", 5, 10], //4
"Potency": [2, "POT", 5, 10], //5
"Defense": [2, "DEF%", 5], //6
"Tenacity": [2, "TEN", 10] }; //7



function determineCompleteSetsAndEffects(character, mods){
var setCounter = {"Health": 0,"Offense":0,"Crit Chance":0,"Crit Damage":0,"Speed":0,"Potency":0,"Defense":0,"Tenacity":0,};
for(i=0; i<mods.length; i++) {
    setCounter[mods[i].set]++;
}
for (var setName in setCounter) {
    while( setCounter[setName] >= allSets[setName][0]) {
        if(character.sets != "")
            character.sets += ",";
        character.sets += setName;
        // insert condition here {
        character = addStat(character, allSets[setName][1], allSets[setName][2], false, null);
        setCounter[setName] -= allSets[setName][0];
        } else {
        character = addStat(character, allSets[setName][1], allSets[setName][3], false, null);
        setCounter[setName] -= allSets[setName][0];
        }
    }
}
return character;

}

if statements on rows r

I have currently have a data frame that is taken from a data feed of events that happened in chronological order. I would like to add a new column onto to each row of my data the corresponds to the next event's player_id if the event type is 1 & the outcome is 1

e.g

player_id <- c(12, 17, 26, 3)
event_type <- c(1, 3, 1, 10)
outcome <- c(1, 0, 1, 1)
df <- data.frame(player_id, event_type, outcome)
df
     player_id  event_type outcome
1        12          1       1
2        17          3       0
3        26          1       1
4         3         10       1

so end result

      player_id event_type outcome next_player_id
1        12          1       1             17
2        17          3       0             NA
3        26          1       1              3
4         3         10       1             NA

Help much appreciated as I'm still in the beginners stage in r

samedi 27 août 2016

How to copy a variable value and paste it on another spreasheet

so what I'm trying to do right now is take a range (lets say C:C), go through all the cells with value and paste them in another spreadsheet. My target is to copy a variable value (because I don't know how many values I would have in C:C) and paste it on another sheet, so that I can have a new range with all the values (were there are no repeated values). My problem right now is that I don't know how to code the If statement (for variable values). If any one can help me I will be thankful. This is what I have to this point:

    Sub Test_1()
    ' Go through each cells in the range
    Dim rg As Range
    Dim copySheet As Worksheet
    Dim pasteSheet As Worksheet

    Set copySheet = Worksheets("Data")
    Set pasteSheet = Worksheets("Data_storage")

    For Each rg In Worksheets("Data").Range("C:C")

        If rg.Value = "Client 1" Then 'Instead of "Client 1" should be a variable value because "Client 1" will be a repetead value in C:C 
            copySheet.Range("C2").Copy 'Starting the counter in C2
            pasteSheet.cells(Row.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValue

        End If

    Next

End Sub

java - efficient form of "OR" in "IF statement"

boolean a = false, b = true, c = true; if ( a == false || b == false || c == false ) { return true; }

Is there any efficient way of coding for this statement using : or ? symbols or any other tricks that you can recommend?

C# If statement hierarchy only if in sequence (Unity)

In Unity, I'm trying to give velocity to my player while jumping, AKA keep going forward if you jump mid-motion. Here is my code so far:

    if (VerVelocity != 0 || HorVelocity != 0) {
            if (Anim.GetCurrentAnimatorStateInfo(0).IsName("jump") || Anim.GetCurrentAnimatorStateInfo(0).IsName("fall")) {
                transform.Translate(Vector3.forward * VerVelocity * JumpSpeedMultiplier * Time.deltaTime);
                transform.Translate(Vector3.right * HorVelocity * JumpSpeedMultiplier * Time.deltaTime);
            }
    }

HorVelocity and VerVelocity are top down, meaning Hor is for left and right and Ver is for forward and backwards. The problem I'm having is these events can happen in any order, meaning you can change direction mid-air. How can I make it check that you were running before you jumped and not after? Thanks for any help you can provide!

So I want to write a code that if the textbox (txtPayment.Text) is entered but the textbox is empty an error message should pop up [duplicate]

This question already has an answer here:

This is the code for Key Press Enter

private void txtPayment_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (txtPayment.Text == null)
            {
                MessageBox.Show("Cash payment is empty", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            else if (e.KeyChar == (char)Keys.Enter)
            {
                payment();
            }
        }

and here's the code for payment method

private void payment()
        {
            Int32 val1 = Convert.ToInt32(txtTotal.Text);
            Int32 val2 = Convert.ToInt32(txtPayment.Text);
            Int32 val3 = val2 - val1;

            if (val2 < val1)
            {
                MessageBox.Show("Insufecient cash payment", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPayment.Text = "";
            }

            else
            {
                txtChange.Text = val3.ToString();
            }
        }

but I always get the error message "Input string was not in a correct format."

Sense of Optional in Java 8

What is a sense of this?

Optional.of(someLinkToNull).ifPresent(present -> {
        System.out.println(present);
    });

gives NullpointerException.

Please, give an example, how to check on null with Optional (less code)?

Python if and elif not working, giving error

I'm new in Python and doing an online tutorial. I have an assignment that I can not accomplish. My problem is that when I run this code, the minimum variable stays the same to None and does not record the new value input.

maximum = None
minimum = None
while True:
    try:
        num2 = raw_input('Type here ')
        if num2 == 'done':break
        else:
            num = int(num2)
            if num <= minimum:
                minimum = num
                print minimum
            elif num >= maximum:
                maximum = num
                print maximum


    except:
        print 'Invalid Entry'


print 'Maximum is %d' % maximum
print 'Minimum is %d' % minimum

Error: expected ")" and primary expression before "if

I am just trying to run this code from a book. I checked more than twice and still getting the two erros mentioned on the title. This code is intended to count how many times a value is repeated from input and if the last value entered is not the same as the previous one, it also has to start the count for this value.

#include <iostream>

    int main()
    {
        int val=0, currVal=0;
        if (std::cin>>currVal){
            int cnt=1;

            while (std::cin>>val){


                (if val==currVal,++cnt)

                else{
                    std::cout<<currVal<<"occurs"<<cnt<<"times"<<std::endl;
                    currVal=val;
                cnt=1;}}

            std::cout<<currVal<<"occurs"<<cnt<<"times"<<std::endl;}



        return 0;
    }

How can I create an array based in a IF funtion

I'm new at VBA and coding. My problem is as follows: I have an array of data in a spreadsheet conformed by client's names and the day the order product. What I need to do is create a new array, in a different spreadsheet, where I can have every client listed (without repeating) on column A and the associated order date for each client on column B, C an so on. So basically is converting the raw data into useful data. I would really appreciate any type of help!! The VBA looks as follows:

Sub Test_1()
Application.ScreenUpdating = False

' Statment

Dim Client As String
Dim Order_date As Date
Dim Counter As Integer
Dim Data As Worksheet
Dim Data_storage As Worksheet
Dim i As Integer

Counter = 10

' Core
' For every value in column B *This values are going to be clients names * They are going to be repeated value in this column *This data is in the Data spreadsheet

' When the counter begins, if new Client is detected
' Then paste in worksheet Data_storage in column A and paste in column B the Order_date value *Every Client will have a order date associated

' If's a repeated Client, only paste the Order_date value in the next column with no value of the existing Client



End Sub

How do I validate more efficiently?

I don't know what everyone calls this but how do I make this piece of code shorter??

I was taught to not repeat code and at the GetAddress() method the if statement I repeat the same line twice, once from the if statement and then another from the else if statement below it

(_CClientFirstName == "John" || _CClientLastName == "Jenkins" || _CClientAge == 21)

How would I do this with less code? Im just wondering if it's possible because if it is, I would love to know. Also, please don't reply with anything too complex as Im only starting out, but if you do then try to explain it as much as you can thanks.

class ClientInfo
{
    private string _CClientFirstName = "Default";
    private string _CClientLastName = "Default";
    private int _CClientAge = 99;

    public ClientInfo(string FullName, string LastName, int Age)
    {
        _CClientFirstName = FullName;
        _CClientLastName = LastName;
        _CClientAge = Age;
    }

    public string GetAddress()
    {
        if (_CClientFirstName == "John" || _CClientLastName == "Jenkins" || _CClientAge == 21)
        {
            return $"{_CClientFirstName}'s address is: 67 Smokey Lane, London, B78 9JN, United Kingdom";
        }
        else if (_CClientFirstName == "Matt" || _CClientLastName == "Benks" || _CClientAge == 25)
        {

        }
    }
}

vendredi 26 août 2016

Two Conditions but invalid syntax

So, I'm still a beginner in python. Right now, I want to create a small script that asked the user for their age.

Instead of asking for their age, I thought that I could, as a learning experience, have the script calculate their age based on their birth year. I also thought I could have the script check if the user's input was an integer and additionally check if the user's input had 4 digits.

Using an if-else statement, once the user's input passed these two conditionals it will print the user's age, else print an error.

My problem is I'm getting an invalid syntax error. The terminal is pointing at the "4" digit with the error.

import datetime

now = datetime.datetime.now()

print('Hello World')
print('What is your name?')
myName = input()
print('It is good to meet you ' + myName + '!')
print('The length of your name is: ' + str(len(myName)) + ' characters')
myAge = input('What year were you born: ')
if type(myAge) == int and len(str(myAge)) = 4
    print('You will be ' + str(now.year - int(myAge)) + ' this year!')
else
    print('That is not a number')

not equals not working in java

I tried the following code :

if (!object.equals(null)) {
                object.setItem(object2.getTime());
}

Here, object and object1 are objects two classes.

The problem is that it enter into the statement for a null value.

Python: Function not holding the value of a variable after execution

I'm trying to convert a string input (y/n) into an integer (1/0). The function appears to be working, as when the 'convert' function is executed using 'a' as an argument, the argument is printed inside the function, however printing outside the function uses the original value of the variable 'a'. I've tried using return inside the 'convert' function, but this appears to have no affect.

a = input("Are you happy?(y/n)")

def convert(x):
    if x == ('y'):
        x = 1
    if x == ('n'):
        x = 0
    print (x)

convert(a)
print (a)

>>> Are you happy?(y/n)y
1
y