mercredi 31 mars 2021

Why does the and comparison work here instead of the or comparison? [duplicate]

Hey I'm new to coding and while I was doing an assignment for my teacher I was trying to make my if statement accept two options for the conditional.

  choice = input("What type of sandwich would you like today?\nYour options are: Chicken - $5.25, Beef - $6.35, or Tofu - $5.75 ")
if choice == ('Chicken' and 'chicken'):
    print('You chose Chicken for $5.25.')
    sandwich_total=(5.25)
    confirm=input('Are you sure this is what you want? Y/N ')
    if confirm == ('Y'):
        print('Okay...')
    elif confirm ==('N'):
        intro()

The idea is that it would accept either chicken lower-cased or Chicken upper-cased and to me it would make sense if it accepted or but it doesn't...It accepts and. The way I was taught and would only work if both conditions are true while or would only work if one of the conditions were true but when i use or it finishes the code.

Need to update a value in a cell based on another cell value from the list in excel vba

I have Excel macro-enabled sheet - Chart.xlsm- where the values are selected from the lists:

enter image description here

My goal is - when selecting Column D (Type of Workday) = "Day Off" then I want the columns E (Day Outcome) and F (Reason) will be automatically updated with "Not Applicable" value.

My values for (Type of Workday), (Day Outcome) and (Reason) columns selections are stored in this same macro spreadsheet file, but in a separate sheets if that's important

I am not a vba savvy so I tried to use the following code (with no success):

    Private Sub Worksheet_Change(ByVal Target As Range)
       Dim sh As Worksheet
       Set sh = ActiveSheet
    If sh.Cells(3, 4) = “Day Off” Then
       Sh.Cells(3,5) = “Not Applicable”
    End If
   End Sub

Bot doesn't read the second reaction when user reacts to 2 reaction.. discord.py

I have a code which the bot needed to read the both reactions of the user on a message but with this code, the bot doesn't print the "second check" which is meant by like bot not reading the second reaction and stopping after the first one come true

reacttn = True
def check(reaction, user):
  return user == members.users[members.leader].user and reaction.message.id == ttreact.id
while reacttn == True:
  reaction, user = await client.wait_for("reaction_add", check=check)

  if len(members.users) == 2:
    if str(reaction.emoji) == "1️⃣":
      print("first check")
    if str(reaction.emoji) == "2️⃣":
      print("second check")
    await asyncio.sleep(5)
    reacttn = False

For loops and if statements in Hooks?

Is there a way where I can use for loops and if statements without breaking the hook rule? To elaborate, I am currently trying to compare two lists (allData and currentSelection) and if there are similarities, I will add them to another list (favData). However, I am constantly either having visibility issues or errors. If I can get some help, I would much appreciate it!

const [favData, setFavData] = useState([]);    
useEffect(() => {     
    getFilterFavMeal();   
}, []);    
function getFilterFavMeal() {        
    allData.forEach((mealList) => {            
        currentSelection.forEach((mealList2) => {                
            if (mealList["menu_item"]["menu_item_id"] === mealList2.value) {                             
            // with push, I have visibility issues 
//                       favData.push(mealList);                       
                setFavData(mealList);                
            }            
        });        
    });        
    setFavData(favData);    
} 

C++: If statement is not accessing the value of an array (using the index) when evaluating the expression

I am supposed to be creating a program that asks a user to populate an array of size 10. There are three functions which by their name are self-explanatory; one fills up the array with elements, the second one displays the array horizontally, and the third array checks to see if a number entered by the user is an element in the array.

That last function, which is a bool function, is not performing the way I thought it would. Here is my code:

#include<iostream>
#include<iomanip>
void fillUpArray(int array[], int size);
void displayArray(int array[], int size);
bool isNumberPresent(int array[], int size, int SearchNum);

int main(){
  int s = 10; //size of array
  int A[s]; //array A with size s
  int num; //search number
  
  fillUpArray(A, s);

  std::cout <<"\n";

  displayArray(A, s);

  std::cout << "\n";

  std::cout << "Enter a number to check if it is in the array:\n";
  std::cin >> num;

  std::cout << std::boolalpha << isNumberPresent(A, s, num) << std::endl;

  return 0;
  
}

void fillUpArray(int array[], int size)
{
  std::cout << "Enter 10 integers to fill up an array, press enter after every number:\n";
  for(int i = 0; i < size; i++){
    
    std::cin >> array[i];

  }

}
void displayArray(int array[], int size)
{
  for(int j = 0; j < size; j++){
    std::cout << array[j] << "\t";
  }
}
bool isNumberPresent(int array[], int size, int SearchNum)
{
  bool isPresent;
  for(int k = 0; k < size; k++){
    if(array[k] == SearchNum)
      isPresent = true;
    else
      isPresent = false;
  }
  return isPresent;
}

I thought by doing array[k] whatever index k is then it should spit out the element in the array and then with the expression if(array[k] == SearchNum) it should then work as if(element == SearchNum) but that doesn't seem to be the case and the output is always false.

Any idea why this "if else" isn't working properly? [closed]

 if (selectedSize = 60) {
    document.getElementById("outputCost").innerHTML = x;
  } else if (selectedSize = "select") {
      document.getElementById("outputCost").innerHTML = " Please choose a size!";
  }
    
  if (selectedSize = 50) {
      document.getElementById("outputCost").innerHTML = y;
  } else if (selectedSize = "select") {
      document.getElementById("outputCost").innerHTML = " Please choose a size!";
  }

When I run it, it ALWAYS goes down to the second if statement and says that it's true. No matter what I do... thoughts?

Tableau Nested IF Statement including STRING and INTEGER

I am trying to count distinct count of specific items which have alphanumeric (STRING ID) that matches a certain criteria, i.e uncollected invoices that had been outstanding for more than 45 days

{FIXED [Invoice ID] : (IF([INOVICE CATEGORY] = 1 THEN (IF [Median Invoice age] > 45 THEN 1 ELSE 0 END)}

But I am getting an error

Solving a problem using logical operators in C programming language


#include <stdio.h>


void main()
{
 int a = 11, b = 5;
 if(a == 7 || 10){
     printf("True");
 }
 else
 printf("False");
}

This is my problem, i saw it in a question and was asked what the output would be. i put false but the answer was true, im trying to understand why because a is not equal to any of them and the condition for it to be true is that a be equal to at least one of them

Why is this if statement not executing when all the conditions are fulfilled?

I've screenshotted here in IntelliJ, while debugging, you can clearly see that y is increasing and x staying the same yet it passes the "fulfilled" condition and carries on. Why?

The language is Java 11, OS is Debian on a virtual machine.

How do I get VBA to exclude cells where the formula returns zero?

I am going to try and explain this as best I can:

  1. I am working with a file that has 4 sheets.

  2. From all of them, I want to copy and paste column A (from A:10) (which contains a concat formula) when some other rows are populated and then save into a csv. all rows from A10 onwards have the concat formula which is then filled in depending on the other columns (the same applies for the other sheets)

  3. I have it currently creating sheet1, and pasting into there, then saving as a csv.

  4. However, from the first sheet it looks at, it takes only the first line (but the second line - J11 (and so A11) are populated.

  5. In the other sheets, it is copy and pasting the 2 rows that are populated, but also all the other rows as there are formulas there that return zero. As I have the .End(xlDown) and technically all the other rows are populated

  6. I have tried doing an IF statement for the last sheet only as a test, and currently it only copies the first populated line, and not the second (but at least it also doesn't copy all the other cells with zero).

  7. Essentially, for each sheet I'd like it to loop through with for example E10 is populated, copy and paste A10 into Sheet1, etc, if E10 is not zero.

I am a VBA beginner so am quite stuck on this!

Any help is appreciated.

Sub Output_test1()
'
' Output_test1 Macro
'

'
    Sheets("Create").Select
    Range("A10", Range("J10").End(xlDown)).Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets.Add.Name = "Sheet1"
    Sheets("Sheet1").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Sheets("Assign").Select
    Range("A10", Range("E10").End(xlDown)).Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Sheet1").Select
    Range("A1").End(xlDown).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Sheets("Date & Time").Select
    Range("A10", Range("E10").End(xlDown)).Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Sheet1").Select
    Range("A1").End(xlDown).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Sheets("Event Type").Select
    Dim rg As Range
    For Each rg In Range("E10").End(xlDown)
    If rg.Value > 0 Then

    End If
        Range("A10").Select
     Application.CutCopyMode = False
    Selection.Copy
             Sheets("Sheet1").Select
    Range("A1").End(xlDown).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Sheets("Sheet1").Select
    Application.CutCopyMode = False
    Next
    

    
    Sheets("Sheet1").Move
    myTime = Format(Now, ("dd.mm.yy"))
    ChDir "C:\Users\"
    ActiveWorkbook.SaveAs Filename:= _
        "Recruit_" & myTime & ".csv", FileFormat:=xlCSVUTF8, _
        CreateBackup:=False
End Sub

String isn't printing out the correct choice in an if else statement in java [duplicate]

        String pizzacrust;
        pizzacrust=JOptionPane.showInputDialog("What type of curst do yo want? (H)Hand-tossed, (T)Thin-crust, or (D)Deep-dish"
                + " (enter H,T, or D)");
        JOptionPane.showMessageDialog(null, "Your type of crust is " + pizzacrust);
        
String pizzacrustname = "Hand-tossed";
        if (pizzacrust == "H")
            pizzacrustname = "Hand-tossed";
        else if (pizzacrust == "T")
            pizzacrustname = "Thin-crust";
        else if (pizzacrust == "D")
            pizzacrustname = "Deep-dish";
        
        System.out.println(pizzacrustname);

The system will just print out "Hand-tossed" every time despite the choice being T or D

Conditioning color of barblot - r

I want to color in red the bar in position multiple of some period (s) in R. I have tried with lm=60 and s=12 and it works, but I don' t understand why it doesn't work with other different lag max (lm).

correlogrammi_mod_season<-function(dati, lm=36, s=12) # plotta i due corr insieme nello stesso plot
{                                                     # e distingue i multipli  di s 
  n.obs<-length(dati)
  par(mfrow=c(1,2))
  acfs <- acf(dati, lag.max = lm, plot = F)
  m.acfs <- max(abs(acfs$acf[-1])) + 0.1
  pacfs <- pacf(dati, lag.max = lm, plot = F)
  m.pacfs <- max(abs(pacfs$acf)) + 0.1
  
  #plot autocorrelazione globale
  id_color<-0:lm    # here I initialized a list to choose which bar to color in red
  #works fine only with lm=60
  barplot(rev(as.matrix(acfs$acf[-1])), beside = T, col=ifelse(id_color%%s == 0,"red","yellow"), horiz = T, xlim = c(-m.acfs,m.acfs), 
          main= "sample ACF", ylab="", cex.names = 0.9, names.arg = rev(seq(1:lm)))
  abline(v=0)
  abline(v=c(-1.96/n.obs^(1/2), 1.96/n.obs^(1/2)), lty=2)
  
  #plot autocorrelazione parziale                              # here' s the condition
  barplot(rev(as.matrix(pacfs$acf)), beside = T, col=ifelse(id_color%%s == 0,"red","yellow"), horiz = T, xlim = c(-m.pacfs, m.pacfs),
          main= "sample PACF", ylab= "", cex.names = 0.9, names.arg = rev(seq(1:lm)))
  abline(v=0)
  abline(v=c(-1.96/n.obs^(1/2), 1.96/n.obs^(1/2)), lty=2)
  
  par(mfrow=c(1,1))
}

Below an output when it works (only one time sadly, with lm=60 and s=12) enter image description here

replace a value for NA in R - whole dataframe

Is there any way to replace all the "-95" that can possibly exist in a dataframe with NA across all the columns?

Thanks

Create a new column from conditions

I have a dataframe with information of some countries and states like this:

data.frame("state1"= c(NA,NA,"Beijing","Beijing","Schleswig-Holstein","Moskva",NA,"Moskva",NA,"Berlin"), 
               "country1"=c("Spain","Spain","China","China","Germany","Russia","Germany","Russia","Germany","Germany"),
"state2"= c(NA,NA,"Beijing",NA,NA,NA,"Moskva",NA,NA,NA), 
"country2"=c("Germany","Germany","China","Germany","","Ukraine","Russia","Germany","Ukraine",""  ),
"state3"= c(NA,NA,NA,NA,"Schleswig-Holstein",NA,NA,NA,NA,"Berlin"), 
               "country3"=c("Spain","Spain","Germany","Germany","Germany","Germany","Germany","Germany","Germany","Germany"))

Now, I would like to create a new column with the information of German states. (the result would look like below). When at least one of the three variables state are a German state, assign it in the new variable.

data.frame("GE_State"=c(NA,NA,NA,NA, "Schleswig-Holstein",NA,NA,NA,NA,"Berlin"))

Please help a beginner for the condition setting. Thank you in advance!

Is there a benefit to using a boolean over say, an int with an 'if' statement

As a begineer coder, I wrote a program, something along the lines of:

ArbitraryVariable = 1
--Code--
--Code--
--Code--
If ArbitraryVariable == 1:
    --Code--
    --Code--
    --Code--

I would set ArbitraryVariable to 1 if I wanted it to do that thing, and anything else (usually 0) if I didn't, which i guess accomplishes a de facto true/false logic.

My friend who actually knows what he's doing informs me this would've been better accomplished with a boolean as it's true/false, which makes sense, but I am curious if there is actually any specific benefit to doing this, other than a very slight increase in optimisation and it seemingly just being the boolean's 'thing'?

I wrote this in python, but feel free to answer across languages.

Having troubles with if/else statement in condition with powerups

I'm new at Unity and programming. I'm working on a top down shooter game where the player can pickup powerups. I have no problems with picking up(colliding) with the powerups(gameObjects) and actually giving it a certain powerup. I gave every powerup a different kind of tag. But the thing is, that my world contains ground of lava which deals damage to the player. I can also make that work. But the problem now is that when I pickup a certain powerup, in this case its a fire powerup, I want the player to be immune to damage. Whatever I try I just can't make it work. I'm pretty sure I understand the if/else statement but it seems like I'm making a mistake somewhere but I can't find out where. Please help me out :(

HERE ARE SOME IMPORTANT INFO ABOUT THE SCRIPT:

public bool onLava = false;

public bool nuke = false;

PlayerHealthManager healthScript;

Void OnTriggerEnter(Collider other) {
//Fire Powerup//
//This code makes sure that I collide with the powerupFire object//
if(other.gameObject.tag == "Fire") {
powerupFire = true;
Destroy(other.gameObject);
if(powerupFire == true) {
//I think here should be the code which make me immune to lava//
}
}

//This code makes sure that I collide with the lava object//
//Lava//
if(other.gameObject.tag == "Lava"){
onLava = true;
if(onLava == true){
healthScript.currentHealth -= (int)healthUp;
health.Script.healthBar.SetHealth(healthScript.currentHealth);
}
//I thought this, (the else/if statement), would make sure it will check if "powerupFire == true"
and if it is true that it would set "onLava" on false which result in not running the previous if
statement but I guess I'm completley wrong in that because it's not working and it's not even
checking if the "powerupFire == true"//

else if (powerupFire == true) {
onLava = false;
}
}
}

IF Else statement is not working with curly braces

I am creating a simple toggle menu using HTML, CSS, and js. I want that by clicking on the "toggle" button the menu should move to the "0px" position from left, and It works correctly. But not going to move on -"200px" from left. Because the width of the menu is 200px.

When I put curly braces for if statement the working stops. But after removing these braces code works perfectly.

// toggle menu for IE-9
const nav = document.querySelector( "#nav" );
const btn = document.querySelector( "#btn" );
btn.addEventListener( "click" , () => {
  var classes = nav.className.split( " " );
  var i = classes.indexOf( "show" );
  if (i >= 0 ) {
    classes.splice(i, 1);
  }
  else { 
    classes.push("show");
    nav.className = classes.join(" ");
  }
} );
body {
  background: #184d47;
}
/* stylin box */
.box {
  padding:20px;
  position: relative;
}
/* styling toggle button */
#btn {
  padding: 10px 25px;
  border: 2px solid #d44000;
  background: #d44000;
  color: #fff;
  font-family: arial;
  font-weight: bolder;
  letter-spacing: 1px;
  border-radius: 5px;
  user-select: none;
  transition: all .3s ease;
}
#btn:hover {
  background: #ff7a00;
  border: 2px solid #ff7a00;
  color: ff7a00;
  cursor: pointer;
  transition: all .3s ease;
}
/* styling list || nav */
#nav {
  width: 250px;
  height: 100%;
  background: #31326f;
  list-style: none;
  padding: 20px 0 0 0;
  position: fixed; 
  top: 60px;
  left: -250px;
  transition: all 1s ease;
}
#nav.show {
  left: 0px;
  transition: all 1s ease;
}
#nav li {
  padding: 10px 60px 10px 40px;
  border-bottom: 1px solid #dbf6e9;
  user-select: none;
  color: #fff;
  font-weight: bold;
  letter-spacing: 0.5px;
}
<div class="box">
  <buton id="btn" class="">Toggle</buton>
  <ul id="nav" class="">
    <li>HOME</li>
    <li>About</li>
    <li>Setting</li>
  </ul>
</div>

R: Why is the if-statement evaluated twice even if there is no loop?

I know there are already a lot of questions about if-statements, but since they almost all contain loops, I haven't found a suitable answer yet.

I built a dataframe with the most important statistical values (p-values, Cohen's d,...) from 3 tests:

p1 = 0.9
p2 = 0.00021
p3 = 0.001
stat <- data.frame(ID=c("Group A","Group B","Group C"),pvalues = c(p1,p2,p3),cohensd=c(0.14,0.5,0.2))

Now, if at least two p-values are smaller than 0.05, I would like to output a message stating which group has the largest effect (based on Cohen's d) - but of course only if the p-value is smaller than 0.05 for this group.

In my case, the desired output would be "The effect is strongest for Group B."

I tried the following:

if(((p1 < 0.05)+(p2 < 0.05) + (p3 < 0.05))>=2 ){paste("The effect is strongest for", stat$ID[which.max(stat$cohensd)&stat$pvalues<0.05])}

But what I get is: "The effect is strongest for Group B" "The effect is strongest for Group C"

Apparently, the if-statement is evaluated twice, but I can't figure out why. Can someone find my error? Thanks a lot!

Why it is throwing wrong answers?? Hexadecimal to decimal conversion problem

Please help me to identify the error in this program, as for me it's looking correct,I have checked it,but it is giving wrong answers. In this program I have checked explicitly for A,B,C,D,E,F,and according to them their respective values.

#include<iostream>
#include<cmath>
#include<bits/stdc++.h>
using namespace std;
void convert(string num)
{
   long int last_digit;
    int s=num.length();
    int i;
    long long int result=0;
    reverse(num.begin(),num.end());                 
    for(i=0;i<s;i++)
    {
        if(num[i]=='a' || num[i]=='A')
        {
            last_digit=10;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='b'|| num[i]=='B')
        {
            last_digit=11;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='c' || num[i]=='C')
        {
            last_digit=12;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='d'|| num[i]=='D' )
        {
            last_digit=13;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='e'|| num[i]=='E' )
        {
            last_digit=14;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='f' || num[i]=='F')
        {
            last_digit=15;
            result+=last_digit*pow(16,i);
        }
        else {
            last_digit=num[i];
        result+=last_digit*pow(16,i);
        }
    }
    cout<<result;
}
int main()
{
    string hexa;
    cout<<"Enter the hexadecimal number:";
    getline(cin,hexa);
    convert(hexa);
}

mardi 30 mars 2021

php form not showing query data in all if statement

i have make a form whit 3 input, i have make a if statement where if there is input 1 it show the query result in a table if there is input 2 show the query result in the table and if there is input 3 show the query result in the table like. the form is working and show the result of the inpur 2 and input 3 but now show the result of the input 1.

code below:

    <?php include('header.php');?>
        
        <div class="row">
            <div class="col-md-4">
                <h1>Prodotti</h1>
            </div>
            <div class="col-md-8">
            <a href="aggiungi_prodotto.php" class="btn btn-primary btn-block">Nuovo Prodotto</a>
            </div>
        </div> 

        <form class="row" action="prodotti.php" method="post">
            <div class="col-md-12">
                <div class="row g-3 align-items-center mb-2">
                    <div class="col-sm-2">
                        <label for="descrizione" class="col-form-label">Descrizione:</label>
                    </div>
                    <div class="col-sm-10">
                        <input type="text" id="descrizione" class="form-control" name="descrizione">
                    </div>
                </div>
                <div class="row g-3 align-items-center mb-2">
                    <div class="col-sm-2">
                        <label for="codiceArt" class="col-form-label">Codice Prodotto:</label>
                    </div>
                    <div class="col-sm-10">
                        <input type="number" id="codiceArt" class="form-control" name="codice-prodotto">
                    </div>
                </div>
                <div class="row g-3 align-items-center mb-2">
                    <div class="col-sm-2">
                        <label for="inputBarcode" class="col-form-label">Barcode:</label>
                    </div>
                    <div class="col-sm-10">
                        <input type="number" id="inputBarcode" class="form-control" name="barcode">
                    </div>
                </div>
                <div class="row g-3 align-items-center mb-2">
                    <div class="col-sm-12">
                    <button type="submit" value="submit" class="btn btn-primary btn-block">Cerca</button>
                    </div>
                </div>
            </div>
        </form>
        
                <table class="table table-hover">
                    <thead>
                        <tr>
                        <th scope="col">Riga</th>
                        <th scope="col">Codice Articolo</th>
                        <th scope="col">Descrizione</th>
                        <th scope="col">Prezzo</th>
                        <th scope="col">Barcode</th>
                        <th scope="col">Data</th>
                        </tr>
                    </thead>
                    <tbody>
                    
                    <?php
                    if($_POST['descrizione']){
                        $descrizione = $_POST['descrizione'];
                        $sql = "SELECT * FROM prodotti WHERE descrizione = ". $descrizione;
                        $result = $mysqli->query($sql);
                        echo $result;
                        if($result->num_rows > 0){
                            $row_number = 0;
                            while ($row = mysqli_fetch_assoc($result)) {
                                $row_number ++;
                            ?>
                                <tr>
                                <th scope="row"><?php echo $row_number;?></th>
                                <td><?php echo $row['codice'];?></td>
                                <td><?php echo $row['descrizione'];?></td>
                                <td><?php echo $row['prezzo'];?></td>
                                <td><?php echo $row['barcode'];?></td>
                                <td><?php echo $row['data_creazione'];?></td>
                                </tr>
                            <?php
                            }
                        }


                    }elseif($_POST['codice-prodotto']){
                        $codice_prodotto = $_POST['codice-prodotto'];
                        $sql = "SELECT * FROM prodotti WHERE codice = ". $codice_prodotto;
                        $result = $mysqli->query($sql);
                        if($result->num_rows > 0){
                            $row_number = 0;
                            while ($row = mysqli_fetch_assoc($result)) {
                                $row_number ++;
                            ?>
                                <tr>
                                <th scope="row"><?php echo $row_number;?></th>
                                <td><?php echo $row['codice'];?></td>
                                <td><?php echo $row['descrizione'];?></td>
                                <td><?php echo $row['prezzo'];?></td>
                                <td><?php echo $row['barcode'];?></td>
                                <td><?php echo $row['data_creazione'];?></td>
                                </tr>
                            <?php
                            }
                        }


                    }elseif($_POST['barcode']){
                        $barcode = $_POST['barcode'];
                        $sql = "SELECT * FROM prodotti WHERE barcode = ". $barcode;
                        $result = $mysqli->query($sql);
                        if($result->num_rows > 0){
                            $row_number = 0;
                            while ($row = mysqli_fetch_assoc($result)) {
                                $row_number ++;
                            ?>
                                <tr>
                                <th scope="row"><?php echo $row_number;?></th>
                                <td><?php echo $row['codice'];?></td>
                                <td><?php echo $row['descrizione'];?></td>
                                <td><?php echo $row['prezzo'];?></td>
                                <td><?php echo $row['barcode'];?></td>
                                <td><?php echo $row['data_creazione'];?></td>
                                </tr>
                            <?php
                            }
                        }

                    }?>
                        
                        
                    </tbody>
                </table>
           
         


<?php include('footer.php');?>

I really don't understand why.

how can i solve the problem?

the database have a table named "prodotti" with the following colums "id, codice, descrizione, barcode, prezzo, data_creazione"

TypeError: '<' not supported between instances of 'function' and 'int' | Python 3.7.9 tkinter

I´m trying to fix this but I don´t know how. Any advice?

I also tried to convert it with the "def conerter():" but it doesn´t worked out yet..

Error:

TypeError: '<' not supported between instances of 'function' and 'int' 

show´s up the whole time....

from tkinter import *
# ------------------------------------------------------------------------------
#                                   GUI
# ------------------------------------------------------------------------------
main = Tk()
main.title("Faltschachtelrechner")
main.geometry("900x500")
main.configure(background='#FFFFFF')
# --------------------------------------------------------------------------------
#                                   Logic
# --------------------------------------------------------------------------------
def converter():
    try:
        int(nenngewicht.get())
        answer.config(text="true")
        
    except ValueError:
        answer.config(text="false")

#Input Nenngewicht
nenngewicht = Entry(main)
nenngewicht.pack(pady=10)


if converter < 100 or converter > 1000:
    fpvo = 0
if fpvo == 0:
    fpvo = 2

How can I change the values of one column using the values of another column or row in R? [duplicate]

I want to change the category value to "z" when the id = 3,4,9 or do the same thing using row number. How can I do it? Something like if rownumber = 3,4,9 then change to category = "z" or if id = 3,4,9 then change the category to "z"

id <- [1:10]
category <- rep(c("x","y"), times = 5)
df <- data.frame(id, category)
print (df)

   id category
1  1  x
2  2  y
3  3  x
4  4  y
5  5  x
6  6  y
7  7  x
8  8  y
9  9  x
10 10 y
I want to get this output
   id category
1  1  x
2  2  y
3  3  z
4  4  z
5  5  x
6  6  y
7  7  x
8  8  y
9  9  z
10 10 y

Python - reduce number of if statements

I am filtering a pandas dataframe based on one or more conditions, like so:

def filter_dataframe(dataframe, position=None, team_id=None, home=None, window=None, min_games=0):
        
        df = dataframe.copy()

        if position:
            df = df[df['posicao_id'] == position] 
        
        if clube_id:
            df = df[df['team_id'] == team_id]
        
        if home:
            if home == 'home':
                df = df[df['home_dummy'] == 1.0]
            elif home == 'away':
                df = df[df['home_dummy'] == 0.0]
        
        if window:
            df = df[df['round_id'].between(1, window)]
        
        if min_games:
            df = df[df['games_num'] >= min_games]

        return df

But I don't think this is elegant.

Is there a simpler way of achieving the same result?

I though of creating rules for conditions like in this SO answer and then use the method any(rules) in order to apply the filtering, if any, but I don't know how to approach this. Any ideas?

Two if statements in a switch in Java. Only one If works when approached

I am pretty new to development and I have a question. I have a program and I want two conditions with if statements. b, t and c, t. Case 1 works, Case two only the part up to sm(); works

System.out.println("lots of text.");
        System.out.println("1. I want x");
        System.out.println("2. I want z");
        choice = myScanner.nextInt();
            switch (choice) {
                case 1:
                    System.out.println("lots of text");
                        k(); 
                        break;
                case 2:
                    System.out.println ("lots of text3");
                        if (b == 1){
                        System.out.println ("lots of text4");
                        t=1;
                        b--;
                         System.out.println("1: go");
                      choice = myScanner.nextInt();
                      sm();
                        }
                        if ( c == 1){
                        System.out.println ("lots of text5");
                        t=1;
                 choice = myScanner.nextInt();
                System.out.println("1: go ");
                    sm(); 
                    break;
                }
             }
        }
}

k and sm are public voids in the program. The program should jump to either one of them them if either b=1 or c=1. Never will both equal 1. Only one of them should get triggered when approaching this part of the code. However, the problem is if(c==1) is never getting triggered. The program just stops at System.out.println ("lots of text3"); It does though work perfectly fine when b==1. Then the program goes to sm();

Any ideas? I checked and c will equal 1 prior to approaching this part of the code.

Thanks in advance.

IF/Else statements with web scraping python

I am currently trying to scrape the amount of snow from a (saved) weather forecast page, the page is from weather underground, which is okay to scrape. Unfortunately the amount of precipitation and the type of precipitation are in two separate lines so I am trying to write and if/else statement that takes the list of types of precipitation I scrapped and if the type of precipitation is "Snow" than it will scrape and append the amount of precipitation to another list. My issue isn't so much the scrapping part as I have found the appropriate nodes/code to create full individual lists for both, but I don't know the correct syntax for how to append a value to a list, given an index position in a different list.

My code is as followed:

# To obtain the list of precipitation types:

[IN]:
precip = []
i = 0

for n in range(0,10):
    precip.append(forcastfun.find_all('div', {'class':'obs-precip'})[n].find('title').get_text())
    i += 1

print(precip)

[OUT]:
['Precip', 'Precip', 'Precip', 'Precip', 'Precip', 'Precip', 'Precip', 'Snow', 'Snow', 'Precip']

# Now I want to iterate through this list and any position it says snow, I then want it to scrape the amount of precipitation for that position and append it to a new list so far I have

[IN]:
amt = [ ]
i = 0

for n in precip:
     if n == "Snow"
     amt.append(forcastfun.find_all('div', {'class':'obs-precip'})[n].find('span', {"_ngcontent-app-root-c236":""}).get_text())
     i  +=0

[OUT]:

TypeError: list indices must be integers or slices, not str

Can someone help me correct this so that the the statement will go ahead and get the amount of snow for index position 7 and 8? As this is meant to work for any time I scrape the forecast.

Thank you

IF definitely doesn’t wok,

no one help me with this: Writing text and DarkMode don’t work together. So... I found a bug. But I don’t know, how I solve it. Please, if I complete if (dmTheme === detect), TypeWriting text doesn’t work. If I left there if (dmTheme === ) so if doesn’t work, but TypeWriting text yes. What of this little bit of darkMode code attack on TypeWritter?

window.onload = function checkCookie() {
  var dmTheme = getCookie("darkmode");
  var detect = "active";
  if (dmTheme === detect) {
   console.log("Darkmode is " + dmTheme);
   $("#switching").prop("checked", true);
   darkMode();
   $("#switching").prop("checked", true);
  } else {
    console.log("Darkmode is " + dmTheme);
    $("#switching").prop("checked", false);
  }
}
    var TxtType = function(el, toRotate, period) {
        this.toRotate = toRotate;
        this.el = el;
        this.loopNum = 0;
        this.period = parseInt(period, 10) || 2000;
        this.txt = '';
        this.tick();
        this.isDeleting = false;
    };

    TxtType.prototype.tick = function() {
        var i = this.loopNum % this.toRotate.length;
        var fullTxt = this.toRotate[i];

        if (this.isDeleting) {
        this.txt = fullTxt.substring(0, this.txt.length - 1);
        } else {
        this.txt = fullTxt.substring(0, this.txt.length + 1);
        }

        this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';

        var that = this;
        var delta = 200 - Math.random() * 100;

        if (this.isDeleting) { delta /= 2; }

        if (!this.isDeleting && this.txt === fullTxt) {
        delta = this.period;
        this.isDeleting = true;
        } else if (this.isDeleting && this.txt === '') {
        this.isDeleting = false;
        this.loopNum++;
        delta = 500;
        }

        setTimeout(function() {
        that.tick();
        }, delta);
    };

    window.onload = function() {
        var elements = document.getElementsByClassName('typewrite');
        for (var i=0; i<elements.length; i++) {
            var toRotate = elements[i].getAttribute('data-type');
            var period = elements[i].getAttribute('data-period');
            if (toRotate) {
              new TxtType(elements[i], JSON.parse(toRotate), period);
            }
        }
        
        var css = document.createElement("style");
        css.type = "text/css";
        css.innerHTML = ".typewrite > .wrap { border-right: 0.08em solid #fff}";
        document.body.appendChild(css);
    };

My if statement is false but it does print the end

x = 5
print('Before 5')
if x > 5:
    print('Is 5')
    print('Is still 5')
    print('Third 5')
    print('Afterwards 5')
    print('Before 6')
if x == 6:
    print('Is 6')
    print('Is still 6')
    print('Third 6')
print('Afterwards 6')

so the beginning its wrong I'm expecting to print only Print('Before 5')print('Afterwards 5') and print('Before 6') but it doesnt, only prints the print('Before 5') and stops. Also I tried by deleting the space so they are not on the same line with true statement and this is my result:

line 9 if x == 6: IndentationError: unexpected indent

Im learning by myself and this is my first time learning a programming language, its so fun but im having a hard time solving this :D Thank you.

IF Formula to compare a date to a nominated date in the future in excel

In one cell I want a date ie: 31/03/21 I want the formula to be able to check that date and when it is X years so 31/03/2023 it can either colour code the box or mark as overdue I've seen this answer: Excel - Want to compare a projected date against a target date

But, this would mean we would have to put in the sheet for 1 year 365 days, 2 years - 730 days e.t.c . Is that the only way to do it or can you do some way for just year, two years etc...?

For some context, I work for a volunteer organization and all volunteers have to do various trainings every X amount of years. So, looking for an easy way to put them on a sheet with the training and have it colour change/highlight/mark as overdue when they come up every few years or so.

Much thanks

Second if statement being treated like else [closed]

I'm very new to Python 2 and am using only the most basic of code to try and make a simple text based game. I've made a few if/else statements where you have to type in one specific thing to go further or it will say it doesn't understand and prompt you to type the action again, and those work well. Now I'm trying to present two options that you can choose from, where either action will lead to a different part of the game, but the code is only checking to see if the first if statement is correct and leading directly to the else if it isn't, even if the action typed fits the second if statement correctly. It's just being skipped over in favor of the else for some reason and I'm too much of a newbie to understand why. I've also tried to have the second statement be ifel, and that hasn't worked either.

Here's the code:

def bedroom():
   # Bedroom after intro
   print """
   You step back into the bedroom. The moon still shines brightly through your window, illuminating the
   otherwise dark space.
   
   There is a nightstand next to the bed, and there are two doors leading out of the room. One goes out to the main
   part of the house, and the other leads to the master bathroom."""
   players_guess = raw_input(action).lower()
   while True:
       if players_guess == "go to main part of house":
           main_house()
           break
       if players_guess == "go to bathroom":
           bathroom_post_mirror()
           break
       else:
           print "I'm sorry, I don't understand that."
           players_guess = raw_input(action).lower()

multiple conditions if statement not working python [closed]

I have tried multiple ways to write the multiple if statement, and when I run the code it just seems like python skips over it. it gives me no errors and the code says it was completed successfully

print("1. Yes")
print("2. No")
more = input("would you like multiple words in your output? (1 or 2): ")

print("1. Yes")
print("2. No")
oi = int(input("would you like special characters? (1 or 2): "))

if ((more== 2) and (oi== 1)):
  f = (int(val)//100)
  d = (f - 2)
#dont mind the part at the bottom, the whole thing was to long to paste after the "if statement"

and it just seems to skip over the code

Python Dataframe Conditional If Statement Using pd.np.where Erroring Out

I have the following dataframe:

count   country year    age_group   gender  type
7       Albania 2006    014         f       ep
1       Albania 2007    014         f       ep
3       Albania 2008    014         f       ep
2       Albania 2009    014         f       ep
2       Albania 2010    014         f       ep

I'm trying to make adjustments to the "gender" column so that 'f' becomes 'female' and same for m and male.

I tried the following code:

who3['gender'] = pd.np.where(who3['gender'] == 'f', "female")

But it gives me this error:

enter image description here

Now when I try this code:

who3['gender'] = pd.np.where(who3['gender'] == 'f', "female", 
                 pd.np.where(who3['gender'] == 'm', "male"))

I get error below:

enter image description here

What am I doing wrong?

How can I combine these two if statements?

Here're two if statements I have (using Python):

if eval0 < eval1 and (theta/pi)%4 < 2:
    gamma *= (-1)
elif eval0 > eval1 and (theta/pi + 2)%4 < 2:
    gamma *= (-1)

I'm trying to shorten the code, so one way I can think of is

if (eval0 < eval1 and (theta/pi)%4 < 2) or (eval0 > eval1 and (theta/pi + 2)%4 < 2):
    gamma *= (-1)

Is there a better way I can do that? Thanks!!

Adding variable 'flag' if user choses that unit javascript

I have a function where I need to add a second variable that checks if a user selected that unit. If not the code runs the second if statement.

I want my function to check that and be able to let the user change the unit as well. For example if we have the number 3,000 the user can change that number to 3K. If we have the number 3,000,000 the user can change it to 3M.

How can I accomplish that with my current code?

function Formatting (num, flag) {
    if (num >= 1000000000 && flag === 'G') {
       return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
    }
    if (num >= 1000000 && flag === 'M') {
       return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
    }
    if (num >= 1000 && flag === 'K') {
       return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
    }
    return num;
}

Change column values when specific condition is satisfied

I have the problem following on which I'm thinking for a while and cannot figure out the solution.

Let's consider some artificial data frame and it's 0.9 and 0.1 quantiles:

set.seed(42)
x = data.frame("Norm" = rnorm(100),
               "Unif" = runif(100),
               "Exp" = rexp(100))

quants_b <- apply(x, 2, quantile, 0.90)
quants_s <- apply(x, 2, quantile, 0.10)

What I want to do in this data frame is to check which values are bigger than its corresponding quantile 0.9 and less than corresponding quantile 0.1 and changed all those values to the limits.

In simpler words:

I want to check which values exceed 0.9 quantile and all those values transform to 0.9 quantile

and I want to do the same with 0.1 quantile.

Troublesomeness of the problem

This problem in my opinion looks very easy at the first sight, however it has one trap - we have to do the transformation in the same time, because if we firstly change the upper bound and then lower, between the transformation quantiles can change.

(Please notice that we want to replace first variable with element of quants_s and quants_b, second with second and so on).

My ideas

My first idea was to use dplyr package and a function mutate_all within it.

x %>% dplyr::mutate_all(
  function(x) {
    ifelse(sweep(x, 2,STATS=quants_s, `<`), quants_s,
           ifelse(sweep(x, 2,STATS=quants_b, `>`), 
                 quants_b, x)
    )
  }
)

This code intuitively is very simple - we just change all values which are lower than quants_s with quants_s, and those which are bigger than quants_b with quants_b. Remaining data stays the same. However I got error following and I'm not sure how to omit it:

Error: Problem with `mutate()` input `Norm`.
x 'dims' cannot be of length 0
i Input `Norm` is `(function (x) ...`.
Run `rlang::last_error()` to see where the error occurred.

Could you please give me a hand solving the problem/pointing another solution ?

Fastest way to get values from dictionary to another dictionary in python without using if?

I need to find a way to get values from one dictionary to another, bases on key name match without using two loops \ if statement.

Main goal is to make it run more efficiently since it's a part of a larger code and run on multiple threads.

If you can keep the dictionary structure it would help

The second dict is initialized with values 0 in advanced

dict_1 = {
    "school": {
        "main": ["first_key"]
    },
    "specific": {
        "students": [
            {
                "name": "sam",
                "age": 13
            },
            {
                "name": "dan",
                "age": 9
            },
            {
                "name": "david",
                "age": 20
            },
            {
                "name": "mike",
                "age": 5
            }
        ],
        "total_students": 4
    }
}

dict_2 = {'sam': 0, 'mike': 0, 'david': 0, 'dan': 0, 'total_students': 0}

for i in dict_1["specific"]['students']:
    for x in dict_2:
        if x == i["name"]:
            dict_2[x] = i["age"]

    dict_2["total_students"] = dict_1["specific"]["total_students"]

print(dict_2)

Is there more elegant way of doing it?

Thanks!!

discord.py SyntaxError: 'await' outside function

When I try to run the command I always get this error message: SyntaxError: 'await' outside function Very simple mistake probably, but I really don't see the mistake in it. Can anyone help?

@commands.command()
    async def unban(ctx, *, member):
        banned_users = await ctx.guild.bans()
        member_name, member_discriminator = member.split('#')

    for ban_entry in banned_users:
        user = ban_entry.user

    if (user.name, user.discriminator) == (member_name, member_discriminator):
        await ctx.guild.unban(user)
        await ctx.send(f'Unbanned {user.mention}')
    return

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.unban' raised an error: SyntaxError: 'await' outside function (unban.py, line 20)

list understanding and recursive if statements in Haskell

I'm currently practicing Haskell in a number of ways. using lists to create a ton of fun things. Now I'm (think) having problems with understanding if statements.

What I want to do is make a Focuslist that shifts the focus to the most left item. Focuslists are already quite tricky, essentially being two independent lists. And it also splits the whole list in half, and reverses the back list.

For instance. If you want to make a focuslist of [0,1,2,3,4,5], and want a focus on 3, The focuslist will be [3,4,5][2,1,0].

I've already made three specific functions. One that makes the focuslist datatype:

data FocusList a = FocusList { forward :: [a], backward :: [a]}

With which you can call it by using

fromList :: [a] -> FocusList a
fromList list = FocusList list []

One that changes it back to a list from a focuslist:

toList :: FocusList a -> [a] 
toList (FocusList fw bw) = reverse bw ++ fw

and one that shifts it to left once, changes [0,1,2,3,4,5] to [0,1,2,3,4,5] which now looks like [2,3,4,5][0,1] as focuslist:

goLeft :: FocusList a -> FocusList a
goLeft (FocusList fw (f:bw)) = FocusList (f:fw) bw

Now, to the main point. If I were to shift it all the way to the left. I want to use goLeft until the length of the list is 1. I was thinking of using a recursive if statement until the length of the first list equals to one. and using goLeft if it was not one.

So i thought of a simple if statement. Which (for now) doesn't work at all. it uses leftMost :: FocusList a -> FocusList a

leftMost (FocusList fw (f:bw)) =  if (length (FocusList fw) == 1)
                                    then FocusList (f:fw) bw
                                    return leftMost
                                   else FocusList fw (f:bw)

I was thinking of it the pythonic way. Which doesn't seem to work. How do I make it logically recursive?

How to write a loop for a dataframe with multiple conditions in R?

I have a dataframe with dates (2014-01-01 - 2021-02-04), hours (0 - 23) and electricity prices.

dataframe

With this data I need to go over each day, find highest and lowest prices and their maximum differences in that day and then collect the dates in which the differences are big enough. I also have another variable nr_hours (number of hours) which can be 1, 2, 3, 4 or 5. If nr_hours is 2, then I need to find 2 lowest and 2 highest prices and keep in mind that the lower prices need to be before higher prices. The first thing I did was to sort prices in group:

data <- data %>%
  group_by(Date) %>%
  arrange(Price, .by_group = TRUE)

I also wrote down the logic on how the loop should work:

nr_hours = 2  #1, 2, 3, 4, 5
i = 1  #max price row number
j = 24  #min price row number
k = 0  #number of selected hours' prices

#for each date in data$Date:
#-if hours are in descending order and k != nr_hours:
#--TRUE: break
#--FALSE: if k == nr_hours:
#---TRUE: next date
#---FALSE: if i row hour <= (max hour - 1):
#----FALSE: i += 1 and move back to the first if
#----TRUE: if j row hour >= (min hour + 1):
#-----FALSE: j -= 1 and move back to the first if
#-----TRUE: if i row hour < j row hour:
#------TRUE: choose i and j row prices, remove these rows and move back to the first if with k += 1, i = 1 and j = 24-2k
#------FALSE: if (i+1) and i row price difference < j and (j-1) row difference:
#-------TRUE: i += 1 and move back to the first if
#-------FALSE: if (i+1) row price < (j-1) row price:
#--------TRUE: j -= 1 and move back to the first if
#--------FALSE: i += 1 and j = 24-2k and move back to the first if

How to write this in R?

If statement not running user input properly [duplicate]

When I run the below code it only runs the if statement even if the user input is "Good" or "Fantastic". I am not sure why the code is only running one of the functions. Any help would be appreciated!!

#Want to calculate the tip. Take the users input of the amount of the bill and then have 3 options for tips: ok service - 18%, good service - 20%, and fantastic service - 25%. Then add that to the bill. 

Ok_Service = 0.18
Good_Service = 0.20
Fantastic_Service = 0.25 

bill = int(input("How much did the dinner cost?"))

service = input("How was the service?")

if service == "Ok" or "ok":
  tip_ok = bill*Ok_Service
  print("The tip is", tip_ok)
  print("Your total bill is", bill+tip_ok)
elif service == "Good" or "good":
  tip_good = bill*Good_Service
  print("The tip is", tip_good)
  print("Your total bill is", bill+tip_good)
elif service == "Fantastic" or "fantstasitc":
  tip_fantastic = bill*Fantastic_Service
  print("The tip is", tip_fantastic)
  print("Your total bill is", bill+tip_fantastic)
else:
  print("I can't calculate the tip.")

python variant is not defined in ' if ' behind ' for ' [closed]

I am trying to load a pretained checkpoint to my own network

net.load_state_dict(checkpoint)

net_dict = net.state_dict() # the load in checkpoint
model_dict = model.state.dict() # the own network model

new_state_dict = {k:v for k, v in net_dict.items() if k in model_dict}

but it returns *** NameError: name 'model_dict' is not defined

I feel quite confused because I do define the model_dict

so I try:

'model_dict' in dir()
return: True

and

{k:v for k, v in net_dict.items() if 'model_dict' in dir()}
return: {}

which means 'model_dict' in dir() returns False in this situation.

Why this happens? What should I do to get k in model_dict?

Iterate and return based on priority - Python 3

I have a df with multiple rows. What I need is to check for a specific value in a column's value and return if there is a matching. I have a set of rules, which takes priority based on order.

My Sample df:

                           file_name    fil_name
0   02qbhIPSYiHmV_sample_file-MR-job1   02qbhIPSYiHmV
1   02qbhIPSYiHmV_sample_file-MC-job2   02qbhIPSYiHmV
2   02qbhIPSYiHmV_sample_file-job3      02qbhIPSYiHmV

For me MC takes the first priority. If MC is present in file_name value, take that record. If MC is not there, then take the record that has MR in it. If no MC or MR, then just take what ever is there in my case just the third row.

I came up with a function like this,

def choose_best_record(df_t):
    file_names = df_t['file_name']
    
    for idx, fn in enumerate(file_names):
        lw_fn = fn.lower()
        if '-mc-' in lw_fn:
            get_mc_row = df_t.iloc[idx:idx+1]
            print("Returning MC row")
            return get_mc_row
            
        else:
            if '-mr-' in lw_fn:
                get_mr_row = df_t.iloc[idx:idx+1]
                print('Returning MR row')
                return get_mr_row
            else:
                normal_row = df_t.iloc[idx:idx+1]
                print('Reutrning normal row')
                return normal_row

However, this does not behave the way I want. I need MC (row index 1), instead, it returns MR row.

If I have my rows in the dataframe in order like this, ...file-MR-job1, ...file-MR-job1, ....file-MR-job1, then it works. How can I change my function to work based on how I need my out put?

lundi 29 mars 2021

Comparison of 3 values? in IF,ELIF

I have school assign about IF,ELIF(and new to this web).Actually its quiet simple,but im a bit confuse because this is my first time dealing with if,i found 3 ways to type the code,

score=int(input('Insert score : ')
if 100 >= score >= 81 :
    print('A')
elif 80 >= score >= 61 :
    print('B')
else : 
    print('C')
print()


----------
score=int(input('Insert score : ')
if 100 >= score and score >= 81 :
    print('A')
elif 80 >= score and score >= 61 :
    print('B')
else : 
    print('C')


----------
score=int(input('Insert score : ')
if 100 >= score :
    print('A')
elif 80 >= score:
    print('B')
else : 
    print('C')

Someone told me that the first one is wrong,Why is it wrong? And well the third one is more efficient,but i just dont know why the first one is wrong. Which code is better and i should use?

Find Date in Data Frame in R

I'm trying to use a list of dates to find the same date in a data frame and using ifelse loop to add a new column. Here is the code:

library(lubridate)
df <- tibble(DateCol = seq(ymd("2021-01-01"),ymd("2021-05-31"),"days"))

df2 <- c("2021-02-04","2021-02-07","2021-02-17","2021-02-25")

for (i in 1:length(df$DateCol)) {
  if (df$DateCol[i] == df2) {
    df$ValueCol[i] <- "1"
    } else {
      df$ValueCol[i] <- "0"
      return(i)
    }
  }

The final df I get only has the first date of df2 is 1 in df$ValueCol. Not sure how to make this loop work, seems like there are some mistakes in the df$DateCol[i] == df2 part.

Why does pipe inside if() function fail when first argument is referred with a '.'

I spent 45 mins to get a very simple if() inside a loop to work, but I want to understand why it was failing in the first place.

It's a simple R Magrittr pipe chain with a if() condition in braces {}

Here's the simplified reprex (reproducible example)

library(tidyverse) # load tidyverse library

# function to check the data type of a column

# Fails
check1 <- function(.df, .colm)
{
  .df %>%
     { if(. %>% pull(var = ) %>% is.character()) 1 else 2} # pull .colm from .df and check if is char

}

# Works
check2 <- function(.df, .colm)
{
  .df %>%
    {if(pull(., var = ) %>% is.character()) 1 else 2} # pull .colm from .df and check if is char
  
}

check1(a, a1) # Fails
#> Error in eval(lhs, parent, parent): object 'a' not found
check2(a, a1) # Works
#> Error in eval(lhs, parent, parent): object 'a' not found

Created on 2021-03-29 by the reprex package (v0.3.0)

Also do let me know if there's a simpler way to do what I'm trying to do

Remove a string from certain column values and then operate them Pandas

I have a dataframe with a column named months (as bellow), but it contains some vales passed as "x years". So I want to remove the word "years" and multiplicate them for 12 so all column is consistent.

index  months
1        5
2        7
3        3 years
3        9 
4        10 years

I tried with

if df['months'].str.contains("years")==True:
  
   df['df'].str.rstrip('years').astype(float) * 12

But it's not working

Nested ifelse statement with multiple selection criteria

YDST Year
0 2020
1 2020
2 2020
3 2020
4 2020
5 2020
6 2020
7 2020
8 2020
9 2020
10 2020
0 2021
1 2021
2 2021
3 2021
4 2021
5 2021
6 2021
7 2021
8 2021
9 2021
10 2021

I have a data frame ('df') where I want to create a new column ('Students') where 'ns' indicates no students and 's' indicates students. However where 'ns' and 's' occur differs between years based on 'YDST'. For instance, in 2020 'ns' should be indicated from 0-3 and 9-10. In 2021, 'ns' should be indicated from '1-4', '6-7', and '9-10'.

How can I write a nested ifelse statement to not only account for 'Year', but also the different 'YDST' selection criteria between years?

Thank you!

Insert row and copy formula only from cell below

This should be easy but I haven't done this in so long I'm struggling with the elements.

I need to insert a new row in A21. I need the formulas ONLY to be copied up into the new row. The below is copying values also. Its making me crazy. I'll need it to repeat three times.

Sub NewData()

' NewData Macro
' Inserts rows and copies formulas up.

' Keyboard Shortcut: Ctrl+d



Range("A21").EntireRow.Insert

Range("A22").EntireRow.Copy
Range("A21").PasteSpecial xlPasteFormulas
Application.CutCopyMode = False

End Sub

I considered a loop but that was a struggle also. The data only goes to column T.

How to save an empty variable in the condition so that it does not omit a line in the statement but continues next?

How can I achieve that if the condition stores an 'empty' variable else continues in code? So as not to miss a line

The code goes through the cycle and gradually prints according to the condition

if frst==1:
    variable=''
else:
 variable= #code something

my output

-7 2 0
-8 3 0 

10 11 -12 13 0

line spacing is my variable

required output

-7 2 0
-8 3 0 
10 11 -12 13 0

I need it to be stored in the variable so as not to leave a space. Is there a way to solve this?

using elif to print whether a user has visited more than 2 continents but less than 6

the program says to print a response if the user has visited more than 2 continents but less than 6

continents = int(input("How many continents have you visited? "))

if continents >= 2:
    print("you've visited more than 2 continents.")
elif continents <= 6:
    print("you've visited less than 6 continents.")

I have this if statement, however it is not reaching the print, why? [duplicate]

I have this code:

    first_command = "moved"
    second_command = "moved"
    third_command = "moved"

    if first_command == second_command == third_command == "moved":
       print("Same")

I don't get an error but it doesn't print "Same". any ideas why? Thanks

C program that prints out the non repeated number in an array using break statement

so I was searching about a program that prints out the non repeated numbers in an array, the program is completely fine but I can't understand what exactly happens in the break statement part so can someone please explains what happens because I can't get it, here is the code down below.

#include<stdio.h>
int main(void){

int n;
printf("enter a value for n: ");
scanf("%d",&n);
int T[n];
int j;  
printf("fill in the array: \n");
for(int i=0 ; i<n ; i++)
{
    printf("enter value %d: ",i+1);
    scanf("%d",&T[i]);
}   
for(int i=0 ; i<n ; i++)
{
    printf("%d ",T[i]);
}


//---------------------------------------------------------------------//

        
printf("the non repeated elements are: \n");
for(int i=0 ; i<n ; i++)
{
    for( j=0 ; j<n ; j++)
    {
        if(T[i]==T[j] && i!=j)
        {
            break;
        }
            
            
    }
    if(j==n)
    {       
    printf("%d ",T[i]);         
    }
}   
return 0;
}

JavaScript Object Array: Removing objects with duplicate properties. same conditions have different output

I am trying to remove an object from an array if the age property matches using the below codes.

 var state= [
    {name: "Nityanand", age:23},
    {name: "Mohit", age:25},
    {name: "Nityanand", age:25}
  ]
  
  
 let a= [...state];
 var ids=[]

 var ar = a.filter(function(o) {
    
        if (ids.indexOf(o.age) !== -1){
        return false;
        }
        
        else if(ids.indexOf(o.age) === -1){
        ids.push(o);
        return true;}
})
console.log(ids)

    // OUTPUT: (NOT working fine)
    {name: "Nityanand", age:23},
    {name: "Mohit", age:25},
    {name: "Nityanand", age:25}

But if I edit the code by pushing only one property in the array, it is working fine:

 var state= [
    {name: "Nityanand", age:23},
    {name: "Mohit", age:25},
    {name: "Nityanand", age:25}
  ]
  
  
 let a= [...state];
 var ids=[]

 var ar = a.filter(function(o) {
    
        if (ids.indexOf(o.age) !== -1){
        return false;
        }
        
        else if(ids.indexOf(o.age) === -1){
        ids.push(o.age); // Here i have edited the code by pushing only age property to the array
        return true;}
})
console.log(ids)

OUTPUT : [23, 25] // Only two items were added.

There is no difference in the Conditions but in the first code's output 3 items were added in the empty array while in the second code only 2 items get added. How is this possible?

If Statements Activating Without The Condition Being Met

The Input Thing Works Fine but The If Statements All Activate when They DONT EVEN MEET the If Statement. Can Anyone Help

https://i.stack.imgur.com/ng4N6.png

Why is Perl giving "Can't modify string in scalar output" error?

I'm pretty new to Perl and this is my most complex project yet. Apologies if any parts of my explanation don't make sense or I miss something out - I'll be happy to provide further clarification. It's only one line of code that's causing me an issue.

The Aim:

I have a text file that contains a single column of data. It reads like this:

0
a,a,b,a
b,b,b,a
1
a,b,b,a
b,b,b,a

It continues like this with a number in ascending order up to 15, and the following two lines after each number are a combination of four a's or b's separated by commas. I have tied this file to an array @diplo so I can specify specific lines of it.

I also have got a file that contains two columns of data with headers that I have converted into a hash of arrays (with each of the two columns being an array). The name of the hash is $lookup and the array names are the names of the headings. The actual arrays only start from the first value in each column that isn't a heading. This file looks like this:

haplo           frequency
"|5,a,b,a,a|"   0.202493719
"|2,b,b,b,a|"   0.161139191
"|3,b,b,b,a|"   0.132602458

This file contains all of the possible combinations of a or b at the four positions combined with all numbers 0-14 and their associated frequencies. In other words, it includes all possible combinations from "|0,a,a,a,a|" followed be "|1,a,a,a,a|" through to "|13,b,b,b,b|" and "|14,b,b,b,b|".

I want my Perl code to go through each of the combinations of letters in @diplo starting with a,a,b,a and record the frequency associated with the row of the haplo array containing each number from 0-14, e.g. first recording the frequency associated with "|0,a,a,b,a|" then "|1,a,a,b,a|" etc.

The output would hopefully look like this:

0   #this is the number in the @diplo file and they increase in order from 0 up to 15
0.011     0.0023    0.003    0.0532    0.163    0.3421    0.128    0.0972    0.0869    0.05514    0.0219    0.0172    0.00824    0.00886    0.00196 #these are the frequencies associated with x,a,a,b,a where x is any number from 0 to 14.

My code: And here is the Perl code I created to hopefully sort this out (there is more to create the arrays and such which I can post if required, but I didn't want to post a load of code if it isn't necessary):

my $irow=1;   #this is the row/element number in @diplo
my $lrow=0;      #this is the row/element in $lookup{'haplo'}
my $copynumber=0;
#print "$copynumber,$diplo[2]";
while ($irow<$diplolines-1) {
while ($copynumber<15) {
while ($lrow<$uplines-1) {
if ("|$copynumber,$diplo[$irow]|" = $lookup{'haplo'}[$lrow]) {  ##this is the only line that causes errors
if ($copynumber==0) {
print "$diplo[$irow-1]\n"; 
#print "$lookup{'frequency'}[$lrow]\t";
}
print "$lookup{'frequency'}[$lrow]\t"; 
}
$lrow=$lrow+1;
}
$lrow=0;
$copynumber=$copynumber+1;
}
$lrow=0;
$copynumber=0;
$irow=$irow+1;
}

However, the line if ("|$copynumber,$diplo[$irow]|" = $lookup{'haplo'}[$lrow]) is causing an error Can't modify string in scalar assignment near "]) ". I have tried adding in speech marks, rounded brackets and apostrophes around various elements in this line but I still get some sort of variant on this error. I'm not sure how to get around this error.

Apologies for the long question, any help would be appreciated.

Write an if statement for a list element in Pandas dataframe cell

I have a Pandas dataframe with a column "genres" which contains a list as cell value:

import pandas
df = pd.DataFrame([
{
    "title": "The Godfather: Part II",
    "genres": ["crime", "drama"],
    "director": "Fracis Ford Coppola"
},
{
    "title": "The Dark Knight",
    "genres": ["actionmovie", "crime", "drama"],
    "director": "Christopher Nolan"
}
])

I'm trying to write an if statement to add a column "action_crime_movie" with values True or False based on matching parts of the string elements in the genres list. In other words: the 2nd line contains the word "action" (in "actionmovie") and "crime" (in "crime") so it should have the value True for "action_crime_movie".

if ("action", "crime") in df["genres"]: df["action_crime_movie"] = True
else df["action_crime_movie"] = False

However, with the above query the value was set to False...

Could anyone help me solve this issue?

OPL CPLEX If statement usage with boolean

I'm a beginner user of CPLEX OPL. Here is my piece of code:

forall(e in employee, d in day:1<=d<=19, t in task, p in period) (x[e][d][p][t]==0)=>(x[e][d+7][p][t]+x[e][d+8][p][t]+x[e][d+9][p][t]==2);

x[e][d][p][t] is a boolean decision variable. This is a small part of code. Is it okay to write a code like this structure?

I appreciate if you would help me. Have a nice day for all.

Alternative to IF Statement for deletion

I have the following script running in a SSIS Execute SQL Task which is taking exceptionally long to execute :

DECLARE @Year int
DECLARE @Month int

SET @Year = YEAR(GETDATE())
SET @Month = MONTH(GETDATE())

IF @Month IN (1,2,3,4,5,6,7,8,9)
 BEGIN

  SET @Year = @Year-1

  DELETE FROM GLYTDMovement 
  WHERE CGYear >= @Year
   AND Entity NOT LIKE 'TT%'

 END
ELSE
 BEGIN

  SET @Year = @Year

  DELETE FROM GLYTDMovement 
  WHERE CGYear >= @Year
   AND Entity NOT LIKE 'TT%'

 END

Any advise on how to adjust to improve performance?

bind action to if-condition in python [closed]

I'm working with a special python-interpreter (not manipulatable) who converts my python-script A, which is a normal python script with if-conditions, classes, functions usw. into a python-script B, which only consists out of defined functions with absolute values. For example:

Script A

s = 30
x = True
TranslatedFunction("20");
if x:
    TranslatedFunction(s)
TranslatedFunction("40");

This script will be converted into Script B:

TranslatedFunction("20");
TranslatedFunction("30");
TranslatedFunction("40");

As you see, the interpreter goes through the condition and checks if its true, when it is, it will write the TranslatedFunction(s) with the value of s into Script B. I can't change this behaivour. I also can't access the variable x or s.

So far so good. Now, I need to know in script B, where the if-condition in script A was. I could to something like this:

Script A

s = 30
x = True
TranslatedFunction("20");
if x:
    TranslatedFunction("startif")
    TranslatedFunction(s)
    TranslatedFunction("endif")
TranslatedFunction("40");

which will result in:

TranslatedFunction("20");
TranslatedFunction("startif");
TranslatedFunction("30");
TranslatedFunction("endif");
TranslatedFunction("40");

That would be enough to work with (after the translation from script A to script B, I got a postprocessor, which will translate script B in another language). But I don't want to mark the if-conditions everytime. Is there a better way to call a function, or do something, everytime an if-condition starts and ends? And would there be also something for loops?

Update

I'm working with RoboDK. A Program to simulate roboters and generate a roboterprogram out of it.

Thanks.

dimanche 28 mars 2021

java:S1121: "Extract the assignment out of this expression."

I've a big java project given by my teacher for the exam, and analysis with sonarcloud gives me this Code Smell to fix on this function

private long selIsBidAction(boolean isBidAction, long takerReserveBidPrice, DirectOrder makerOrder) {
    if(isBidAction) {
        return takerReserveBidPrice;
    } else {
        return makerOrder.reserveBidPrice;
    }
}

In particular it's about "if(isBidAction)". I thought to put isBidAction=true immediately upon that if to fix this.Could it be a solution?

Rock Paper Scissor Javascript only lets me tie, no matter what I input when invoking the function. I don't understand where I went wrong?

First off: I am sorry for another rock paper scissors JS question.

I do not think I made any errors with syntax and honestly do not comprehend why it always returns "tie" three times in a row, stating that the computer chose the same choice, three times in a row. If I re-run the code it chooses a different choice, but it still repeats three times, despite the user input in the function evocations being different in all three...

const computer = Math.random()

function game(user, computer){
  if (user = "paper" && computer > .66) {
    return console.log("computer chose paper! it's a tie");
  }
  else if (user = "rock" && computer <= .33 && computer <= .66) {
    return console.log("computer chose rock! it's a tie");
  }
  else if (user="scissors" && computer >= .33) {
    return console.log("computer chose scissors! it's a tie");
  }
  /* you lose */
  else if (user = "paper" && computer >= .33) { /*comp scissor */
    return console.log("computer chose scissors! you lose!");
  }
  else if (user = "scissors" && computer <= .33 && computer <= .66) { /* comp rock */
    return console.log("computer chose rock! you lose!");
  }
  else if (user = "rock" && computer > .66) { /* comp paper */
    return console.log("computer chose paper! you lose!");
  }
  /* you win */
  else if (user = "scissors" && computer > .66) { /* comp paper*/
    return console.log("computer chose paper! you win!");
  }
  else if (user = "rock" && computer >= .33) { /* comp scissors */
    return console.log("computer chose scissors! you win!");
  }
  else if (user = "paper" &&  computer <= .33 && computer <= .66) { /*rock */
    return console.log("computer chose rock! you win!");
  }
}

game("paper", computer);
game("rock", computer);
game("scissors", computer);

I know that there are definitely more efficient and different ways of creating this game, but I still want to understand what is wrong with what I did here, and the logic behind it... Thanks in advance. Have a good day.

use comparison operators continuous in c#

Hello my name is parsa and I'm a c# programmer i want to use comparison operators continuous for example imagine we have three Variables named V1,V2,V3 each of them is equal to a random number between 1 and 4 then we want to see are they equal together and are they equal to 3 ? we have to use this code

    if(V1 == V2 && V1 == V3 && V1 == 3)
        //body

if i want to use it such as this this it will be get me a error !

    if(V1 == V2 == V3 == 3)
        //body

can i use it such as code i wrote ?

discord '>' not supported between instances of 'Context' and 'int'

When I try to run the command I always get this error message: "TypeError: '>' not supported between instances of 'Context' and 'int'"

from discord.ext import commands

class clear(commands.Cog):

    def __init__(self, client):
        self.client = client

# Events

    @commands.Cog.listener()
    async def on_ready(self):
        print('Clear modul started')

# Command

    @commands.command()
    async def clear(ctx, amount=5, max=100, min=1):
        if (amount > max):
            await ctx.send(f"The value is too high! Enter a value `{min}-{max}` between.", delete_after=5)
        elif (amount < min):
            await ctx.send(f"The value is too small! Enter a value `{min}-{max}` between.", delete_after=5)
        else: 
            await ctx.channel.purge(limit=amount+1)
            await ctx.send(f"Törölve {amount}", delete_after=5)

def setup(client):
    client.add_cog(clear(client))```

Fading UI text from object Checksphere and interact

I'm trying to come up with a generic rule that I can add to any GameObject. Items like tables, chairs etc that once collided and interacted fade in the white text, then after a few seconds the text fades out.

Ideally I'd be able to offset the position of this text with a Vector3 so I can position it around my character

At the moment I have, some code but the CrossFade.Alpha doesn't seem to work. this might or might not be the best way to go about this, I'm open to new ideas

    using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class Qwerty : MonoBehaviour
{

    public float Radius = 1f;
    public Text TextToUse;
    [SerializeField] private LayerMask playerMask;
    private bool isInSphere;


    // Start is called before the first frame update
    void Start()
    {
        isInSphere = false;
    }

    // Update is called once per frame
    void Update()
    {
        isInSphere = Physics.CheckSphere(transform.position, Radius, playerMask);
        if (isInSphere && Input.GetKey(KeyCode.F) == true)
        {
            // Check if collision is detected and F is pressed
            isInSphere = true;
            Debug.Log("Hello");
            //Fade in over 2 seconds
            TextToUse.CrossFadeAlpha(1, 2f, false);
        }

        else if (!isInSphere && !Input.GetKey(KeyCode.F))

        {
            //Fade out on leave over 2 seconds
            isInSphere = false;
            TextToUse.CrossFadeAlpha(0, 2f, false);
        }

    }
}

Label.Text function not writing result to form design

I am writing a program that calculates total cost for shipping bees here is the code so far:

            if (this.comboBox1.SelectedIndex == 0)
            {
                int VIC = 12;
                if (this.comboBox1.SelectedIndex == 1) ;
                int NT = 15;
                if (this.comboBox1.SelectedIndex == 2) ;
                int ACT = 15;
                if (this.comboBox1.SelectedIndex == 3) ;
                int QLD = 20;
                if (this.comboBox1.SelectedIndex == 4) ;
                int SA = 15;

                if (this.comboBox1.SelectedIndex == 5)
                {
                    int WA = 25;
                    float queen = Convert.ToInt32(textBox1.Text);
                    float worker = Convert.ToInt32(textBox2.Text);
                    float calc1 = queen * 15;
                    double calc2 = worker * 0.05;
                    double calc3 = calc1 + calc2 + WA;
                    label2.Text = "Total cost: $" + calc3;
                }
                else if (this.comboBox1.SelectedIndex == 6)
                {
                    int TAS = 15;
                    float worker = Convert.ToInt32(textBox2.Text);
                    float queen = Convert.ToInt32(textBox2.Text);
                    float calc1 = queen * 15;
                    double calc2 = worker * 0.05;
                    double calc3 = calc1 + calc2 + TAS;
                    label2.Text = "Total cost: $" + calc3;

But when I run the program, use all the text box spaces as intended and select a shipping option from the combo box (one of the two that I have so far written it for) and submit the inputs nothing shows up in label. It stays blank as "Total cost: "(Which it is set as by default in the properties).

I have tried tweaking with the braces and if else statements, that either yields no results (same problem as just described) or the program runs through and executes the code until the last time it sees "label2.Text = "Total cost: $" + calc3;". Which will then display on label2. Which also isn't helpful because if I choose WA which has $25 shipping it will instead display the TAS shipping which is $15.

Python if statement and bitwise operator

I just started a new python project in image segmentation and i run across this line of python code:

if tf.random.uniform(()) &gt; 0.5:

Can someone explain to me what exactly is this line doing? The source of the code can be found here.

How to change values of a column according to some conditions?

I have a data frame named data1.
> data1 <- data.frame(name = c("apple","apple","apple", "pine","pine","pine", 
                                 "apple","apple","apple", "pine","pine","pine"),
                        characters = c("red","green","white","yellow","brown","black",
                                       "big","sweet","small","delicious","medium","ache"))
> data1  
    name characters
1  apple        red
2  apple      green
3  apple      white
4   pine     yellow
5   pine      brown
6   pine      black
7  apple        big
8  apple      sweet
9  apple      small
10  pine  delicious
11  pine     medium
12  pine       ache

And I want to change the values of the name variable according the values of characters column.Just like data2:

> data2
        name characters
1   colapple        red
2   colapple      green
3   colapple      white
4  colorpine     yellow
5  colorpine      brown
6  colorpine      black
7   othapple        big
8   othapple      sweet
9   othapple      small
10   despine  delicious
11   despine     medium
12   despine       ache

How can I realize it?

Unexpected behavior in multiple condition if statement

In the following code, I expect to see yes and no in the output, respectively, but the opposite happens.

>>> if 'a' or 'b' in 'c':
>>>     print('yes')
>>> else:
>>>     print('no')
yes # I expect no

also:

>>> if ('a' or 'b') in 'b':
>>>     print('yes')
>>> else:
>>>     print('no')
no # I expect yes

Why does this happen?

If Else if in Java [duplicate]

Dears, Could you please help me to solve these lines?

import java.util.Scanner;
public class InputOutput {
public static void main(String[] ar) {
Scanner inp = new Scanner(System.in);
System.out.println("Enter User Name");
String UserName=inp.nextLine();
 if (UserName=="Ramsid") {
    System.out.println("This is Admin User");
 }
 else if(UserName=="nv"){
    System.out.println("This is Operator User");
 }
 else if (UserName=="abc") {
    System.out.println("This is Super User");
 }
 else {
    System.out.println("User Not Exist");
      }
 }

I am getting always "User Not Exist"

Solution of Finding nth Ugly Number

Hello I have a question of a solution of LC264- Ugly Number.

Given an integer index, return the index-th ugly number. Ugly number is a positive number whose prime factors only include 2, 3, and/or 5.

A possible solution is at below:


import java.lang.Math;
public class Solution {
    public int GetUglyNumber_Solution(int index) {
        
        if(index<1){
            return 0;
        }
        int i2=0;
        int i3=0;
        int i5=0;
        
        int[]dp=new int[index];
        dp[0]=1;
        for(int ugly=1;ugly<index;ugly++){
            int t2=dp[i2]*2;
            int t3=dp[i3]*3;
            int t5=dp[i5]*5;
            dp[ugly]=Math.min(t2,Math.min(t3,t5));
            if(t2==dp[ugly]){
                i2++;
            }
            if(t3==dp[ugly]){
                i3++;
            }
            if(t5==dp[ugly]){
                i5++;
            }
            
        }
        return dp[index-1];
    }
}

If I change the aforementioned algorithm to below, and remain other parts the same, the result is wrong.

            if(t2==dp[ugly]){
                i2++;
            }else if(t3==dp[ugly]){
                i3++;
            }else{
                i5++;
            }

So I do not understand why I can't use "if-else if-else", instead of using 3 if-judgements? Thanks!

How to check every combination of a word in an if statement in c++? [duplicate]

For example:

std::string word;

std::cout << "Type the word "Play"\n";

std::cin >> word;

Here i need to check if the user typed the right word, in any of his forms (pLaY, PLaY, plaY..etc)

print even and odd numbers

now my code looks like this

!/bin/bash

read INPUT
for number in $(seq 1 $INPUT); do
        if [ $((number%2)) -eq 0 ]
        else [ $((number%2)) -eq 1 ]; then
           echo $number
        fi
done

but then I get the next error

./script.sh: line 6: syntax error near unexpected token `else'
./script.sh: line 6: `        else [ $((number%2)) -eq 1 ]; then'

Python condition to check whether "a"(case sensitive) has appeared more than twice [duplicate]

I want to test whether the letter a appears more than once in my string employee_name.

I have tried this code :

if 2*"a" in employee_name:
    return a

This did not work. What am I doing wrong?

samedi 27 mars 2021

Unwanted run through else/if not loop

This is a small but crucial error because it affects the code where you have to give a specific 'not found message'....but the problem might also lie with the fact that i'm using csv files. In this code I specified that 'not found' must be printed only if the record is not found, but it keeps printing anyways.

CODE

import csv
with open('data.csv','w') as f:
    ans='y'
    while ans=='y':
        s=csv.writer(f)
        g=int(input("Enter GR number:"))
        n=input("Enter name:")
        m=float(input("Enter total marks:"))
        s.writerow([g,n,m])
        print()
        ans=input('Enter more?')
        
with open('data.csv','r') as f:
    print("SEARCHING FOR GR NUMBER")
    print()
    gr=int(input('Enter GR number to search:'))
    s=list(csv.reader(f))
    for i in s:
        if str(gr) in i:
            print(i)
    if str(gr) not in i:
        print('Record not found')

OUTPUT

Enter GR number:234
Enter name:Mia
Enter total marks:80

Enter more?y
Enter GR number:456
Enter name:Mark
Enter total marks:80

Enter more?n
SEARCHING FOR GR NUMBER

Enter GR number to search:234
['234', 'Mia', '80.0']
Record not found

I have even tried other methods to print not found...but the same error occurs anyways lol. Any help appreciated. Thanks!

(JS) If statement calculate lowest variable

I wish to return the lowest value of the 4 variables. These values change all the time and i wish to display the lowest value. My issue; I keep getting [null] as result. I have checked the variables itself one by one, the all have values in them so the problem probably is in my if statement only i cant find out where. I appreciate any and all help ;)

Code:

var FL = $prop('GarySwallowDataPlugin.Leaderboard.Position01.Telemetry.TyresWearFR');
var FR = $prop('GarySwallowDataPlugin.Leaderboard.Position01.Telemetry.TyresWearFR');
var RL = $prop('GarySwallowDataPlugin.Leaderboard.Position01.Telemetry.TyresWearRL');
var RR = $prop('GarySwallowDataPlugin.Leaderboard.Position01.Telemetry.TyresWearRR');

{
   if (FL < FR && FL < RL && FL < RR){var returnValue = 100 - FL + '%';}
   else if (FR < FL && FR < RL && FR < RR){var returnValue = 100 - FR + '%';}
   else if (RL < FR && RL < FL & RL < RR){var returnValue = 100 - RL + '%';}
   else if (RR < FR && RR < RL && RR < FL){var returnValue = 100 - RR + '%';}
}

return returnValue;

Python comparison of tuples inside a list

I have this exercise that requires us to compare two lists of tuples.

The first list (games) has 3 tuples, each one corresponding to a game match, with the names of 2 people.

The second list (results) has also 3 tuples, each one corresponding to the results of each match (ordered with games).

games = [("anna", "ross"), ("manny", "maria"), ("rita", "joel")]
results = [(2, 0), (1, 3), (1, 1)]

The desired output is supposed to be this:

['anna', 'maria', 'TIE']

When both scores for a match are the same, the output 'TIE'.

I tried to solve it with the zip function, but for some reason I can't iterate properly in all the levels of the tuples.

1st try:

lst = []
i = 0
for a, b in zip(games, results):
    if b[i] == max(b):
        lst.append(a[i])
    elif min(b) == max(b):
        lst.append("TIE")
i = i + 1
print(lst)

This returned ['anna', 'rita'], which made me think there was some issue with iterating the list / tuples using b[i].

Then I tried to do this:

lst = []
for i, c in list(zip(games, results)):
    for j, k in i, c:
        if k == max(c):
            lst.append(i[j])
        elif min(c) == max(c):
            lst.append('TIE')
print(lst)

This returned ['maria', 'TIE', 'joel'], so I suppose the issue is not only with the iteration but maybe with the way that I'm making the comparison (using max function to find the highest score).

Can anyone give any tips or hints to help me move forward to the solution? I'm asking only after spending a long time looking for a similar problem online and not being able to find anything that could really help.

Using Loop inside a function with If statement in R

I am learning about function in R recently. I successfully make this function work

check_spot = function(one_spot, cluster_id, marker_gene){
one_spot = sample(glio_spatial@assays$SCT@misc$vst.out$cells_step1, 1)
cluster_id  = sample(as.data.frame(Idents(glioblastoma))[,1], 1)
marker = FindMarkers(glioblastoma, ident.1 = cluster_id)
marker = cbind(gene = rownames(marker), marker)
rownames(marker) = 1:nrow(marker)
marker_gene = sample(marker[,1], 5)
a = as.data.frame(glio_spatial@assays$Spatial@counts)
b = a[one_spot]
b = rename(b,c("count_spot" = all_of(one_spot)))
b = subset(b, b[,1] != 0, )
b = cbind(gene = rownames(b), b)
rownames(b) = 1:nrow(b)
intersection = inner_join(b, marker)
if (marker_gene[1] %in% intersection[1,]) sprintf("The gene %s is a marker gene for the cluster %s and is expressed in the spot %s", marker_gene, cluster_id, one_spot)
else if
     (marker_gene[2] %in% intersection[1,]) sprintf("The gene %s is a marker gene for the cluster %s and is expressed in the spot %s", marker_gene, cluster_id, one_spot)
else if
     (marker_gene[3] %in% intersection[1,]) sprintf("The gene %s is a marker gene for the cluster %s and is expressed in the spot %s", marker_gene, cluster_id, one_spot)
else if
     (marker_gene[4] %in% intersection[1,]) sprintf("The gene %s is a marker gene for the cluster %s and is expressed in the spot %s", marker_gene, cluster_id, one_spot)
else if
     (marker_gene[5] %in% intersection[1,]) sprintf("The gene %s is a marker gene for the cluster %s and is expressed in the spot %s", marker_gene, cluster_id, one_spot)
else
    sprintf("The gene %s is a marker gene for the cluster %s, but not expressed in the spot %s", marker_gene, cluster_id, one_spot)
 }

It will print this: Joining, by = "gene"

'The gene NKD1 is a marker gene for the cluster 8, but not expressed in the spot CTACCCTAAGGTCATA-1'

'The gene RPL8 is a marker gene for the cluster 8, but not expressed in the spot CTACCCTAAGGTCATA-1'

'The gene TSPAN13 is a marker gene for the cluster 8, but not expressed in the spot CTACCCTAAGGTCATA-1'

'The gene HSBP1 is a marker gene for the cluster 8, but not expressed in the spot CTACCCTAAGGTCATA-1'

'The gene BHLHE41 is a marker gene for the cluster 8, but not expressed in the spot CTACCCTAAGGTCATA-1'.

Then, I have tried to make a simpler function for this function using for statement to get more generalise number of samples, I try this

check_spot = function(one_spot, cluster_id, marker_gene){
one_spot = sample(glio_spatial@assays$SCT@misc$vst.out$cells_step1, 1)
cluster_id  = sample(as.data.frame(Idents(glioblastoma))[,1], 1)
marker = FindMarkers(glioblastoma, ident.1 = cluster_id)
marker = cbind(gene = rownames(marker), marker)
rownames(marker) = 1:nrow(marker)
marker_gene = sample(marker[,1], length(marker[,1]))
a = as.data.frame(glio_spatial@assays$Spatial@counts)
b = a[one_spot]
b = rename(b,c("count_spot" = all_of(one_spot)))
b = subset(b, b[,1] != 0, )
b = cbind(gene = rownames(b), b)
rownames(b) = 1:nrow(b)
intersection = inner_join(b, marker)
for (i in 1:length(marker_gene)){
    if (marker_gene[i] %in% intersection[1,]) {sprintf("The gene %s is a marker gene for the cluster %s and is expressed in the spot %s", marker_gene, cluster_id, one_spot)}
    else {sprintf("The gene %s is a marker gene for the cluster %s, but not expressed in the spot %s", marker_gene, cluster_id, one_spot)}
}}

When I call check_spot(), it does not show errors and does not show the output as well. Could please anyone help so I can get the similar result (but ore general, more number of markers) as shown by the first function? Even if I take the sample for marker only 5, it still does not work. Thank you very much.

Mean from a list with a condition in Python

list = [[159.2213, 222.2223, 101.2122]
        [359.2222, 22.2210, 301.2144]]

if list[1][0] < list[0][0]:
    avg = (list[1][0] + list[0][0] - 200)/2
else:
    avg = (list[1][0] + list[0][0] + 200)/2

Hello! I want to do this for every column and output the results in another list.

How to use If with listBox1.SelectedItem to change a picture box

So I want a Listbox and when u press an element in the list box the picture box changes the picture so i have 4 picture boxes behind each other and I want to do

If listBox1.SelectedItem "Flowers" Then
pictureBox1.Show():
pictureBox2.Hide();
pictureBox3.Hide();

but iI keep getting an error I can't use if with selected item help

im using c# winfroms .net frameworks

How to find the longest English Word that can be displayed in a seven segment display?

I was inspired from Tom Scott's Video about seven segment displays (link Below), and set out to find out the longest english word that can be displayed in a seven segment display using python, I am a beginner and the best code I could write was this:

var1=open("c:/Users/Choutisha Banerjee/Desktop/words.txt", "r")
list1=var1.readlines()
list2 = ["g","k","m","q","v","w","x","z"]
longword=" "
for n in list1:
    if len(n)>len(longword):
        for x in n:
         if x in list2:
             continue
    else:
         longword=n
else:
    continue
print(longword)

It is printing the longest word present in the list. It would be a great help if you could inform me about where I went wrong.

(I used a premade list of all english words i.e. words.txt)

Link to Tom's Video: https://youtu.be/zp4BMR88260

link to .py (just in case you need it): https://drive.google.com/file/d/1M78YP67VkqC2Uz3mbQxcqk15vO7mW6Rx/view?usp=sharing

Please Help Thank you.

If statement with Match function in vba

I'm working on collection database, that can be used for sport cards. I'm nearly done with everything, but I have a problem with Match function in VBA. I tried to combine it with If statement, but if the Match function does not giving back a result, then the macro stops. Here is this part of the code:

Dim shortnamee As Integer
Dim ittkeres As Range
    Set ittkeres = Range("X:X") 
    shortnamee = WorksheetFunction.Match(Range("V2"), ittkeres, 0)
    Range("V3") = shortnamee
    If Range("V3").Value > 0 Then

This part connects to the first page, where I can add new items to the collection sheets, and here it looks for duplicates from a concatenated name (V2 - the new items name; X:X - where the rest of the collection is, already uploaded. Thanks a lot!

How to continue python programme when a webpage is not reachable

Hello Stackoverflow members, I am very new to python hence i need a little bit of help with this small dilemma i have come across, what needs to be done is: if 10.10.10.2 is reachable the programm should exit() but if 10.10.10.2 is not reachable in 10 seconds 192.168.100.5 will be opened and the programm will continue... If anyone could give a small example as to how that could be done it would be much appreciated.

import requests
import urllib.request
import eventlet
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
from xml.dom import minidom
import urllib.request
import time

preflash = urllib.request.urlopen("http://10.10.10.2").getcode()
correct = urllib.request.urlopen("http://192.168.100.5").getcode()

print(100*"#")

#eventlet.monkey_patch()
#with eventlet.Timeout(10):

if True:
         print("Web page status code:",preflash)
         print("Web page is reachable")

else:    
    print("Web page status code:", correct)
    print("Web page is reachable")
url_str = 'http://192.168.100.2/globals.xml'

# open webpage and read values
xml_str = urllib.request.urlopen(url_str).read()

# Parses XML doc to String for Terminal output
xmldoc = minidom.parseString(xml_str)

# Finding the neccassary Set points/ Sollwerte from the xmldoc

# prints the order_number from the xmldoc
order_number = xmldoc.getElementsByTagName('order_number')
print("The Order number of the current device is:", order_number[0].firstChild.nodeValue)
print(100*"-")