jeudi 30 septembre 2021

Unable to change the value of variable inside for-loop & if-else statement in Java

I'm working on a java function involving for-loop and if-else statement. and I have a need to change the value of a flag variable according to the conditions in multiple iterations. I declared a variable named flag and wants to change according to the condition in each iteration. And I need to print the value of the flag variable at the end of each iteration. But while I printing the variable it shows an error that the variable isn't initialized. If I gives it an initial value, it prints the initial value all the time, not the value manipulated inside the if-else statement. I can't initialize the flag variable inside the for-loop according to my requirement. Below is my code:

    int flag;

    for(int i=0; i< fileOneLines.length; i++){
        diffs = diffMatchPatch.diffMain(fileOneLines[i],fileTwoLines[i]);
        diffMatchPatch.diffCleanupSemantic(diffs);
        for (DiffMatchPatch.Diff aDiff : diffs) {
            if(aDiff.operation.equals(DiffMatchPatch.Operation.INSERT)){
                flag = 1;
            }
            else if(aDiff.operation.equals(DiffMatchPatch.Operation.DELETE)){
                flag = 2;
            }
            else if(aDiff.operation.equals(DiffMatchPatch.Operation.EQUAL)) {
                flag = 0;
            }
        }
        System.out.println(flag);
    }

It's the error shown:

java: variable flag might not have been initialized

All the if statements running in c#?

I have some code below which is a URL Parser and the if statement doesn't work instead of executing the code when it is true it executes all the code in all the if statements.

    public static class var
    { //Global variables
        public static string stre = System.Uri.UnescapeDataString(Environment.CommandLine);
        public static string[] str = stre.Remove(stre.Length - 1).Split(new string[] { "cmd:" }, StringSplitOptions.None);
    }
    public CMD()
    { //I suppose this class runs first so all my is statements are here
        AClsMsgBox.Show("Parsing...", "CMD Parser", 1000); //msgbox
        if (var.stre.Length > 5) { InitializeComponent();} //This executes even if I type "cmd:" which should trigger the statement below. (Always executes) This should run when typing "cmd:echo a command"
        if (var.stre.Length == 4) { Process.Start("cmd.exe"); } //This should run when typing "cmd:"(Never executes)
        else { AClsMsgBox.Show("This is a URL Parser use it by typing 'cmd:<command>' in the url field of a browser.","CMD Parser",60000); } //Always executes
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        string stra = var.str[1].Replace("&", "&&");
        label1.Text += stra;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Process.Start("cmd.exe", " /k " + var.str[1]);
        this.Close();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
    }
    private void label1_Click(object sender, EventArgs e) { }
}

This is C# GUI so I am running InitializeComponent() only if I need to display the rest of buttons and stuff. (I think it should stop the GUI)

And there are no errors! But appear after building the code.

Google Sheets Apps Script - How to add an Arrayformula and multiple associated IF functions within a script (Without showing the formula within UI)

I was wondering if someone is able to assist?

I'm trying to add an Arrayformula consisting of two IF functions, so I'm wanting to merge the following two formulas into one cell:

  1. =ARRAYFORMULA(IF(D13:D104="","",(IF(K13:K104,K13:K104*20,"$0"))))
  2. =ARRAYFORMULA(IF(D105:D="","",(IF(K105:K,K105:K*C4,"$0"))))

So the first section of the sheet needs to be multiplied by 20, and then the figure has changed and needs to be multiplied by 25 (which is cell C4)

  1. Is it possible to merge these into one cell containing an Arrayformula+the two IF functions (or is there another/easier way for this)
  2. Is it possible to add this into Google Apps Script so that it works in the backend (so not just a script that applies the formula into a cell - but doesn't show in the frontend or sheet)
  3. More of a general question - When using Arrayformula with IF; and for example the output is specific text e.g. "Test Complete" associated to the range F2:F (checking if E2:E contains a particular phrase e.g. "Done") - for the empty cells in between (due to setting the False outcome as "") is it possible to somehow randomly add data into these blank cells without interrupting the formula? (so I have to option for automated text if the cell to the left states a particular term/word, but still have the option to manually add random data into blank cells)

Any assistance would be greatly appreciated

most efficient way to have a if statement in C++

I am trying to do some Monte Carlo simulation, and as it is with this kind of simulation, it requires a lot of iterations, even for the smallest system. Now I want to do some tweaks with my previous code but it increases the wall time or running time, by 10 fold, which makes a week of calculations to more than two months. I wonder whether I am doing the most efficient way to do the simulation.

Before that, I was using a set of fixed intervals to get the properties of the simulations, but now I want to record a set of random intervals to get the system information as it is the most logical thing to do. However I don't know how to do it.

The code that I was using was basically something like that:

for(long long int it=0; it<numIterations; ++it)
{
    if((numIterations>=10) && (it%1000==0))
    {
        exportedStates = system.GetStates();
        Export2D(exportedStates, outputStatesFile1000, it);
    }
}

As you see, before the tweaks made it was going through the simulation and only record the data, every 1000th iterations.

Now I want to do something like this

for(long long int it=0; it<numIterations; ++it)
{
    for(int j = 1; j <= n_graph_points; ++j){
        for (int i = 0; i < n_data_per_graph_points; ++i){
            if (it == initial_position_array[j][i] || it == (initial_position_array[j][i] + delta_time_arr[j])) {
                exportedStates = system.GetStates();
                Export2D(exportedStates, outputStatesFile, it);
            }
        }
    }
}

In this part, the initial position array is just an array with lots of random numbers. The two for loop inside of each other checks every iteration and if the iterations is equal to that random number, it starts recording. I know this is not the best method as it is checking lots of iterations that are not necessary. But, I don't know how can I improve my code. I am a little helpless at this point, so any comment would be appreciated

Making a list of the first n prime numbers in Python

I'm currently new to programming, and I am currently struggling to make a list of the first n prime numbers using if/else/while or recursion.

This is the current messy code I have. It currently runs an infinite amount of times:

def prime_list(n):
    num = 1
    div = 1
    brac = []
    if len(brac) <= n:
        if num >= div:
            if num % div != 0:
                append.count(num)
            if num % div == 0:
                div += 1
        else:
            num += 1
    return brac

I know my code definitely isn't close to what I desire to want, but can you lead me into the right direction on how to fix it? Thank you in advance!

How statement "if(a=b){} " compiled [duplicate]

int main() {
    int a = 10; 
    int b = 5;
    if (a =b) cout << "hello";
}

I accidentally compiled the following code, but no error appeared, and hello was printed. I wonder why c++ considers the wrong comparison operation a=b to be true.

Trying to go back one loop but not to main parent loop

This game requires two inputs from the user: "user_choice" and "player_choice". I get the user_choice input first. The final issue I am running into is on the 2nd input (player_choice). If the user enters something invalid it is making them reselect user_choice, and I just want them to have to reselect player_choice.

def playGame(wordList):
       
    hand = []   
    while True:   
    # ask the user if they want to play
        user_choice = input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
        # if they enter 'e' end the game
        if (user_choice == 'e'):
            break
        elif (user_choice == 'r' and len(hand) == 0):
            print('You have not played a hand yet. Please play a new hand first!')
        # if they enter an invalid command send them back
        elif (user_choice != 'n' and user_choice != 'r'):
            print('Invalid command.')
        
        # if they enter n or r ask them who is going to play
        if (user_choice == 'n' or user_choice == 'r'):
            player_choice = input('Enter u to have yourself play, c to have the computer play: ')
            # if human is playing follow the steps from before
            if (player_choice == 'u'):
                if (user_choice == 'n'):
                    hand = dealHand(HAND_SIZE)
                    playHand(hand, wordList, HAND_SIZE)
                elif (user_choice == 'r' and len(hand) != 0):
                    playHand(hand, wordList, HAND_SIZE)
                else :
                    print('You have not played a hand yet. Please play a new hand first!')
                    
            # if computer is playing . . .
            elif (player_choice == 'c'):
                if (user_choice == 'n'):
                    hand = dealHand(HAND_SIZE)
                    compPlayHand(hand, wordList, HAND_SIZE)
                elif (user_choice == 'r' and len(hand) != 0):
                    compPlayHand(hand, wordList, HAND_SIZE)
                else:
                    print('You have not played a hand yet. Please play a new hand first!')
            else:
                print('Invalid command.')
                continue

'''

How can I make if-statement working in JQUERY?

I want make this if/ else work can someone help me? Thanks... Sorry if the question so bad, i am new at here :)

$('input[type=radio]').on("click", function(){var jawaban = $(this).val();});

function optionSelected(){
  if (jawaban = "goodanswer"){
    alert("benar");
  }else{
    alert("salah");
  }
});

If-else statement inside of for loops skipping/not working properly [closed]

I'm having problems with two for loops inside of my program and the if/else statements inside of them. The counter starts at 0, then increments every time the loop is run. I have tested, and the counter increments properly, but the if/else statements act as if the counter starts at 1 and then stays there (I have added comments in my code where it seems to "get stuck".) Can anyone help me? It's probably something super-obvious but I just don't see it. Thank you.

using namespace std;



// Define global constants

// The integer maximum number of cards that can be in a player’s hand = 10
const int maxCards = 10;
// The integer maximum number of players = 5
const int maxPlayers = 5;

// Define 2 global data structures:

struct card {
 //The suit as a character:  H-hearts, S-spades, C-clubs, D-diamonds
 char cardSuit;
 // The face as a character: A-ace, K-king, Q-queen, J-jack, T-ten, 9-2
 char cardFace;
 // The value as an integer: A=13, K=12, Q=11, J=10, 9-2
 int cardValue;
 // Status of the card in the deck: true=in the deck, false=in the stack or a player’s hand
 bool cardStatus;


};


struct player {
 // An array of Cards up to the max number of cards in a player’s hand above

 card playerCards[maxCards] = {};

};

int main(void) {
 // Initialize stack
 //  Declare an array of 52 Cards to represent a new stack of cards 
 card initialCards[52];


 // For every card
 int initialCardCounter = 0;


 // For each suit
 for (int initialSuitCounter = 0; initialSuitCounter < 4; initialSuitCounter++) {



     int initialSuitLoopCounter = initialSuitCounter;

     // Assign a Suit
     if (initialSuitLoopCounter = 0) {
         initialCards[initialCardCounter].cardSuit = 'H';


     }
     // !!! It skips to this point, then doesn't increment. !!!
     else if (initialSuitLoopCounter = 1) {
         initialCards[initialCardCounter].cardSuit = 'S';


     }
     else if (initialSuitLoopCounter = 2) {
         initialCards[initialCardCounter].cardSuit = 'C';


     }
     else if (initialSuitLoopCounter = 3) {
         initialCards[initialCardCounter].cardSuit = 'D';


     }
     else if (initialSuitLoopCounter > 3) {
         cout << "Error";
     }

     cout << initialCards[initialCardCounter].cardSuit;

     // For each face
     for (int initialFaceCounter = 0; initialFaceCounter < 14; initialFaceCounter++) {

         int initialFaceLoopCounter = initialFaceCounter;

         if (initialFaceLoopCounter = 0) {
             initialCards[initialCardCounter].cardFace = 'A';
             initialCards[initialCardCounter].cardValue = 13;

         }
         // !!! Same issue here, skips to here even though InitialFaceLoopCounter = 0 and just stays here filling the entire array with 'K' !!!
         else if (initialFaceLoopCounter = 1) {
             initialCards[initialCardCounter].cardFace = 'K';
             initialCards[initialCardCounter].cardValue = 12;

         }
         else if (initialFaceLoopCounter = 2) {
             initialCards[initialCardCounter].cardFace = 'Q';
             initialCards[initialCardCounter].cardValue = 11;

         }
         else if (initialFaceLoopCounter = 3) {
             initialCards[initialCardCounter].cardFace = 'J';
             initialCards[initialCardCounter].cardValue = 10;
         }
         else if (initialFaceLoopCounter = 4) {
             initialCards[initialCardCounter].cardFace = 'T';
             initialCards[initialCardCounter].cardValue = 9;
         }
         else if (initialFaceLoopCounter = 5) {
             initialCards[initialCardCounter].cardFace = '9';
             initialCards[initialCardCounter].cardValue = 8;
         }
         else if (initialFaceLoopCounter = 6) {
             initialCards[initialCardCounter].cardFace = '8';
             initialCards[initialCardCounter].cardValue = 7;
         }
         else if (initialFaceLoopCounter = 7) {
             initialCards[initialCardCounter].cardFace = '7';
             initialCards[initialCardCounter].cardValue = 6;
         }
         else if (initialFaceLoopCounter = 8) {
             initialCards[initialCardCounter].cardFace = '6';
             initialCards[initialCardCounter].cardValue = 5;
         }
         else if (initialFaceLoopCounter = 9) {
             initialCards[initialCardCounter].cardFace = '5';
             initialCards[initialCardCounter].cardValue = 4;
         }
         else if (initialFaceLoopCounter = 10) {
             initialCards[initialCardCounter].cardFace = '4';
             initialCards[initialCardCounter].cardValue = 3;
         }
         else if (initialFaceLoopCounter = 11) {
             initialCards[initialCardCounter].cardFace = '3';
             initialCards[initialCardCounter].cardValue = 2;
         }
         else if (initialFaceLoopCounter = 12) {
             initialCards[initialCardCounter].cardFace = '2';
             initialCards[initialCardCounter].cardValue = 1;
         }
         else if (initialFaceLoopCounter > 12) {
             cout << "Error";
         }

         cout << initialCards[initialCardCounter].cardFace;
         // Increment the card counter

         if (initialCardCounter < 51) {
             initialCardCounter++;
         }

     } // end for each face


 } // end for each suit





} // end main

Tic Tac Toe runs and functions completely, but after getting 3 in a row, another move has to be made for it to end

So I am completely new to posting on this website, however I have been using it to find answers to my programming questions checking out already existing questions that had been answered.

Now, I am with a problem neither me nor my significant other are able to solve, and Google didn't succeed in giving me a valueable answer.

Is anyone of you able to find out why it loops around 1 extra time even though the while condition isn't true anymore?

NOTE: No clue if this is the right way of doing stuff on here, but here's the code. My code also isn't the most optimized, as I was planning on doing that after I got stuff working, but, well... That isn't the case right now...

import nl.saxion.app.SaxionApp;

import java.util.ArrayList;

public class Application implements Runnable {

    public static void main(String[] args) {
        SaxionApp.start(new Application(), 650, 500);
    }

    public void run() {
        // Game Size
        int sizeInput = boardSize(); // Call method "boardSize()"

        if (sizeInput < 50) {
            sizeInput = 50;
            SaxionApp.printLine("Input too low, defaulted to min(50)");
        } else if (sizeInput >90) {
            sizeInput = 90;
            SaxionApp.printLine("Input too high, defaulted to max(90)");
        }

        int absoluteWidth = sizeInput*7;
        int absoluteHeight = sizeInput*7;
        SaxionApp.resize(absoluteWidth, absoluteHeight);

        int celWidth = absoluteWidth/5;
        int celHeight = absoluteHeight/5;

        int fontSize = celHeight / 3;

        ArrayList<String> cells = new ArrayList<>();
        setFields(cells);

        String cell1 = cells.get(0);
        String cell2 = cells.get(1);
        String cell3 = cells.get(2);
        String cell4 = cells.get(3);
        String cell5 = cells.get(4);
        String cell6 = cells.get(5);
        String cell7 = cells.get(6);
        String cell8 = cells.get(7);
        String cell9 = cells.get(8);


        // Game over code
        boolean gameOver = false;
        // Winconditions
        String playerSymbol = "";

        int activePlayer = 1;
        int playerMove = 0;

        while (!gameOver){
            drawBoard(celWidth, celHeight, fontSize, cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8, cell9);



            SaxionApp.print("Player " + playerSymbol + ", make your move(1-9)?");
            playerMove = SaxionApp.readInt();


            if (activePlayer == 1 && !gameOver) {
                // Player 1 turn
//                SaxionApp.print("Player X, make your move(1-9)?");
//                playerMove = SaxionApp.readInt();

                activePlayer = 2;

                if (playerMove == 0) {

                    SaxionApp.clear();
                    SaxionApp.printLine("Thank You For User Our App! :D");
                } else if (cells.get(playerMove-1).equals("O") || cells.get(playerMove-1).equals("X")) {
                    SaxionApp.clear();
                    SaxionApp.printLine("This cell has already been chosen, pick another!");
                    activePlayer = 1;

                } else if (playerMove == 1) {
                    cell1 = "X";
                    cells.set(0, "X");
                    SaxionApp.clear();
                }
                else if (playerMove == 2) {
                    cell2 = "X";
                    cells.set(1, "X");
                    SaxionApp.clear();
                }
                else if (playerMove == 3) {
                    cell3 = "X";
                    cells.set(2, "X");
                    SaxionApp.clear();
                }
                else if (playerMove == 4) {
                    cell4 = "X";
                    cells.set(3, "X");
                    SaxionApp.clear();
                }
                else if (playerMove == 5) {
                    cell5 = "X";
                    cells.set(4, "X");
                    SaxionApp.clear();
                }
                else if (playerMove == 6) {
                    cell6 = "X";
                    cells.set(5, "X");
                    SaxionApp.clear();
                }
                else if (playerMove == 7) {
                    cell7 = "X";
                    cells.set(6, "X");
                    SaxionApp.clear();
                }
                else if (playerMove == 8) {
                    cell8 = "X";
                    cells.set(7, "X");
                    SaxionApp.clear();
                }
                else if (playerMove == 9) {
                    cell9 = "X";
                    cells.set(8, "X");
                    SaxionApp.clear();
                }
                playerSymbol = "O";

                /*else if (playerMove == 0) {
                    i = 9;
                    SaxionApp.clear();
                    SaxionApp.printLine("Thank You For User Our App! :D");
                }*/

            } else if (activePlayer == 2 && !gameOver){
                // Player 2 turn
//                SaxionApp.print("Player O, make your move(1-9)?");
//                playerMove = SaxionApp.readInt();

                activePlayer = 1;

                if (playerMove == 0) {

                    SaxionApp.clear();
                    SaxionApp.printLine("Thank You For User Our App! :D");
                } else if (cells.get(playerMove-1).equals("X")) {
                    SaxionApp.clear();
                    SaxionApp.printLine("Player X has already chosen this, pick another!");
                    activePlayer = 2;

                } else if (playerMove == 1) {
                    cell1 = "O";
                    cells.set(0, "O");
                    SaxionApp.clear();
                }
                else if (playerMove == 2) {
                    cell2 = "O";
                    cells.set(1, "O");
                    SaxionApp.clear();
                }
                else if (playerMove == 3) {
                    cell3 = "O";
                    cells.set(2, "O");
                    SaxionApp.clear();
                }
                else if (playerMove == 4) {
                    cell4 = "O";
                    cells.set(3, "O");
                    SaxionApp.clear();
                }
                else if (playerMove == 5) {
                    cell5 = "O";
                    cells.set(4, "O");
                    SaxionApp.clear();
                }
                else if (playerMove == 6) {
                    cell6 = "O";
                    cells.set(5, "O");
                    SaxionApp.clear();
                }
                else if (playerMove == 7) {
                    cell7 = "O";
                    cells.set(6, "O");
                    SaxionApp.clear();
                }
                else if (playerMove == 8) {
                    cell8 = "O";
                    cells.set(7, "O");
                    SaxionApp.clear();
                }
                else if (playerMove == 9) {
                    cell9 = "O";
                    cells.set(8, "O");
                    SaxionApp.clear();
                }
                playerSymbol = "X";
            }

            ArrayList<Boolean> differentWins = winConditions(cells, playerSymbol);
            int counter = 0;
            while (counter < differentWins.size()) {
                System.out.println("gameOver while works");
                if (differentWins.get(counter)) {
                    System.out.println("gameOver if works");
                    gameOver = true;
                    SaxionApp.clear();
                    SaxionApp.printLine("Player " + playerSymbol + " has won! Congratulations!");
                    break;
                } else {
                    System.out.println("gameOver if DOES NOT WORK");
                    counter++;
                }

            }

//            gameOver = true;

        }

        SaxionApp.printLine("Thank you for playing our game! :D");
        // Saving Image for easy preview
        SaxionApp.saveImage("Exercise4/end_test_output.png");

    }

    public int boardSize() {
        SaxionApp.print("What size do you wish the game window to be (min.50 and max.90)? ");
        int input = SaxionApp.readInt();
        SaxionApp.clear();
        return input;
    }

    private void drawBoard(int celWidth, int celHeight, int fontSize, String cell1, String cell2, String cell3, String cell4, String cell5, String cell6, String cell7, String cell8, String cell9) {
        SaxionApp.turnBorderOn();

        // Draw Board
        SaxionApp.drawLine(celWidth*2, celHeight, celWidth*2, celHeight*4);
        SaxionApp.drawLine(celWidth*3, celHeight, celWidth*3, celHeight*4);
        SaxionApp.drawLine(celWidth*1, celHeight*2, celWidth*4, celHeight*2);
        SaxionApp.drawLine(celWidth*1, celHeight*3, celWidth*4, celHeight*3);

        SaxionApp.turnBorderOff();

        // Draw Cell Values
        SaxionApp.drawBorderedText(" "+cell1,celWidth*1+fontSize, celHeight+fontSize, fontSize);
        SaxionApp.drawBorderedText(" "+cell2,celWidth*2+fontSize, celHeight+fontSize, fontSize);
        SaxionApp.drawBorderedText(" "+cell3,celWidth*3+fontSize, celHeight+fontSize, fontSize);
        SaxionApp.drawBorderedText(" "+cell4,celWidth*1+fontSize, celHeight*2+fontSize, fontSize);
        SaxionApp.drawBorderedText(" "+cell5,celWidth*2+fontSize, celHeight*2+fontSize, fontSize);
        SaxionApp.drawBorderedText(" "+cell6,celWidth*3+fontSize, celHeight*2+fontSize, fontSize);
        SaxionApp.drawBorderedText(" "+cell7,celWidth*1+fontSize, celHeight*3+fontSize, fontSize);
        SaxionApp.drawBorderedText(" "+cell8,celWidth*2+fontSize, celHeight*3+fontSize, fontSize);
        SaxionApp.drawBorderedText(" "+cell9,celWidth*3+fontSize, celHeight*3+fontSize, fontSize);
    }

    public void setFields(ArrayList<String> cells) {
        for (int i = 1; i < 10; i++) {
            String cellNumber = String.valueOf(i);
            cells.add(cellNumber);
        }
        System.out.println(cells);
    }

    public ArrayList<Boolean> winConditions(ArrayList<String> cells, String playerSymbol) {

        boolean winConditionWidth1 = cells.get(0).equals(playerSymbol) && cells.get(1).equals(playerSymbol) && cells.get(2).equals(playerSymbol);
        boolean winConditionWidth2 = cells.get(3).equals(playerSymbol) && cells.get(4).equals(playerSymbol) && cells.get(5).equals(playerSymbol);
        boolean winConditionWidth3 = cells.get(6).equals(playerSymbol) && cells.get(7).equals(playerSymbol) && cells.get(8).equals(playerSymbol);

        boolean winConditionHeight1 = cells.get(0).equals(playerSymbol) && cells.get(3).equals(playerSymbol) && cells.get(6).equals(playerSymbol);
        boolean winConditionHeight2 = cells.get(1).equals(playerSymbol) && cells.get(4).equals(playerSymbol) && cells.get(7).equals(playerSymbol);
        boolean winConditionHeight3 = cells.get(2).equals(playerSymbol) && cells.get(5).equals(playerSymbol) && cells.get(8).equals(playerSymbol);

        boolean winConditionDiagonal1 = cells.get(0).equals(playerSymbol) && cells.get(4).equals(playerSymbol) && cells.get(8).equals(playerSymbol);
        boolean winConditionDiagonal2 = cells.get(2).equals(playerSymbol) && cells.get(4).equals(playerSymbol) && cells.get(6).equals(playerSymbol);

        ArrayList<Boolean>differentWins = new ArrayList<>();
        differentWins.add(winConditionWidth1);
        differentWins.add(winConditionWidth2);
        differentWins.add(winConditionWidth3);

        differentWins.add(winConditionHeight1);
        differentWins.add(winConditionHeight2);
        differentWins.add(winConditionHeight3);

        differentWins.add(winConditionDiagonal1);
        differentWins.add(winConditionDiagonal2);

        return differentWins;
    }

}

Why does the code in line 21 not get executed? [duplicate]

When lastInputs equals ['.', 'c', 'w'] the code inside should be executed but it doesn't work.

Here is the code:

from pynput import keyboard

loops = 0
lastInput = '0'
lastInputs = ['', '', '']

def on_release(key):
    lastInput = key
    
    loops = 0
    while loops < len(lastInputs):
        lastInputs[loops - len(lastInputs)] = lastInputs[loops + 1 - len(lastInputs)]
        loops += 1
    lastInputs[-1] = lastInput

    if key == keyboard.Key.esc:
        # Stop listener
        return False

    if lastInputs == ['.', 'c', 'w']:
        print('Printed')
    print(lastInputs)

# Collect events until released
with keyboard.Listener(
        on_release=on_release) as listener:
    listener.join()

if with AND operator

I'm learning react and I came across the next expression
ReactDOM.render(true && 123 && <functionThatReturnBool> && "foo")

I tried to research a bit, didn't find too many sources, so I played with the code a little bit, and this is what I came up with:

  • if something is false/null/Nal/undefined/""/0 then it will return this value and won't continue to the next expression (as expected)
  • if everything is true it will return the last value
  • React doesn't render bool just like he doesn't render null, undefined etc. Since that, In case something is false nothing will render, unless something is 0.

Is there any sources that explain this expression?
I missed/wrong at something?

If statements not updating?

I am using key listeners to check if the user has the spacebar pressed. If it is pressed, the boolean spaceHeld sets to true, while when the key is released, it is set to false. If statements check to see the booleans value, and then does something with it. The only problem is that the if statements are only checking once, while i need the to check every time that the boolean is changed. My goal is to have a gravity value updated every time that the user presses and releases the spacebar. How can I update the if statements every time the value is changed? Here is my code, help is appreciated.

import java.awt.event.*;
import javax.swing.*;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Calendar;



public class Game implements KeyListener {
    JFrame frame;
    JLabel player;

    boolean grounded = false;
    int velocity = 0;
    int finalY = 0;
    boolean spaceHeld = false;


    Action spaceAction;

    Game() {
         
        frame = new JFrame("Nicholas Seow-Xi Crouse");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1920, 1080);
        frame.setLayout(null);
        
        frame.setFocusable(true);
        frame.addKeyListener(this);

        player = new JLabel();
        player.setBackground(Color.red);
        player.setBounds(10, 1800, 50, 50);
        player.setOpaque(true);

        frame.add(player);
        frame.setVisible(true);
        
         Timer flightTime = new Timer();
         TimerTask flight = new TimerTask() {
         
            public void run() {
                  if(velocity > -5) {
                  velocity -= 1;
                  }
                  else{
                  velocity = -5;
                  }
                  if (finalY < -61) {
                   finalY = finalY + velocity;
                   }
                   else{
                   finalY = -61;
                   }
                   player.setLocation(player.getX(), player.getY() + finalY);
                   if (player.getY() <= 0){
                   cancel();
                   velocity = 0;
                   finalY = 0;
                   player.setLocation(player.getX(), 0);
                    
                   }  
            }
      };
         

         Timer gravityTime = new Timer();
         TimerTask gravity = new TimerTask() {


            //creates a timer run method that simulates the falling gravity when not grounded
            public void run() {
                if(velocity < 5){
                velocity += 1;
                }
                else{
                velocity = 5;
                }
                //creates the variable the tells where the player is located
                if (finalY < 61) {
                finalY = finalY + velocity;
                }
                else{
                finalY = 61;
                }
                player.setLocation(player.getX(), player.getY() + finalY);
                if (player.getY() >= 1000){
                cancel();
                velocity = 0;
                finalY = 0;
                player.setLocation(player.getX(), 990); 
                }
                
            }
        };

        if (spaceHeld == false ) {
            gravityTime.scheduleAtFixedRate(gravity, 0, 33);
        }
        if (spaceHeld == true ) {
            flightTime.scheduleAtFixedRate(flight, 0 ,33);
    }
}

public void keyTyped(KeyEvent e) {
}

public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE){
spaceHeld = true;
//debug
System.out.println(spaceHeld);
}
}

public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE){
spaceHeld = false;
//debug
System.out.println(spaceHeld);
}
}
}```

ifelse is giving me NAs when I want 0s

I am trying to create a variable using ifelse, and would like the column to be 0 when the condition is not true, but they are showing up as NA. Any tips?

df$z <- ifelse (df$x == 1 |
                df$y == 1, 1,
                ifelse (df$x == 2 |
                        df$y == 2 ,2, 0))

My understanding is that the above code should make everything that isn't 1 or 2 coded as 0, but I only get 1, 2 and NA. No zeros.

Pythonic way of setting limits based on list length [duplicate]

I want to limit the height of a tkinter widget based on a length of a list. For this, i want to set 5 as a lower and 10 as an upper limit. The height should be 10 if my list exceeds 10 elements, 5 when there are equal or less than 5 elements, and the exact amount of elements if the list is in that range. I am wondering if there is a more pythonic way than this:

if 5 <= len(self.content) <= 10:
    lb_height = len(self.content)
elif len(self.content) <= 5:
    lb_height = 5
else:
    lb_height = 10

ifelse doesn't work when applying filter on r

Good I am trying to make a filter in R but the result is not as expected

x1 = c("PIB","PIB","PIB","PIB","PIB")
x2 = c("IBR","IBR","IBR","IBR","IBR")
coef_x1 = c(0.001,0.004,0.002,-0.099,-0.88)
coef_x2 = c(0.12,0.15,-0.99,-0.77,0.45)
Signo_x1 = c("+","+","+","+","+") 
Signo_x2 = c("+","+","+","+","+")

Table = data.frame(x1,x2,coef_x1,coef_x2,Signo_x1,Signo_x2)

that's the table I have

   x1  x2 coef_x1 coef_x2 Signo_x1 Signo_x2
1 PIB IBR   0.001    0.12        +        +
2 PIB IBR   0.004    0.15        +        +
3 PIB IBR   0.002   -0.99        +        +
4 PIB IBR  -0.099   -0.77        +        +
5 PIB IBR  -0.880    0.45        +        +

I need to perform a filter as follows

x1  x2 coef_x1 coef_x2 Signo_x1 Signo_x2
1 PIB IBR   0.001    0.12        +        +
2 PIB IBR   0.004    0.15        +        +
3 PIB IBR   0.002   -0.99        +        +

for the filter I am executing the following code:

updated here

 Table = ifelse(Table$Signo_x1 == "+",Table %>% dplyr::filter(Table$coef_x1 >= 0),Table %>% dplyr::filter(Table$coef_x1 <= 0))

[[1]]
[1] "PIB" "PIB" "PIB"

[[2]]
[1] "IBR" "IBR" "IBR"

[[3]]
[1] 0.001 0.004 0.002

[[4]]
[1]  0.12  0.15 -0.99

[[5]]
[1] "+" "+" "+"

anyone has the knowledge of how to convert it back as a dataframe or if the code i am using is not correct how could i fix it?

If else statements between multiple variables R

I have a set of dummy variables for yes no questions. I want to extract numeric values to another new variable based on these questions. for example: first questions are as:

do you accept the amount 1€(Yes/No) do you accept the amount 2€(Yes/No) do you accept the amount 3€(Yes/No)

then I should extract the numeric answers to another new variable. so how can I use that ifelse function for this kind of coding ?

thank you in advance,

Subtract an image that is representing a life in a game

Im try to code a mini game. The game has two boxes you can click on. The boxes are assigned a random number between 1 and 2.

When the game starts, you have 5 lives. These lives are represented as 5 pictures of a small human.

When the player gets 3,5 and 7 correct points you get a extra life. Which i have achieved.

Now im trying to subtract a life everytime the player clicks on the wrong box.

function setRandomNumber(){ randomNumber = Math.floor( Math.random() * 2 + 1);

        if( randomNumber === 1){

            numberOfRightAnswersSpan.innerHTML = `${++correctNumber}`;
           
            outputDiv.innerHTML = `Det er riktig svar.`;

            if( correctNumber === 3 || correctNumber === 5 || correctNumber === 7){
                numberOfLivesDiv.innerHTML += `<img src="images/person1.jpg"/>`

            }
            }
            else{

            numberOfWrongAnswersSpan.innerHTML = `${++wrongNumber}`;
            outputDiv.innerHTML = `Det er feil svar.`;
            
        }
        
    }

Creating an if statement to compare column values in a dataframe and replace it with another one?

I currently have a dataframe of football results that goes something like this:

year home_team away_team home_score away_score winner penalty_winner
1872 Scotland England 0 0 Draw NaN
1956 England France 1 1 Draw NaN
1976 France England 4 0 France NaN
1999 Germany Portugal 1 1 Draw Germany
2021 England Italy 0 0 Draw Italy

What I want to do is replace the "Draw" values in the "winner" column with the values in the "penalty_winner" column only if the values are not "NaN".

I tried something like this:

if merged_international_results_df.loc[merged_international_results_df['winner'] == 'Draw'] and merged_international_results_df.loc[merged_international_results_df['penalty_winner'].isnull() == False]:
    merged_international_results_df['winner'] = merged_international_results_df['penalty_winner']

The output I get is

The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How can I correct this?

Python Pandas IF ELSE [closed]

Would appreciate any help on this, trying to do my first Pandas IF ELSE statement, but I'm struggling with the syntax...

if g['Operator'] == 100151:    
    g['floor']=g['y'].mean() 
elif g['Operator'] == 20137: 
    g['floor']=g['y'].mean() 
elif g['Operator'] == 152: 
    g['floor']=g['y'].mean() 
else: 
    g['floor']=g['y'].mean()/2

Thanks Gav

IF function in PHP

Why this is not working?

<?php if (count($payment_method) > 0 && !(count($payment_method) == 1 && implode('',$payment_method) == 'PayPal'));?>

Error is here Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\signup\templates\default\html\subscription.php on line 239

Google Apps Script: How to find column number of specific value in array?

What I'm trying to achieve is to get the column number of a specific cell. If the cell value in the array equals to the value of today's date, then give back the column number of that cell.

dateArrayD = 1 row containing all the dates from January 1 to December 31, formatted

dateTodayD = the date today, formatted

So if dateTodayD equals dateArrayD, then dateCol would be the column number. I simply can't find a solution for this.

for(var z = 0; z < dateArrayD.length; z++){
    if(dateTodayD !== dateArrayD[0][z]){
      var dateCol = z;
    } // end if
  } // for end

JS Conditional statement

Hi in the below code the e.price is the price of a product, i want to know how i can put If conditional statement in this so that price with price 0 shall not be show(no price),and if amount is greater then 0 then it will be show. I tried if(e.price == 0) but i dont know how and in which line it should be written. Thanks in advance

formatResult: function(e, a) {
  var i = "(" + (a = "&" === a ? "&#038;" : a).replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + ")",
    a = "";
  return (
    e.divider && (a += ' <h5 class="search-divider-text">' + e.divider + "</h5>"),
    e.thumbnail && (a += ' <div class="search-thumb">' + e.thumbnail + "</div>"),
    e.value && (a += '<h4 class="search-title">' + e.value.replace(new RegExp(i, "gi"), "<strong>$1</strong>").replace(/&lt;(\/?strong)&gt;/g, "<$1>") + "</h4>"),
    e.no_found && (a = '<div class="no-result">' + e.value + "</div>"),
    e.view_all_products && (a = '<div class="view-all-products"></div>'),
    e.sku && (a += ' <div class="search-sku">' + e.sku + "</div>"),
    e.price && (a += ' <div class="search-price">' + e.price + "</div>"),
    a
  );
},

filter key-value pair in json array object [duplicate]

i have json module with 3 json array with given objects as follows:

i want to filter out the array with following result based on the condition : Id = '1234' and Description = "Issued"

expected result should be an object of above conditions as:

result = {
  "Description" = "xyz"}

ARRAY OF OBJECTS:

[
    "Id" : "5678",
    "Code" : "Issued",
    "Description" : "hijklmnop"
},
{
    "Id" : "1234",
    "Code" : "MFC",
    "Description" : "abcdefg"
},
{
    "Id" : "1234",
    "Code" : "Issued",
    "Description" : "xyz"
}

]

Obtain days between dates in array of different ID's

I would like to get the days and total days between each date for only the same row IDs. So far, found some code that can help me get the days between each date and separately determine if each current row is the same or different from the previous row. I'm unable to join both in order to only get the corresponding days between each date corresponding to the same ID. Desired result

Code inside C2:

={"Days Since Previous Payment";ArrayFormula(IFNA(vlookup(row(A3:A),{query(filter(row(A3:A),B3:B>0),"Select * offset 1",0),filter(if({filter(A3:A,B3:B>0);0}*{0;filter(A3:A,B3:B>0)},{filter(A3:A,B3:B>0);0}-{0;filter(A3:A,B3:B>0)},),if({filter(A3:A,B3:B>0);0}*{0;filter(A3:A,B3:B>0)},{filter(A3:A,B3:B>0);0}-{0;filter(A3:A,B3:B>0)},)<>"")},2,0)))}

Code inside E3 and on until E18:

=ArrayFormula(IF(INDIRECT("B"&(ROW()))<>INDIRECT("B"&(ROW()-1)),INDIRECT("B"&(ROW())),INDIRECT("B"&(ROW()-1))))

Just in case, here is the dummy page: https://docs.google.com/spreadsheets/d/1HSZKq5JhrHRtl-XPQ6QJF1wNX4e2_5jmyjNK2pPZpDM/edit?usp=sharing

IF loop not working correctly after running selection once

I am trying to run an interactive session where user is able to choose from selection what to do. After user selects the module they want, selected module will run and return back to selection page. However, if user selects the same module again, the IF loop sort of goes wrong. Anybody knows what went wrong with my code? Please refer to the code below for more details.

def comparison_select():
    global month1, month2
    while True:
        try:
            comparison_menu()
            compare_input = int(input("Enter selected comparison: "))
            if compare_input == 1:
                print("Selected comparison period is: Daily")
                from compare_exp_daily import command_daily
            elif compare_input == 2:
                print("Selected comparison period is: Monthly")
                from compare_exp_monthly import command_monthly
            elif compare_input == 0:
                print("Thank you & Goodbye!")
                break
            else:
                print("Error, please enter a number from the menu.\n"
                      "Thank you!")
        except:
            print("Error, please enter a valid selection.")

The first output works fine but subsequently when user selects back the same selection, it goes wrong.

output:

    Comparison Available:         
1. Daily
2. Monthly
0. Exit


Enter selected comparison: 1
Selected comparison period is: Daily

Enter Date (DD/MM/YYYY): 12/07/2021

Enter Date (DD/MM/YYYY): 16/07/2021
-------------------------------------------------------------------------------
Expense for 2021-07-12 is 15.0 dollars.
Expense for 2021-07-16 is 21.0 dollars.
-------------------------------------------------------------------------------
You have spent 6.0 dollars more on 2021-07-16 than on 2021-07-12

Comparison Available:         
1. Daily
2. Monthly
0. Exit


Enter selected comparison: 1
Selected comparison period is: Daily

Comparison Available:         
1. Daily
2. Monthly
0. Exit


Enter selected comparison: 1
Selected comparison period is: Daily

Comparison Available:         
1. Daily
2. Monthly
0. Exit


Enter selected comparison: 0
Thank you & Goodbye!

How to apply a single line if statement in Javascript?

I want to return a class by using a single line if statement like described here. In my approach I'm using Material-UI and want to set a class.

So I want to use this appraoch if(condition) expression

    <Typography className={ if (typeof title === 'string') classes.title } >{ title }</Typography>

I get the following error: Parsing error: Expression expected

What am I doing wrong here?

Swift-like "guard-let" in Scala

In Swift, one can do something like:

    guard let x = z else {return}  // z is "String?"

In this simple case, if z (an optional) is empty, the function will exit.

I really like this structure and recently started developing in Scala, and I was wondering if there's an equivalent in Scala.

What I found is this:

    val x = if (z.isEmpty) return else z.get  // z is "Option[String]"

It works - but I still wonder if there's a more "Scala-ish" way of doing it.

JavaScript - increment with +1 every time random number === 1 from Math.random

I want my encounter to increment every encounter by 1 or 2 it only add the first encounter at 1 or 2, why?

        function setAnswerCorrect() { // Points counter, add hp === 3p,5p,7p
            addPoint = 0;        // scope addPoint
            addPoint++
            minPoint = 0;       // scope minPoint
            minPoint++
            if (randomNumber === 1) { // If num 1

                for (var i = 0; i < randomNumber; i++) { // for num 1 ++
                }
                answerCorrect.innerHTML = `<p>Correct counter: ${addPoint}</p>`

            } else if (randomNumber === 2) {  // else if num 2 then ++

                for (var i = 0; i < randomNumber; i++) {
                }
                answerWrong.innerHTML = `<p>Wrong counter: ${minPoint}</p>`;
            }
        };
        function setRandomNumber() {
            randomNumber = Math.floor(Math.random() * 2 + 1);
            console.log(randomNumber);
        } setRandomNumber();

mercredi 29 septembre 2021

how to change a vector to corresponding names without using for loop

I have a vector c(1,3,4,2,5,4,3,1,6,3,1,4,2), and I want make 1="a", 2="b", and so on

So my final outputs should look like c(a,c,d,b...)

I know that I can use for loop and if statement to do this, but is there any other quicker ways to do?

Making a function -- R error says "Error: unexpected '}' in "}""

I am making a function where I am trying to get R to take in a vector then print out a phrase depending on the number input.

for example, if I have the vector

x <- c(4,2,7,9,10,5,2,1,4,6,8,10)

I want R to say "troubled" for numbers between 1-5, "potentially troubled" for numbers between 6-7, and "not troubled" for numbers between 8-10.

The dataset I have only has numbers between 1-10. This is what I have right now:

pls <- function(x){
if(5>=x){
  print("Troubled")
} else if(8>x>5){
  print("Potentially troubled")
} else if(x>=8){
  print("Not troubled")
}
}

the error message I am getting says:

Error: unexpected '}' in "}"

I do not understand why it is not running

C# logic problem get to the wrong loop with the same input

Is a simple c# guessing game in which class encapsulates a random number and driver random a number to guess it is too high or too low, the problem is for the driver when it comes to Higher( this one I used to check the guess number is higher than target number or not) it gives me the wrong message if you saw I hardcore the target is 10, and guess number be 11 which guess > target then should go to (db[i].higher) this loop all the time, but it went to else loop after it hits the right path. I have no idea what's wrong with that. ``` status = true; reseted = false; higher = false; //lower = false;

    }
    public bool Query(int guess)
    {

        if (!status|| guess < 0) return false;
        total_round++;

        if (guess > num )
        {
            higher_count++;
            higher = !higher;
            return false;
        }
        if (guess < num)
        {
            lower_count++;
            //!Compare;
            //higher = false;
            Console.WriteLine("get here!\n");
            return false;
        }
        else
        {
            right_count++;
            status = !status;
            return true;
        }
        //return false;
    }

    public bool Higher
    {
        get { return higher;}
    }
``` int input= rnd.Next(5, 10);
        //int round = rnd.Next(5,10);
        int round = 2;
        targetInt[] db = new targetInt[2];
        for (int i = 0; i < db.Length; i++)
        {
            Console.WriteLine("==================New Round Of 
          Game=================");
            db[i] = new targetInt(i);
            int counter = 1;
            while (counter <= round)
            {
                int bound = 0, upperbound = 100;
                //int guess = rnd.Next(bound, upperbound);
                int guess = 11;//guess < target
                //int guess = i;
                Console.WriteLine("Guess number is: " + guess);
                //list[i] = guess;

                if (db[i].Query(guess))
                {
                    Console.WriteLine("Round : " + db[i].TotalRound + " Guess number 
           is: " + guess + "\n");
                    Console.WriteLine("You are right!\n");
                    break;
                }
                else
                {
                    if (!db[i].Status)
                    {
                        Console.WriteLine("You dont have any chance left!");
                        break;
                    }

                    
                    if (db[i].Higher)//guess > num                       
                    {
                        Console.WriteLine(db[i].Higher.ToString());
                        Console.WriteLine("Guess number is too big, guess again");
                        upperbound = guess - 2;
                        Console.WriteLine("Round : " + db[i].TotalRound + " Guess 
          number is: " + guess + "\n");
                        

                    }
                   // if(!db[i].Higher && db[i].Status)//guess < num
                    else
                    {
                        Console.WriteLine(db[i].Higher.ToString());
                        Console.WriteLine("Guess number is too small, guess again");
                        bound = guess + 2;
                        Console.WriteLine("Round : " + db[i].TotalRound + " Guess 
         number is: " + guess + "\n");   
                    }   
                }
                counter++;
            }

            //Console.WriteLine("You dont have any chance left!");
            Console.WriteLine("====================Game 
             Statics====================");
            Console.WriteLine("Total round: " + db[i].TotalRound);
            Console.WriteLine("Right guess count: " + db[i].RightCount);
            Console.WriteLine("Higher guess count: " + db[i].HigherCount);
            Console.WriteLine("lower guess count: " + db[i].LowerCount);
            Console.WriteLine("GAME OVER!!!!\n");
        }
```
>this is output message, the round two should be the same as round 1 since my guess 
```  number is hardcoded 11;
Target: 10
Guess number is: 11
True
Guess number is too big, guess again
 Round : 1 Guess number is: 11

Guess number is: 11
False
Guess number is too small, guess again
Round : 2 Guess number is: 11

Google Sheets with Multiple And Or Statement

I'm looking for a formula that will allow me to create a boolean from three columns So column E will say Yes if both "House" and "Car" are included in any order of the B:D Columns like this

Name Priority Priority Priority Boolean in question
John House Car Loans Yes
Ned House Groceries Car Yes
Dom Family Car Going Fast No
Thanos Stones Balance House No
Homer Donuts Car House Yes

How can I write a formula to create this outcome.

Python - Find a substring within a string using an IF statement when iterating through a pandas DataFrame with a FOR loop

I want to iterate through a column in a pandas DataFrame and manipulate the data to create a new column based on the existing column. For example...

For row in df['column_variable']:

      if 'substring1' in row:

              df['new_column'] = ...
      
      elif 'substring2' in row:

              df['new column'] = ...

      elif: 'substring3' in row:

              df['new column'] = ...

      else:

              df['new column'] = 'Not Applicable'

Even though type(row) returns 'str' meaning it is of the class string, this code keeps returning the new column as all 'Not Applicable' meaning it is not detecting any of the strings in any of the rows in the data frame even when I can see they are there.

I am sure there is an easy way to do this...PLEASE HELP!

I have tried the following aswell...

For row in df['column_variable']:

  if row.find('substring1') != -1:

          df['new_column'] = ...

  elif row.find('substring2') != -1:

          df['new column'] = ...

  elif: row.find('substring3') != -1:

          df['new column'] = ...

  else:

          df['new column'] = 'Not Applicable'

And I continue to get all entries of the new column being 'Not Applicable'. Once again it is not finding the string in the existing column.

Is it an issue with the data type or something?

How to find a string match ( both partial and exact match) between column header and row values in python using if condition

id  references  apple  pomegranate
a234    papaya      0      1
b231    pomegranate 1      0
a234    apple       0      1
g34     mango       0      0
y34     strawberry  0      1

Is there a way to match column name "apple" with names in "references" column, so that I could extract the corresponding "id"....considering the data frame as say a distance value of two data frames about features of fruits.

The match is searched for exact string match in first iteration if it's not found, partial match also searched, say some "references" value may have a name "green apple". So it is partial match this case is considered when exact match is unavailable.

My code is in an infinite loop and I need it taken out. It should output 5 rows with 3 columns with no duplicates in each row

So there is a bug in my code that puts it in an infinite loop. I need that taken out and I cannot find it for the life of me.

Here is the code:

#include <iostream>
#include <cstdlib>

const int MAX             = 6;
const int SIZE_OF_SAMPLES = 3;
const int REP             = 5;

bool inArray     (int[], int, int  );
void UniqRandInt (int,   int, int[]);

int main() {
//   std::cerr<<"in main\n";

int arr[SIZE_OF_SAMPLES];

srand(9809);  //Seed random number generator.


for (int i = 0; i < REP; i++) {
    UniqRandInt(MAX, SIZE_OF_SAMPLES, arr);
    for(int j = 0; j < SIZE_OF_SAMPLES; j++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}
return 0;
}
void UniqRandInt(int max, int n, int result[]) {

int cntr = 0, r;

while(cntr < n) {

    r = rand();  //Get random number
    r = r % (max + 1);
    if (inArray(result, cntr, r)) {
        result[cntr] =  r;
        cntr++;
    }
}
return;
}
bool inArray(int array[], int arrSize, int x) {
for (int i = 0; i < arrSize; ++i) {
    if (array[i] == x) {
        return true;
    }
}
return false;
}

It is outputting somthing like: 222 000 555 000 Here is what is supposed to output: something like: 254 105 035 432 523 I need 5 rows with all different numbers.

Replicate H Lookup Functionality in Python Pandas for Dataframe

Question - How to best attempt the problem as nested loops is slowing the process and not giving the desired result

Same thing can be done in the Excel using Hlookup, but as it is a repetitive exercise, I need to automate it

I have the below lookup table.

lookup = pd.DataFrame({'Fruit': ['Apple','Mango','Guava'],'Rate':[20,30,25],
               'Desc':['Apple rate is higher', 'Mango rate is higher', 'Guava rate is higher']})

My objective is to mark desc in my input data wherever the rate is greater than as mentioned in lookpup table

input_data = pd.DataFrame({'Id':[1,2,3,4,5], 'Apple':[24,27,30,15,18], 'Mango':[28,32,35,12,26],
                       'Guava':[20,23,34,56,23]})

Expected Output data sample -

output_data = pd.DataFrame({'Id':[1,2,3,4,5], 'Apple':[24,27,30,15,18], 'Mango':[28,32,35,12,26],
                       'Guava':[20,23,34,56,23], 'Desc':['Apple rate is higher', 
                                                         'Apple rate is higher, Mango rate is higher',
                                                         'Apple rate is higher, Mango rate is higher, Guava rate is higher',
                                                         'Guava rate is higher', '']})

I have tried using the loop and created two list which gives me the index and value to be inserted. I am confused how to progress to next step and it seems a very slow method as I have multiple nested loops

for i in range(0,len(lookup)):
var1 = lookup['Fruit'][i]
value1 = lookup['Rate'][i]
desc1 = lookup['Desc'][i]

for j in range(0, len(input_data.columns)):
    var2 = input_data.columns[j]
    a=[]
    b=[]

    if var1 == var2:
        for k in range(0, len(input_data)):
            if input_data[var2][k] > value1:
                a.append(desc1)
                b.append(k)
        print (a)
        print (b)

Output of my code

['Apple rate is higher', 'Apple rate is higher', 'Apple rate is higher'] [0, 1, 2]

['Mango rate is higher', 'Mango rate is higher'] [1, 2]

['Guava rate is higher', 'Guava rate is higher'] [2, 3]

python 'if' statement invalid syntax [closed]

guess_row = input("guess row: ").strip()
guess_col = (input("guess col: ").strip()

if guess_row.isnumeric() and guess_col.isnumeric():

it says invalid syntax on the ':' why is that and how can I fix it?

MS Access form module/formula to multiply field by a variable

I have a database of elect components. For capacitors the database wants value to be numeric. So for a 0.01uF the table wants to see 0.00000001. I am not good at counting zeros, I want to enter in the form fields | 0.01 | u | and the resulting field to be |0.00000001| using an if else statement for p(ico) and n(ano) values. Do I do this in a form or a query? Not sure of where to start.

In bash, download and install a package but only if not installed

I'm writing a script that can run on CentOS or Ubuntu, but my logic might not be optimal. This part is just doing an install for CentOS

type apt &> /dev/null && MANAGER=dnf && DISTRO="Debian/Ubuntu"
type yum &> /dev/null && MANAGER=yum && DISTRO="RHEL/Fedora/CentOS"
type dnf &> /dev/null && MANAGER=dnf && DISTRO="RHEL/Fedora/CentOS"   # $MANAGER=dnf will be default if both dnf and yum are present

[[ "$MANAGER" = "dnf" ]] && (NOT) [ type pydf &> /dev/null ] && wget -P /tmp/ https://download-ib01.fedoraproject.org/pub/fedora/linux/development/rawhide/Everything/x86_64/os/Packages/p/pydf-12-11.fc35.noarch.rpm
[[ "$MANAGER" = "dnf" ]] && [[ -f /tmp/pydf-12-11.fc35.noarch.rpm ]] &> /dev/null && rpm -i /tmp/pydf-12-11.fc35.noarch.rpm && rm /tmp/pydf-12-11.fc35.noarch.rpm

I want to check [ is dnf is present? AND is dfc NOT present? ]. If these are true THEN download the rpm, then [ is dnf present? AND is the rpm present ]. If these are true, then install the rpm.

In each case, I'm a little confused if I am using the right approach, and I never really know if I should be using [ ] or [[ ]]. I get that && is 'only if previous statement is true, then run the next one', but I feel a bit confused that I'm maybe not approaching this is an correct / optimal way (and definitely, my logic is broken in the download line I think)?

Should it maybe look more like this, though I don't know how to construct the first condition:

if [[ $MANAGER == "dnf" && ( NOT type pydf &> /dev/null ) ]]; then 
    wget -P /tmp/ https://download-ib01.fedoraproject.org/pub/fedora/linux/development/rawhide/Everything/x86_64/os/Packages/p/pydf-12-11.fc35.noarch.rpm
    RPM=/tmp/pydf-12-11.fc35.noarch.rpm; type $RPM &> /dev/null && rpm -i $RPM && rm $RPM
fi 

keep getting '"code is running" notification with no output. Ran it on other online compilers and it worked but it does not work on visual studio code [closed]

THERE IS NO PROBLEM IN THIS CODE BECOZ IT WORKS ON OTHER COMPILERS ONLINE BUT IT JUST DOESNT WORK ON VISUAL CODE STUDIO. I dont understand where the problem lies. should i add getc() in the end of the code. it is a C++ program.

#include<iostream>
using namespace std;
int main()
{
            int num1, num2;             **//codeblock 1**
   char p;
   cout << "enter 1st numbers:";
   cin>>num1;
    cout<<"enter a an operand:";
   cin>>p;
   cout<<"enter 2nd number:";
   cin>>num2;
  
          int ans;                **//code block 2** 
if (p ='+')
{ans=num1+num2;}

else if(p=='-')
{ans=num1-num2;}

else if(p=='/')
{ans=num1/num2;}

else if(p=='*')
{ans=num1*num2;}

else
{
cout<<"invalid operator";
}                            **//code block 2 end**
cout<<ans; 

   return 0;                **//code block 1 end**
}

I want to make if condition between two dates difference

const today = new Date();
var date2 = new Date("10/29/2021");

var Difference_In_Time = date2.getTime() - today.getTime();

var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

document.write(
  "Total number of days between dates  <br>" +
  today +
  "<br> and <br>" +
  date2 +
  " is: <br> " +
  Difference_In_Days
);

Why do I get the same value for all the different maturities if statement? [closed]

DateFrame df that I got from web-scraping :

  • Date d'échéance : due date# date 12-10-2018
  • Transaction : Transaction#float64 104.11
  • Taux moyen pondéré : weighted average rate#2.3%
  • Date de la valeur : value date#date 11-09-2018
  • maturite : maturity (calculated)# 27 days

I should add column to my dataframe df called " Taux act" :

  • If Maturity 'maturite' > 1 YEAR : Taux act = weighted average rate 'Taux moyen pondéré'
  • If Maturity < 1 YEAR : Taux act = ((1 + weighted average rate maturity)/360)**(365/maturity)-1

How to run a JavaScript snippet only if an iframe exists on the current page?

I want to do a modification to YouTube embedded iframes to improve the Lighthouse score but I cannot make the if statement work:

if (document.getElementsByTagName('iframe')){
function init() {
    var vidDefer = document.getElementsByTagName('iframe');
    for (var i=0; i<vidDefer.length; i++) {
    if(vidDefer[i].getAttribute('data-src')) {
    vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
    } } }
    window.onload = init;
    function parseJSAtOnload() {
        var element = document.createElement("script");
        element.src = "https://www.youtube-nocookie.com/yts/jsbin/player_ias-vflRCamp0/en_US/base.js";
        document.body.appendChild(element);
        }
        if (window.addEventListener)
            window.addEventListener("load", parseJSAtOnload, false);
        else if (window.attachEvent)
            window.attachEvent("onload", parseJSAtOnload);
        else window.onload = parseJSAtOnload;
}

I only want to run this snippet if there exists an iframe element on the current page and not always. This way I could embed the code on every page of my website, no matter of the content. With the above code it still gets active always. How to make it work only on pages with an iframe?

How to count how many the non-zero value in a row in 2d array in C

How can I calculate how many non-zero values include in a row

I try to calculate the average of the total value inside a row but somehow it is always dividend in 5 How can I create a counter to count how many non-zero value inside the array?

Sorry for my bad english

int main () 
{
    float Sum, average;

    float a[4][5] = { {2.30,4.00,5.00},
                      {3.00,2.10,1.00,4.00},
                      {1.00,2.00,3.00,4.00,5.00},
                      {4.00,2.50}};
    int rows, columns;
    int length;
 
 
    for(rows = 0; rows < 4; rows++)
    {
        Sum = 0;
        for(columns = 0; columns < 5; columns++)
        {
        
            Sum = Sum + a[rows][columns];
        }
        
        printf("The Sum of rows Elements in a Matrix =  %.2f \n", Sum );
        average = Sum / columns;
        printf("Product %d : %f\n",rows + 1,average);
    }
    

      
      return 0;
   }

The output cames out is:

The Sum of rows Elements in a Matrix =  11.30
Product 1 : 2.260000
The Sum of rows Elements in a Matrix =  10.10
Product 2 : 2.020000
The Sum of rows Elements in a Matrix =  15.00
Product 3 : 3.000000
The Sum of rows Elements in a Matrix =  6.50
Product 4 : 1.300000

But I was aspect it will comes out

The Sum of rows Elements in a Matrix =  11.30
Product 1 : 3.77
The Sum of rows Elements in a Matrix =  10.10
Product 2 : 2.53
The Sum of rows Elements in a Matrix =  15.00
Product 3 : 3.00
The Sum of rows Elements in a Matrix =  6.50
Product 4 : 3.25

condition check in If statement [duplicate]

I have a question regarding how and in which order if() checks multiple conditions. I would like to call functions directly in the if statement. In an if statement like this:

if (condition1 || function1)
        return SOMETHING;

The first part of the logical expression will be checked, so if condition1 == 1. If this proved to be true, the whole statement is true, therefore the function function1 will not be executed, am I right?

What happens with something like this:

if (!(condition1 && function1))
        return FAIL;

Will the compiler turn this into:

if (!condition1 || !function1)
        return FAIL;

And not execute function1 if !condition1 turns out to be true? Or will it first check condition1 and execute function1 because of the AND operator and than negate the result? What if I switch the order?

IF Year(today) is x years greater than Year(A1) Then

I am struggling to get this formula working.

If the current year minus the year in A1 is greater than 50 years, then yes, otherwise no

=IF((YEAR(TODAY)-YEAR(F13)>50), yes, no)

Python - Can Multiple if-condition and append be simplified

If it is possible to simplify the following code.

c0, c1, c2, c3, c4, c5, c6, c7, c8, c9 = ([] for _ in range(10))
  
  for i in dataset:
    if i[1] == 0:
      c0.append(i)
    elif i[1] == 1:
      c1.append(i)
    elif i[1] == 2:
      c2.append(i)
    elif i[1] == 3:
      c3.append(i)
    elif i[1] == 4:
      c4.append(i)
    elif i[1] == 5:
      c5.append(i)
    elif i[1] == 6:
      c6.append(i)
    elif i[1] == 7:
      c7.append(i)
    elif i[1] == 8:
      c8.append(i)
    else:
      c9.append(i)

Trying to divide the whole dataset into class-wise multiple datasets. Code below is just for example which has only 10 classes, but the dataset I'm working on has massive numbers of classes, so need to simplify as possible.

If statement gives error, program works perfectly without it

sorry if the answer is too obvious. This is for an assignment I am working on, so since I need and want to learn it by mistake, I will just post what I think is messing up my code.

      keyboard.useDelimiter("[*\\s]+");
      
      int månad, dag;
      double sek, minutdelat1, minutdelat2, timmeupp,
      minutupp, timmened, minutned, soltimmar, wh, produktion;
    
      System.out.print("Skriv dagens datum [mm-dd]: ");
      String response = keyboard.next();

      månad = keyboard.nextInt();
      dag = keyboard.nextInt();
      keyboard.nextLine();
      
      if (månad >= 06 && månad <= 07)
         {
         System.out.print("Skriv in tidpunkt soluppgång [hh:mm]: ");

         }
     else 
        {
         System.out.print("Fel månad, programet stängs");
        }```

Without the "if" code, the program runs perfectly. If it is not understandable, then I want the the "mm" (month) to be synced to "månad" and if the month is not 06 or 07, then the program will close, if it is correct then it will continue.

If I just write "07" "06" 3 times then it will go on to the next question but if I write for example "07-18" then I will get an error. I think the "-" is missing the code up.

It is important that I learn this myself so please just point me in the right way, and since this is beginning Java, please no advance programming. Thank you!

mardi 28 septembre 2021

Only the functions in if work. Why don't my elif conditions work? [closed]

so this is my code :

import pandas as pd
import plotly.express as px
import os

def one():
    something = input('\nWhat Chart Do You Want To Do Today ?\nChoose One From These : (line/scatter/pie/bar) : ')

    if(something == 'line'):
        line()

    elif(something == 'scatter'):
        scatter()

    elif(something == 'pie'):
        pie()

    elif(something == 'bar'):
        bar()

    else:
        print('\nTHAT IS NOT A VALID INPUT DUMB')
        two()

def two():
    something = input('\nWhat Chart Do You Want To Do Today ?\nChoose One From These : (line/scatter/pie/bar) : ')

    if(something == 'line'):
        line()

    elif(something == 'scatter'):
        scatter()

    elif(something == 'pie'):
        pie()

    elif(something == 'bar'):
        bar()

    else:
        print('\nTHAT IS NOT A VALID INPUT DUMB')
        one()

def line():
    pathLine = input("\nType The Address Of Your File\n( Example : C:/Users/userName/Directory/FileName.csv ) : ")
    pathExists = os.path.exists(pathLine)
    if(pathExists == True):
        df = pd.read_csv(pathLine)
        x_axis = input("\nWhich Column Do You Want In The X Axis : ")
        y_axis = input("\nWhich Column Do You Want In The Y Axis : ")
        colorThing = input("\nWhich Column Do You Want The Colors To Be : ")
        titleThing = input("\nWhat Do You Want Your Chart's Title To Be : ")
        fig = px.line(df,x=x_axis, y=y_axis, color=colorThing, title=titleThing)
        print("\nYour Chart Should Open In A Few Moments...")
        fig.show()
    else:
        print('\nThat Is Not A Valid File Location')
        one()

def scatter():
    pathScatter = input("\nType The Address Of Your File\n( Example : C:/Users/userName/Directory/FileName.csv ) : ")
    pathExists = os.path.exists(pathScatter)
    if(pathExists == True):
        df = pd.read_csv(pathScatter)
        x_axis = input("\nWhich Column Do You Want In The X Axis : ")
        y_axis = input("\nWhich Column Do You Want In The Y Axis : ")
        colorThing = input("\nWhich Column Do You Want The Colors To Be : ")
        titleThing = input("\nWhat Do You Want Your Chart's Title To Be : ")
        fig = px.scatter(df,x=x_axis, y=y_axis, color=colorThing, title=titleThing)
        print("\nYour Chart Should Open In A Few Moments...")
        fig.show()
    else:
        print('\nThat Is Not A Valid File Location')
        one()

def pie():
    pathPie = input("\nType The Address Of Your File\n( Example : C:/Users/userName/Directory/FileName.csv ) : ")
    pathExists = os.path.exists(pathPie)
    if(pathExists == True):
        df = pd.read_csv(pathPie)
        colorThing = input("\nWhich Column Do You Want The Colors To Be : ")
        valuesThing = input("\nWhich Column Do You Want The Values To Be : ")
        titleThing = input("\nWhat Do You Want Your Chart's Title To Be : ")
        fig = px.pie(df,names=colorThing, values=valuesThing, color=colorThing, title=titleThing)
        print("\nYour Chart Should Open In A Few Moments...")
        fig.show()
    else:
        print('\nThat Is Not A Valid File Location')
        one()

def bar():
    pathBar = input("\nType The Address Of Your File\n( Example : C:/Users/userName/Directory/FileName.csv ) : ")
    pathExists = os.path.exists(pathBar)
    if(pathExists == True):
        df = pd.read_csv(pathBar)
        x_axis = input("\nWhich Column Do You Want In The X Axis : ")
        y_axis = input("\nWhich Column Do You Want In The Y Axis : ")
        colorThing = input("\nWhich Column Do You Want The Colors To Be : ")
        titleThing = input("\nWhat Do You Want Your Chart's Title To Be : ")
        fig = px.bar(df,x=x_axis, y=y_axis, color=colorThing, title=titleThing)
        print("\nYour Chart Should Open In A Few Moments...")
        fig.show()
    else:
        print('\nThat Is Not A Valid File Location')
        one()

one()

My goal was that anyone can create a chart easily or something like that... but the problem is that.. everytime i run it it only performs the line() function even if i type the input as bar/pie/scatter. can anyone explain what i have done wrong ?? (also ummmm i am new to python so please dont mock me)

(i am just writing this because stackoverflow says i have to add more details and i dont know what else to type so im just typing this to fill up the space dont mind this ok ?)

How to write an 'else' condition in python? [closed]

if len(rule_response['Rules']) < 1:
            response = remote_event_client.put_rule(
            Name=eventrulename,
            EventPattern='{"detail-type":["EC2 Instance State-change Notification"],"source":["aws.ec2"],"detail":{"state":["running","terminated"]}}',
            State='ENABLED',
            Description='pdxc mad cloudwatch event rule for '+os.environ['Environment']
            )
            log.debug(response)
            target_response = remote_event_client.put_targets(
                Rule=eventrulename,
                Targets=[
                    {
                        'Arn': sns_response['TopicArn'],
                        'Id': targetname
                    }
                ]
            )
            log.debug(target_response)

These are the hints to write the else condition in python program enter image description here

How to reference the previous value of the same column in a ifelse function on R

I am trying to give an ID to each event, like on the picture 1 but I struggle to tell R "if the previous cell in start_f is a 0, then I want the same ID as the previous cell" (the column start_f looks like picture 2

I tried to use the function lag() in a ifelse function but it did not work.

I am not sure on how to refer to the previous cell in that case. Do you have any idea?

if and else user verification issue

int main()
{
    int account_or_not;
    account obj;
    menu menu_obj;

    cout << "Do you have an account? 1 for yes or 2 for no " << endl;
    cin >> account_or_not;


    if (account_or_not == 1)
    {
        menu_obj.user_menu();
    }
    else if (account_or_not == 2)
    {
        obj.create_account();
    }
    else
    {
        cout << "You entered a value other than 1 or 2 please try again "<< endl;
        cin >> account_or_not;
    }
  
    return 0;
}

This is what is in the main of my code, and im not sure if I am being dumb, but I have tried a switch case and if else and in the else (or default for switch) when I check what the user has entered was wrong and prompt them to enter it again the program ends when they enter the correct value. E.g if 3 was entered it would tell the user to try again, then when 1 or 2 is entered the program ends. Any ideas, thanks in advance.

Why i get the same value for all the different maturities?

DateFrame df that i got from webscraping :

  • Date d'échéance : due date
  • Transaction : Transaction
  • Taux moyen pondéré : weighted average rate
  • Date de la valeur : value date
  • maturite : maturity (calculated)

I should add column to my dataframe df called " Taux act" :

  • If Maturity 'maturite' > 1 YEAR : Taux act = weighted average rate 'Taux moyen pondéré'
  • If Maturity < 1 YEAR : Taux act = ((1 + weighted average rate maturity)/360)**(365/maturity)-1

Dataframe df : |Date d'échéance|Transaction|Taux moyen pondéré|Date de la valeur| maturite |taux | |---------------|-----------|------------------|-----------------|----------|----- | | 2019-04-14 | 104.47 | 2.300 | 2019-03-18 | 27 days |7.59..| |2019-05-20 | 71.28 | 2.333 | 2019-03-11 | 70 days |7.59..|

Nesting multiple IFS

I have the following formula which works fine:

=IF(AND(Input!$G$54="",Input!$I$54="",Input!$K$54="",Input!$K$56),0,IF(AND(Input!$I$54="",Input!$K$54="", Input!$K$56=""),B20*Input!$G$54*Lookups!AF4,IF(AND(Input!$G$54="",Input!$K$54="", Input!$K$56=""),Lookups!AM2*$J$5*Lookups!AF4,IF(AND(Input!$G$54="",Input!$I$54=""),SUM(B20*Input!$K$54*Lookups!AF4,Lookups!AM2*$J$5*Lookups!AF4)))))

But I need to add the following condition to one of the equations, which appears twice in the formula.

=IF(Lookups!$A$O2<30,Lookups!AM2*$J$5*Lookups!AF4,0)

I've input dashes ------- where the above needs to go.

=IF(AND(Input!$G$54="",Input!$I$54="",Input!$K$54="",Input!$K$56),0,IF(AND(Input!$I$54="",Input!$K$54="", Input!$K$56=""),B20*Input!$G$54*Lookups!AF4,IF(AND(Input!$G$54="",Input!$K$54="", Input!$K$56=""),-------Lookups!AM2*$J$5*Lookups!AF4-------,IF(AND(Input!$G$54="",Input!$I$54=""),SUM(B20*Input!$K$54*Lookups!AF4,-------Lookups!AM2*$J$5*Lookups!AF4-------)))))

Whatever way I try to add this I get the 'not trying to type a formula' error. Please can someone help?

Is it possible to use implode() as a condition ? If not, what's the best way to check if the array can be imploded?

I want implode an array in a loop. Sometime this array is a simple array so it works, sometime that's a multidimensional array and my script throw an error.

Is it possible to do something like that :

if (implode($array) ) {

$builded = implode($array);

}

I know that's possible with some function returning false like if (file_get_contents($file)). If not possible, what's the best way checking if an array can be imploded ?

I'm aware about if (count($array) == count($array, COUNT_RECURSIVE)) and others solutions checking if the array is multidimensional but that's not working with empty sub array (end i often got the case).

How I can sort these two columns using R

I have a large database, but here is a sample of it:

 df<-read.table (text=" Col1 Col2
        65  NA
        NA  91
        56  NA
        71  71
        67  100
        NA  45
        44  NA
        NA  90
        NA  40
        84  71
        44  63
        NA  20
    ", header=TRUE)

I want to add "1" to Col1 and complete NA in Col1 using Col2. Considering row 2, NA in Col1 would be 91. Here we do not add "1".In Col1, However, we add 1 at the beginning if they do not have NA.

The outcome of interest is:

   Out
    165
    91
    156
    171
    167
    45
    144
    90
    40
    184
    144
    20

How do I determine whether time-coded data falls into time range?

I have been trying to write a for loop in order to determine whether my time data falls within specific time ranges. I have gone through all related questions on stack overflow and so far this is where I have gotten:

Basically, I have one data frame with acoustic measures of vowels. For each vowel, I also have the time in seconds at which the participants uttered the vowel.

Then I have a second dataframe including time intervals. Those intervals correspond to time periods where the participant was talking and there was no overlapping noise. Those intervals therefore identify the vowels from my first dataframe that can be used in subsequent analyses because their acoustic measures are not contaminated by other noises

I need to create a new column ("target") in data frame 1 that indicates, for each participant and for each recording, whether YES or NO the vowel falls into one of the intervals from data frame 2.

these are the variables of interest in data frame 1:

    Participant RecordingNumber    time
1        FSO110               1  37.258
2        FSO110               1  37.432
3        FSO110               1  37.496
4        FSO110               1  38.138
5        FSO110               1  38.499
6        FSO110               1  42.124
7        FSO110               1  61.733
8        FSO110               1  61.924
9        FSO110               1  61.980
10       FSO110               1  62.260
11       FSO110               1  62.610
12       FSO110               1  62.943
13       FSO110               1 194.929
14       FSO110               1 195.403
15       FSO110               1 401.114
16       FSO110               1 401.341

these are the variables of interest in data frame 2:

Participant RecordingNumber    tmin    tmax 
FSO110       1                 445.695 447.250   
FSO110       1                 448.444 449.093   
FSO110       1                 452.990 453.292   
FSO110       1                 481.177 481.709   
FSO110       2                 41.202  41.511   
FSO110       2                 42.176  43.132   
FSO110       2                 44.640  47.710   
FSO110       2                 53.819  56.253   
FSO110       2                 113.453 114.803   
FSO110       2                 123.135 123.374

So far, I have gotten there:

# split dataframes by Participant and Recording Number
data1 <- split(data1, paste0(data1$Participant, data1$RecordingNumber))
data2 <- split(data2, paste0(data2$Participant, data2$RecordingNumber))

# loop through each element of each splitted df 
for (n in seq_along(data1)){
  for (m in seq_along(data2)){
    if(n == m){
    data_split[[n]][["target"]] = as.character(lapply(data1[[n]][["time"]], FUN = function(x){
      for (i in 1:nrow(data2[[m]])){
          if(data2[[m]][["tmin"]]<=x & x<= data2[[m]][["tmax"]]){
            return(paste0("in"))}
        else{
          return(paste0("overlap"))}
          }
      }
    ))}
}

The function seems to work. However, it only works for i == 1 (rows of data2). Therefore, it correctly identifies time points from data 1 that fall into the first interval of each splitted element of data 2 but does not continue for other intervals.

Solutions I have tried:

  1. use ifelse instead of if statement
for (n in seq_along(data1)){
  for (m in seq_along(data2)){
    if (n == m){
      data1[[n]][["target"]] = as.character(lapply(data1[[n]][["time"]], FUN = function(x){
        for (i in 1:nrow(data2[[m]])){
          ifelse((data2[[m]][["tmin"]]<=x & x<= data2[[m]][["tmax"]]), "in", "overlap")
        }
      }
      ))}}
}

However, this function returns NULL for each row of my new "target column".

  1. adding any() to my if statement:
for (n in seq_along(data_split)){
  for (m in seq_along(data_split_target)){
    if(n == m) {
    data_split[[n]][["target"]] = as.character(lapply(data_split[[n]][["time"]], FUN = function(x){
      for (i in 1:nrow(data_split_target[[m]])){
          if(any(data_split_target[[m]][["tmin"]])<=x & any(x<= data_split_target[[m]][["tmax"]])){
            return(paste0("in"))}
        else{
          return(paste0("overlap"))}
          }
      }
    ))}
}

Again, the function seems to work as it correctly creates a new "target" column with "in" and "overlap" rows but the function erroenously returns "in" row values even when the time point did not fall into one of the intervals.

Can someone help me? Many thanks!

I want to use S as an input for the variable A but S is not defined when i run the program in Pycharm [closed]

"""

A = str(input("Social Status: "))

B = int(input("Age: "))

if A == S:
    print("Qualified!")
elif B > 16 and B < 25:
    print("Qualified!")
else:
    print("Sorry! Not Qualified")

"""

#output

Social Status: S

Age: 12

Traceback (most recent call last):

line 4, in #

if A == S:

NameError: name 'S' is not defined

Process finished with exit code 1

Why is my if statement ignored even after typing hello in input [duplicate]

#include <stdio.h>

int main()
{
    char a[]=("hello");
    char b[10];
    printf("enter value: ");
    scanf("%s",b);
    if(b==a){
        printf("%s",a);
    }

    return 0;
}

when I run this code it shows me to 'enter value' as expected but when I enter 'hello' which is equal to variable 'a' it is not showing the if statement.

Flutter ListView search and click

So I'm currently trying to implement some searching functionality to my ListView and this does work great actually. When I type in some letters it automatically shows me the right things (-> See Screenshot_Listview_1.png and Screenshot_Listview_2.png).

There is only one problem. I want the different texts from my listview to be clickable, so when I click on them a new ModalBottomSheet should appear. For example: I'm searching for "Apple" and when I click on the text "Apple" a ModalBottomSheet opens and I can read some facts about apples. I tried the onTap method and it works so far but I only managed to open the same BottomSheet.. But I need different BottomSheets depending on what I have tapped on.

This is what I got so far. Can you please help me out? I really don't know how to solve this problem. Thank you so much!!

import 'package:flutter/material.dart';
import 'dart:ui' as ui;


class GlossarScreen extends StatefulWidget {
  @override
  _GlossarScreenState createState() => _GlossarScreenState();
}

class _GlossarScreenState extends State<GlossarScreen> {
  TextEditingController _textEditingController = TextEditingController();

  List<String> glossarListOnSearch = [];
  List<String> glossarList = [
    'Apple',
    'Orange',
    'Banana',
    'Grapefruit',
    'Mango',
    'Kiwi',
    'Grapes',
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Glossar'),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Color(0xffFBD23E), Color(0xffF6BE03)],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter),
          ),
        ),
        bottom: PreferredSize(
          preferredSize: Size(0, 60),
          child: Padding(
            padding: const EdgeInsets.fromLTRB(12, 0, 12, 10),
            child: Container(
              //height: 50,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                    colors: [Colors.white60, Colors.white70],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter),
                borderRadius: BorderRadius.circular(50),
              ),
              child: Padding(
                padding: const EdgeInsets.fromLTRB(20, 0, 0, 0),
                child: TextField(
                  textAlign: TextAlign.left,
                  onChanged: (value) {
                    setState(() {
                      glossarListOnSearch = glossarList
                          .where((element) => element
                              .toLowerCase()
                              .contains(value.toLowerCase()))
                          .toList();
                    });
                  },
                  controller: _textEditingController,
                  decoration: InputDecoration(
                      border: InputBorder.none,
                      errorBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                      contentPadding: EdgeInsets.all(0),
                      hintText: 'Search'),
                ),
              ),
            ),
          ),
        ),
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
              colors: [Color(0xffFEFDFD), Color(0xffBDBDB2)],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight),
        ),
        child: _textEditingController.text.isNotEmpty &&
                glossarListOnSearch.isEmpty
            ? Column(
                children: [
                  Align(
                    alignment: Alignment.center,
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(0, 50, 0, 0),
                      child: Text(
                        'No results',
                        style: TextStyle(
                            fontFamily: 'Avenir',
                            fontSize: 22,
                            color: Color(0xff848484)),
                      ),
                    ),
                  )
                ],
              )
            : ListView.builder(
                itemCount: _textEditingController.text.isNotEmpty
                    ? glossarListOnSearch.length
                    : glossarList.length,
                itemBuilder: (context, index) {
                  return GestureDetector(
                    onTap: () {
                      _testFuction(context);
                    },
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(12, 15, 12, 15),
                      child: Text(
                        _textEditingController.text.isNotEmpty
                            ? glossarListOnSearch[index]
                            : glossarList[index],
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: 20,
                            fontFamily: 'Avenir'),
                      ),
                    ),
                  );
                },
              ),
      ),
    );
  }
}

void _testFuction(context) {
  showModalBottomSheet(
    context: context,
    builder: (BuildContext bc) {
      return Scaffold(
        body: Text('This text should be dependent on what I have tapped on. If I tap on "Apple" a different ModalBottomSheep shall appear then when I press on "Banana".'),
      );
    },
  );
}

Screenshot_ListView_1

Screenshot_ListView_2

How to simplify if statements

How can I simplify below if statements?, I'm trying to achieve the possibly most efficient code.

// doSomething based on x value and y value   
function doSomething(x int, y int) {

      //x not zero and y not zero
      if x != 0 && y != 0 {
        do a

        //do b if x greater or equal y
        if x >= y {
            do b
            return
        }
        
        //do c if x lower than y
        if x < y && x != 0 && y != 0 {
            do c
            return
        }
        
        //do b if x not zero and y zero
        if x != 0 && y == 0 {
            do b
            return
        }

        //do d if x zero and y not zero
        if x == 0 && y != 0 {
            do d
            return
        }
      }

      //do e if both x and y zero
      if x == 0 && y == 0 {
          do e
          return
      }
    }

What is the most concise and efficient way to simplify?

lundi 27 septembre 2021

How to replace numbers with text in R

I am new to using R and I am encountering a really annoying roadblock.

I am trying to use a dataset and convert all 0's to a value of "Not_Eaten' and all 1's to a value of Eaten.

I am using this statement

attach(data)
Eaten <- ifelse(Eaten==0, "Not_Eaten",'Eaten')

but the datasheet does not update and the Eaten column is still populated with 0's and 1's.

Can someone please point out what I am doing wrong here?

If it helps, the class is integer and not numeric for some reason.

Nested If else statements used in a WordPress template isn't working

I'm not sure what is wrong with the nested conditions below. The else block never seems to get executed even when the image variable is not set(hero image being absent). Please help me find the problem with it.

<?php
if ( is_singular() || is_page() ):
if( have_rows('hero') ): while( have_rows('hero') ): the_row();
if( have_rows('hero_-_background_options') ): while( have_rows('hero_-_background_options') ): the_row();
$image = get_sub_field('background_-_image');
if($image):
?>
.default-hero .col .hero-bkg {
    display:none;
}
<?php  endif; endwhile; endif; endwhile; else: ?>
.default-hero.relative.bg-grey-light {
  display: none;
}
<?php endif; endif; ?>

How do I replace values with text [closed]

I am new to using R and I am encountering a really annoying roadblock.

I am trying to use a dataset and convert all 0's to a value of "Not_Eaten' and all 1's to a value of eaten.

I am using this statement

attach(data)
Eaten <- ifelse(Survived =0, "Not_Eaten",'Eaten')````

but I keep getting the error 
````unused argument (Eaten= 0)````

Can someone please point out what I am doing wrong here?

If it helps, the class is integer and not numeric for some reason. 

How to check and list all false conditionals in if statement - JavaScript?

I'm trying to improve my code and have better logging.

Is there an ideal way of how to tell which conditions are false in a list of conditionals?

i.e)

if(isAnimal && isCarnivore && isPlant){
 // want to console.log all the false conditions
}

We could write

let falseString = ""


if (!isAnimal) {
 falseString = falseString + "is not an Animal";
} 

if (!isCarnivore) {
 falseString = falseString + "is not a Carnivore";
}

if (!isPlant) {
 falseString = falseString + "is not a Plant";
}

console.log("string of false conditions" , falseString)

Then this would log a string of which conditions are false, but this seems to be a naive solution.

What is a better way to do this in JavaScript?

Thank you!

Comparing Two Data frame Columns to Add a New Column With the Results

using this as a demo data set:

    a = [['11', '2'], ['15', '70'], ['8', '5']]
    df = pd.DataFrame(a, columns=['Person','one', 'two'])

    Out[8]: 
        Person one  two
    0   Jim    10  1.2
    1   John   15  70
    2   Bob    8   5 

I want to create some sort of logic calculation to compare only columns' one and two, comparing both of them and outputting a new column with the results

a calculation like this if column one is > column two put a 1 else 0

Desired output:

    Out[8]: 
        Person one  two  Results
    0   Jim    10  1.2   1
    1   John   15  70    0
    2   Bob    8   5     1

Checking for an exception and other values in an if statement

Let's say I want to check the avarage of 2 test scores. I don't want the user to input any letters or a value less than 0.

What comes to my mind is this code:

while True:
    try:
        score1 = float(input('Enter the your 1st score: '))
        score2 = float(input('Enter the your 2nd score: '))
    except:
        print('Invalid value, try again...')
        continue

    if (score1 < 0 or score2 < 0):
        print('Invalid value, try again...')
        continue

    print(f'Your average is {(score1 + score2) / 2}')
    break 

Is there a way to check for an exception and if a score is less than 0 in the same if statement?

Finding the biggest number for a sequence given by the while loop

I'm currently learning Python, more specifically, how the loop while works. As far as I know, this loop can be used to create sequences of numbers with and specific condition. For example,

n=1

while n < 10:
    n = n*2
    print(n)

Which gives the powers of two up to 16:

2
4
8
16

But I was wondering if there's a way for the loop to print only the biggest number of the sequence, in this case, it would be 16. Here's my attempt,

n=1
bigNumber = 0
while n <= 10:
    bigNumber = n
    n = n*2
    if n < bigNumber:
        print(bigNumber)

However it doesn't work. Could someone point out were the mistake is?

issue with scope from 2 javascript statements

I have a question about plugging the results of the for statement into the If statement. it says bill is not defined, but it is defined in the for statement. i know this has something to do with scope. but i am still new to coding javascript so i wanted to know how can i make it work"?

the code is:

'use strict';

const bills = [125, 555, 44]

for (var i=0; i< bills.length; i++) {
  let bill = bills[i]
  console.log(bill)
}

if(bill >= 50 && bill<= 300  ) {
  let tip = bill *.15
} else {
  let tip = bill *.20
}