vendredi 31 juillet 2015

If test on Pandas DataFrame

I would like to do an if test on the 'ave_data' DataFrame below:

ave_data=

Time ------------ F7 --------------- F8 --------------- F9
00:00:00 ---- 43.005593 ---- -56.509746 ---- 25.271271
01:00:00 ---- 55.114918 ---- -59.173852 ---- 31.849262
02:00:00 ---- 63.990762 ---- -64.699492 ---- 52.426017

Specifically, I would like to test if any of the values are less than 0.05 and output 1 if they are not, and 0 if they are, so that the output (named, for example, 'tested_ave_data') looks like this:

tested_ave_data=

Time ------------ F7 --- ------- F8 ---------- F9
00:00:00 -------- 1 ------------ 0 ------------ 1
01:00:00 -------- 1 ------------ 0 ------------ 1
02:00:00 -------- 1 ------------ 0 ------------ 1

Can anyone help me develop a code to do this? I've searched for ways to do this for a long time now but not been successful.

something wrong about T.gt()

In order to obtain the usage of T.gt(), i wrote a toy code.

def f(data):
# return T.gt(data, 0)
if T.gt(data, 0):
    print "1"
    return -data
else:
    print "2"
    return data


a = T.scalar()
t = f(a)

print t.eval({a:-4})

I expect the returned value is -4 when a=-4 and -4 when a=4, but it always satisfy the condition and run the return -data. I don't know why. Can you help me? thanks for your time.

Why do I get the 'Use of unresolved identifier' error when writing this code in Swift?

I have the following code:

let FOO = true
if (FOO) {
    let BAR = "Off"
} else {
    let BAR = "On"
}
print(BAR)

My problem that is the line that says print(BAR) returns the error:

Use of unresolved identifier 'BAR'

From what I can see, there is no reason that this code shouldn't compile is there? The constant BAR will always be created so can always be printed to the console.

C# Multiple strings in a if-statment

I'm trying to check if a user input matches a few already known values. How do I do this in C#?

I've tried this:

if (UserInput.Text == "2", "4", "8", "16", "32")

      { do things 

      }
      else
      {
        do other things
      }

And a couple of other signs between my strings. Is it possible to check against all my strings or do I have to set up a seperate if-statment for all my strings?

.mouseleave not working with "if" statement

I have a navigation menu.I want it to change the opacity to 1 when i hover the cursor over it then IF the page is scrolled down and mouse is no longer hovering over it decrease opacity to 0.5. I have this jQuery code :

  // JavaScript Document
jQuery(document).ready(function() {


  var navOffset = jQuery("nav").offset().top;

  jQuery(window).scroll(function() {

    var scrollPos = jQuery(window).scrollTop();

    if (scrollPos > navOffset) {
      jQuery("nav").stop(true);
      jQuery("nav").addClass("fixed");
      jQuery("nav").fadeTo(1000, 0.5);

    } else {
      jQuery("nav").stop(true);
      jQuery("nav").removeClass("fixed");
      jQuery("nav").fadeTo(1000, 1.0);
    }

   });

   $("nav").mouseenter(function(){
       jQuery("nav").stop(true);
      jQuery("nav").fadeTo(1000,1.0);  
     });


  jQuery("nav").mouseleave(function(){
      if (scrollPos > navOffset) {
       jQuery(this).stop(true);
       jQuery(this).fadeTo(1000,0.5);
      }
      });

});

And this CSS code :

.fixed { 
position:fixed;
top:0;
}

When i hover the mouse it works but when i no longer hover over it and my page is scrolled down, wont return to his opacity.Thank you for any help that you can give.

If string statement

I have a problem with the following code:

int main(){

    string name;
    cout<<"Enter: ";
    cin>>name;
    if(name == "AHAH"||"AHAH"||"ADAD"||"ACAC"||"ASAS"||"AHAD"||"AHAC"||"AHAS"||"ADAH"||"ADAC"\
        ||"ADAS"||"ACAH"||"ACAD"||"ACAS"||"ASAH"||"ASAD"||"ASAC"){
        cout<<"Call! Good hand!";
    }
    else if(name == "2H2H")
        cout<<"Rase";

system("pause");
};

No matter what I input the program outputs:

Call! Good hand!

What's the problem?

Hangman guesses with two same letters

I have a hangman code(you don't have to read it all):

import random

import sys

guess = ''

guess2 = 0

guess3 = 0

guess4 = 0

guess5 = 0

guess6 = 0

guess7 = 0

guess8 = 0

guess9 = 0

guess10 = 0

guess11 = 0

guess12 = 0

guess13 = 0

guess14 = 0

guess15 = 0

guess16 = 0

guess17 = 0

guess18 = 0

guess19 = 0

guess20 = 0

guess21 = 0

aa1 = 0

aa2 = 0

aa3 = 0

aa4 = 0

aa5 = 0

aa6 = 0

aa7 = 0

aa8 = 0

aa9 = 0

aa10 = 0

aa11 = 0

aa12 = 0

aa13 = 0

aa14 = 0

aa15 = 0

aa16 = 0

aa17 = 0

rong = [ ]

lis = [ ]



uy = 'jrekghqegherwgbeuihrweig'

choice = 'bhekvvvvvfaktgrwekubfhdbvbvdvbd'

z = 'bqhjrfqfbrqkqbg'

s = 'ksl'

s_space = 'bhks'

li = [ ]

a1a = None

a2a = None

a3a = None

a4a = None

a5a = None

a6a = None

a7a = None

a8a = None

a9a = None

a10a = None

a11a = None

a12a = None 

a13a = None

a14a = None

a15a = None

a16a = None

a17a = None

a1 = a1a

a2 = a2a

a3 = a3a

a4 = a4a

a5 = a5a

a6 = a6a

a7 = a7a

a8 = a8a

a9 = a9a

a10 = a10a

a11 = a11a

a12 = a12a

a13 = a13a

a14 = a14a

a15 = a15a

a16 = a16a 

a17 = a17a

correct = 0

dup = 0

t = list(s)




hangman = """
 +---+
 |   |
     |
     |
     |
     |
 =========
"""

hangman1 = """
 +---+
 |   |
 O   |
     |
     |
     |
 =========
"""

hangman2 = """
 +---+
 |   |
 O   |
 |   |
     |
     |
 =========
"""

hangman3 = """
 +---+
 |   |
 O   |
 |/  |
     |
     |
 =========
"""

hangman4 = """
 +---+
 |   |
 O   |
\|/  |
     |
     |
 =========
"""

hangman5 = """
 +---+
 |   |
 O   |
\|/  |
 |   |
     |
 =========
"""

hangman6 = """
 +---+
 |   |
 O   |
\|/  |
 |   |
  \  |
 =========
"""

hangman7 = """
 +---+
 |   |
 O   |
\|/  |
 |   |
/ \  |
 =========

Game Over.
"""

hangman0 = hangman


animals = ['llama']
animals2 = [ 'bear', 'Giraffe', 'Tiger', 'Lion', 'Panda', 'Penguin', 'Gorilla', 'Chimpanzee', 'Monkey', 'Owl', 'Gorilla', 'Zebra', 'Koala', 'Jaguar', 'Hippopotamus', 'Kangaroo', 'Swan', 'Rhinoceros', 'Moose', 'Camel', 'Horse', 'Dog', 'Meerkat', 'Orangutan', 'Peacock', 'Badger', 'Sloth', 'Seal', 'Deer', 'Alligator', 'Crocodile', 'Skumk', 'Leopard', 'Lizard', 'Bat', 'Snake', 'Okapi', 'Birds', 'Turtle', 'Fox', 'Tortoise', 'Dolphin', 'Panther', 'Cheetah', 'Buffalo', 'Cougar', 'Hawk', 'Cat', 'Ostrich', 'Frog', 'Lemur', 'Duck', 'Walrus', 'Goat', 'Warthog', 'llama', 'Parrot', 'Baboon', 'Emu', 'Toad', 'Goose', 'Emu', 'Crane', 'Vulture', 'Squirrel', 'Raccoon', 'Sheep']

space = ['astronomy', 'gas', 'nebula', 'planet', 'Earth', 'sun', 'space', 'star', 'Venus', 'Mars', 'Mercury', 'Pluto', 'Neptune', 'Uranus', 'ice', 'Jupiter', 'Saturn', 'asteroid', 'comet', 'Kepler', 'ISS', 'station', 'quasar', 'galaxy', 'Andromeda', 'moon', 'Phobios', 'Demios', 'orbit', 'gravity', 'matter']

food = ['pizza', 'bagel', 'donut', 'candy', 'cake', 'casserole', 'salmon', 'bacon', 'caviar', 'apple', 'bannana', 'orange', 'acai', 'pomegranete', 'pear', 'cheese', 'turkey', 'steak', 'Cabbage', 'Calorie', 'Carbohydrate', 'Casserole', 'Caterer', 'Celery', 'Chef', 'Chewy', 'Chicken', 'Chicory', 'Chipotle', 'Chips', 'Chocolate', 'Chocolatier', 'Choice', 'Chutney', 'Cocoa', 'Coffee', 'Condiment', 'mango', 'Crackers', 'Croutons', 'Crunchy', 'Cucumbers', 'potato', 'sandwich']

chemicals = ['alum', 'sodium', 'titin', 'Bichrome', 'Azurite', 'Borax', 'Calomel', 'Gypsum', 'graphite', 'hypo', 'lime', 'acetone', 'pollen', 'Aluminium', 'starch', 'soap', 'calcium', 'alchohol', 'seltzer', 'aspirin', 'bronze', 'chalk', 'diamond', 'marble', 'quartz', 'sand', 'silicon', 'vinegar', 'carbon', 'nitrogen', 'vapor', 'oxide', 'phosphorus', 'magnesium', 'acid', 'chemical', 'ackey']



print 'Welcome to hangman!'

import time
time.sleep(3)
print 'Pick a topic:'
print '1.Animals'
print '2.Space'
print '3.Food'
print '4.Chemicals'

topic = str(raw_input('Choose a topic(1/2/3/4):'))

while not topic.isalpha():
    if topic == '1':
        choice = animals
        print 'animals'
        break
    elif topic == '2':
        choice = space
        print 'space'
        break
    elif topic == '3':
        choice = food
        print 'food'
        break
    elif topic == '4':
        choice = chemicals
        print 'chemicals'
        break
    else:
        print 'Invalid Input'
        topic = str(raw_input('Choose a topic(1/2/3/4):'))
    if topic != '1' or '2' or '3' or '4':
        print 'Invalid Input'
        topic = str(raw_input('Choose a topic(1/2/3/4):'))




if choice == animals:
    word = random.choice(animals)

if choice == food:
    word = random.choice(food)

if choice == space:
    word = random.choice(space)

if choice == chemicals:
    word = random.choice(chemicals)

word = word.lower()
length = len(word)

if length == 3:
    s = '_ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    lis = [a1a, a2a, a3a]

if length == 4:
    s = '_ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    lis = [a1a, a2a, a3a, a4a]

if length == 5:
    s = '_ _ _ _ _' 
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    lis = [a1a, a2a, a3a, a4a, a5a]

if length == 6:
    s = '_ _ _ _ _ _' 
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    lis = [a1a, a2a, a3a, a4a, a5a, a6a]

if length == 7:
    s = '_ _ _ _ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    a7a = word[6]
    list = [a1a, a2a, a3a, a4a, a5a, a6a, a7a]

if length == 8:
    s = '_ _ _ _ _ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    a7a = word[6]
    a8a = word[7]
    lis = [a1a, a2a, a3a, a4a, a5a, a6a, a7a, a8a]

if length == 9:
    s = '_ _ _ _ _ _ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    a7a = word[6]
    a8a = word[7]
    a9a = word[8]
    lis = [a1a, a2a, a3a, a4a, a5a, a6a, a7a, a8a, a9a]

if length == 10:
    s = '_ _ _ _ _ _ _ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    a7a = word[6]
    a8a = word[7]
    a9a = word[8]
    a10a = word[9]
    lis = [a1a, a2a, a3a, a4a, a5a, a6a, a7a, a8a, a9a, a10a]

if length == 11:
    s = '_ _ _ _ _ _ _ _ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    a7a = word[6]
    a8a = word[7]
    a9a= word[8]
    a10a = word[9]
    a11a = word[10]
    lis = [a1a, a2a, a3a, a4a, a5a, a6a, a7a, a8a, a9a, a10a, a11a]

if length == 12:
    s = '_ _ _ _ _ _ _ _ _ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    a7a = word[6]
    a8a = word[7]
    a9a = word[8]
    a10a = word[9]
    a11a = word[10]
    a12a = word[11]
    lis = [a1a, a2a, a3a, a4a, a5a, a6a, a7a, a8a, a9a, a10a, a11a, a12a]

if length == 13:
    s = '_ _ _ _ _ _ _ _ _ _ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    a7a = word[6]
    a8a = word[7]
    a9a = word[8]
    a10a = word[9]
    a11a = word[10]
    a12a = word[11]
    a13a = word[12]
    lis = [a1a, a2a, a3a, a4a, a5a, a6a, a7a, a8a, a9a, a10a, a11a, a12a, a13a]

if length == 14:
    s = '_ _ _ _ _ _ _ _ _ _ _ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    a7a = word[6]
    a8a= word[7]
    a9a= word[8]
    a10a = word[9]
    a11a = word[10]
    a12a = word[11]
    a13a = word[12]
    a14a = word[13]
    lis = [a1a, a2a, a3a, a4a, a5a, a6a, a7a, a8a, a9a, a10a, a11a, a12a, a13a, a14a]

if length == 15:
    s = '_ _ _ _ _ _ _ _ _ _ _ _ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    a7a = word[6]
    a8a = word[7]
    a9a = word[8]
    a10a = word[9]
    a11a = word[10]
    a12a = word[11]
    a13a = word[12]
    a14a = word[13]
    a15a = word[14]
    lis = [a1a, a2a, a3a, a4a, a5a, a6a, a7a, a8a, a9a, a10a, a11a, a12a, a13a, a14a, a15a]

if length == 16:
    s = '_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    a7a = word[6]
    a8a = word[7]
    a9a = word[8]
    a10a = word[9]
    a11a = word[10]
    a12a = word[11]
    a13a = word[12]
    a14a = word[13]
    a15a = word[14]
    a16a = word[15]
    lis = [a1a, a2a, a3a, a4a, a5a, a6a, a7a, a8a, a9a, a10a, a11a, a12a, a13a, a14a, a15a, a16a]

if length == 17:
    s = '_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _'
    a1a = word[0]
    a2a = word[1]
    a3a = word[2]
    a4a = word[3]
    a5a = word[4]
    a6a = word[5]
    a7a = word[6]
    a8a = word[7]
    a9a = word[8]
    a10a = word[9]
    a11a = word[10]
    a12a = word[11]
    a13a = word[12]
    a14a = word[13]
    a15a = word[14]
    a16a = word[15]
    a17a = word[16]
    lis = [a1a, a2a, a3a, a4a, a5a, a6a, a7a, a8a, a9a, a10a, a11a, a12a, a13a, a14a, a15a, a16a, a17a]







while hangman != hangman7 or s_space != word:

    correct = 0 
    print """



    """
    print hangman
    print s


    guess = str(raw_input('Enter a letter:'))

    if guess20 == guess:
        guess21 = guess
    if guess19 == guess:
        guess20 = guess
    if guess18 == guess:
        guess19 = guess
    if guess17 == guess:
        guess18 = guess
    if guess16 == guess:
        guess17 = guess
    if guess15 == guess:
        guess16 = guess
    if guess14 == guess:
        guess15 = guess
    if guess13 == guess:
        guess14 = guess
    if guess12 == guess:
        guess13 = guess
    if guess11 == guess:
        guess12 = guess
    if guess10 == guess:
        guess11 = guess
    if guess9 == guess:
        guess10 = guess
    if guess8 == guess:
        guess9 = guess
    if guess7 == guess:
        guess8 = guess
    if guess6 == guess:
        guess7 = guess
    if guess5 == guess:
        guess6 = guess
    if guess4 == guess:
        guess5 = guess
    if guess3 == guess:
        guess4 = guess
    if guess2 == guess:
        guess3 = guess
    if guess == guess:
        guess2 = guess
        if guess == guess:
            guess0 = guess
        li = [guess, guess2, guess3, guess4, guess5, guess6, guess7, guess8, guess9, guess10, guess11, guess12, guess13, guess14, guess15, guess16, guess17, guess18, guess19, guess20, guess21]



    if guess.isalpha():




        if not guess in lis:
            print 'Try again'
            inc = guess
            if hangman == hangman6:
                hangman = hangman7
                incorrect = guess
                rong.append(incorrect)
                print s
                print 'incorrect:'
                print rong
                print hangman7
                print ('The word was', word)
                sys.exit(" ")
            elif hangman == hangman5:
                hangman = hangman6
                incorrect = guess
                rong.append(incorrect)
                print s
                print 'incorrect:'
                print rong
            elif hangman == hangman4:
                hangman = hangman5
                incorrect = guess
                rong.append(incorrect)
                print s
                print 'incorrect:'
                print rong
            elif hangman == hangman3:
                hangman = hangman4
                incorrect = guess
                rong.append(incorrect)
                print s
                print 'incorrect:'
                print rong
            elif hangman == hangman2:
                hangman = hangman3
                incorrect = guess
                rong.append(incorrect)
                print s
                print 'incorrect:'
                print rong
            elif hangman == hangman1:
                hangman = hangman2
                incorrect = guess
                rong.append(incorrect)
                print s
                print 'incorrect:'
                print rong
            elif hangman == hangman0:
                hangman = hangman1
                incorrect = guess
                rong.append(incorrect)
                print s
                print 'incorrect:'
                print rong

            else:
                gue = 'hi'



        abc = list(lis)


        if guess in lis:


            if guess == a1a:
                correct = a1a
                t = list(s)
                t[0] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")


            elif guess == a2a:
                correct = a2a
                t = list(s)
                t[2] = guess
                s = "".join(t)
                print hangman
                print guess
                s_0 = s.replace(" ","")


            elif guess == a3a:
                correct = a3a
                t = list(s)
                t[4] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")


            elif guess == a4a:
                correct = a4a
                t = list(s)
                t[6] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")


            elif guess == a5a:
                correct = a5a
                t = list(s)
                t[8] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")


            elif guess == a6a:
                correct = a6a
                t = list(s)
                t[10] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            elif guess == a7a:
                correct = a7a
                t = list(s)
                t[12] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            elif guess == a8a:
                correct = a8a
                t = list(s)
                t[14] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            elif guess == a9a:
                correct = a9a
                t = list(s)
                t[16] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            elif guess == a10a:
                correct = a10a
                t = list(s)
                t[18] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            elif guess == a11a:
                correct = a11a
                t = list(s)
                t[20] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            elif guess == a12a:
                correct = a12a
                t = list(s)
                t[22] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            elif guess == a13a:
                correct = a13a
                t = list(s)
                t[24] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            elif guess == a14a:
                correct = a14a
                t = list(s)
                t[26] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            elif guess == a15a:
                correct = a15a
                t = list(s)
                t[28] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            elif guess == a16a:
                correct = a16a
                t = list(s)
                t[30] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            elif guess == a17a:
                correct = a17a
                t = list(s)
                t[32] = guess
                s = "".join(t)
                print guess
                s_0 = s.replace(" ","")

            print hangman
            print s
            if s_0 == word:
                print s_0
                print 'You Won!'
                import time
                time.sleep(3)
                print ' This program was written using Python, by Slass33'
                break
                co = raw_input('Do you want to play again?(yes/no):')
                if co == 'yes':
                    print """

                    """
                elif co == 'no':
                    sys.exit

                else:
                    co = raw_input('Do you want to play again?(yes/no):')



sys.exit

My problem is that, when I run the program, if the word has, say, 2 as, or multiple bs, it only prints one of the bs, or as(these letters are examples). My problem might be here:

        abc = list(lis)


    if guess in lis:


        if guess == a1a:
            correct = a1a
            t = list(s)
            t[0] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")


        elif guess == a2a:
            correct = a2a
            t = list(s)
            t[2] = guess
            s = "".join(t)
            print hangman
            print guess
            s_0 = s.replace(" ","")


        elif guess == a3a:
            correct = a3a
            t = list(s)
            t[4] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")


        elif guess == a4a:
            correct = a4a
            t = list(s)
            t[6] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")


        elif guess == a5a:
            correct = a5a
            t = list(s)
            t[8] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")


        elif guess == a6a:
            correct = a6a
            t = list(s)
            t[10] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a7a:
            correct = a7a
            t = list(s)
            t[12] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a8a:
            correct = a8a
            t = list(s)
            t[14] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a9a:
            correct = a9a
            t = list(s)
            t[16] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a10a:
            correct = a10a
            t = list(s)
            t[18] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a11a:
            correct = a11a
            t = list(s)
            t[20] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a12a:
            correct = a12a
            t = list(s)
            t[22] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a13a:
            correct = a13a
            t = list(s)
            t[24] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a14a:
            correct = a14a
            t = list(s)
            t[26] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a15a:
            correct = a15a
            t = list(s)
            t[28] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a16a:
            correct = a16a
            t = list(s)
            t[30] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a17a:
            correct = a17a
            t = list(s)
            t[32] = guess
            s = "".join(t)
            print guess
            s_0 = s.replace(" ","")

To try and fix this, I added:

        if len(lis) != len(set(list)): 
        dup = collections.counter(lis)

    if dup != 0:
        if dup == a17a:
            correct1 = a17a
            ts = list(s)
            ts[32] = dup
            s = "".join(ts)
            print dup
            s_0 = s.replace(" ","")     
        elif dup == a16a:
            correct1 = a16a
            ts = list(s)
            ts[30] = dup
            s = "".join(ts)
            print dup
            s_0 = s.replace(" ","")

        elif guess == a15a:
            correct = a15a
            ts = list(s)
            ts[28] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a14a:
            correct = a14a
            ts = list(s)
            ts[26] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")
        elif guess == a13a:
            correct = a13a
            ts = list(s)
            ts[24] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a12a:
            correct = a12a
            ts = list(s)
            ts[22] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a11a:
            correct = a11a
            ts = list(s)
            ts[20] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a10a:
            correct = a10a
            ts = list(s)
            ts[18] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a9a:
            correct = a9a
            ts = list(s)
            ts[16] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a8a:
            correct = a8a
            ts = list(s)
            ts[14] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a7a:
            correct = a7a
            ts = list(s)
            ts[12] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a6a:
            correct = a6a
            ts = list(s)
            ts[10] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a5a:
            correct = a5a
            ts = list(s)
            ts[8] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a4a:
            correct = a4a
            ts = list(s)
            ts[6] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a3a:
            correct = a3a
            ts = list(s)
            ts[4] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")

        elif guess == a2a:
            correct = a2a
            ts = list(s)
            ts[2] = guess
            s = "".join(ts)
            print hangman
            print guess
            s_0 = s.replace(" ","")

        elif guess == a1a:
            correct = a1a
            ts = list(s)
            ts[0] = guess
            s = "".join(ts)
            print guess
            s_0 = s.replace(" ","")      

This didn't work. Any help please?

switch case loop statement

Hello i am having problem with my one assignment. I made one function name chequingsaving and when i call this function it prints some data which is correct but when i entered character depends on my selection of account it directly goes out of loop. if i entered correct character value then same thing happens.I am sending you that function code. help me to find out my mistake. the thing is i used also switch case but still it directly goes to default. same thing happens with if else loop.

void chequingsaving()  /*Chequing and saving account function*/
{
    char a;
    double r, Initialamount = 0;
    printf(" c) Chequing\n");
    printf(" s) Savings\n");
    printf("Which account would you like to use?\n");
    scanf("% c", &a);

    if (a == 'c' || a == 'C')
        {
            printf("Please enter the amount for deposit\n");
            scanf("% lf", &r);
            Initialamount = Initialamount + r;
            printf("Your chequing account balance is=%lf", Initialamount);
        }
    else
        if (a == 's' || a == 'S')
        {
            printf("Please enter the amount for deposit\n");
            scanf("%lf", &r);
            Initialamount = Initialamount + r;
            printf("Your chequing account balance is=%lf", Initialamount);
        }
        else

        printf("Invalid character\n");

} 

Too many if statements

I have some topic to discuss. I have a fragment of code with 24 ifs/elifs. Operation is my own class that represents functionality similar to Enum. Here is a fragment of code:

if operation == Operation.START:
    strategy = strategy_objects.StartObject()
elif operation == Operation.STOP:
    strategy = strategy_objects.StopObject()
elif operation == Operation.STATUS:
    strategy = strategy_objects.StatusObject()
(...)

I have concerns from readability point of view. Is is better to change it into 24 classes and use polymorphism? I am not convinced that it will make my code maintanable... From one hand those ifs are pretty clear and it shouldn't be hard to follow, on the other hand there are too many ifs.

My question is rather general, however I'm writing code in python so I cannot use constructions like switch.

What do you think?

IF Statement in Woocommerce product category

I've been trying for a while now to try and make the code below work but i think im missing something obvious.

I'm using Woocommerce and i'm basically looking to add a php file into the category based on criteria

  1. is in the tshirts category
  2. is in the tshirt category and the tshirt is tagged for men
  3. is in the tshirt category and the tshirt is tagged for women

3 templates, 3 scenarios.

I'm sure there is a more elegent way to do this. Apologies for the rookie question but i really did look this up.

<?php
    $tshirt = (has_term('tshirt', 'product_cat'));
    $men = (has_term('men', 'product_tag'));
    $women = (has_term('women', 'product_tag'));

    if (($tshirt = '1') && ($men = '') && ($women = '')){
    include ('template1.php'); 
    }
    elseif (($tshirt = '1') && ($men = '1') && ($women = '')) {
    include ('template2.php'); 
    }

    elseif (($tshirt = '1') && ($men = '') && ($women = '1')) {
    include ('template3.php');  

    }

?>

Rewrite with if and else

i have to add if and else to my rewrite rule.

My rewrite is this

  RewriteCond %{THE_REQUEST} \ /+catalogsearch/result/\?cat=(.*)&q=([^&\ ]+)
RewriteRule ^ /q_%2_cat_%1? [L,NE,R=301]
RewriteRule ^q_(.*)_cat_(.*)?$ /http://ift.tt/1JVzBHk [QSA,P,NC]

and i would like to change to this if cat is in null

RewriteCond %{THE_REQUEST} \ /+catalogsearch/result/\?cat=&q=([^&\ ]+)
RewriteRule ^ /q_%1? [L,NE,R=301]
RewriteRule ^q_(.*)$ /http://ift.tt/1KDWN2L [QSA,P,NC]

Is it possible? Thanks in advance

Imacros if else error

Hello stackoverflow i need you help with a script im trying to make. The script im trying to make is a cointoss script that does the following.

The first part i want it to do is insert a amount i want to play with.

If i win insert same value as the first bet and set my datasource back to the first line.

If i loose use datasource to insert a new value and play again.

Here is what i came up with:

Cointoss.js

VERSION BUILD=8920312 RECORDER=FX

SET !DATASOURCE cointoss25.csv
SET !DATASOURCE_COLUMNS 1
SET !DATASOURCE_LINE {{!LOOP}}

if(iimPlay(WIN.iim)>0)
{
iimPlay(WINPLAY.iim)
}
else if(iimPlay(LOOSE.iim)>0)
{
iimPlay(LOOSEPLAY.iim)
}

WIN.iim Script

SEARCH SOURCE=TXT:"You guessed right! You win"

WINPLAY.iim Script

TAG POS=1 TYPE=A ATTR=TXT:PLAY<SP>AGAIN
TAG POS=1 TYPE=INPUT:TEXT ATTR=ID:bet CONTENT=25
TAG POS=1 TYPE=IMG ATTR=SRC:http://ift.tt/1KEZmid
SET !DATASOURCE_LINE 1

LOOSE.iim Script

SEARCH SOURCE=TXT:"You guessed wrong. Try again!"

LOOSEPLAY.iim Script

TAG POS=1 TYPE=A ATTR=TXT:PLAY<SP>AGAIN
TAG POS=1 TYPE=INPUT:TEXT ATTR=ID:bet CONTENT={{!COL1}}
TAG POS=1 TYPE=IMG ATTR=SRC:http://ift.tt/1KEZmid

The problem is i keep getting this error:

SyntaxError: missing ; before statement, line NaN (Error code: -991)

VBA - Compare opening file cell value with another workbook

I have many documents in a folder and a similar but different list in an Excel file. The documents in the folder are not always name correctly, but the value in one of the cells has the accurate name.

END GOAL: what I want to do is have code that runs through that folder, opens each file, looks at the file name in a cell*(code for that part below)* and compare it to Column A in the other Excel file, ACTIVE_FILES.xls. If it is in the list, it will move on to the next file. If it is not in the list, it will delete that file from the folder.

I already have working code which loops though a folder to open files and output information from them. I just do not know how to do a comparisson to a separate Excel worksheet or how to delete a file from a folder if it is not present.

CURRENT CODE:

This is how my current code starts out with looping through the folder (hard coded into MyFolder) to open files:

Option Explicit

Sub Active()


Sub LoopThroughDirectory()

    Dim objFSO As Object, objFolder As Object, objFile As Object, dict As Object
    Dim MyFolder As String
    Dim StartSht As Worksheet, ws As Worksheet
    Dim WB As Workbook
    Dim i As Integer
    Dim hc As Range, hc1 As Range, hc2 As Range, hc3 As Range, hc4 As Range, d As Range, TDS As Range

    Set StartSht = Workbooks("masterfile.xlsm").Sheets("Sheet1")
    'turn screen updating off - makes program faster
    Application.ScreenUpdating = False

    'location of the folder in which the desired TDS files are
    MyFolder = "C:\Users\trembos\Documents\TDS2\progress\"

    'find the header
    Set hc4 = HeaderCell(StartSht.Range("A1"), "TOOLING DATA SHEET (TDS):")

    'create an instance of the FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'get the folder object
    Set objFolder = objFSO.GetFolder(MyFolder)
    i = 2
    'loop through directory file and print names
'(1)
    'code for every excel file in the specified folder
    For Each objFile In objFolder.Files
        If LCase(Right(objFile.Name, 3)) = "xls" Or LCase(Left(Right(objFile.Name, 4), 3)) = "xls" Then
'(2)
            'Open folder and file name, do not update links
            Set WB = Workbooks.Open(Filename:=MyFolder & objFile.Name, UpdateLinks:=0)
            Set ws = WB.ActiveSheet

Then, this is how I grab the cell value which contains the file name I am looking for

(searches for header "TOOLING DATA SHEET (TDS):" and then grabs the value of the cell to the right of that header cell. In my previous code, it would then print it to the next available row in column C which is no longer needed but I kept in to show my GetLastRowInColumn function which could help search through column A in the plan I want to execute)

With ws
'Print TDS name by searching for header
    If Not ws.Range("A1:K1").Find(What:="TOOLING DATA SHEET (TDS):", LookAt:=xlWhole, LookIn:=xlValues) Is Nothing Then
        Set TDS = ws.Range("A1:K1").Find(What:="TOOLING DATA SHEET (TDS):", LookAt:=xlWhole, LookIn:=xlValues).Offset(, 1)
        StartSht.Range(StartSht.Cells(i, 1), StartSht.Cells(GetLastRowInColumn(StartSht, "C"), 1)) = TDS
    Else                
    End If
    i = GetLastRowInSheet(StartSht) + 1
End With

And finally, here are my functions which help make it all possible. Numbers designate a new function and there is an explanation next to each one.

'(8)
'Get the Values from columns with specified headers
Function GetValues(ch As Range, Optional vSplit As Variant) As Scripting.Dictionary
    Dim dict As Scripting.Dictionary
    Dim dataRange As Range, cell As Range
    Dim theValue As String
    Dim splitValues As Variant
    Dim counter As Long
Set dict = New Scripting.Dictionary
Set dataRange = ch.Parent.Range(ch, ch.Parent.Cells(Rows.count, ch.Column).End(xlUp)).Cells
' If there are no values in this column then return an empty dictionary
' If there are no values in this column, the dataRange will start at the row
' *above* ch and end at ch
If (dataRange.Row = (ch.Row - 1)) And (dataRange.Rows.count = 2) And (Trim(ch.Value) = "") Then
    GoTo Exit_Function
End If
For Each cell In dataRange.Cells
    counter = counter + 1
    theValue = Trim(cell.Value)
    If Len(theValue) = 0 Then
        theValue = " "
    End If
        'exclude any info after ";"
        If Not IsMissing(vSplit) Then
            splitValues = Split(theValue, ";")
            theValue = splitValues(0)
        End If
        'exclude any info after ","
        If Not IsMissing(vSplit) Then
            splitValues = Split(theValue, ",")
            theValue = splitValues(0)
        End If
        If Not dict.exists(theValue) Then
        dict.Add counter, theValue
        End If
Next cell
Exit_Function:
Set GetValues = dict
 End Function
'(9)
'find a header on a row: returns Nothing if not found
Function HeaderCell(rng As Range, sHeader As String) As Range
    Dim rv As Range, c As Range
    For Each c In rng.Parent.Range(rng, rng.Parent.Cells(rng.Row, Columns.count).End(xlToLeft)).Cells
        'copy cell value if it contains some string "holder" or "cutting tool"
        If Trim(c.Value) = sHeader Then
        'If InStr(c.Value, sHeader) <> 0 Then
            Set rv = c
            Exit For
        End If
    Next c
    Set HeaderCell = rv
End Function
'(10)
'gets the last row in designated column
Function GetLastRowInColumn(theWorksheet As Worksheet, col As String)
    With theWorksheet
        GetLastRowInColumn = .Range(col & .Rows.count).End(xlUp).Row
    End With
End Function
'(11)
'gets the last row in designated sheet
Function GetLastRowInSheet(theWorksheet As Worksheet)
Dim ret
    With theWorksheet
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            ret = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          LookAt:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row
        Else
            ret = 1
        End If
    End With
    GetLastRowInSheet = ret
End Function

If loop not working as expected java

Reading a lines from a "text.txt" and then storing them into a tremap until the word apply appears how ever after performing this I don't have the last row "4 apply" I want in the treemap

text.txt
1 add 
3 multiply
4 apply
6 add


    Scanner input = new Scanner(file);
        while(input.hasNextLine()){

        String line = input.nextLine();
        String[] divline = line.split(" ");

        TreeMap<Integer, String> valores = new TreeMap();

        if(!divline[1].equals("apply")){
            valores.put(Integer.valueOf(divline[0]), divline[1]);   
        } else {
            valores.put(Integer.valueOf(divline[0]), divline[1]);
            break;
        }

            System.out.println(valores);

        }

MySql SELECT with if statement and LIKE operator

I am working on an advertisement site.

I have one table with a column for each day. I need to check in the table which ads is saved as default to update only those ads.

I have tried this, but it not working.

SELECT Monday if (Monday LIKE '%default%'),
Tuesday if (Tuesday LIKE '%default%')
FROM `Ad_Relationshp`

MySql gives me this error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if (Monday LIKE '%default%') FROM Ad_Relationshp LIMIT 0,' at line 1. I have tried changing the syntax to everything I can think off, but I still get the same error.

Multiple conditions using for loop

I'm beginning programming with codecademy and I tried to write a "search for word" program, but I don't know how to write a condition in "if" using a "for" loop to check all the letters in a search word, no matter the length. I know the for loop gives me "true" or "false", but I would like it to generate as many "text[j]===myWord[j-i]" conditions to my code as there are letters. Is there something wrong with my syntax or should I use other command that I don't know of?

var text = "Within the field of literary criticism, text also refers to the original information content of a particular piece of writing; that is, the text of a work is that primal symbolic arrangement of letters as originally composed, apart from later alterations, deterioration, commentary, translations, paratext, etc. Therefore, when literary criticism is concerned with the determination of a text, it is concerned with the distinguishing of the original information content from whatever has been added to or subtracted from that content as it appears in a given textual document (that is, a physical representation of text).";

var myWord = "literary";
var hits = [];

for (var i=0; i < text.length; i++) {
    if (for (var j=i; j<(i + myWord.length); j++){
            text[j]===myWord[j-i]
        })
        hits.push(text[i])
    }
}

if (hits.length === 0) {
        console.log("Your name wasn't found!");
}
else {
        console.log(hits);
}

Double nested if-statement in JavaScript

I'm trying to validate a form with JS. For this, I have an if-statement that checks 1), if email is empty and, 2) if email is valid. To check if the email is valid, I tried two things (both failed):

  1. A nested if-statement, like this:
    if (email == "") {
        return false;
    }else if (email != null) {
        var my_pattern = (regex);
        var my_validate = my_pattern.test(email); 

            if (my_validate == false) {
            return false;
          }
    }

  1. I put the nested if-statement (the one found in the else-if statement in a function that returns true or false; then I put it in the else-if statement, like this:
else if (my-func == false) {

    ...do something
}

If I run any of these if-statements on their own, they work; it's only when I try to nestle them like this, that they get stuck in the nested else-if statement. I want JS to evaluate every nested if-statement and then continue on evaluating the rest of the if-statements.

What can be done to achieve this?

Set select value based on h1 text

I have the following form:

$(function() {
    if () {}
    else {}
});

<script src="http://ift.tt/1oMJErh"></script>
<h1>Sandeep</h1>
<form>
    <select>
        <option>Non Selected</option>
        <option selected>Michael</option>
        <option>Sandeep</option>
    </select>   
</form>

I want to find a way to say in javascript: if the text of the h1 is Sandeep the option selected will be sandeep.

I don't know how to define the condition inside the if statement. Any ideas?

Display youtube iframe if url stored in mySQL

I created a form where we can register youtube embed url in a post. I'd like to display the iframe only if an url has been register for this post.

I made this code to display the report information :

<?php

$req = $db->query('SELECT id, title, author, category, date_event, country, city, content, tag, youtube FROM report ORDER BY date_creation DESC LIMIT 0, 10');

while ($data = $req->fetch())
{
?>

<div class="news">
      <h3><?php echo htmlspecialchars($data['title']); ?></h3>
      <p>Author: <?php echo htmlspecialchars($data['author']); ?></p>
            <p>Category : <?php echo htmlspecialchars($data['category']); ?></p>
            <p>Date of the event : <?php echo htmlspecialchars($data['date_event']); ?></p>
            <p>Country : <?php echo htmlspecialchars($data['country']); ?></p>
            <p>City : <?php echo htmlspecialchars($data['city']); ?></p>
            <p class="display_list"><?php echo html_entity_decode($data['content'], ENT_HTML5 , 'UTF-8'); ?></p>
            <p>Tag : <?php echo htmlspecialchars($data['tag']); ?></p>
            <p>

            <?php
$youtube=1;

if($youtube==1){
    echo "<p>display iframe</p>";
}else{
{
        echo "<p>don't display iframe</p>";
    }
}        
?>
</p>

Actually all the posts are displayed with the "display iframe" message.

The condition statement for $youtube variable is certainly not right but I can't figure out the issue.

jeudi 30 juillet 2015

Javascript Drag and drop How to add a droppable target id into if statement to check correct answers?

I am working on a drag and drop task in javascript. The idea is to drag any one of three possible answers to certain target areas (e.g. measure 1 line 1 etc). There could be 2 correct answers in case of "G sharp". I try to implement a control structure to check correct answers. So far I have only 1st part of conditional statement : it checks draggable id. How can I add 2nd part of conditional statement to check droppable id? For example the correct answer should be considered only if:

draggable id (data) == "measure_1_sharp" AND droppable id (dropTarget) == "m_1_l_1.5" OR "m_1_l_5.5".

So far I have the following draft code:

http://ift.tt/1IcanUY

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="../css/main_css.css">

<script  src="http://ift.tt/1LdO4RA">  </script>


</head>

<body>

<div id="m_1_l_5.5" ondrop="drop(event, this)" ondragover="allowDrop(event)" class= "g_sharp measure_1_grand_staff dropTarget_1" style="width:200px;height:25px; background-color:#fff;">measure 1 line 5.5
</div>    


<div id="m_1_l_5" ondrop="drop(event, this)" ondragover="allowDrop(event)" class= "g_sharp measure_1_grand_staff dropTarget_1" style="width:200px;height:25px; background-color:#007fff;">measure 1 line 5
</div>

<div id="m_1_l_4.5" ondrop="drop(event, this)" ondragover="allowDrop(event)" class= "g_sharp measure_1_grand_staff dropTarget_1" style="width:200px;height:25px; background-color:#fff;">measure 1 line 4.5
</div>    


<div id="m_1_l_4" ondrop="drop(event, this)" ondragover="allowDrop(event)" class= "other measure_1_grand_staff dropTarget_1" style="width:200px;height:25px; background-color:#907f99;">measure 1 line 4
</div>

<div id="m_1_l_3.5" ondrop="drop(event, this)" ondragover="allowDrop(event)" class= "g_sharp measure_1_grand_staff dropTarget_1" style="width:200px;height:25px; background-color:#fff;">measure 1 line 3.5
</div>    


<div id="m_1_l_3" ondrop="drop(event, this)" ondragover="allowDrop(event)" class= "other measure_1_grand_staff dropTarget_1" style="width:200px;height:25px; background-color:#e00e97;">measure 1 line 3
</div>

<div id="m_1_l_2.5" ondrop="drop(event, this)" ondragover="allowDrop(event)" class= "g_sharp measure_1_grand_staff dropTarget_1" style="width:200px;height:25px; background-color:#fff;">measure 1 line 2.5
</div>    


<div id="m_1_l_2" ondrop="drop(event, this)" ondragover="allowDrop(event)" class= "other measure_1_grand_staff dropTarget_1" style="width:200px;height:25px; background-color:#eeef97;">measure 1 line 2
</div>

<div id="m_1_l_1.5" ondrop="drop(event, this)" ondragover="allowDrop(event)" class= "g_sharp measure_1_grand_staff dropTarget_1" style="width:200px;height:25px; background-color:#fff;">measure 1 line 1.5
</div>    

<div id="m_1_l_1" ondrop="drop(event, this)" ondragover="allowDrop(event)" class= "g_sharp measure_1_grand_staff dropTarget_1" style="width:200px;height:25px; background-color:#15ef97;">measure 1 line 1
</div>  

<div id="m_1_l_0.5" ondrop="drop(event, this)" ondragover="allowDrop(event)" class= "g_sharp measure_1_grand_staff dropTarget_1" style="width:200px;height:25px; background-color:#fff;">measure 1 line 0.5
</div>    

<div id = "question_1_a_notes">

<ul class="note_1_a_inline">

  <li id = "q_1_a_note_1">G sharp</li>

  </ul>  
  </div>  

<div class = "additional_instructions" id = "task_1_a">Click a note and accidental (if needed) and drag-and-drop it to an appropriate place on the staff.
</div>       

<div id="navcontainer_1a">    
<ul id = "button_list">
<li class = "measure_1 button_small" id = "measure_1_note" draggable="true" ondragstart="drag(event)">O</li>
<li class = "measure_1 button_small" id = "measure_1_sharp" draggable="true" ondragstart="drag(event)">&#x266F O</li>    
<li class = "measure_1 button_small" id = "measure_1_flat O" draggable="true" ondragstart="drag(event)">&#x266D O</li> 

</ul>
</div>  

<script>

var totalCorrectAnswers = 0;           

function drag(ev) {
ev.dataTransfer.setData("text/html", ev.target.id);
}    

 function allowDrop(ev) {
 ev.preventDefault();
 }                                          

function drop(ev,target) {
ev.preventDefault();

var data = ev.dataTransfer.getData("text/html");

ev.target.appendChild(document.getElementById(data));

if(data=="measure_1_sharp") { 
console.log(data);
console.log(dropTarget.id);
totalCorrectAnswers ++;
console.log("You have provided " + totalCorrectAnswers + " correct    answer(s)");
} else {
console.log(data);
console.log("Wrong!!!");
console.log(dropTarget.id);
}
} 

$(document).ready(function() {    

}); // end ready

</script>

</div>

</body>
</html>

Why in for loop this conditions multilpy and divide by two (when i use >>= in for loop)

I was practicing some sample in c/c++ i found a code where the code is given below :

unsigned int num;
int c = 0;
cin >> num;
for (; num; z=num <<= 1)
{
    if (int y=num & 1)
    {
        c++;
    }
}
cout << "c : " << c << endl;

So i have following questions in mind:

(1) In this for loop condition the second parameter is num (what is the significance keeping it num, why not any condition like num<29 or may be some other value).

(2) Whereas the third parameter is z=num <<= 1 , here i had kept z to do some debugging to know the value obtained on this condition i found that it just doubles when symbol is >>= and halves when <<= , Why this behavior ?

(3) In the if condition we have if (int y=num & 1) i am not able to understand what it do by & 1?

I tried to understand it by debugging but i want to know clear explanation of this three questions so thats why wanted to ask experts.

Count on macro from another table

Can anyone help me? I have to create a macro that takes data from a column from another table on excel (Days Of Last Update, which is decimal), and then makes a count based if the day are above 1 (showing the result in a new column). It seems to be very simple, but i am a beginner and have no idea how to proceed.

Run the Correct Array function based on a session variable php

As a very novice php coder and beginner in web development i am in need of some advice and help, I have a calculation.php script that i am including into a landing page.. The script calculates a price depending on the user input value during the form process. Without making things to complicated and because i am going to try and run a dynamic landing page, The calculated price the script outputs can be different due to 2 different services we provide so service 1 is cheaper than service 2.

How can i go about having the array function run based if a session variable is equal to a specific value for example:

<?php
session_start();
if($_SESSION['service1'] == 'yes') {

Here is the Calculation.php script:

$data = array(
    array(
        'min' => "0",
        'max' => "100,000",
        'value' => 249
    ),
    array(
        'min' => "100,001",
        'max' => "200,000",
        'value' => 255
    )
);

function getAdjustedPrice($price, &$table) {
    $priceData = current(array_filter($table, function($value) use(&$price) {
        return $value['min'] <= $price && $value['max'] >= $price;
    }));
    return $priceData['value'];
}

$input = intval($_SESSION["servicecost"]);
printf("", 
       $input, 
       getAdjustedPrice($input, $data));

and if the session variable 1 is not set to yes but is set to "NO" then run the second variant of the calculation and then i will echo the output as variant number 2 is basically service 2 and is a higher price..

<?php
session_start();
if($_SESSION['service1'] == 'no') {

$data = array(
    array(
        'min' => "0",
        'max' => "100,000",
        'value' => 450
    ),
    array(
        'min' => "100,001",
        'max' => "200,000",
        'value' => 600
    )
);

function getAdjustedPrice($price, &$table) {
    $priceData = current(array_filter($table, function($value) use(&$price) {
        return $value['min'] <= $price && $value['max'] >= $price;
    }));
    return $priceData['value'];
}

$input = intval($_SESSION["servicecost"]);
printf("", 
       $input, 
       getAdjustedPrice($input, $data));

Hope this has made sense, Ive tried to do it myself using the elseif state and doing it like: if($_SESSION['service1'] == 'yes') { then run the code below it and then } else { if($_SESSION['service1'] == 'no') { but i have had no luck and constant silly errors. Any advice or input is greatly appreciated. Thanks.

Regex and matching in perl

I have an array with CA, C, CB, CZ. I want an if statement to match only C, CB, CZ.

@array = ("CA", "C", "CB", "CZ");

foreach (@array) {
if ($_ =~ m/^C|^C.&[^CA])
print "true \n";
}

This doesn't work, but I think it might be close. What perl regex expressions can I use to achieve my goal?

if else statement with two condition

This maybe trivial but I have this code

if(condition 1 & condition 2){
// apply some code
}
else{
// apply other code}

my question is when else is applied. is it applied when both conditions are false or its enough for one condition to be false

If statement in grouped Pandas dataframe

I have a dataset that contains columns of year, julian day, hour and temperature. I have grouped the data by year and day and now want to perform an operation on the temperature data IF each day contains 24 hours worth of data. Then, I want to create a Dataframe with year, julian day, max temperature and min temperature. However, I'm not sure of the syntax to make sure this condition is met. Any help would be appreciated. My code is below:

df = pd.read_table(data,skiprows=1,sep='\t',usecols=(0,3,4,6),names=['year','jday','hour','temp'],na_values=-999.9)
g = df.groupby(['year','jday'])

if #the grouped year and day has 24 hours worth of data
    maxt = g.aggregate({'temp':np.max})
    mint = g.aggregate({'temp':np.min})
else:
    continue

And some sample data (goes from 1942-2015):

Year    Month   Day Julian  Hour    Wind    TempC   DewC    Pressure    RH
1942    9   24  267 9   2.1 18.5    15.2    1014.2  81.0
1942    9   24  267 10  2.1 23.5    14.6    1014.6  57.0
1942    9   24  267 11  3.6 25.2    12.4    1014.2  45.0
1942    9   24  267 12  3.6 26.8    11.9    1014.2  40.0
1942    9   24  267 13  2.6 27.4    11.9    1014.2  38.0
1942    9   24  267 14  2.1 28.0    11.3    1013.5  35.0
1942    9   24  267 15  4.1 29.1    9.1 1013.5  29.0
1942    9   24  267 16  4.1 29.1    10.7    1013.5  32.0
1942    9   24  267 17  4.6 29.1    13.0    1013.9  37.0
1942    9   24  267 18  3.6 25.7    12.4    1015.2  44.0
1942    9   24  267 19  0.0 23.0    16.3    1015.2  66.0
1942    9   24  267 20  2.6 22.4    15.7    1015.9  66.0
1942    9   24  267 21  2.1 20.2    16.3    1016.3  78.0
1942    9   24  267 22  3.1 20.2    14.6    1016.9  70.0
1942    9   24  267 23  2.6 19.6    15.2    1017.6  76.0
1942    9   25  268 0   3.1 18.5    13.5    1018.3  73.0
1942    9   25  268 1   2.6 16.9    13.0    1018.3  78.0
1942    9   25  268 2   4.1 15.7    5.2 1021.0  50.0
1942    9   25  268 3   4.1 15.2    4.1 1020.7  47.0
1942    9   25  268 4   3.1 14.1    5.8 1021.3  57.0
1942    9   25  268 5   3.1 13.0    5.8 1021.3  62.0
1942    9   25  268 6   2.1 13.0    5.2 1022.4  59.0
1942    9   25  268 7   2.1 12.4    1.9 1022.4  49.0
1942    9   25  268 8   3.6 13.5    5.8 1024.7  60.0
1942    9   25  268 9   4.6 15.7    3.5 1025.1  44.0
1942    9   25  268 10  4.1 17.4    1.3 1025.4  34.0
1942    9   25  268 11  2.6 18.5    3.0 1025.4  36.0
1942    9   25  268 12  2.1 19.1    0.8 1025.1  29.0
1942    9   25  268 13  2.6 19.6    2.4 1024.7  32.0
1942    9   25  268 14  4.1 20.7    4.6 1023.4  35.0
1942    9   25  268 15  3.6 21.3    4.1 1023.7  32.0
1942    9   25  268 16  1.5 21.3    4.6 1023.4  34.0
1942    9   25  268 17  5.1 20.7    7.4 1023.4  42.0
1942    9   25  268 18  5.1 19.1    8.5 1023.0  50.0
1942    9   25  268 19  3.6 18.0    9.6 1022.7  58.0
1942    9   25  268 20  3.1 16.3    9.6 1023.0  65.0
1942    9   25  268 21  1.5 15.2    11.3    1023.0  78.0
1942    9   25  268 22  1.5 14.6    11.3    1023.0  81.0
1942    9   25  268 23  2.1 14.1    10.7    1024.0  80.0

Nested if logic with Error Messaging in SQL

I have 6 integer fields (called genre1 ... genre6 respectively). User enters selects from a drop down on the front end. What I would like to happen is messaging to appear stating that he's selected the same values for fields 1 and 2 or 1 and 3 etc.

It looks like this.

genre1 int,
genre2 int,
genre3 int,
genre4 int,
genre5 int,
genre6 int,

if genre1 = genre2
or genre1 = genre3
or genre1 = genre4
or genre1 = genre5
or genre1 = genre6
or genre2 = genre3
or genre2 = genre4
or genre2 = genre5
etc ... 

I don't need to state the combination of fields that he's entered incorrectly only that he's done so and he should review the data before continuing.

This has to happen in a trigger (insert and update) on the table. There is other logic being tested and evaluated within the trigger as well but at the end I've added the following logic to start and it doesn't seem to work.

declare @genre1 int
set @genre1 = (select genre1 from lt_wmi_men_org_cs where   id_key = @id_key) 
-- select * from lt_wmi_men_org_cs

BEGIN TRY
        IF (@genre1 = 6) -- This is used to test a particular value. 
        BEGIN
            Select @genre1
        END
END TRY
BEGIN CATCH
   --  SELECT ERROR_MESSAGE() + @genre1 AS ErrorMessage;

    DECLARE @ErrorNumber INT = ERROR_NUMBER();
    DECLARE @ErrorLine INT = ERROR_LINE();
    DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
    DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
    DECLARE @ErrorState INT = ERROR_STATE();

    PRINT ERROR_MESSAGE() + @genre1;
    PRINT 'Actual error number: ' + CAST(@ErrorNumber AS VARCHAR(10));
    PRINT 'Actual line number: ' + CAST(@ErrorLine AS VARCHAR(10));

END CATCH; 

I've also tried a more complex if statement but none of it seems to be working.

BEGIN TRY
        IF (@genre1 = @genre2 OR  @genre1 = @genre3 OR  @genre1 = @genre4 OR  @genre1 = @genre5 OR  @genre1 = @genre6 )
        BEGIN
            Select @genre1
        END
END TRY

Please advise.
Thank you

Detect for how long if and else statements were executed

In processing (which is based on java), the draw method is constantly being executed as long as the program is running. I'm trying to measure for how long the condition in the if statement was true. I have a if statement:

if (matrix [3][5]== 3) {
      System.out.println("Closed");
}
else {
 System.out.println("Opened");
    } 

The value of matrix [3][5]changes dynamically (I use Reactivision, and based on some markers position, this value will change). When I run the program, the condition is false so I'll have:

opened
opened
...
opened

and then the condition will be true so it will print:

closed
closed 
etc

Before eventually turning back to opened. I want to measure for how long the condition was true and printed closed, and when it changes, for how long it stayed opened etc: for each lapse of time it returned opened or closed, I want to know for how long.

I started a timer in my setup:

void setup () {
startTime = System.nanoTime();
}

that I could end in the if statement:

if (matrix [3][5]== 3) {
          System.out.println("Closed");
         long estimatedTime = System.nanoTime() - startTime;
         System.out.println("Was opened for"+ estimatedTime);
    }

So I would know for how long it's been opened. But how can I make it start again to make it measure now for how long it's closed, then opened etc back and forth ? I can't figure this out

Verilog: Why is there a if(0) if if(1) is always true?

I have the verilog always block as below:

always @ (a)

begin

if(1) begin .. end

if(0) begin .. end.

end

Does if(1) mean that this statement is executed all the time once the always block is triggered? Then what is the point having if(0)? When is it executed?

Note: This is a legacy code, I'm not the owner of it.

Please help.

Bash script for usb controller connection output?

I have a bash script that configures my USB controller to act like an Xbox 360 controller for use with Steam. Here is the current script:

#!/bin/bash
lsmod | grep xpad

sudo xboxdrv --evdev /dev/input/event14 --evdev-absmap ABS_X=x1,ABS_Y=y1,ABS_RX=x2,ABS_RZ=y2,ABS_HAT0X=dpad_x,ABS_HAT0Y=dpad_y --axismap -Y1=Y1,-Y2=Y2 --evdev-keymap BTN_TOP=x,BTN_TRIGGER=y,BTN_THUMB2=a,BTN_THUMB=b,BTN_BASE3=back,BTN_BASE4=start,BTN_TOP2=lb,BTN_PINKIE=rb,BTN_BASE=lt,BTN_BASE2=rt,BTN_BASE5=tl,BTN_BASE6=tr --mimic-xpad --silent &

exit 0

I would like to add some sort of "if" "else" statement to say that if the script is successful then notify me that it worked. But I don't know how I would do it.

e.g

if "script runs fine" then notify-send -t 2000 USB controller connection successful else "do nothing"

My questions are:

1.Would I need 2 seperate scripts? i.e one to run the first, the other to read the output of that script and produce the notification, or can I do it all in the same script?

2.How do I read that output?

Generally after it has created the new event in the terminal after the script runs, it will tell me the new event number (usually event15). If not it flags up an error.

Any help will be greatly appreciated,

Thanks in advance

CONCATENATE(IF()) - how to simplify current solution?

My data looks like this:

     ColumnName    PrimaryKey
1    ID               Y
2    JOB_NAME         N
3    JOB_DESC         N
4    START            N
5    END              N
...

I'm looking to list all columns that are primary keys - so, all columns where PrimaryKey = "Y" - in one cell, with "+" signs inbetween each returned row for ColumnName. This is the code I have so far:

=CONCATENATE((IF(C1="Y",B1,"")),(IF(C2="Y",B2,"")),(IF(C3="Y",B3,"")),(IF(C4="Y",B4,"")),(IF(C5="Y",B5,"")))

It gets the job done, but since I have over 50 rows in the ColumnName column, it ought to be a bit more concise.

xts indexing lag error

I have a question about indexing with xts. I understand that when I use SPY['2002-10-17/'], I can get all of the data in my xts object from 2002-10-17 to the last date. This however is not true if I write an ifelse statement and do the same call. Below is code:

library(quantmod)
getSymbols('SPY',from='2002-01-01') 
SPY=Cl(SPY) #pull only the closes
returns=(SPY-lag(SPY,1))/(lag(SPY,1)) #returns calculation
head(SPY['2002-10-17/']) #This works and starts at 2002-10-17
head(ifelse(returns>0,1,0)['2002-10-17/']) #this for some odd reason starts at 2002-10-18

Can anyone tell me why this is the case. I am truly befuddled.

EXCEL: Return a value from table if two criteria are met. One is a date range

Here is my dilemma. I have a column in one table that is blank. to fill it I need to look up user id in another table, and return a value from that table, but if and only if the the date from the 1st table falls within the range of dates from two columns in the 2nd table.

  1. Look up userid in sheet 2
  2. If found look up transdate trans date must fall on or between placefromdt and placetodate
  3. If criteria 1 and 2 met return the value in place

I tried to post pictures of the sheets but I am not authorized. Here is an abbreviated look

UserID      TransDate   Place

93696732A   12/01/2014  
99898585F   12/01/2014  
99898585F   11/01/2014  
91867459C   12/01/2014  
91867459C   11/01/2014  
91867459C   10/01/2014  
91867459C   09/01/2014  
91867459C   08/01/2014  
91867459C   07/01/2014  


userid      station placeid place    placefrmdt  placetodt

E13332190   HW      105612  STJWCC   09/01/2014  02/28/2015
A97059190   HW      105614  TCI      01/01/2014  12/31/9999
A56586039   HW      105614  TCI      01/01/2014  12/31/9999
C02409039   HW      107549  USCEFSGA 12/01/2014  01/31/2015
C67974990   HW      107539  KH       05/01/2015  12/31/9999
C99804409   HW      105612  STJWCC   01/01/2015  04/30/2015
C59064990   HW      105611  SBFHG    08/01/2014  04/30/2015
F09035309   HW      107540  LAC      07/01/2014  12/31/9999
D49047905   HW      105612  STJWCC   10/01/2014  01/31/2015
D13929089   HW      107549  USCEFSGA 09/01/2014  01/31/2015

Excel 2010 Formula to replace numbers

I have a list of results that may return a decimal value between 0 and 5. For business purposes I need to force Excel to replace the number as follows:

  • Any decimal value between 0 and 1 needs to show as the whole number 0
  • Any decimal value between 1 and 2 needs to show as the whole number 1
  • Any decimal value between 2 and 3 needs to show as the whole number 2
  • Any decimal value between 3 and 4 needs to show as the whole number 3
  • Any decimal value between 4 and 4.5needs to show as the whole number 4
  • Any decimal value between 4.5 and 5 needs to show the actual decimal value.

So, if the decimal value is 1.5, I want Excel to show it in the cell as 1. Or, if the decimal value is 4.5, I want excel to show it as 4.5.

I've tried using the following nested IF function (in this example the number to replaces is in cell L28):

=IF(L28>=4.5,L28,IF(L28<4.5>=4,"4",IF(L28=4,"4",IF(L28<4>=3,"3",IF(L28<2>=1,"2",IF(L28<1>=0,"0"))))))

However for some reason it works on values 4 or greater, but for anything <4 still shows 4, and I can't figure out why.

Should I be doing this in VBA instead?

Thanks in advance, and I'm hoping I explained this clearly...

How to put a variable into an if variable

I'm having an issue, I've tried to solve it but I can't... I have this code:

if($lang['LINGUA'] != 'Italiano') { $description = 'content of description meta tag' ?>

Obviously the meta tag description doesn't show. What I see inspecting the code is <meta name="description" content="">

Any help would be very appreciated! Thank you

Logic - within multiple for loops and dynamic arrays

Third day programming VBA. I have generated this code and wanted someone to run an eye over it as it is not having the intended affect.

The idea is to pull data from a MS Project export in one sheet and reproduce it as a schedule in another.

The code works I just have a logic error (I am guessing somewhere within my array). It is also very time consuming as it has a triple For loop. I can't think of a way to remove this so if anyone has any ideas let me know!

Private Sub CommandButton1_Click()

Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim m As Integer
Dim n As Integer
Dim p As Integer

Dim Arr() As Variant

For j = 6 To 29
k = 1
For i = 1 To 1000
    ReDim Preserve Arr(1 To 3, k)
    If ThisWorkbook.Worksheets("Sheet2").Cells(j, 1).Value = ThisWorkbook.Worksheets("Sheet1").Cells(i, 10) Then
    Arr(1, k) = ThisWorkbook.Worksheets("Sheet1").Cells(i, 4).Value
    Arr(2, k) = ThisWorkbook.Worksheets("Sheet1").Cells(i, 6).Value
    Arr(3, k) = ThisWorkbook.Worksheets("Sheet1").Cells(i, 7).Value
    k = k + 1
    End If
Next i

k = k - 1

For p = 1 To k
    m = 1
    For i = 3 To 253
        n = i + 1
        If Arr(2, m) <= ThisWorkbook.Worksheets("Sheet1").Cells(i, 6).Value And Arr(3, m) >= ThisWorkbook.Worksheets("Sheet1").Cells(n, 6).Value Then
        ThisWorkbook.Worksheets("Sheet2").Cells(j, i).Value = Arr(1, m)
        End If
    Next i
    m = m + 1
Next p
ReDim Arr(1 To 3, k)
Next j
End Sub

Nested If Wont Trigger When True

This code loops through a column of data. If the cell in the column Is a WIP it goes to a corresponding column and loops through that data. If not it takes the data and pastes it in the summary tab. Yet for some reason it will not pick up if there Is a WIP in column R.

Can someone see why the code does not trigger my second IF.

Cheers

 Sub summary_2()

Dim MainLoop As Double
Dim Secondloop As Double
Dim TopRow As Integer
Dim TopRow1 As Integer

Dim ThirdLoop As Double
Dim FourthLoop As Double


Dim ParentName As String
Dim ParentSku As Double


Dim WipSku As Double
Dim WipSku1 As Double
Dim childDesc As String
Dim childDesc1 As String
Dim childType As String
Dim childType1 As String



Range("A6" & ":" & "G1000").ClearContents

MainLoop = 5
Secondloop = 0
ThirdLoop = 0
FourthLoop = 0
TopRow = 5
TopRow1 = 5

Application.ScreenUpdating = False
Worksheets("Final").Activate

'loop 1
Do While MainLoop < ActiveSheet.Cells(Rows.count, "B").End(xlUp).Row

    ParentSku = Range("A" & MainLoop).Value
    ParentName = Range("B" & MainLoop).Value

    Worksheets("Recipe Book").Activate


    Range("C" & (ActiveSheet.Cells(Rows.count, "C").End(xlUp).Row) + 2).Value = ParentSku
    Range("D" & (ActiveSheet.Cells(Rows.count, "D").End(xlUp).Row) + 2).Value = ParentName
    Range("E" & (ActiveSheet.Cells(Rows.count, "E").End(xlUp).Row) + 2).Value = "Parent"
    Range("F" & (ActiveSheet.Cells(Rows.count, "F").End(xlUp).Row) + 2).Value = " - "


    Worksheets("Final").Activate

    'loop 2
    Do While Secondloop < 10

        'If 3
        If Range("H" & (MainLoop + Secondloop)) = "WIP" Then

            WipSku = Range("F" & (MainLoop + Secondloop)).Value

            'loop 4
            Do While TopRow < ActiveSheet.Cells(Rows.count, "B").End(xlUp).Row

                'If 5
                If Range("J" & TopRow).Value = WipSku Then

                    'loop 6
                    Do While ThirdLoop < 15

                       childSKU = Range("P" & (TopRow + ThirdLoop)).Value
                       childDesc = Range("Q" & (TopRow + ThirdLoop)).Value
                       childType = Range("R" & (TopRow + ThirdLoop)).Value
                       childPKG = Range("S" & (TopRow + ThirdLoop)).Value

                       'Find WIPs in R (this is where the code wont pick up) 
                        If Range("R" & (TopRow + ThirdLoop)).Value = "WIP" Then

                            WipSku1 = Range("P" & (TopRow + ThirdLoop)).Value

                            Do While TopRow1 < ActiveSheet.Cells(Rows.count, "B").End(xlUp).Row

                                If Range("T" & TopRow1).Value = WipSku1 Then


                                    Do While FourthLoop < 15

                                            childSKU1 = Range("Z" & (TopRow1 + FourthLoop)).Value
                                            childDesc1 = Range("AA" & (TopRow1 + FourthLoop)).Value
                                            childType1 = Range("AB" & (TopRow1 + FourthLoop)).Value
                                            childPKG1 = Range("AC" & (TopRow1 + FourthLoop)).Value

                                            Worksheets("Recipe Book").Activate

                                            Range("A" & (ActiveSheet.Cells(Rows.count, "C").End(xlUp).Row) + 1).Value = ParentSku
                                            Range("B" & (ActiveSheet.Cells(Rows.count, "D").End(xlUp).Row) + 1).Value = ParentName

                                            Range("C" & (ActiveSheet.Cells(Rows.count, "C").End(xlUp).Row) + 1).Value = childSKU1
                                            Range("D" & (ActiveSheet.Cells(Rows.count, "D").End(xlUp).Row) + 1).Value = childDesc1
                                            Range("E" & (ActiveSheet.Cells(Rows.count, "E").End(xlUp).Row) + 1).Value = childType1
                                            Range("F" & (ActiveSheet.Cells(Rows.count, "F").End(xlUp).Row) + 1).Value = childPKG1
                                            Range("G" & (ActiveSheet.Cells(Rows.count, "F").End(xlUp).Row) + 1).Value = "3"

                                            Worksheets("Final").Activate


                                            FourthLoop = FourthLoop + 1
                                    Loop


                                ElseIf Range("T" & TopRow1).Value <> WipSku1 Then

                                End If

                            TopRow1 = TopRow1 + 1

                            Loop

                            Worksheets("Final").Activate

                        ElseIf childType = "ING" Or childType = "MAT" Or RangechildType = "PKG" Then

                        End If
                        'End If for WIPs in R

                       Worksheets("Recipe Book").Activate

                        Range("A" & (ActiveSheet.Cells(Rows.count, "C").End(xlUp).Row) + 1).Value = ParentSku
                        Range("B" & (ActiveSheet.Cells(Rows.count, "D").End(xlUp).Row) + 1).Value = ParentName

                        Range("C" & (ActiveSheet.Cells(Rows.count, "C").End(xlUp).Row) + 1).Value = childSKU
                        Range("D" & (ActiveSheet.Cells(Rows.count, "D").End(xlUp).Row) + 1).Value = childDesc
                        Range("E" & (ActiveSheet.Cells(Rows.count, "E").End(xlUp).Row) + 1).Value = childType
                        Range("F" & (ActiveSheet.Cells(Rows.count, "F").End(xlUp).Row) + 1).Value = childPKG
                        Range("G" & (ActiveSheet.Cells(Rows.count, "F").End(xlUp).Row)).Value = "2"

                        Worksheets("Final").Activate


                    ThirdLoop = ThirdLoop + 1

                    'loop 6
                    Loop

                'Else 5
                ElseIf Range("J" & TopRow).Value <> WipSku Then

                'If 5
                End If

            TopRow = TopRow + 1

            'loop 4
            Loop


        Worksheets("Final").Activate

        'Else 3
        ElseIf Range("H" & (MainLoop + Secondloop)) = "ING" Or Range("H" & (MainLoop + Secondloop)) = "MAT" Or Range("H" & (MainLoop + Secondloop)) = "PKG" Then

            childSKU = Range("F" & MainLoop + Secondloop).Value
            childDesc = Range("G" & MainLoop + Secondloop).Value
            childType = Range("H" & MainLoop + Secondloop).Value
            childPKG = Range("I" & MainLoop + Secondloop).Value

            Worksheets("Recipe Book").Activate

                        Range("A" & (ActiveSheet.Cells(Rows.count, "C").End(xlUp).Row) + 1).Value = ParentSku
                        Range("B" & (ActiveSheet.Cells(Rows.count, "D").End(xlUp).Row) + 1).Value = ParentName

                        Range("C" & (ActiveSheet.Cells(Rows.count, "C").End(xlUp).Row) + 1).Value = childSKU
                        Range("D" & (ActiveSheet.Cells(Rows.count, "D").End(xlUp).Row) + 1).Value = childDesc
                        Range("E" & (ActiveSheet.Cells(Rows.count, "E").End(xlUp).Row) + 1).Value = childType
                        Range("F" & (ActiveSheet.Cells(Rows.count, "F").End(xlUp).Row) + 1).Value = childPKG
                        Range("G" & (ActiveSheet.Cells(Rows.count, "F").End(xlUp).Row)).Value = "1"

             Worksheets("Final").Activate

        'if 3
        End If

    'Loop 2
    Secondloop = Secondloop + 1

    Loop


    MainLoop = MainLoop + 20
    Secondloop = 0
    ThirdLoop = 0
    FourthLoop = 0
    TopRow1 = 0
    TopRow = 5
Loop

Worksheets("Recipe Book").Activate

End Sub

how to make if statement using value from case

i have select statement and the result is :

ax | country    | country_id | town   | pop |
1  | neverland  | 1          | ntown  | 10  |
1  | wonderland | 2          | wtown  | 20  |
2  | wonderland | 2          | wLtown | 20  |
1  | toysIsland | 3          | ttown  | 5   |

but it supposed to be like:

ax | country    | country_id | town   | pop |
1  | neverland  | 1          | ntown  | 10  |
1  | wonderland | 2          | wtown  | 20  |
2  | wonderland | 2          | wLtown | NULL|
1  | toysIsland | 3          | ttown  | 5   |

i have an if statement using value from case :

select (case country
when @c
then @co = @co +1
else @co = 1, @c = country
end ) as ax,
country, country_id, town, (case when town_id = param_ti then population_c) as pop
from tb_town a left join
tb_country b on b.country_id = a.country_id;

if ax = 1 then
 pop= pop
else
 pop= '';
end if;

i don't know what should i write in if statement :(

Use if statements with a number variable in JS

I am working on a gallery. So basically my idea works like this: The value of my variable picnumber is 1. If you click on the next button it will trigger my function nextpicture, and of course if you click on the previous button it will trigger my function previouspicture.

So what is the job of those functions?

  • nextpicture = picnumber + 1

  • previouspicture = picnumber + 1

Ok, so for example we have clicked on nextpicture once the value of picnumber should be 2 (if the value is 2 it should show 002.jpg)

I want to achieve that it shows a different picture on whether the value of picnumber is 1 - 6

I tried to do this with if and else if statements, however it didn't work.

var picnumber = 1;
function nextpicture(picnumber){
picnumber = picnumber + 1
}
function previouspicture(picnumber){
picnumber = picnumber - 1
}
if (picnumber == 1){
document.getElementById('gallerypicture').src = "img/gallery/001.jpg";
document.getElementById('galleryprevious').style.display = 'none';
}
else if (picnumber == 2){
document.getElementById('gallerypicture').src = "img/gallery/002.jpg";
}
else if (picnumber == 3){
document.getElementById('gallerypicture').src = "img/gallery/003.jpg";
}
else if (picnumber == 4){
document.getElementById('gallerypicture').src = "img/gallery/004.jpg";
}
else if (picnumber == 5){
document.getElementById('gallerypicture').src = "img/gallery/005.jpg";
}
else if (picnumber == 6){
document.getElementById('gallerypicture').src = "img/gallery/006.jpg";
document.getElementById('gallerynext').style.display = 'none';
}
else {  
document.getElementById('gallery').style.display = 'none';
}

Here's my HTML

<img id="gallerypicture" src="" alt="Photo">
<a href="javascript:void(0)" onclick="previouspicture(picnumber);"><div id="galleryprevious"></div></a>
<a href="javascript:void(0)" onclick="nextpicture(picnumber);"><div id="gallerynext"></div></a>

As you can see in my first and in my last if statement, I'd like to hide the div to click previous or next, so the value of picnumber can't be lower than 1 or higher than 6 (since I only have 6 pictures in this gallery)

Matlab: How to establish a relationship between two elements belonging to the same table?

I have three matrix like these:

categories1 =

     1     2   NaN
     3   NaN   NaN
     4   NaN   NaN

categories2 =

     1     2     3   NaN
     4     5     6   NaN
     4     5     6     7

that put beside give:

all_categories =

     1     2   NaN     1     2     3   NaN
     3   NaN   NaN     4     5     6   NaN
     4   NaN   NaN     4     5     6     7

Then, I have two vectors like:

obj1 = [4 2 1]

obj2 = [2 3 5]

How can I establish a condition that permits a certain operation between an element of obj1 and one of obj2, if and only if their correspondent category belong to the same line in all_categories? In other words, I would like to start a if block in the form:

if (a specified element of array `obj1` is on the same line of another specified element of the array`obj2`)
    do something
end

For instance, the condition would be verified in case of obj1(2) and obj2(1), because their correspondent value are both on the 1st line of all_categories).

Basically, I am trying to implement the condition that only if there is compatibility between and object belonging to a certain category and another object belonging to another category than an operation can happen. Hope this has not been too long to explain. Many thanks.

Excel VBA If not equal not working

I have this problem where my code doesn't check if cell has the value I need. I used box to check value it look good from box, but if doesn't take value. Any ideas whats wrong? I tried add value manually to cells, but if does't working.

If ThisWorkbook.ActiveSheet.Cells(virsus, desinen).value <> "CH" Or ThisWorkbook.ActiveSheet.Cells(virsus, desinen).value <> "SSC" Then 
   If ThisWorkbook.ActiveSheet.Cells(virsus, desinen - 1).value <> "CH" Or ThisWorkbook.ActiveSheet.Cells(virsus, desinen - 1).value <> "SSC" Or ThisWorkbook.ActiveSheet.Cells(virsus, desinen - 1).value <> "" Then  
       MsgBox ThisWorkbook.ActiveSheet.Cells(virsus, desinen - 1).value

If else condition not working on button click

If i don't use any condition on click to call another Activity then it works, but when i use some condition then its not responding, neither calling if section nor else:

btnUpload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // uploading the file to server

            try {

                strGetName = pref.getString("key_name", null);
                strGetEmail = pref.getString("key_email", null);

                if (strGetEmail.equals("")&&strGetName.equals("")) {
                    Toast.makeText(UploadActivity.this, "Please create your account first", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(UploadActivity.this, BasicActivity.class);
                    startActivity(intent);
                }
                else {
                    new UploadFileToServer().execute();
                }

            } catch (Exception e) {
                // TODO: handle exception
            }
        }
   });

can't get If else statement work in Powershell AD script

The problem is, this script works perfect. The problem is.. it also works on a "Administrator" and "Guest" account, and that's something I don't want. So I created a if else statement but it's not working, maybe someone is seeing really fast what I am doing wrong?

What does the script? When someone is locked in the AD, it creates an HTML mail with info (hostname, domain, username).

This is the script:

$DC = "DC1"
$Report= "c:\powershell\html.html"
$Name1 = "Administrator", "Guest"
$log2 = "C:\powershell\temp.log"

$HTML=@"
<title>Account locked out Report</title>
<style>
BODY{background-color :#FFFFF}
TABLE{Border-width:thin;border-style: solid;border-color:Black;border-collapse: collapse;}
TH{border-width: 1px;padding: 1px;border-style: solid;border-color: black;background-color: ThreeDShadow}
TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color: Transparent}
H2{color: #457dcf;font-family: Arial, Helvetica, sans-serif;font-size: medium; margin-left: 40px;
</style>
"@

$Account_Name = @{n='Account name';e={$_.ReplacementStrings[-1]}}
$Account_domain = @{n='Account Domain';e={$_.ReplacementStrings[-2]}}
$Caller_Computer_Name = @{n='Caller Computer Name';e={$_.ReplacementStrings[-1]}}


$event= Get-EventLog -LogName Security -ComputerName $DC -InstanceId 4740 -Newest 1 |
   Select TimeGenerated,ReplacementStrings,"Account name","Account Domain","Caller Computer Name" |
   % {
     New-Object PSObject -Property @{
      "Account name" = $_.ReplacementStrings[-7]
      "Account Domain" = $_.ReplacementStrings[5]
      "Caller Computer Name" = $_.ReplacementStrings[1]
      Date = $_.TimeGenerated
    }
   }

 $event | ConvertTo-Html -Property "Account name","Account Domain","Caller Computer Name",Date -head $HTML -body  "<H2> User is locked in the Active Directory</H2>"|
     Out-File $Report -Append

Get-EventLog -LogName Security -ComputerName DC1 -InstanceId 4740 -Newest 1 | Format-List >> $log2


If ((Get-Content $log2 ) -contains $Name1 )

{
#Don't do shit
}

Else
{
$MailBody= Get-Content $Report
$MailSubject= "User Account locked out"
$SmtpClient = New-Object system.net.mail.smtpClient
$SmtpClient.host = "smtp.eurotransplant.org"
$MailMessage = New-Object system.net.mail.mailmessage
$MailMessage.from = "mailadress@mailadress.com"
$MailMessage.To.add("mailadress@mailadress.com")
$MailMessage.Subject = $MailSubject
$MailMessage.IsBodyHtml = 1
$MailMessage.Body = $MailBody
$SmtpClient.Send($MailMessage)
}


Remove-Item c:\powershell\html.html
Remove-Item C:\Powershell\temp.log

Thanks in advance!

How to use ifelse inside the for loop in R

I have to check the names of all variables in a data.frame and if match found, need to replace the NA values in that variable with Median, else for others replace NAs with mean.

The data.frame cyl_spec has 11 variables and I have to replace NA as below:

  1. Viscosity: Impute with median
  2. Wax: Impute with median
  3. Others: Impute with Mean

I can certainly do it by picking the variables one at a time but I was trying the following code :

attach(cyl_spec)
var <- colnames(cyl_spec)
for(val in var)
{
  if(val == 'viscosity'){viscosity[is.na(viscosity == T)] <- median(viscosity, na.rm = T)}
  else if(val == 'wax'){wax[is.na(wax == T)] <- median(wax, na.rm = T)}
  else {val[is.na(val == T)] <- mean(val, na.rm = T)}
}
detach(cyl_spec)

Somehow the code is not doing anything and I am still getting the same no of NA in the variable using this command :

sum(is.na(cyl_spec$viscosity) 

Also, when I run this code I get the following warning message :

Warning messages:
1: In mean.default(val, na.rm = T) :
  argument is not numeric or logical: returning NA
2: In mean.default(val, na.rm = T) :
  argument is not numeric or logical: returning NA
3: In mean.default(val, na.rm = T) :
  argument is not numeric or logical: returning NA
4: In mean.default(val, na.rm = T) :
  argument is not numeric or logical: returning NA
5: In mean.default(val, na.rm = T) :
  argument is not numeric or logical: returning NA
6: In mean.default(val, na.rm = T) :
  argument is not numeric or logical: returning NA
7: In mean.default(val, na.rm = T) :
  argument is not numeric or logical: returning NA
8: In mean.default(val, na.rm = T) :
  argument is not numeric or logical: returning NA
9: In mean.default(val, na.rm = T) :
  argument is not numeric or logical: returning NA

Could someone please help me with finding the solution for this, am stuck! Thanks in advance!!

Count the correct score

I was given an assignment to asks questions and then calculate the total score at the end. Here is my code. TIA

    Scanner userInput = new Scanner(System.in);
    int userAnswer;

    System.out.print("Q1.) Who is the main character in the Legend of Zelda?\n"
            + "1.) Link\n2.) Princess Zelda\n3.)Super Mario"
            + "\nAnswer: ");
    userAnswer = userInput.nextInt();
    if (userAnswer == 1){
        System.out.print("That is correct! ");
    }
    else {
        System.out.print("I'm sorry but that is wrong.");
    }

    System.out.print("\nQ2.) Who is the main character in the Naruto?\n"
            + "1.) Sasuke\n2.) Naruto\n3.) Sakura"
            + "\nAnswer: ");
    userAnswer = userInput.nextInt();
    if (userAnswer == 2){
        System.out.print("That is correct! ");
    }
    else {
        System.out.print("I'm sorry but that is wrong.");
    }

    System.out.print("Q3.) Who is the main character in the Dragon Balls??\n"
            + "1.) Krillin\n2.) Bulma\n3.) Goku"
            + "\nAnswer: ");
    userAnswer = userInput.nextInt();
    if (userAnswer == 3){
        System.out.print("That is correct! ");
    }
    else {
        System.out.print("I'm sorry but that is wrong.");
    }

The only question is, what statement should I add to add up the total scores?

mercredi 29 juillet 2015

C short writing way of code

my code is :

  if(nemrh<=305){  nemf=75; }
      if(305<nemrh<=325){ nemcarpan=0.05; nemkalan=nemrh-305; nemaratop=nemkalan*nemcarpan; nemf=76+nemaratop; }
      if(325<nemrh<=350){ nemcarpan=0.04; nemkalan=nemrh-325; nemaratop=nemkalan*nemcarpan; nemf=77+nemaratop; }
      if(350<nemrh<=370){ nemcarpan=0.05; nemkalan=nemrh-350; nemaratop=nemkalan*nemcarpan; nemf=78+nemaratop; }
      if(370<nemrh<=393){ nemcarpan=0.0435; nemkalan=nemrh-370; nemaratop=nemkalan*nemcarpan; nemf=79+nemaratop; }
      if(393<nemrh<=415){ nemcarpan=0.0454; nemkalan=nemrh-393; nemaratop=nemkalan*nemcarpan; nemf=80+nemaratop; }
      if(415<nemrh<=440){ nemcarpan=0.04; nemkalan=nemrh-415; nemaratop=nemkalan*nemcarpan; nemf=81+nemaratop; }
      if(440<nemrh<=465){ nemcarpan=0.04; nemkalan=nemrh-440; nemaratop=nemkalan*nemcarpan; nemf=82+nemaratop; }
      if(465<nemrh<=490){ nemcarpan=0.04; nemkalan=nemrh-465; nemaratop=nemkalan*nemcarpan; nemf=83+nemaratop; }
      if(490<nemrh<=515){ nemcarpan=0.04; nemkalan=nemrh-490; nemaratop=nemkalan*nemcarpan; nemf=84+nemaratop; }
      if(515<nemrh<=540){ nemcarpan=0.04; nemkalan=nemrh-515; nemaratop=nemkalan*nemcarpan; nemf=85+nemaratop; }
      if(540<nemrh<=563){ nemcarpan=0.0435; nemkalan=nemrh-540; nemaratop=nemkalan*nemcarpan; nemf=86+nemaratop; }
      if(563<nemrh<=592){ nemcarpan=0.0344; nemkalan=nemrh-563; nemaratop=nemkalan*nemcarpan; nemf=87+nemaratop; }
      if(592<nemrh<=620){ nemcarpan=0.0357; nemkalan=nemrh-592; nemaratop=nemkalan*nemcarpan; nemf=88+nemaratop; }
      if(620<nemrh<=648){ nemcarpan=0.0357; nemkalan=nemrh-620; nemaratop=nemkalan*nemcarpan; nemf=89+nemaratop; }
      if(648<nemrh<=678){ nemcarpan=0.0333; nemkalan=nemrh-648; nemaratop=nemkalan*nemcarpan; nemf=90+nemaratop; }
      if(678<nemrh<=705){ nemcarpan=0.037; nemkalan=nemrh-678; nemaratop=nemkalan*nemcarpan; nemf=91+nemaratop; }
      if(705<nemrh<=735){ nemcarpan=0.03333; nemkalan=nemrh-705; nemaratop=nemkalan*nemcarpan; nemf=92+nemaratop; }
      if(735<nemrh<=766){ nemcarpan=0.0322; nemkalan=nemrh-735; nemaratop=nemkalan*nemcarpan; nemf=93+nemaratop; }
      if(766<nemrh<=797){ nemcarpan=0.0322; nemkalan=nemrh-766; nemaratop=nemkalan*nemcarpan; nemf=94+nemaratop; }
      if(797<nemrh<=830){ nemcarpan=0.0303; nemkalan=nemrh-797; nemaratop=nemkalan*nemcarpan; nemf=95+nemaratop; }
      if(830<nemrh<=860){ nemcarpan=0.0333; nemkalan=nemrh-830; nemaratop=nemkalan*nemcarpan; nemf=96+nemaratop; }
      if(860<nemrh<=894){ nemcarpan=0.0294; nemkalan=nemrh-860; nemaratop=nemkalan*nemcarpan; nemf=97+nemaratop; }

how i write this code that short way ? i want to right it short version. can anybody show me ?

Avoiding multiple if statements in C# factory method

I have C# application that stores data in a NoSQL database. The app has a repository class that uses a series of objects to translate the data from the NoSQL form to that used by the C# models, and vice versa (essentially a form of ORM). The objects implement a 'converter' interface, and each object works on one specific data type (string, bool, etc). Internally they use reflection to perform the transformation. Instances of these objects are created by a method that returns the object for the given type. Currently the logic looks something like the following:

if(type == typeof(string)
    return new StringConverter(...);

if(type == typeof(int) || type == typeof(uint))
    return new IntegerConverter(...);

... // and so on

However all those 'if' statements bother me. I know I could do something like create a dictionary to map types to creation methods but I am not sure if this will result in more readable, easy to maintain/extend code(?). Given the need to create the type abstractions what is the best way to go about doing this? Any suggestions welcomed. Huge thanks in advance.

A simple if else in R that creates a new column dependent on the result

I am stuck on what should be a fairly simple if else statement in R.

I have a data frame named UK that contains several columns, one of which is named location which contains the name of the UK city to which that row's data pertains.

My goal is to create a new column, named capital that will simply separate the rows into a binary London or UK ex London. I haven't done many if else statements and I'm struggling to get the syntax right, my attempt below:

if (UK$location[UK$location == "London"]) UK$capital <- "London" else UK$capital <- "UK ex London"

Should if else not be the best way to do this, I am happy to adopt a different method. Many thanks in advance for the help.

How to check if a program is installed and install it if it is not?

I would rather not use WMI due the integrity check.

This is what I have that does not work:

$tempdir = Get-Location
$tempdir = $tempdir.tostring()

$reg32 = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
$reg64 = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"

if((Get-ItemProperty $reg32 | Select-Object DisplayName | Where-Object { $_.DisplayName -Like '*Microsoft Interop Forms*' } -eq $null) -Or (Get-ItemProperty $reg64 | Select-Object DisplayName | Where-Object { $_.DisplayName -Like '*Microsoft Interop Forms*' } -eq $null))
        {
        (Start-Process -FilePath $tempdir"\microsoft.interopformsredist.msi" -ArgumentList "-qb" -Wait -Passthru).ExitCode
        }

It always returns false. If I switch it to -ne $null it always returns true so I know it is detecting $null output even though, I believe (but could be wrong), the Get-ItemProperty is returning a result that should be counting as something other than $null.

Struct Array Generation Loop Matlab

Say I have a list of directories:

/users/david/patients/patientID/Day
/users/david/patients/patientID/Daya/HospID_x/Data
/users/david/patients/patientID/Dayb/HospID_y/Data
/users/david/patients/patientID/Dayc/HospID_z/Data
/users/david/patients/patientID/Day
/users/david/patients/patientID/Daya/HospID_x/Data
/users/david/patients/patientID/Dayb/HospID_y/Data
/users/david/patients/patientID/Dayc/HospID_z/Data
/users/david/patients/patientID/Day
.
.

The data is mixed, contains images, vectors, text and so on.

I want loop through the directories and create a structure along the way to hold my data. I have generated a list of the folders of interest. The struct i want to have is of the form.

Patient{i,j}.PatientID.DayID.HospitalID.Data

As you can see from the directory list the first folder holds some subfolders, how do I loop through these.

Java | int Method | I need ELSE {Return nothing}

I've come across a situation where I need to use a method to check if the sum of the two digits of a number from 10 to 50 is larger than 10 and then display that number. I must use a for loop.

This is my main:

public class nested_loop2   { 

public static void main(String args[])  {

    for (int i=10;i<=50;i++){

    System.out.println(ax(i));      }

} This is my method:

public static int ax(int i){

    int a=i/10;
    int b=i%10;

    if((a+b)>10){ return i; }

    else {      return 0;}

    }}

The problem I have with this is that I want it to display only those particular numbers that pass the verification. In the current state, it also prints out 0 for all the ones that didn't fit. I don't want it to return 0, I just want it to not return anything for the else{} statement.

Check integer number is between two values

I have a int variable named number with value 21.

int number = 21;

if (number >= 6 && number < 12) {
    System.out.println("catch 1");
}
else if (number >= 12 && number < 17) {
    System.out.println("catch 2");
}
else if (number >= 17 && number < 21) {
    System.out.println("catch 3");
}
else if (number >= 21 && number < 6) {
    System.out.println("catch 4");
}

Why i can't see the catch 4 message?