jeudi 31 janvier 2019

Program jumps into the if-statement no matter the the expression is

I have created a simple method. It bring a String of 1 char into the method. It then searches another string to see if that char is in the string. If it is not it returns an int index of -1. If int index is < 0 it moves on (which means there was not a match. If there is a match, it returns the index of the char (which would be 0 or higher). For some reason, no matter what it returns, it jumps in to that if-statement.

static void letterCheck(String guess) 
{


    String usedLetters = "abc";
    int index = usedLetters.indexOf(guess);
    System.out.println("\nYour letter is \"" + index + "\".");

    if (index >= 0);
    {
        System.out.println("\nYour index # is \"" + index + "\".");
        System.out.println("You have already guessed letter " + guess + " 
        before.");
        match(word, userGuess);;
    }


}

R will only use true statement in ifelse. False statement ignored for some reason

All results give pass even if math score is less than 50 when using the ifelse statement I'm new to R (2 weeks) and I have no clue as to why "fail" won't show up.

.

nosleep<- nosleep %>% + mutate(mathResult = ifelse('math score'>=50, "pass","fail"))

expected result: fail under 50 actual result: all pass

A question of efficiency : A boolean function to return a change in a vector and true/false

I am trying to create a function which takes 2 numbers as a range of values of a vector. It pushes all the numbers to the left and adds two adjacent numbers if they are equal. For example:

v (before):

[0 0 0 5 1 2 0 2 2 0 0 0 2 0 0 2 6 0 0 5 0 6 4]

bi: 1

ei: 4


v (after):

[0 5 0 0 1 2 0 2 2 0 0 0 2 0 0 2 6 0 0 5 0 6 4]

return: true

The function:

bool left_push(std::vector<int>& v, int bi, int ei){

    std::vector<int> tmp;
    bool check = false ;

    for(int i = bi+2 ; i <= ei ; i++){

        if(v[i]==v[i-1]){
            v[i-1] = v[i]+v[i];
            v[i] = 0;

            check = true;
        }

        if(v[i-1]==0){
            v[i-1] == v[i];
            v[i] = 0;

            check = true ;
        }

    return check;
}

The issue with this is that after it goes through this code one whole time, It would not have yet reached a point where it fully pushes all the numbers to the left and adds them to the left. For example say we just added two numbers e.g 2 2 this means we now have 4 0 and so not all the zeros would be pushed to the left.

This mean I need to perform this whole thing multiple times by putting it all into a for loop. The problem with this is that this would lead to inefficiencies as you could be going through the loop even after all possible movements have happened.

I have tried doing it in other methods. For example, remove all the zeros and then add them but even then you still get the same problems.

How exactly could I overcome this issue? I would appreciate any ideas/pointers.

How to Create a New Variable that repeats certain values of an existing variable in Pandas Dataframe?

I have an indicator variable in my dataframe that takes on the values 1 0 or -1. I'd like to create a new variable that avoids the 0's and instead repeats the nonzero values of the indicator variable until it changes to 1 or -1.

I tried various constructions using the np.where statement, but I cannot solve this problem.

Here is the original dataframe:

import pandas as pd
df = pd.DataFrame(
{'Date': [1,2,3,4,5,6,7,8,9,10],
'Ind': [1,0,0,-1,0,0,0,1,0,0]})
df

enter image description here

I am hoping to get a dataframe that looks like the following:

df2 = pd.DataFrame(
{'Date': [1,2,3,4,5,6,7,8,9,10],
'Ind': [1,0,0,-1,0,0,0,1,0,0],
'NewVar':[1,1,1,-1,-1,-1,-1,1,1,1]})

enter image description here

how to filter inside php socket

i have this socket writed on php, the problem is:

how to filter users and send a msg to choosed user,

example: from a external form i can choose an user and send a msg, but i need the msg just go to a selected user, no to all connected users, because sometimes i send a function to move user and all user is moved because all users receive the function and not just the choosed user,

how i can filter by user and the function send to a selected user?

the function is just a javascript line (but how i can do that? with a if or else??? )

//
//error_reporting(1);
set_time_limit(0);
//
//
define('CON_IP', '127.0.0.1');
define('CON_PORT', 4000);
//
//
//INICIO KEEP ALIVE
$KTimer   = (20);
$LastTime = time();
//END KEEP ALIVE
//
$null     = NULL; //null var
//
$socket   = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // CREAR STREAM SOCKET TCP
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); //REUTILIZAR PUERTO
socket_bind($socket, CON_IP, CON_PORT); //VINCULA EL SOCKET AL HOST ESPECIFICADO
socket_listen($socket); //ESCUCHAR PUERTO
//
//CREAR Y AÑADIR SOCKETS A LA LISTA
$clients = array(
    $socket
);
echo ('running...');
//
//INICIAR CICLO PARA QUE EL SCRIPT NO SE DETENGA
//
while (true) {
    //
    //MANEJAR MULTIPLES CONEXIONES
    $changed = $clients;
    //RETORNA LOS RECURSOS DE SOCKET EN EL ARRAY ($changed)
    socket_select($changed, $null, $null, 0, 10);
    //
    //BUSCA UN NUEVO SOCKET
    if (in_array($socket, $changed)) {
        $socket_new = socket_accept($socket); //ACEPTAR NUEVO SOCKET
        $clients[]  = $socket_new; //AÑADIR SOCKET CLIENTE A ARRAY()
        //
        $header     = socket_read($socket_new, 1024); //LEER DATOS ENVIADOS POR EL SOCKET
        //
        //HEADER FIX
        if (substr($header, 0, 3) == 'GET' || substr($header, 0, 4) == 'POST' || substr($header, 0, 4) == 'OPTI') {
            //
            //HTML HEADER INCLUDE
            socket_write($socket_new, ("HTTP/1.1 200 OK\r\n"));
            socket_write($socket_new, ("Server: NStream/5.8.425.10413\r\n"));
            socket_write($socket_new, ("Content-Type: text/html; charset=utf-8;\r\n"));
            socket_write($socket_new, ("Cache-Control: private\r\n\r\n"));
            //
            //
            socket_write($socket_new, $html);
        }
        //END HEADER FIX
        //
        socket_getpeername($socket_new, $RemoteAddr, $RemotePort); //OBTENER DIRECCION IP Y PUERTO DE LOS SOCKETS CONECTADOS
        MsgSend('[' . $RemoteAddr . ':' . $RemotePort . ']=>>IC', 'ILC'); //NOTIFICAR NUEVAS CONEXIONES
        //
        //CREAR UN NUEVO CANAL PARA SOCKETS NUEVOS
        $found_socket = array_search($socket, $changed);
        unset($changed[$found_socket]);
        //CMD PARSE
        //si sesion coincide con usuario, mostrar packet
        if (!empty($header)) {
            $GedCmdId = (explode(':', @explode('"', $header)[1]));
            //CMD SY
            if ($GedCmdId[0] == 'sy') {
                $ParsePaket = (explode('|', preg_replace(array(
                    "/'/",
                    "/,/"
                ), array(
                    NULL,
                    '|'
                ), $GedCmdId[1])));
                $header     = ("parent.ParsePacket(\"sy:'" . $ParsePaket[0] . "','" . $ParsePaket[1] . "','" . $ParsePaket[2] . "','" . $ParsePaket[3] . "','" . $ParsePaket[4] . "','" . $ParsePaket[5] . "'," . $ParsePaket[6] . "\");");
            }
        }
        //}
        //END CMD PARSE
    }
    //VOID
    //
    //KA - FIX
    if (time() - $LastTime > $KTimer) {
        MsgSend('[' . $LastTime . '==>' . time() . ']=>>KA(' . (time() - $LastTime) . ')', 'ILC');
        MsgSend("k();");
        $LastTime = time();
        continue 1;
    }
    //END KA - FIX
    //
    //LOOP A TRAVEZ DE TODOS LOS SOCKETS CONECTADOS
    foreach ($changed as $changed_socket) {
        //check for any incomming data
        if (!empty($header)) {
            //PREPARAR INFO PARA SER ENVIADA A SOCKET
            //prepare data to be sent to client
            MsgSend('[' . $RemoteAddr . ':' . $RemotePort . ']=>>MSG', 'ILC');
            MsgSend($header); //send data
        }
        $buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ);
        if ($buf === false) { // VERIFICAR CLIENTES DESCONECTADOS
            //
            // REMOVER CLIENTE DE ARRAY ($clients)
            $found_socket = array_search($changed_socket, $clients);
            socket_getpeername($changed_socket, $RemoteAddr);
            unset($clients[$found_socket]); //NOTIFICAR NUEVAS DESCONEXIONES
            MsgSend('[' . $RemoteAddr . ':' . $RemotePort . ']<<=ID', 'ILC');
        }
    }
}
//
//CIERRA LA ESCUCHA EN EL SOCKET
socket_close($socket);
function MsgSend($msg, $msgt = 'sock')
{
    global $clients;
    if ($msgt == 'ILC') {
        echo ($msg . "\r\n");
    } else {
        if (!empty($msg)) {
            foreach ($clients as $changed_socket) {
                @socket_write($changed_socket, '<script>' . $msg . "</script>\r\n");
            }
        }
    }
    return true;
}

Batch Script: if folder exists, copy ONLY SUB-folders/files to archive network folders based on first two digits of folder name i.e. "02" for February

In my new role, at the beginning of each year, we move all client data files from from two years prior (this year they are 2016 data files) from one network and all of their associated analysis data files from another network, to our archive drive/network.

I am looking for a way to automate this task because previously users would just click-and-drag each of the data folders to the archive, which is time consuming and tedious.

I have been looking into creating a batch script to alleviate this, however, I just started learning batch scripting yesterday. So here goes:

I have two network folders: A:\ where we store our client data analysis files and templates broken down by client, then year, then month (A:\Client Names\2016\06 June 2016), and B:\ where we store the client source data files which is broken down by year, then month, then client (B:\All Client Data\2016\01 Client Data\"Client Name").

I need to move all 2016 analysis folders to their respective folders in the All Client Data network. Then move the entire All Client Data\2016\ directory to our archive network.

The main problem so far, is that there is not always a 2016 folder in the A:\ drive, and when there is, the month folders within can vary.

So the problem then:

I need to FOR LOOP through the subdirectories of the A:\Client Names\ drive

IF EXIST Client Names\2016\ then xcopy/robocopy ONLY the sub folder(s) and their files to the appropriate folder in the B:\ drive, matching those folders by the first 2 digits in their folder names.

I am new to batch scripting, actually just started yesterday, but I feel like I am on the right path.

My problem is that I do not know how to resolve the pathname to the sub folders if the 2016 folder exists (I havent gotten past this step). I also do not know how to copy those folders to the specific folder in the B:\ drive.

I have been writing my code on a smaller scale by creating a folder on my local drive and another netwrok drive to see if I cant get the basics down, but I've ran into a wall.

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION


:: variables

SET scriptname=%~n0
SET parentpath=%~dp0
SET archyear=2016
SET "sourcepath=C:\Data_Files"
SET "destinpath=Z:\Batch_Test"

NET USE Z: \\C_WSDUSA_Groups\PRA\GBL

:: begin main script language

CD %sourcepath%

FOR /D /R "%sourcepath%" %%A IN (%archyear%) DO (
    IF EXIST "%%~fA\%%A\2016" (
        xcopy "%%~fA\%%A\2016\*" "%destinpath%" /e /v /g /h
    ) ELSE IF NOT EXIST (
        ECHO %%~pA does not contain %archyear% data
    )
)

PAUSE

:END
ENDLOCAL
ECHO ON
@EXIT /B 0

In the above code, in the %sourcepath% I have copied over two client folders, one with a 2016 folder and \02 February 2016\ and \08 August 2016 CAP\ sub folders, and the other client folder with just data files in it (no 2016 folder or sub-folders)

I know the problems and errors in the above code are in the IF EXIST line, Because I do not know how to dynamically reference the path to the 2016 folder.

-- After correcting for this, will I have to create a nested IF EXIST command to find what the beginning strings are: "02" and "08", to then be able to match them to the appropraite folder in the B:\ drive when copying?

-- Thank you all very much for your help. I am learning on the fly here and appreciate and help or guidance you can offer. I come to this site frequently as a lurker for SAS and SQL help, which is more my background, but this is my first time posting. I apologize for the long-winded post. Thanks again!

Output values of the array only if not empty or null

I am really new to php and do not know what I should look up to get this solved. I am trying to show only the values if the variable is not empty nor null.

Within an array I assign:

$attributes [
'glutenfree'               => getPublicClassificationsDescription($classifications, ARTICLE_GLUTENFREE),
            'lactosefree'              => getPublicClassificationsDescription($classifications, ARTICLE_LACTOSEFREE),
            'flavouringfree'           => getPublicClassificationsDescription($classifications, ARTICLE_FLAVOURINGFREE),
            'corerange'                => getPublicClassificationsDescription($classifications, ARTICLE_CORERANGE),
            'engro'                    => getPublicClassificationsDescription($classifications, ARTICLE_ENGRO),
            'vegan'                    => getPublicClassificationsDescription($classifications, ARTICLE_VEGAN),
...
];

and a lot of other attributes more. I want the output that it is only printed to the CSV if it is not empty nor null.

Right now I get the result like this:

glutenfree=,lactosefree=,flavouringfree=,corerange=,engro=,vegan=No,...

The output I need is like everything that is empty/null should be gone but the ones with value should be there. In this example:

vegan=No,...

For example if I try with "empty" or "isset" it does not work and I get a blank page with no errors.

$glutenfree = getPublicClassificationsDescription($classifications, ARTICLE_GLUTENFREE);

$attributes [
 if (!empty($glutenfree)) {
                'glutenfree'          => $glutenfree,
                'lactosefree'              => getPublicClassificationsDescription($classifications, ARTICLE_LACTOSEFREE),
                'flavouringfree'           => getPublicClassificationsDescription($classifications, ARTICLE_FLAVOURINGFREE),
                'corerange'                => getPublicClassificationsDescription($classifications, ARTICLE_CORERANGE),
                'engro'                    => getPublicClassificationsDescription($classifications, ARTICLE_ENGRO),
                'vegan'                    => getPublicClassificationsDescription($classifications, ARTICLE_VEGAN),
    ...
    ];

I need to compare text fields and bring numeric (value) results depending on the matching

I have a base sheet where I have a drop-down using 4 text options (ALIVE, DEAD, WALKER, NON-WALKER) - This is for a GoT Deadpool game.

I will create a new sheet for each player who joins with the same options. Then I need to compare his choices to the baseline on the first sheet and return the following matches: If both are ALIVE - return the number 1 (for 1 point) If both are DEAD - return the number 1 again If both are WALKER - return 2 but if it differs return -1 (a point is taken) If both are NON-WALKER - results are same as the above for WALKER

Quoting the official rules for better understanding: "If you predict the character dead, you have the option to predict if they become a White Walker. Gain one point if you correctly predict if they become a Walker. Lose a point if you predict incorrectly."

How can I do that? Which formula to use?

Thank you in advance, people!

Having trouble counting iterations of different outputs in my javascript code

Trying to set up code to take inputted numbers, determine whether they are negative or positive, displaying this, and then when 0 is put in the code displays the amount of positive numbers put in and the amount of negative numbers put in and then terminates. Having trouble with the counting part and I am not sure how to set this up better. I am also not sure how to set this up to terminate after 0 is put in.

function mapping() {

 var num=parseInt(document.getElementById("num1").value);

 var countp = 0
 var countn = 0



if (num!==0) {

  if (num>0){

  document.getElementById("output").innerHTML="positive"
  countp +=1;

} else {

  document.getElementById("output").innerHTML="negative"
  countn += 1

}}  else {

document.getElementById("output").innerHTML="countp: " + countp;
document.getElementById("output").innerHTML="countn: " + countn;
}


}

Thank you.

Efficient way to create a DataFrame of custom summary measures by group

I want to create a new dataframe grouped by store that creates several new columns of summaries for each store. In the example below, for each store, I want to create the four variables. The variables are similar to sumif and countif in excel but calculated for each group (store).

  1. A variable that sums all product revenues above say $50.
  2. A variable that sums all product revenues below $50
  3. A variable that counts the number of products with revenues above $50
  4. A variable that counts the number of products with revenues below $50.

I have tried various forms of groupby and agg function. I perceive that I should use lambda but I am unsure how I would strutcure that syntax in order to create multiple variables at one time.

import pandas as pd
import numpy as np

n = 20

df = pd.DataFrame({'Store': np.random.choice(['Store_1', 'Store_2'], n),
            'Revenue': (np.random.random(n) * 50 + 10).round(2)
              })
df

So I can easily calculate multiple summary measures on Revenue. I don't know how to create custom summary measures like sumif or countif:

df2 = df.groupby('Store')['Revenue'].agg({'Rev_sum': 'sum', 'Rev_max': 'max'})

For each store (i.e. store_1, store_2) I want four variables in the new dataframe as described above (i.e. Rev_sum_great_50 , etc...)

If statements within a while loop with user input

This code was working earlier, but now I'm having issues with the while 0 <= int(relationship) > 3 block of code. The user should be able choose the type of relationship to the letter recipient, which will populate a salutation and valediction into a letter.

If I keep the if/elif statements within the while loop, the sal/val strings don't populate into the letter.

If I bring the if/elif statements flush with the while loop, the strings populate for the letter ONLY if the user types 1, 2, or 3 on the first time around. If the user types a number besides 1, 2, or 3, the program will continue but the sal/val strings will not populate.

Originally, I only had one set of if/elif statements, but I created two (which is redundant, and also not fixing the issue) sets of statements to see if that would solve the problem. I've messed around with indentation as well. I also tried creating functions for each type of relationship, but I kept getting name errors for salutation.

I can get the program to work if the user follows directions the first time around, or have it run if the user is prompted to type 1, 2, or 3 after mistyping on the first try. But I can't get the sal/val to populate in both cases. I feel like the issue must be related to indentation, but when I change the indentation levels, the problem is't solved.

# Function for an infinite nested dictionary to add content to a personalized letter 
def lkng_glss_lttr_bot():             

    lgl_num = 0 
    while command == 'compose': 

        store_lkng_glss_lttr = {}
        new_lgl = {} 
        new_lgl_num = len(store_lkng_glss_lttr) + 1 
        store_lkng_glss_lttr[new_lgl_num] = new_lgl

        address_acquaintence = ['Dear', 'Cordially,']
        address_friend = ['Dearest', 'With warmest regards,']
        address_beloved = ['My Darling', 'With all my love and affection,']
        salutation = ''
        valediction = ''

        recipient = input("\nWhat is the recipient’s name?\n") 
        new_lgl['recipient'] = recipient

        email = input("\nWhat is the recipient's email?\n")
        new_lgl['email'] = email


        print("\nWhat is your relationship to %s?" % recipient)
        relationship = int(input("""Type 1 for Acquaintence
    Type 2 for Friend
    Type 3 for Beloved\n"""))

        while 0 <= int(relationship) > 3:
            relationship = input("Please type 1, 2, or 3.\n")

            if relationship == 1:
                for salutation in address_acquaintence:
                    salutation = address_acquaintence[0]                
                for valediction in address_acquaintence:
                    valediction = address_acquaintence[1]

            elif relationship == 2:    
                for salutation in address_friend:
                    salutation = address_friend[0]        
                for valediction in address_friend:
                    valediction = address_friend[1]

            elif relationship == 3:
                for salutation in address_beloved:
                    salutation = address_beloved[0]      
                for valediction in address_beloved:
                    valediction = address_beloved[1]

        if relationship == 1:
            for salutation in address_acquaintence:
                salutation = address_acquaintence[0]                
            for valediction in address_acquaintence:
                valediction = address_acquaintence[1]

        elif relationship == 2:    
            for salutation in address_friend:
                salutation = address_friend[0]        
            for valediction in address_friend:
                valediction = address_friend[1]

        elif relationship == 3:
            for salutation in address_beloved:
                salutation = address_beloved[0]      
            for valediction in address_beloved:
                valediction = address_beloved[1]



        print("\nPlease inquire about %s's well being." % recipient)
        inquiry = input("You can ask about the weather, or what %s has been doing to pass the time in the interim between your last exchange:\n" % recipient)

        body = input("\nPlease write a few sentences to inform %s of the recent happenings in your life:\n" % recipient)

        final_sentiment = input("\nPlease close the letter by expressing the importance of your friendship and your desire to spend time with %s in the future:\n" % recipient ) 

        sender = input("\nWhat is your name?\n")

        postscript = input("\nPlease write a short postscript to %s:\n" % recipient) 


        # Concatenate greeting and recipient
        part_1 = salutation + " " + recipient + "," + "\n"

        # Concatenate inquiry and body
        part_2 = inquiry + " " + body + "\n"

        # Concatenate part_1, part_2, final_sentiment, closing, sender, & postscript in reverse order for a non-tradional letter format
        non_trdtnl_lttr = "P.S. " + postscript + "\n" + sender + "\n" + valediction + "\n" + final_sentiment + "\n" + part_2 + part_1

        # Using the non-traditional letter format, reverse the order of the entire letter using an extended slice to create a Looking Glass Letter & store in dictionary
        lkng_glss_lttr = non_trdtnl_lttr[::-1]
        new_lgl['lkng_glss_lttr'] = lkng_glss_lttr


        # Notify sender that their letter contents have been added to the Bot
        print(store_lkng_glss_lttr)
        print("\nYour letter to %s has been composed by the Looking Glass Letter Bot:\n" % recipient + lkng_glss_lttr)
        print("\nYour Looking Glass Letter to %s will be emailed immediately." % recipient)


        # Ask user to add another client 
        print("\nWould you like to compose another letter? Y/N")
        sender_response = input().lower().strip() 


        if sender_response == 'y' or sender_response == 'yes': 
            continue 

        else:
            print("\nWe hope you enjoyed using the Looking Glass Letter Bot.\nWe look forward to serving your Looking Glass Letter composition needs in the future.")
            break 

The output should be something like:

,boB raeD

!doog m'I ?uoy era woH

!!uoy ssim I

,yllaidroC

G

.em llaC .S.P

But the Dear and Cordially, are not populating if the user types something besides 1, 2, or 3 and has to be prompted a second time.

How to do IF statement for the final character in a cell (VBA)

I am using the current code

If Left(cell.Value, 1) = ")" Then

....

End If

But it still seems to apply to every cell, not just the cells ending with ")"

Any help would be great ( I am still a noob)

Passwords/username from a file

Ive recently been having trouble writing a program that involves taking the password and usename from a .txt file. So far i have written:

username_file = open("usernameTest1.txt","rt")
name = username_file.readlines()
username_file.close()
print(username_file)
print(name)
print(name[0])
print()

print(name[1])
Player1Name = name[0]
print(Player1Name)
nametry = ""
while nametry != (name[0]):
    while True:
        try:
            nametry = input("What is your Username player1?: ")
            break
        except ValueError:
            print("Not a valid input")

(The various prints are to help me to see what the error is) The password is succesfully extracted from the file however when it is put into a variable and put through an if statement it dosent work!

Any help would be much apreciated! Hopefully this is a simple fix!

Try, Except / If Statement Combination - Missing results

I am comparing one list of universities with several others, finding fuzzy string matches and writing results to a csv. Example of the lists:

data = ["MIT", "Stanford",...]

Data1 = ['MASSACHUSETTS INSTITUTE OF TECHNOLOGY (MIT)'], ['STANFORD UNIVERSITY'],...

With StackOverflow's help I got as far as:

for uni in data:
hit = process.extractOne(str(uni[1]), data10, scorer = fuzz.token_set_ratio, score_cutoff = 90)
     try:
        if float(hit[1]) >= 94:
            with open(filename, mode='a', newline="") as csv_file:
                fieldnames = ['bwbnr', 'uni_name', 'match', 'points']
                writer = csv.DictWriter(csv_file, fieldnames=fieldnames, delimiter=';')
                writer.writerow({'bwbnr': str(uni[0]), 'uni_name': str(uni[1]), 'match': str(hit), 'points': 10})

    except:
        hit1 = process.extractOne(str(uni[1]), data11, scorer = fuzz.token_set_ratio, score_cutoff = 90)
           try:
              if float(hit1[1]) >= 94:
                  with open(filename, mode='a', newline="") as csv_file:
                        fieldnames = [""]
                        writer = csv.DictWriter("")
                        writer.writerow({""})

... until the last excepts where I include those with scores lower than 94 and end with a "not found":

    except:
  hit12 = process.extractOne(str(uni[1]), data9, scorer = fuzz.token_set_ratio)
    try:
        if float(hit12[1]) < 94:
            with open(filename, mode='a', newline="") as csv_file:
                   fieldnames = [""]
                   writer = csv.DictWriter("")
                   writer.writerow({""})
      except:
          with open(filename, mode='a', newline="") as csv_file:
                fieldnames = [""]
                writer = csv.DictWriter("")
                writer.writerow({""})

However, I am returned only 2854 results as opposed to the 3175 in my original list (which all need to be checked and written to the new csv).

When I throw all my lists together and do my extractOne I do get 3175 results:

scored_testdata = []
for uni in data:
     hit = process.extractOne(str(uni[1]), big_list, scorer = fuzzy.token_set_ratio, score_cutoff = 90)
     scored_testdata.append(hit)
print(len(scored_testdata))

What am I missing here? I get the feeling results returning "None" in the process.extractOne are being dropped for some reason. Any help would be much appreciated.

How do I change this if statement and stop repeating forever?

My current bot works by using app.js to call commands from the /commands directory, and uses data.js to hold "global data" (eg users typed !p are added to and stored in export.players[] in data.js)

I have the below snippet of code (pl.js) that adds a list of users with the @Participating role by their discord nickname inside a RichEmbed.

It works okay, but because of the if requires message.content, and I already have a global prefix set; it requires command input more than once to start, and then repeats the entire embed output until the bot is rebooted.

Is there a way to change my if statement to start the code without checking the message.content? or to work if the command is called through app.js?

and how can I make it post once per command/stop it repeating?

pl.js

const Discord = require("discord.js");
const embed = new Discord.RichEmbed()
const client = new Discord.Client()

// Calling Global Data
var data = require('./../data.js');

    exports.run = (client, message, args) => {

      client.on("message", message => {

          if(message.content == `!pl`) {
              const ListEmbed = new Discord.RichEmbed()
                  .setTitle('Participants:')
                  .setDescription(message.guild.roles.get('###############').members.map(m=>m.user.username));
              message.channel.send(ListEmbed);

            }
        }
    )}

app.js

const Discord = require("discord.js");
const Enmap = require("enmap");
const fs = require("fs");  
const client = new Discord.Client();
const config = require("./config.json");


client.config = config;

fs.readdir("./events/", (err, files) => {
  if (err) return console.error(err);
  files.forEach(file => {
    const event = require(`./events/${file}`);
    let eventName = file.split(".")[0];
    client.on(eventName, event.bind(null, client));
  });
});

client.commands = new Enmap();

fs.readdir("./commands/", (err, files) => {
  if (err) return console.error(err);
  files.forEach(file => {
    if (!file.endsWith(".js")) return;
    let props = require(`./commands/${file}`);
    let commandName = file.split(".")[0];
    console.log(`Attempting to load command ${commandName}`);
    client.commands.set(commandName, props);
  });
});



client.login(config.token);

Values cleared after add dynamic textbox

i programmed a dynamic textbox button. When i click on the button, a dynamic textbox will created on my program. I have two more textboxes which are static on my program.

Now the problem: When i add a value in the two static textboxes, i can show me the values with a MessageBox.Show. After i click the the "add dynamic textbox" button, the values are NULL. So the values from the static textboxes are empty. The dynamic textboxes are not NULL and i can show me the values of them.

{

public partial class Form1 : Form static int i = 1;

    public Form1()
    {
        InitializeComponent();
    }

    private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
    {

    }


    private void button2_Click(object sender, EventArgs e)
    {
        if (i < 8)

        {
            InitializeComponent();
            TextBox tb = new TextBox();
            Label lb = new Label { };
            lb.Text = i + ". label";
            lb.Name = "label" + i;
            tb.Name = "textbox" + i ;
            tb.Width = 238;
            tb.Height = 35;
            lb.Width = 238;
            lb.Height = 35;
            tb.Font = new Font(tb.Font.FontFamily, 18);
            lb.Font = new Font(lb.Font.FontFamily, 18);

            Point p = new Point(223, 144 + (40 * i));
            Point p2 = new Point(50, 144 + (40 * i));

            lb.Location = p2;
            tb.Location = p;

            this.Controls.Add(tb);
            this.Controls.Add(lb);
            i++;
        }
        else
        {
            MessageBox.Show("Maximum reached");
        }
    }


    public void insert()
    {



        TextBox tb1 = this.Controls.Find("textbox1", false).FirstOrDefault() as TextBox;
        TextBox tb2 = this.Controls.Find("textbox2", false).FirstOrDefault() as TextBox;
        TextBox tb3 = this.Controls.Find("textbox3", false).FirstOrDefault() as TextBox;
        TextBox tb4 = this.Controls.Find("textbox4", false).FirstOrDefault() as TextBox;
        TextBox tb5 = this.Controls.Find("textbox5", false).FirstOrDefault() as TextBox;
        TextBox tb6 = this.Controls.Find("textbox6", false).FirstOrDefault() as TextBox;
        TextBox tb7 = this.Controls.Find("textbox7", false).FirstOrDefault() as TextBox;

  MessageBox.Show(textboxstatic1.ToString());

}

expected result: entered value result after add dynamic textbox: no value

Sorting vs if else if in javascript which one to choose?

I have a scenario in which I need to display the data in an increasing order of the index number.

myArray = [
{custom_carousel: false, default_label: "SmartCards", index: 3, visible: true}, 
{custom_carousel: false, default_label: "Pathways", index: 2, visible: false},
{custom_carousel: false, default_label: "Pathways", index: 1, visible: false},
{custom_carousel: false, default_label: "Pathways", index: 0, visible: false}
]

Should I first sort the array or add if else if condition ?

if(index === 0){

}else if (index === 1){

}else if (index === 2){

}else if (index === 3){

}


A boolean function to return a change in a vector and true/false

I am learning c++ and have taken an online course with a project to create a 2048 game.

I am in the final stages and have come across a small problem. I am trying to create a function which takes 2 numbers as a range of values of a vector. It pushes all the numbers to the left and adds two adjacent numbers if they are equal. For example:

v (before):

[0 0 0 5 1 2 0 2 2 0 0 0 2 0 0 2 6 0 0 5 0 6 4]

bi: 1

ei: 4


v (after):

[0 5 0 0 1 2 0 2 2 0 0 0 2 0 0 2 6 0 0 5 0 6 4]

return: true

The function:

bool left_push(std::vector<int>& v, int bi, int ei){

    std::vector<int> tmp;
    bool check = false ;

    for(int i = bi+2 ; i <= ei ; i++){

        if(v[i]==v[i-1]){
            v[i-1] = v[i]+v[i];
            v[i] = 0;

            check = true;
        }

        if(v[i-1]==0){
            v[i-1] == v[i];
            v[i] = 0;

            check = true ;
        }

    return check;
}

The issue is that when I test this, nothing happens. At all.

I am not too sure what I am doing wrong. I would appreciate any pointers.

R: dataframe new column using multiple if conditions

I have a data frame that contains phone numbers in different formats, I'm trying to clean wrongly formatted numbers and unify the format by creating a new column. phone numbers exist in 3 columns: CountryCode, AreaCode, MobileNumber. I've written the following code to create a new column based on multiple if conditions:

library(dplyr)
data <- mutate(data, Number = 
                 if(nchar(data$MobileNumber >= 12))
                             {paste("+", data$MobileNumber)
                   } else if (nchar(data$MobileNumber >= 9))
                            {paste("+", data$CountryCode, data$MobileNumber)
                   } else if (data$CountryCode == data$AreaCode)
                            {paste("+", data$CountryCode, data$MobileNumber)
                   } else   (paste("+", data$CountryCode, data$AreaCode, data$MobileNumber)))

it acts based on the condition of the first row only, giving the following warning:

Warning message:
In if (nchar(data$MobileNumber >= 12)) { :
  the condition has length > 1 and only the first element will be used

I've also tried to create 3 vectors for CountryCode, AreaCode, MobileNumber then to create a function that takes the 3 vectors as input and the correctly formatted number as output using if conditions and for loop but also wasn't successful.

# x is number y is country code z is area code n is the output
x <- data$MobileNumber
y <- as.character(data$CountryCode)
z <- data$AreaCode

#cleaning function
out <- vector("character", nrow(data))
CleanNum <- function(x, y, z) 
  { for(i in 1:length(x))
       { if(nchar(x[i] >= 12))      {n[i] <- paste("+", x[i])
       } else if (nchar(x[i] >= 9)) {n[i] <- paste("+", y[i], x[i])
       } else if (y[i] == z[i])     {n[i] <- paste("+", y[i], x[i])
       } else                       (n[i] <- paste("+", y[i], z[i], x[i])) 
            out[i] <- n[i]    }}

Num_vec <- CleanNum(x, y, z)

I've a little experience in R and any help is much appreciated.

TypeError: NoneType is unsubscriptable - IF statement

I am trying to find fuzzy string matches for university names and print a certain score (10, 5 ,3) to a csv each time depending on what list the closest match came from.

data = ["MIT", "Stanford",...]

Data1 = ['MASSACHUSETTS INSTITUTE OF TECHNOLOGY (MIT)'], ['STANFORD UNIVERSITY'],...

So far I have tried:

1 for uni in data:
2    hit = process.extractOne(str(uni[1]), data1, scorer = fuzz.token_set_ratio, score_cutoff = 90)
3    if float(hit[1]) < 100:
4       print("not found")
5    else:
        print("Closest match for " + str(uni[1]) + " is " + str(hit[0]) " + "score: 10")

At this point I get the TypeError: NoneType is unsubscriptable for line 3

I have checked the type of my variable:

print(type(hit)) #I was getting tuple now NoneType...
print(len(hit))  # Was getting 2 now unsubscriptable
print(float(hit[1])) # 100

As I understood this error comes up when a variable is not the type one thinks it is. Any idea how to resolve this issue? Many thanks

R Create dummy datasets based on reference dataset

Context

I'd like to build a two dummy survey dataframes for a project. One dataframe has responses to a Relationship survey, and another to aPulse survey.

Here are what each look like -

  1. Relationship Dataframe

    #Relationship Data
    rel_data= data.frame(
                TYPE=rep('Relationship',446),
                SURVEY_ID = rep('SURVEY 2018 Z662700',446),
                SITE_ID=rep('Z662700',446),
                START_DATE= rep(as.Date('2018-07-01'),446),
                END_DATE= rep(as.Date('2018-07-04'),446)
                )
    
    
  2. Pulse Dataframe

    #Pulse Data
    pulse_data= data.frame(
                TYPE=rep('Pulse',525),
                SURVEY_ID = rep('SURVEY 2018 W554800',525),
                SITE_ID=rep('W554800',525),
                START_DATE= rep(as.Date('2018-04-01'),525),
                END_DATE= rep(as.Date('2018-04-04'),525)
                )
    
    

My Objective

I'd like to add columns to each of these two dataframes, based on conditions from a reference table.

The reference table consists of the questions to be added to each of the two survey dataframes, along with further details on each question asked. This is what it looks like

  1. Reference Table

    #Reference Table - Question Bank
    qbank= data.frame(QUEST_ID=c('QR1','QR2','QR3','QR4','QR5','QP1','QP2','QP3','QP4','QP5','QP6'),
                  QUEST_TYPE=c('Relationship','Relationship','Relationship','Relationship','Relationship',
                         'Pulse','Pulse','Pulse','Pulse','Pulse','Pulse'),
                  SCALE=c('Preference','Satisfaction','Satisfaction','Satisfaction','Preference','NPS',
                         'Satisfaction','Satisfaction','Satisfaction','Preference','Open-Ended'),
                  FOLLOWUP=c('No','No','No','No','No','No','Yes','No','Yes','No','No'))  
    
    

The Steps

For each survey dataframe( Relationship & Pulse), I'd like to do the following -

1) Lookup their respective question codes in the reference table, and add only those questions to the dataframe. For example, the Relationship dataframe would have only question codes pertaining to TYPE = 'Relationship' from the reference table. And the same for the Pulse dataframe.

2) The responses to each question would be conditionally added to each dataframe. Here are the conditions -

  • If SCALE = 'Preference' in the Reference table, then responses would be either 150,100,50,0 or -50. Also, these numbers would be generated in any random order.
  • If SCALE = 'NPS' in the Reference table, then responses would range from 0 to 10. Numbers would be generated such that the Net Promoter Score (NPS) equals 50%. Reminder: NPS = Percentage of 9s & 10s minus Percentage of 0s to 6s.
  • If SCALE = 'Satisfaction' in the Reference table, then responses would range from 1 (Extremely Dissatisfied) to 5 (Extremely Satisfied). Numbers would be generated such that the percentage of 1s & 2s equal 90%.
  • If SCALE = 'Open-Ended' in the Reference table, then ensure the column is empty (i.e. contains no responses).

My Attempt

Using this previously asked question for the conditional response creation and this one to add columns from the reference table, I attempted to solve the problem. But I haven't got what I was looking for yet.

Any inputs on this would be greatly appreciated

Desired Output

My desired output tables would look like this -

Relationship Dataframe Output

            TYPE            SURVEY_ID SITE_ID START_DATE   END_DATE QR1 QR2 QR3 QR4 QR5
1   Relationship SURVEY 2018 Z662700 Z662700 2018-07-01 2018-07-04 150   5   1   2   2
2   Relationship SURVEY 2018 Z662700 Z662700 2018-07-01 2018-07-04 100   1   2   2   2
3   Relationship SURVEY 2018 Z662700 Z662700 2018-07-01 2018-07-04 100   4   5   2   2
4   Relationship SURVEY 2018 Z662700 Z662700 2018-07-01 2018-07-04 150   1   1   2   2

and so on

And the Pulse Dataframe Output

     TYPE           SURVEY_ID SITE_ID START_DATE   END_DATE QP1 QP2 QP3 QP4 QP5 QP6
1   Pulse SURVEY 2018 W554800 W554800 2018-04-01 2018-04-04   7   1   3   3 100    
2   Pulse SURVEY 2018 W554800 W554800 2018-04-01 2018-04-04   8   5   3   1 100    
3   Pulse SURVEY 2018 W554800 W554800 2018-04-01 2018-04-04   3   1   4   3 100    
4   Pulse SURVEY 2018 W554800 W554800 2018-04-01 2018-04-04   1   2   4   3 100

and so on

Excel SUMIF statement inside IF statement

I would like to create a SUMIF statement inside another statement. My data is below. I would like to create a SUM of time for 'Person A', but only if 'Type 2'. So for my formula is =SUMIF(B$1:B$5,"A",A$1:A5)

"Time . Person . Type

1:10 . A . 1

0:21 . B . 1

0:45 . A . 2

3:45 . C . 1

1:54 . A . 2"

else preceding an else if preceding an if in javascript won't register

Writing code to display the amount of roots in a quadratic function. However it displays the message for the second if condition whether it is satisfied or not. Could anyone tell me what I could change?

function equation() {

  var a=parseInt(document.getElementById("num1").value);
  var b=parseInt(document.getElementById("num2").value);
  var c=parseInt(document.getElementById("num3").value);

var t1 = b*b
  var t2 = 4*a*c


  if (t1>t2) {

    document.getElementById("output").innerHTML="it has 2 distinct roots"

  } else if (t1=t2) {

    document.getElementById("output").innerHTML="its roots are identical"

  } else {

    document.getElementById("output").innerHTML="it has no roots in real numbers"

  }

}

mercredi 30 janvier 2019

How to insert an opposite value(of a previous value of a column) if a condition is met in SQL-Server?

I'm working on an attendance sheet project for a store with 11 employees. Employees will clock in and clock out in their pre-determined times. I have a problem with shifts. I want to find a way for the system to figure out if the last line recorded was in the morning shift, the subsequent line should be in evening shift and vice versa.

The structure of my program is this: I have a button on my program for employees to determine the morning shift or the evening shift with a boolean variable. I have a text box, which when an employeeId/memberId is entered in it and pressed enter, it will process the eligibility of that memberId with a stored procedure with this logic: memberIds who 1. have clockedIn but have not ClockedOut (union with) 2.members who are generally in our tbl_attendanceMembers but have not entered in the attendance sheet are eligible to be entered in the textbox. Store these two in a medium table called tbl_availableMembers.

CREATE PROCEDURE duplicateCheck3

    @inputdate date

    AS

    BEGIN
            DELETE FROM tbl_availableMembers

    Insert into tbl_availableMembers SELECT memberId
                FROM tbl_attendancemembers
                WHERE memberId NOT IN
                (SELECT memberId 
                 FROM tbl_attendanceSheet
                 WHERE DATE = @InputDate)
            UNION
                SELECT memberId from tbl_attendancesheet
                WHERE [date] = @InputDate
                AND [clockin] IS NOT NULL
                AND [clockout] IS NULL
    END

Then in C# I will read the values of tbl_availableMembers everytime a memberId has entered the textbox like this:

SqlCommand sqlcmdread_availablemembers = new SqlCommand("select * from tbl_availablemembers", sqlcon);
                    SqlDataReader sqldr_availablemembers = sqlcmdread_availablemembers.ExecuteReader();
                    while (sqldr_availablemembers.Read())
                    {
                        if (sqldr_availablemembers[1].ToString() == textBoxX1.Text)
                        {
                            member_available = true;
                            break;
                        }
                    }

And if the entered id in the textbox is equal to the ones that are read, it goes through a stored procedure like this:

 CREATE PROCEDURE InputClockStacks
        @QmemberId nvarchar(20),
        @InputName nvarchar(20),
        @DateString nvarchar(100),
        @InputDate date,
        @InputShift Bit,
        @InputTime time(7),
        @EnterDist nvarchar(50),
        @EnterDelay time(7),
        @ExitDist nvarchar(50),
        @ExitDelay time(7)
    AS

    UPDATE [dbo].[tbl_attendanceSheet]
    SET [clockout] = @InputTime, [exitdelay]=@ExitDelay, ExitDist=@ExitDist
    WHERE MemberId = @QmemberId
    AND [date] = @InputDate
    AND [clockin] IS NOT NULL
    AND [clockout] IS NULL

    IF @@ROWCOUNT = 0 
    BEGIN

        INSERT INTO tbl_attendanceSheet(MemberId,name,datestring,date,morning_shift,clockIn,EnterDist,EnterDelay)
        VALUES (@QmemberId,  @InputName,@DateString, @InputDate, @InputShift, @InputTime,@EnterDist,@EnterDelay)

    END

It basically, has the following logic: if the ClockOut column is null and clockIn column is not null it means the employee has to only exit one's workplace so the system should insert the time into ClockOut column. Otherwise, it means that the employee has not even come to work so it should insert a new row with clockIn and ClockOut.

The logic of tbl_availableMembers has a problem. The problem is that if a member has clockedIn and out in the morning shift, the duplicateCheck3 stored procedure will not let him/her to clockIn in the evening shift.

I want to implement a logic like this:

SELECT * FROM tbl_attendanceSheet
WHERE date = @inputDate  // to get all users who have clocked in and(or) out 
                            in the given date or current date.
IF morning_shif is true, only allow him/ her to ClockIn in the evening shift

or this logic: allow every employee to occupy only two rows in the attendance sheet table. one for clocking in and out in the morning shift and one for clocking in and out in the evening shift.

or this logic: find a way for the system to figure out if the last line recorded was in the morning shift, the subsequent line should be in evening shift and vice versa.

At last, I want to thank you all for your remindings of SQL-injection, I will fix it later. and Thank You for your time

My tables:

CREATE TABLE [dbo].[tbl_attendanceSheet] (
    [Id]            INT            IDENTITY (1, 1) NOT NULL,
    [MemberId]      INT            NULL,
    [name]          NVARCHAR (20)  NULL,
    [date]          DATE           NULL,
    [datestring]    NVARCHAR (100) NULL,
    [morning_shift] BIT            NOT NULL,
    [clockin]       TIME (7)       NULL,
    [clockout]      TIME (7)       NULL,
    [HouresWorked]  AS             (CONVERT([time],dateadd(millisecond,datediff(second,[clockin],[clockout])*(1000),(0)))),
    [EnterDist]     NVARCHAR (50)  NULL,
    [EnterDelay]    TIME (7)       NULL,
    [ExitDist]      NVARCHAR (50)  NULL,
    [ExitDelay]     TIME (7)       NULL,
    [desc]          NVARCHAR (150) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC),
    FOREIGN KEY ([MemberId]) REFERENCES [dbo].[tbl_attendanceMembers] ([memberId])
);

and

CREATE TABLE [dbo].[tbl_attendanceMembers] (
    [memberId]      INT            IDENTITY (101000, 10) NOT NULL,
    [name]          NVARCHAR (20)  NULL,
    [branchId]      INT            NULL,
    [isOpener]      BIT            NULL,
    [cellularphone] NVARCHAR (20)  NULL,
    [exp]           NVARCHAR (100) NULL,
    [address]       NVARCHAR (100) NULL,
    CONSTRAINT [PK_tbl_attendanceMembers] PRIMARY KEY CLUSTERED ([memberId] ASC)
);

and

CREATE TABLE [dbo].[tbl_availableMembers] (
    [Id]       INT IDENTITY (1, 1) NOT NULL,
    [memberId] INT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

What I have searched, myself:

Change value in a 2-value column to its opposite only if a condition in another column is met Its different but has a similar Idea But I can't understand the answer he marked as solution.

Is there an elegant way to Invert a Bit value in an SQL insert Statement? It is really good, But I don't know how to implement it.

Thank you for your time.

How to use if-statement with randgen

I'm trying to make sure two randomly generated numbers don't match, is there a way to do this in an if-statement?


i'm fairly new to javascript and couldn't find anything that answered my question, rand2 and rand3 both pick from the same list and it would make the outcome seem odd if they matched. my code also stopped working when i put the if-statement in (if i messed that up i guess it wouldn't matter if i got an answer).

      function sentence() {
        var rand1 = Math.floor(Math.random() * 2);
        var rand2 = Math.floor(Math.random() * 12);
        var rand3 = Math.floor(Math.random() * 12);
        var rand4 = Math.floor(Math.random() * 10);
        var rand5 = Math.floor(Math.random() * 10);
        var rand6 = Math.floor(Math.random() * 10);
        //                var randCol = [rand1,rand2,rand3,rand4,rand5];
        //                var i = randGen();

        if (rand2 == rand3) {
        // whatever changes one
        } else {
        //
        }

How to make simple if statement bubble style?

How make this if-statement more simple ? , as a function it's working well but i think it's not good on coding.

this is the code :

        if (empty($checkMaxID)) 
        {
            $this->model->insert_temp_code($code_request,$cabang_code);
        }

        $checkHasTempCode = $this->model->checkHasTempCode($user_id);

        if ($checkMaxID['tempcode_created_by'] !=  $user_id ) {
            $data['code_request'] = str_pad($checkMaxID['tempcode_value'] + 1, 5, 0, STR_PAD_LEFT);        

            if (empty($checkHasTempCode) ) {
                $this->model->insert_temp_code($data['code_request'],$cabang_code);
            }
        }
        else
        {
            $data['code_request'] = $code_request;
        }

`

anyone can help me please ?

Thank you

I'm wondering how to turn this city in java made of asterisks 90 degrees (so it actually looks like a city)

public class HelloWorld {

 public static void main(String []args)
 {
   int[] arr = {5,10,23,6,9};
    for(int i = 0; i<arr.length; i++)
    {

        for( int j = 0; j< arr[i]; j++)
        {
            System.out.print("*");

        } 

        System.out.println();
    }
 }

}

That is my code, however, it prints the city horizontally, while I'd like it to print vertically. Any thoughts.

Using Python with Schedule library with an IF statement

Hoping for some help with the scheduling a python script. I understand the syntax, but since I've added the IF statement logic, I can't get the script to run for two days in a row. The next morning it will either only run the daily job OR skips it entirely and only runs the fifteen-minute job. I need the if logic so the jobs runs on the weekdays only. Does anyone have any clever workarounds?

Thanks for the help. I included a simplified version of my code below:

import schedule
import time

def daily_job(text):
    print(text)

def fifteen_min_job():
    print('15 minute job...')

if True: # For example only run on weekdays
    schedule.every().day.at("09:32").do(daily_job, text='daily job...')
    schedule.every(15).minutes.do(fifteen_min_job)

while True:
    schedule.run_pending()
    time.sleep(1)

MS SQL IF statement in WHERE clause

I can't seem to get the IF statement to work in my WHERE clause for MS SQL.

Basically, if @PK is 0, I want to skip those two lines in the IF statement.

Here is what I have:

WHERE
  IF (@PK <> 0)
    pk.ID >= @PK
    AND pk.ID < (@PK + 500)
  ELSE
    Set_No = Set_No
  END
  AND Set_No IN (1,2,3,4)

Also tried:

WHERE
  CASE WHEN @PK <> 0
     pk.ID >= @PK
    AND pk.ID < (@PK + 500)
  ELSE
    Set_No = Set_No
  END
  AND Set_No IN (1,2,3,4)

Edit: I searched SO and tried several things I found (including above), but they didn't work.

What is the check "if var:" actually doing in the background in Python3?

I kind of know the difference between var == None and var is None, however my question is about the following condition check:

if var:
  action

Is the above equivalent to:

if not var == None:
  action

or is it equivalent to:

if var is not None:
  action

Or does it depend on what is the current type of the "var" variable, how it performs the check?

Or does it have a completely different mechanic in the background?

Coming from that as a follow up what would happen if the value of "var" is actually 0 and it's of type float or int and I use the if var: construct?

Any insights about the inner workings of Python3 are much appreciated. Thanks!

How to open a file in python, read the comments ("#"), find a word after the comments and select the word after it?

I have a function that loops through a file that Looks like this:

"#" XDI/1.0 XDAC/1.4 Athena/0.9.25

"#" Column.4: pre_edge

Content

That is to say that after the "#" there is a comment. My function aims to read each line and if it starts with a specific word, select what is after the ":"

For example if I had These two lines. I would like to read through them and if the line starts with "#" and contains the word "Column.4" the word "pre_edge" should be stored.

An example of my current approach follows:

with open(file, "r") as f:
        for line in f:
            if line.startswith ('#'):
                word = line.split(" Column.4:")[1]
            else:
                print("n")

I think my Trouble is specifically after finding a line that starts with "#" how can I parse/search through it? and save its Content if it contains the desidered word.

How to create a column requiring more than 50 different factor values in R using ifelse statement[read comments]

I am using ifelse statements more than 100 times to create >100 visit categories as shown in below .

df<-data.frame(visit_time=c(12,20,70,100),city=c("X","X","X","X"))

df$visit_category<-ifelse(df$visit_time>=0 & df$visit_time<12 ,"0-12",ifelse(df$visit_time>=12 & df$visit_time <20,"12-20",ifelse(df$visit_time>=20 & df$visit_time <50,"20-50",ifelse(df$visit_time>=50 & df$visit_time <100,"50-100",">100"))))

As shown in sample data [ visit category column] , I have 4 different values for sample data , and I need to create >50 different categories on actual data.

When I try to create more than 50 categories , I get an error in R like this [ Did some research n found out that R does not allow more than 50 iflese statements at the same time !!, Dont know if its true ]

#Error: unexpected ')' in
#Error: contextstack overflow at line 42

Is there any better way to create >50 different visit category values other than using ifelse statements in R ??

How do I keep powershell from opening an excel file if its already open?

I need to open file B when file A is changed and then let file B open file A without triggering the watcher again. My thoughts are that I can do this with an if statement in '$changeAction' that checks to see if File B is open first.

I imagine this would be something like:

if(file B is open, then do nothing, else open file B)

How do I write this in Powershell?

 Function Register-Watcher {
        param ($folder)
        $filter = "*.xlsx"
        $folder = "\\powershell\watcher\test\folder"

        $watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{ 
            IncludeSubdirectories = $false
            EnableRaisingEvents = $true


        }

        $changeAction = [scriptblock]::Create('

            $path = $Event.SourceEventArgs.FullPath
            $name = $Event.SourceEventArgs.Name
            $changeType = $Event.SourceEventArgs.ChangeType
            $timeStamp = $Event.TimeGenerated

            Write-Host "The file $name was $changeType at $timeStamp"

            $Excel = New-Object -ComObject Excel.Application
            $Excel.Workbooks.Open("\\powershell\watcher\test\folder\fileB.xlsm") #this should be the 'else' in the 'if File B is open#

        ')

        Register-ObjectEvent $Watcher "Changed" -Action $changeAction
    }

     Register-Watcher "\\powershell\watcher\test\folder\fileA.xlsx"
     $Change

Check If A PyGame Mixer Channel Is Playing A Sound

I am looking for a way to see if a pygame.mixer.Channel is currently playing a sound. So for example do something only after the sound played in a specific channel has finished. Here is my current code to just play the sound:

import pygame

pygame.mixer.pre_init()
pygame.mixer.init()
pygame.init()

pygame.mixer.Channel(0).play(pygame.mixer.Sound('coolsound.wav'), maxtime=2000)

I was thinking an if statement something like this:

if pygame.mixer.Channel(0) = playing a sound:
    print("playing a sound")
else:
    print("not playing")

Obviously this wouldn't work, just to give you an idea of what I am looking for. Thanks!

R Build dummy dataframes conditionally based on reference dataframe

Context

I'm trying to build a two dummy survey dataframes for a personal project. One dataframe contains responses to a Relationship survey, and the other to aPulse survey.

Here are what each look like -

  1. Relationship Dataframe

    #Relationship Data
    reldata= data.frame(
                TYPE=rep('Relationship',446),
                SURVEY_ID = rep('SURVEY 2018 AU662700',446),
                SITE_ID=rep('X662700',446),
                START_DATE= rep(as.Date('2018-07-01'),446),
                END_DATE= rep(as.Date('2018-07-04'),446)
                )
    
    
  2. Pulse Dataframe

    #Pulse Data
    pulsedata= data.frame(
                TYPE=rep('Pulse',525),
                SURVEY_ID = rep('SURVEY 2018 Y554800',525),
                SITE_ID=rep('Y554800',525),
                START_DATE= rep(as.Date('2018-04-01'),525),
                END_DATE= rep(as.Date('2018-04-04'),525)
                )
    
    

My Objective

I would like to add columns to each of these two dataframes, based on conditions from a reference table.

The reference table consists of the questions to be added to each of the two survey dataframes, along with further details on each question asked. This is what it looks like

  1. Reference Table

    #Reference Table - Question Bank
    qbank= data.frame(QUEST_ID=c('QR1','QR2','QR3','QR4','QR5','QP1','QP2','QP3','QP4','QP5','QP6'),
                  QUEST_TYPE=c('Relationship','Relationship','Relationship','Relationship','Relationship',
                         'Pulse','Pulse','Pulse','Pulse','Pulse','Pulse'),
                  SCALE=c('Preference','Satisfaction','Satisfaction','Satisfaction','Preference','NPS',
                         'Satisfaction','Satisfaction','Satisfaction','Preference','Open-Ended'),
                  FOLLOWUP=c('Yes','No','No','No','No','No','Yes','No','Yes','No','Yes'))  
    
    

The Steps

For each survey dataframe( Relationship & Pulse), I'd like to do the following -

1) Lookup their respective question codes in the reference table, and add only those questions to the dataframe. For example, the Relationship dataframe would have only question codes pertaining to TYPE = 'Relationship' from the reference table. And the same for the Pulse dataframe.

2) The responses to each question would be conditionally added to each dataframe. Here are the conditions -

  • If SCALE = 'Preference' in the Reference table, then responses would be either 150,100,50,0 or -50. Also, these numbers would be generated in any random order.
  • If SCALE = 'NPS' in the Reference table, then responses would range from 0 to 10. Numbers would be generated such that the Net Promoter Score (NPS) equals 50%. Reminder: NPS = Percentage of 9s & 10s minus Percentage of 0s to 6s.
  • If SCALE = 'Satisfaction' in the Reference table, then responses would range from 1 (Extremely Dissatisfied) to 5 (Extremely Satisfied). Numbers would be generated such that the percentage of 1s & 2s equal 90%.
  • If SCALE = 'Open-Ended' in the Reference table, then ensure the column is empty (i.e. contains no responses).
  • Finally, if FOLLOWUP = 'Yes' AND the response is either 1 or 2, add a blank column and call it QFOLLOWUP.

My Attempt

Using this previously asked question for the conditional response creation and this one to add columns from the reference table, I attempted to solve the problem. But I haven't got what I was looking for yet.

Any inputs on this would be greatly appreciated

(R) How to transform string input in a function to a variable?

I want to make a function in which you can input a string of text. Then I want this string input to correspond to a variable inside my function. However, I do not know how to approach this.

The goal is to order a data frame based on a specific variable in the data frame. But, the user can input an abstraction of this variable by inputting a string. For example, the variable name is 'attack', for which the user can input the text "heart attack" when calling the function.

best <- function(state, outcome) {

hospData <- read.csv(paste(getwd(), "/R_ProgAssignment3-data/outcome-of-care-measures.csv", sep=""));

    stateSet <- subset(hospData, State == state);
    attach(stateSet);

# translates input string to outcome variable based on type of disease
if (outcome == "heart attack") { outcome <- attack; }
if (outcome == "heart failure") { outcome <- failure; }
if (outcome == "pneumonia") { outcome <- pneum; }

    #orders the state subset based on the outcome specified above
    stateSet <- arrange(stateSet, outcome);
    detach(stateSet);

    #prints the first row of the state subset with corresponding hospital and ordered mortality rate (e.g. lowest first)
    stateSet[1, c("Hospital.Name", outcome)];

}

As such, in the code above, the user can specify which state he or she wants to analyze, and the disease he wants data for, for example by inputting best("TX", "heart attack"), "failure" or "pneumonia", Where TX is the abbreviation for Texas in the dataset hospData. This text has to correspond to a variable in the data frame, which are respectively 'attack', 'failure' and 'pneum', since I want to sort the data frame for this variable.

Finally, I want to show the hospital with the lowest mortality rate in the final code line.

I think the problem lies in the if-conditions for e.g. outcome <- attack, which probably simply copies the content of either hospData$attack or stateSet$attack (another question here, how to link only the data from the subset?) to the variable 'outcome'.

To summarize, how can I recode a string input to the correct variable in the data frame, so I can sort the data frame for the specific variable?

Thanks in advance!

How can I optimize the loop and condition statements?

winner = False

def player():
    global winner
    while winner==False:

        print("player 1: please choose rock/paper/scissor !")
        choice1 = input()
        print("player 2: please choose rock/paper/scissor !")        
        choice2 = input()

        if choice1!=choice2:
            if choice1=="rock" and choice2=="scissor" :
                print("player 1 is the winner, Congrats!!")

            elif choice1=="rock" and choice2=="paper" :
                print("player 2 is the winner, Congrats!!")

            elif choice2=="rock" and choice1=="scissor" :
                print("player 2 is the winner, Congrats!!")

            elif choice2=="rock" and choice1=="paper" :
                print("player 1 is the winner, Congrats!!")

            elif choice1=="scissor" and choice2=="paper" :
                print("player 1 is the winner, Congrats!!")

            elif choice1=="paper" and choice2=="scissor" :
                print("player 2 is the winner, Congrats!!")
        else:
            print("its a draw")


        print("do you want to start a new game?,yes or no")
        answer = input()
        if answer=="yes":
            print("lets start another game!")
            winner = False
        elif answer=="no":
            print("see you next time!")
            winner = True


player()

as you can see there is too much inefficient if statements in my code ,how can i minimize them if possible

How to make program continue code without printing it more then once

I have this code:

public void checkUserLuckyNumber(PC p, User u) {
    int userLuckyNumber = Integer.parseInt(JOptionPane.showInputDialog(null, "Input lucky number from 1 - 10:"));
    if (userLuckyNumber < 1 || userLuckyNumber > 10) {
        JOptionPane.showMessageDialog(null, Constants.INVALIDINPUTNUMBER);
        System.exit(0);
    }
    for (int i = 1; i <= 3; i++) {
        int threeLuckyNumbers = (int) (Math.random() * 10);

        if (userLuckyNumber == threeLuckyNumbers) {
            JOptionPane.showMessageDialog(null, "you hit a happy number");
        } else {
            JOptionPane.showMessageDialog(null, "you did not hit a lucky number");
        }
    }
}
}

My problem is that my program print me three time message, if user hit lucky number program print me one message "you hit a happy number" and if user miss lucky number, program print me one message "you hit a happy number" and then twice " you did not hit a lucky number".

So my question is how to make program that print just one message.

How to hide uibutton if its title text is empty or unassigned?

The code and question represents an Xcode project in Swift. I have a a group of buttons that display options according to which text is presented on a label. The label text is derived from the keys of a dictionary and the button texts are derived from the values of that same dictionary. The dictionary type is [String: [String]. The keys and values are both placed in arrays. I currently display the correct data but some values differ in length than others. For example one key has 3 values and another key has 5. I want to hide the buttons if there is not text to send to it. So if a key is presented in a label and has 3 values I only want to display 3 buttons and so. What would be the best way to achieve this functionality? Here is my code:

    func startSurvey() {

    if surveyQuestions.isEmpty {
        surveyQuestions = Array(SampleSurvey().surveyquestions.keys)
        print(surveyQuestions)
    }

    let rand = Int(arc4random_uniform(UInt32(surveyQuestions.count)))
    questionTitle.text = surveyQuestions[rand]

    var choices = SampleSurvey().surveyquestions[surveyQuestions[rand]]!
    print(choices)
    print(choices.count)
    surveyQuestions.remove(at: rand)

    var button = UIButton()
    var x = 0
 // var choicePool = choices.count

    if choices.count == 2 {
        for index in 1...2 {
            button = view.viewWithTag(index) as! UIButton
            button.setTitle(choices[x], for: .normal)
            x += 1
            if button.titleLabel?.text == nil {
                button.isHidden = true
            }
        }
    }

    else if choices.count == 4 {
    for index in 1...4 {
        button = view.viewWithTag(index) as! UIButton
        button.setTitle(choices[x], for: .normal)
        x += 1

        if button.titleLabel == nil {
            button.isHidden = true
        }

        }
    }

Here is a screenshot of the simulator, as you can see this particular key has only 2 values so there are 3 blank buttons, I want to hide the buttons that are blank:

enter image description here

Trying to end a script if debian versions arent one of two options

I'm trying to write a short intro to a bash script that checks what Debian version that's running, and if it's NOT wheezy or jessie, will end the entire script.

This is what I have:

release=$(lsb_release -cs)

if [["$release" != "jessie" && "$release" != "wheezy"]]; then echo "this is the wrong version" exit fi

echo "this should only be shown if the OS is either jessie or wheezy"

I've tried to rewrite the if statement several times, but running thios script on for example ubuntu cosmic still outputs "this should only be shown if the OS is either jessie or wheezy"

mardi 29 janvier 2019

Mutliple IF statements results in False instead of Blank ("")

Multiple IF statements are giving me a FALSE response instead of the requested BLANK.

I figured that the last of the IF statements that has a "" would give BLANK if none of the conditions are met.

I've tried isolating each IF to see if I'm missing a statement but I don't see it.

Here is my formula:

=IF((LEFT(D5,2))=H2,IF(C5="Yearly",G5,IF(C5="Fixed Monthly",G5/12,"")))

How can I modify this formula so that it does not give me a FALSE and instead gives me a BLANK as requested on the 3rd IF statement.

Thank you.

Python - If Statement With input() Not Functioning Inside def() Function

Everything in the code runs properly except def a() and def b() have and if statements that examine and input() function though when I run the code it will lead to 'good for you' being printed no matter the input. For instance if I type False or Whatever into the code which should lead to different results, both lead to the response 'good for you' as though the input is always True or true. I haven't been coding for very long so excuse me if this is an obvious fix.

    tsil = ['input',]

while True:
  print('Write A Number (Print "done" When Finished)')
  num = input()
  tsil.append(num)
  print()
  if num == 'done':
    break

if True == True:
  print(tsil)

def a():
  print('you like short lists? (True or False)')
  ans = input()
  if ans == 'True' or 'true':
    return '\ngood for you'
  elif ans == 'False' or 'false':
    return '\nstop making short lists then'
  else:
    return '\nstop printing the wrong things loser'


def b():
  print('you like long lists? (True or False)')
  ans = input()
  if ans == 'True' or 'true':
    return '\ngood for you'
  elif ans == 'False' or 'false':
    return '\nstop making short lists then'
  else:
    return '\nstop printing the wrong things loser'

if len(tsil) < 10:
  print('^ short list large gorge')
  print()
  print(a())
else:
  print('^ big boy list')
  print()
  print(b())

Python List Comprehension (ending with if, doesn't take else)

conditions = [1, 2, 3, 4]
values = [1, 2, 3, 3]

[print("YAY") for c,v in zip(conditions,values) if c==v]

This works but if I add an else statement as in the following example it raises a syntax error:

[print("YAY") for c,v in zip(conditions,values) if c==v else print("NAY")]

why is it forbidden to do so? would have made full of sense if it had worked (at least for me)

?Is there a reason why my program won't perform it's if elif else statement after receiving proper input

Basically, the goal of this program is to take input from the user on what they want to order, process the cost of the item and tack on sales tax and a tip and return that. I'm struggling with how to go about getting my program to take input and run an if elif else statement based on what the input is. I'm fairly new and I'm still figuring out how to ask a constructive question, so bear with me here. Also, I know there a bits of it that are unfinished, which may factor into it, but I'm not really concerned with the incomplete bits

I've tried making the if statement conditions dependent on the input given using the == operator as well as changing that to an "if answer is __: print a response. I'm fairly confident that I can get the program to print out a tip and tax tacked onto a price, but everything I've tried so far keeps exiting my program after receiving any form of input.

salesTax = 0.07 #the tax added onto the total
tip= 0.18 #the percentage for a tip
steak= 96 # a var for a steak priced so deliciously, that it *must* be good.
goose= 42 #var for the oddly familiar, yet disturbingly alien meal that is goose.
narwhal= 109 #var for a meal that questions its own existence, then laughs in the face of that question

menu = ['high-stakes steak', 'uncanny boiled goose', 'endangered carribrean narwhal caccitore']

print("Tonight's menu at Joe's ethically questionable eatery includes")
print(menu)
input('Hon hon, what\'ll it be, monsieur? the goose, stake or narwhal?')
answer = input

if answer == 'goose':
print("Ah, very good monsieur the cost will be 42. We will beegen ze cooking of ze goose")
elif answer is 'steak':
    print("Ah, a high roller, we will begin")

I expect it to take 'goose' as an answer and print a response (eventually i'd make this take the number assigned to goose and calculate tax), but it simply ignores any input every single time.

Python re.search inside for-loop is giving false positives. How do I fix this?

I am creating a code that automatically updates my website, and when working on a code to identify tags and properly label pages on my database, I encountered a bug that I have no clue of how to fix.
I made a for loop to iterate the .php's lines, then used a if statement to find the tags. But somehow my if statement is responding twice, judging from its output.

First I checked if my regex was giving false positives. Used text editing softwares to manually search using the same regex from the code, but it only found one line.
Then I went to check how re.compile and re.search works, but there was nothing I was doing wrong there.

Here is the portion of the code.

        mydb = mysql.connector.connect(
        [Personal information redacted]
        )
        mycursor = mydb.cursor()
        local = input('Select directory.')
        for paths, dirs, files in os.walk(local):
            for f in files:
                print(f)
                if(splitext(f)[1] == ".php"):
                    print("found .php")
                    opened = open(local + f, 'r')
                    lines = opened.readlines()
                    date = splitext(f)[0]
                    flagD = re.compile(r'<!--desc.')
                    flagS = re.compile(r'<!--subject.')
                    flagE = re.compile(r'-->')
                    desc = None
                    subject = None
                    for l in lines:
                        if(flagD.search(l) != None):
                            print("found desc")
                            desc = re.sub(flagD, "",l)
                            descF = re.sub(flagE,"",desc)
                        if(flagS.search(l) != None):
                            print("found subj")
                            subject = re.sub(flagS, "",l)
                            subjectF = re.sub(flagE,"",subject)
                    if(desc == None or subject == None):
                        continue
                    sql = "INSERT INTO arquivos (quando, descricao, assunto, file) VALUES (%s, %s, %s, %s)"
                    val = (date, descF, subjectF, f)
                    mycursor.execute(sql, val)
                    mydb.commit()  

and this is the output:

2018-11-15.php
found .php
2018-11-16.php
found .php
2018-11-26.php
found .php
2019-01-13.php
found .php
2019-01-15.php
found .php
2019-01-16.php
found .php
2019-01-17.php
found .php
2019-01-22.php
found .php
found desc
found subj
2019-01-24.php
found .php
found desc
found desc
found subj
found subj
BdUpdate.php
found .php
BdUpdate1.php
found .php
Comentarios.php
found .php
FINAL.php
found .php
Foot.inc
Formulario.php
found .php
FormularioCompleto.php
found .php
Head.inc
index.php
found .php
index1.php
found .php
Java.php
found .php
Layout Base - Copy.php
found .php
Layout Base.php
found .php
Php_Test.ste
Phyton.php
found .php
SalvandoDB.php
found .php
sidenav.inc
Side_Menu.php
found .php
Thema.php
found .php
Translations.php
found .php
Web.php
found .php
2019-01-13.php
found .php

As you can see, somehow the print("found desc") and print("found subj")
is being called twice within one print("found .php"). Meaning it is giving a false positive somewhere in my code, but it is simply impossible, as I tested this regex in other softwares. This is totally unintended, and leaves the rest of the code as a entry on my database.

PS. Most of my questions is getting closed or locked and no one explains why. I have edited past questions to match the guidelines but the question is buried soon after. Please stop.

how could I display more than one if/else to one ID?

say two of the if statements below are true, how could I make them write to the same tag at different times.

if (a===b) {
        document.getElementById("LW").innerHTML = "statement 1"
    }
else  if (c===d) {
        document.getElementById("LW").innerHTML = "statement 2"
    }
else  if (e===f) {
        document.getElementById("LW").innerHTML = "statement 3";
    }
else {
        document.getElementById("LW").innerHTML = "";
    }

It would go to this

<p id="LW"></p>

for example, if two of the if statements were true, could it be possible to have one statement write to the p tag for 3 seconds, then display the next true statement? maybe a function or setTimer?

i have tried many ideas and searched all over but I can't seem to figure this one out! any help would be great! thanks in advance, I can try to explain further if necessary!

Does the if sentence on python execute only once?

im new on this, and im using an if statement to load an image in case X thing happens, this is my code:

if  self.puntos > 0:
        self.fondo = load_image('Fondo2.png', IMG_DIR)
        self.primera_vez = True

So when puntos (points) get over 0 the background changes, the problem is that the new image loads constantly causing low framerates, is this because the if statement executes constantly or what? Thanks

How to change output of Invoke-WebRequest?

I want to be able to get the results of Invoke-WebRequest and have my script print either "Failed" if the server was not reached or "Online" if it was reached.

This is what I'm doing to try to do that.

 $IW_Results = $Servers_to_Check | ForEach-Object { Invoke-WebRequest -Uri $_ }

 $err = $IW_Results | ?{$_.gettype().Name -eq "ErrorRecord"}
 if($err){
 Write-Output "Failed"
 }
 else {
 Write-Output "Online"
 }

I was able to get the script to print "Online" if the server is reached. However when it can't be reached, my script wont print "Failed". Instead it will give me the error:

 Invoke-WebRequest : Unable to connect to the remote server
 At C:\Users\admin\Documents\VM-scripts\VM-tester.ps1:32 
 char:52
 + ... ts = $Servers_to_Check | ForEach-Object { Invoke-WebRequest -Uri $_ }
 +                                               ~~~~~~~~~~~~~~~~~~~~~~~~~
 + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:Htt 
 pWebRequest) [Invoke-WebRequest], WebException
 + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe 
 ll.Commands.InvokeWebRequestCommand

How can I get the script to print out "Failed" instead of this error message?

Also the $Servers_to_Check variable is multiple servers

Turn NESTED IF Formula into Macro

I would like to turn my formula into a macro. I want to look up values on column A and return a different value to column D depending on conditions.

My formula is :

=IF(ISNUMBER(SEARCH("*10*",D2,6)),"word1",IF(ISNUMBER(SEARCH("*15*",D2,1)),"word2",IF(ISNUMBER(SEARCH("*1*",D2,1)),"word3",IF(ISNUMBER(SEARCH("*20*",D2,1)),"word4",IF(ISNUMBER(SEARCH("*30*",D2,1)),"word5")))))

I need to make sure that search for 1 comes after 10 or 15 so that formula doesn't return word3 for all cells containing "1".

Column A contains a text that is at times is misspelled so the only common value is the numbers. That is why I want to search the numbers within text to return word12345.

What is the Conditional Formatting formula for two conditions?

I have an excel file that I need to format a certain color.

I have tried:

=AND(A:A=FALSE,B:B<>Null)
=AND(A:A="FALSE",B:B<>" ")
=AND(A:A=FALSE,NOT(ISBLANK(B:B)))

Along with multiple If-statements with this scenario.

Picture won't work but my file is somewhat like this:

     A    |   B
1 FALSE   |  1/14/2017
2 FALSE   |  4/21/2019
3 TRUE    |  3/9/2018
4 TRUE    |  2/24/2018
5 FALSE   | 
6 TRUE    |  9/21/2017 
7 FALSE   |   
8 FALSE   |  5/22/2019

I want to get the cells in "B" RED, if Column "A" is FALSE and Column "B" is not empty.

So Cells (B1, B2, AND B8) should be formatted to that color.

Thanks in advance.

How can I incorporate leap years in an age calculator?

I have made an age calculator in python that, after you answer a series of questions, gives you your age in years, months and days. I am trying to incorporate leap years in it using an if statement that adds an extra day onto your age for every leap year experience, but I think there could be a shorter way. Any ideas?

Here is my code:

currentDay = int(input('What day of the month is it?'))
currentMonth = int(input('What month is it?'))
currentYear = int(input('What year is it?'))
birthDay = int(input('What day of the month were you born on?'))
birthMonth = int(input('What month were you born?'))
birthYear = int(input('Which year were you born in?'))
ageDays = currentDay - birthDay
ageMonths = currentMonth - birthMonth
ageYears = currentYear - birthYear
daysToAdd = 0

if currentMonth == 1 or currentMonth == 3 or currentMonth == 5 or 
currentMonth == 7:
    daysToAdd = 31

elif currentMonth == 2:
    daysToAdd = 28

elif currentMonth == 8 or currentMonth == 10 or currentMonth == 12:
    daysToAdd = 31

else:
    daysToAdd = 30

if birthDay > currentDay:
    ageMonths = ageMonths + 1
    ageDays = ageDays + daysToAdd

if birthMonth > currentMonth:
    ageMonths = ageMonths + 12

if birthYear < 2016:
    ageDays = ageDays + 1
    if birthYear < 2012:
        ageDays = ageDays + 1
        if birthYear < 2008:
            ageDays = ageDays + 1
            if birthYear < 2004:
                ageDays = ageDays + 1
                if birthYear < 2000:
                    ageDays = ageDays + 1
                    if birthYear < 1996:
                        ageDays = ageDays + 1

print('You are: ', ageYears, ' years, ', ageMonths, ' months, ', ageDays, ' 
days.')

How to loop through pandas dataframe, and conditionally assign values to a row of a variable?

I'm trying to loop through the 'vol' dataframe, and conditionally check if the sample_date is between certain dates. If it is, assign a value to another column.

Here's the following code I have:

vol = pd.DataFrame(data=pd.date_range(start='11/3/2015', end='1/29/2019'))
vol.columns = ['sample_date']
vol['hydraulic_vol'] = np.nan
for i in vol.iterrows():
    if  pd.Timestamp('2015-11-03') <= vol.loc[i,'sample_date'] <= pd.Timestamp('2018-06-07'):
        vol.loc[i,'hydraulic_vol'] = 319779

Here's the error I received: TypeError: 'Series' objects are mutable, thus they cannot be hashed

Categorizing using an IF Then Function with non-numerical values

I am trying to wring a code to automated categorization of natural and induced fractured by fracture type in a data sheet. I am trying to use an If Then function for fracture types that are known to be Induced fractures rather than naturally occurring ones. I have tried two different ways of getting this categorization to work for even a single type by I keep getting compiling errors and syntax errors. Is there a better way to go about this sort of problem?

Sub Simple_if()
    If Range(G4, [G1004]) = "Twist" Then Range(I4, [I1004]) = "Induced"
    End If

Also have tried

 Dim G As Integer
 For G = 4 To 1004

and

 Dim I As Integer
 For I = 4 To 1004
    If Cells(G, 5).Value = "Twist" Then Cells(I, 5).Value = "Induced"

Siding Garage Door calculator

Ok so I am making a siding garage door calculator and I am a little confused. So i have the calculations and everything I am just confused on the if statements if I want to round up the material needed to the fixed price so say that the example is: I buy 400 sq ft of wood but you can only buy 300 sq ft worth of wood so youd have to buy 600 how would i write that out?

Problem in my IF Statement, the Else is not working right

My simple code just receive the income from the user and calculate which bracket a user is in.

The IF statement is working fine, but when the user input some value with two decimals (ex. 100.50) value the code output the right tax and the else statement.

What can I do to fix it?

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

/**********************************************************************
 * This function will calculate which tax bracket a user is in.
 ***********************************************************************/
bool computeTax(float income)
{
   if (income >= 0.00 &&  income  <= 15100.00)
      cout << "10%" << endl;
   if (income > 15100.00 &&  income <= 61000.00)
      cout << "15%" << endl;
   if (income > 61300.00 &&  income <=123700.00)
      cout << "25%" << endl;
   if (income > 123700 && income <= 188450.00)
      cout << "28%" << endl;
   if (income > 188450.00 && income <= 336550.00)
      cout << "33%" << endl;
   if (income > 336550.00)
      cout << "35%" << endl;
   else
      cout << "Please enter a valid value" << endl;
   return 0;
}
int main()
{
   // configure the output to diplay money
   cout.setf(ios::fixed); // no scientific notation except for the deficit
   cout.setf(ios::showpoint); //always show the decimal point
   cout.precision(2); // two decimal for cents

   float income;
   cout << "Please enter your income: ";
   cin >> income;
   computeTax(income);
   return 0;
}

if statement always being skipped

I'm trying to make a basic little banking program to get my bearing with Go. I run the program and when I type in my answer for either of the if statements, the program just moves on. Any solutions?

here's my code;

package main
        import (
        "bufio"
        "fmt"
        "os"
        "strconv"
        "strings"
    )

    func main() {
        reader := bufio.NewReader(os.Stdin)
        fmt.Print("Enter your name: ")
        name, _ := reader.ReadString('\n')
        fmt.Print("Hello ", name)
        balance := 0
        fmt.Print("Do you want to deposite? (y/n) ")
        doDeposite, _ := reader.ReadString('\n')
        if strings.TrimRight(doDeposite, "\n") == "y" {
            fmt.Print("How much would you like to deposite? ")
            depositeAmount, _ := reader.ReadString('\n')
            da, _ := strconv.Atoi(depositeAmount)
            balance += balance + da
            fmt.Print("Your balance is ", balance)
        } else {
            fmt.Print("Would you like to withdraw?(y/n) ")
            doWithdraw, _ := reader.ReadString('\n')
            if strings.TrimRight(doWithdraw, "\n") == "y" {
                fmt.Print("How much would you like to withdraw? ")
                withdrawAmount, _ := reader.ReadString('\n')
                wa, _ := strconv.Atoi(withdrawAmount)
                balance += balance + wa
                fmt.Print("Your balance is ", balance)
            }

        }

    }

How to prevent unwanted variable assignment inside condition?

Typing = instead of == make unwanted assignment inside a condition. For example, consider the scenario below (this example is in C).

CASE A:

int g=1;

if ( g == 3 )
{
    printf("g is 3");   
}
else
{
    printf("g is not 3"); 
}

//this return: "g is not 3"

CASE B: (typo: missing = inside condition)

int g=1;

if ( g = 3 )
{
    printf("g is 3");   
}
else
{
    printf("g is not 3");
}

//this return: "g is 3"

Both the cases are formally correct, so the code will work but not as we want; and may be hard to debug.

How to prevent this situation?

Pagebreak in if statement triggers regardless if the statement is true

I'm currently working on creating a Word-Template (first time so maybe the question is more trivial than i actually think). The following is my problem:

Ive got the statement:

{if {MERGEFIELD group}<>"" "{MERGEFIELD group \b "[str+enter]"}" "test"}

I've got the data set up as:

Company |Group     | address  | phone
lorem        |  ipsum  | dolor       | sit
amet         |              |consetetur| sadipscing
lorem 2     | ipsum2 | dolor        | sit
amet2       |              |consetetur| sadipscing
.
.
.

What i try to achieve:

Grouping my data and having a pagebreak before each new group starts.

What i get:

A pagebreak after each package is handled, non regarding if group is empty or not (he prints "test" and "MERGEFIELD group" at the correct times).

If loop without a boolen condition in c

what actually happens in if statement here?

#include <stdio.h>
    int x;
    void main()
    {
      if (x)
         printf("hi");
      else
         printf("how are u");
    }

Why won't the value I am searching in an Array return true even though the matching value exists?

I have been trying to figure this out for the last 3 hours. I generate a random number, 0 - 36. I also generate an array with the numbers 0-36 in steps of 2 (odd numbers only). I do a var_dump on both the random number and the array and I can see the matching value in the array, however, my if statement won't return true.

I also tried in_array and that did not work. I tried array_map, no luck... I have googled endlessly and tried every thing I can think of. What gives?

$this->number = rand(0, 36); 
$this->colorBlack = array(range(1, 36, 2));

foreach ($this->colorBlack as $this->color){

            var_dump($this->color);
            var_dump($this->number);

        if ($this->color == $this->number){
            echo 'yes';
            var_dump($this->colorBlack);
        }
    }

I would expect the above code to return true when the random number generated matches a value in the array, however that is not the case.

the Var dump looks like this:

array(18) { [0]=> int(1) [1]=> int(3) [2]=> int(5) [3]=> int(7) [4]=> int(9) [5]=> int(11) [6]=> int(13) [7]=> int(15) [8]=> int(17) [9]=> int(19) [10]=> int(21) [11]=> int(23) [12]=> int(25) [13]=> int(27) [14]=> int(29) [15]=> int(31) [16]=> int(33) [17]=> int(35) } int(26)

VBA - Check if range is filled, then generate PDF

I would like to ask you for a help. I have code that generates PDF and that works fine, but I would like to add condition. User should fill cells D15, D17, D19 and D21, if they are blank, then it should notify the user by MsgBox. If they are filled then it should continue to generate the PDF file.

I've tried to put the condition, but it gives me an error msg Wrong number of arguments or invalid property assignment on line Set rng = .Range("D15", "D17", "D19", "D21")

The full code is:

Private Sub CBSaveasPDF_Click()
    Dim sPath As String
    Dim sFile As Variant
    Dim ws As Worksheet
    Dim rng As Range

    With Worksheets("Dashboard")
    Set rng = .Range("D15", "D17", "D19", "D21")
    End With

    On Error GoTo ErrHandle

    If IsEmpty(rng) Then
                        MsgBox ("Please fill the yellow cells")
                    Exit Sub
    Else

    sPath = ThisWorkbook.Path & "\" & Me.Range("D9") & " -" & Me.Range("D8") & " -" & Me.Range("J8") & " " & Me.Range("B4")

    sFile = Application.GetSaveAsFilename _
                (InitialFileName:=sPath, _
            FileFilter:="PDF Files (*.pdf), *.pdf", _
            Title:="Select Folder and FileName to save")
        If sFile = "False" Then
            MsgBox ("Document not saved")
            Exit Sub
        End If

        Me.ExportAsFixedFormat _
            Type:=xlTypePDF, _
            Filename:=sFile, _
            Quality:=xlQualityStandard, _
            IncludeDocProperties:=True, _
            IgnorePrintAreas:=False, _
            OpenAfterPublish:=True
    End If

        Exit Sub
ErrHandle:
    MsgBox ("Document Not Saved")
End Sub

Could you advise me, how should I define the range better, please?

Many thanks!

Matching or if statement

I'm new to R and trying to learn by getting my hands dirty.

It sounds simple, but all I'm trying to do is convert an old identifying code into a new identifying code with data retention.

For example; 01 now becomes 24A, my problem starts where 01 should become anything from 24a to 25d.

I hope this makes sense.

lundi 28 janvier 2019

How to add else statement if they put a string on an int input variable?

whenever I run this code, if I type a string as my input, I get an error on line 11. Help? I am not sure how to run an else statement or something asking what if they put a string rather than an integer (choice variable). I am new, so much help would be appreciated!

Here is my code:

import java.util.Scanner;

public class rockPaper {
    public static void main(String args[]) {
        System.out.println("Hello world");
        int rock = 0;
        int paper = 1;
        int scissors = 2;
        Scanner input = new Scanner(System.in);
        System.out.println("Rock, Paper, or Scissors(0, 1, or 2)? Enter your integer: ");
        int choice = input.nextInt();
        int aIChoice = (int) (Math.random() * 3);
        if (choice == rock) {
            switch (aIChoice) {
            case 0:
                System.out.println("AI chose rock.");
                System.out.println("Rock ties with rock!");
                break;
            case 1:
                System.out.println("AI chose paper.");
                System.out.println("Fail. Paper trumps rock.");
                break;
            case 2:
                System.out.println("AI chose scissors.");
                System.out.println("You win! Rock trumps scissors.");
                break;
            default:
                break;
            }

        } else if (choice == paper) {
            switch (aIChoice) {
            case 0:
                System.out.println("AI chose rock.");
                System.out.println("You win! Paper trumps rock.");
                break;
            case 1:
                System.out.println("AI chose paper.");
                System.out.println("Paper ties with paper!");
                break;
            case 2:
                System.out.println("AI chose scissors.");
                System.out.println("Fail. Scissors trumps paper.");
                break;
            default:
                break;
            }
        } else if (choice == scissors) {
            switch (aIChoice) {
            case 0:
                System.out.println("AI chose rock.");
                System.out.println("Fail. Rock trumps scissors.");
                break;
            case 1:
                System.out.println("AI chose paper.");
                System.out.println("You win! Scissors trumps paper.");
                break;
            case 2:
                System.out.println("AI chose scissors.");
                System.out.println("Scissors ties with scissors!");
                break;
            default:
                break;
            }
        } else {
            System.out.println("Nope!");
        }
        input.close();
    }

}

As stated above, if I run the code, and I type in any letters(a string), I get an error referencing to line number eleven. I am not sure what I should do, because obviously as I've mentioned adding an else statement to all of this does not ensure the "nope" if they entered a string.