dimanche 28 février 2021

If, else if, else statements and logical operators in R and creating functions

I have worked on this for two days and simply I am stuck in the mud! I am working on using if, else if and else statements in R

I have created a function to draw 3 random cards for two players to simulate a game

face=c("king", "queen", "jack", "ten", "nine", "eight", "seven", "six", "five", "four", "three", "two", "ace")
value=c(13, 12,11,10,9,8,7,6,5,4,3,2,1) 
deck <-data.frame(face=rep(face,4),
                  suit=c(rep("spades", 13), rep("clubs", 13), rep("diamonds", 13), rep("hearts", 
                  13)),
                  value=rep(value,4)) 

This is the function I created to get their hands

get_cards<-function(){
  Player.A<-draw_n_random_cards(deck, 3)
  Player.B<-draw_n_random_cards(deck, 3)
}

1 I added up the values of each player's hand to get their scores

Sum.Player.A<-sum(Player.A$value)
Sum.Player.B<-sum(Player.B$value)

2 If all the cards in the hand are the same suit (all hearts) their sum will be multiplied by 2 #3 If all the cards are the same suit (all aces) there sum will be multiplied by 2 also Ok, so I created a logical test for my if, else if, else statement

combo.1=c("ace", "ace", "ace")
combo.2=c("heart", "heart", "heart")

This is my if statement

if (Sum.Player.A==combo.1){
  Sum.Player.A<-Sum.Player.A*2
}else{
  Sum.Player.A
}

if(Sum.Player.A==combo.2){
  Sum.Player.A<-Sum.Player.A*2
}else{
  Sum.Player.A
}

if (Sum.Player.B==combo.1){
  Sum.Player.B<-Sum.Player.B*2
}else{
  Sum.Player.B
}

if(Sum.Player.B==combo.2){
  Sum.Player.B<-Sum.Player.B*2
}else{
  Sum.Player.B
}

My end result is to write a function that displays each player's hand and declares a winner.

winner<-function(){
if(Sum.Player.A<Sum.Player.B){
          "Player B is the winner"
        }else if (Sum.Player.A>Sum.Player.B){
          "Player A is the winner"}else {
           "tie"}
}

So my trouble is putting this sequence of functions into a single function to play this game I created. If I create a function called

play_game<-function(){

#1 draw 3 random cards for each player
#2 score their cards
#3 compare their score to delcare a winner
}

This is where I have been stuck. I am looking for direction on this question.

Google App Script check if the edited cell contains space

The following code is not working when I put a value with space in editedCellValue

function onEdit(e) {

var editedCellRange = 
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test").getActiveRange();
var editedCellValue = 
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test").getActiveRange().getValue;
if (RegExp(editedCellValue).test("\s")==true){editedCellRange.setValue("contains space")}
else 
{editedCellRange.setValue("ELSE IF")}
}

Please help on why this is not working.

thanks.

I am getting error: 'else' without "if", why? [closed]

I am getting an error on my first else if. I don't understand why I would have an error what am I missing. Please help.

 if(ticket >=1 && ticket <= 5) {
 discount = cost * 0.00; 
 
 else if(ticket >= 6 && ticket <= 10){
 discount = cost * 0.05;
 }
 else if(ticket >=11){
 discount =cost * 0.10;
 }
 else {
   discount =0;
 }
 
 double totalcost = ticket + Discount;
 double tax = totalcost * 0.07;
 double total = ticket + tax;
 }

Return statement being skipped even though line above it is run [duplicate]

I have a strange problem when trying to return a value from a function. Basically my recursive function will enter the "if" when the base case is reached. Otherwise will go through the else statement and call itself again. It will (always) end up reaching the base case after several recursions. So I place the "return"inside the "if" statement.

In the output I see that it correctly enters in the "if" statement, as I can see the value of "MinCutEdges" being printed, from the explicit print(MinCutEdges) sentence. However the ouput of the function call is "None".

def ContractEdges(edgelist):
    if RemovedEdges == EdgesToBeRemoved:
        MinCutEdges = len(edgelist)
        print("MinCutEdges is: %d" % MinCutEdges)   # I can see the correct output
        return MinCutEdges                          # gets skipped (even if i put return "hi") 
    else:
        edge = RandomChooseEdge(edgelist)
        a = len(edgelist)
        min_v = min(edge[0],edge[1])
        k =[]
        for i in range(a):
            if edgelist[i][0] in edge:
                edgelist[i][0] = min_v
                if edgelist[i] == edge or edgelist[i] == reversed(edge):
                    k += [i]
            if edgelist[i][1] in edge:
                edgelist[i][1] = min_v
        reduced = ReduceArray(edgelist, k)
        RemovedEdges += 1
        ContractEdges(reduced)


### Run
print(ContractEdges(edgelist))

Output:

MinCutEdges is 20

None

Invalid Syntax while checking if skill list is empty

I am trying to extract skills from a resume which works fine but now I want to check if in case skill is empty then the program should open up a rawtext.json file but the problem is that as soon as I write elif to check if the skill is empty then, I get invalid syntax or unexpected indent.

def getSkills(sentences):
    try:
        sen=[]
        z=0
        for words in sentences:
            for i in range(len(words)):
                if(words[i][0].lower()=='skills') and words[i][1]=='NNP':
                    index =[z,i]
                    break
            z+=1

        skills=[]
        for i in sentences[index[0]][index[1]+1:]:
            if i[0].isalpha() and i[1]=='NNP':
                skills.append(i[0])
        return skills
            elif skills == []:
                with open('rawtext.json','r', encoding='utf-8') as f:
    data = json.load(f)
result = [x["name"].replace("@", " ").lower() for x in data]
print(result)
    else:
        return None
    except:
        return None

Can someone please guide me on how can I implement this logic? Thank you for your assistance in this regard.

C# , how to make a Key word to fulfill specific command

I need a help with the correct command (please read my question in the code below so that you understand what I'm asking precisely, method: static void Main(string[] args) )

namespace Bank
{
    class Bank
    {
        class BankAccount
        {
            private double balance = 0;
            public void Deposit(double n)
            {
                balance += n;
                Console.WriteLine($"You currently have {balance}");
            }
            public void Withdraw(double n)
            {


                  
                  

  if (balance >= n)
                { balance -= n;
                    Console.WriteLine($"After Withdrawal you have remained {balance}" + " in your Account");
                }
                else
                { Console.WriteLine("You need more money to Withdraw" + $"You currently have { balance}"); }
                
  

      }
        public double GetBalance()

        {
            Console.WriteLine($"Your Balance is : {balance}");
            return balance;
        }

    }
        static void Main(string[] args)
        {
        
        BankAccount Acc1 = new BankAccount();
        /* I want to type a specific key words that will allow me to proceed with certain command. 
         For example if I type "Deposit" it will proceed with the Deposit command below. And the same for Withdraw. But not both of them one by one (unless I type them both on purpose). */

        if (/* need correct command*/)
        { Acc1.Deposit(Convert.ToDouble(Console.ReadLine())); }

        else if (/* need correct command*/)
        { Acc1.Withdraw(Convert.ToDouble(Console.ReadLine())); }

        
    }
   
    }
}

Need to make negative number recognise as a int, float, isnumeric or isdigit

I need vastus to be recognised as a number, or int or float type. So if i input vastus as -2 it goes to else statment but i need it to go to if statment. When i type any negative number it is recognised as a str. If there is any better way to slove it i would appriciate the help. I tried google and got nothing, still a total noob.

vastus = (input("Vastus:"))
            print (type(vastus))
            if vastus.isnumeric():
                if float(vastus) == (a+b):
                    print ("Õige vastus")
                    tulemus = tulemus + 1
                    arv = arv + 1
                else:
                    print ("Vale vastus, õige vastus on" ,(a+b))
                    arv = arv + 1
            else:
                print ("Peate sisestama arvu")

How to alter a switch statement that essentially creates empty rounds?

I am trying to make a four-person attack game that randomly selects the attacker and prints out the winner, but in my output, I keep getting empty rounds. I believe this is due to my switch statement but am unsure how to get the same result minus these essentially empty rounds. I have created an array of my characters to put into my randomly generated switch statement but with the if statements inside the cases are not skipped how I envisioned them being skipped. I've also tried removing the players from the array as they die, but that does not work and results in an error and exception message.

  import project3.characters.Plumber;
  import project3.characters.Vampire;
  import project3.characters.Werewolf;

  import java.util.ArrayList;
  import java.util.Random;

  public class Game {

  public static void main(String[] args) {
      GameCharacter player1 = new Plumber("Mario", 10, 20);
      GameCharacter player2 = new Fairy("Tinker Bell", 10, 20);
      GameCharacter player3 = new Vampire("Edward", 10, 20);
      GameCharacter player4 = new Werewolf("Derek", 10, 20);

      int round = 0;

      ArrayList<GameCharacter> player = new ArrayList<GameCharacter>. 
      ();

      player.add(player1);
      player.add(player2);
      player.add(player3);
      player.add(player4);

      while (player1.isAlive() || player2.isAlive() || 
          player3.isAlive() || player4.isAlive()) {
          System.out.println("Round " + (round + 1) + ": ");
          System.out.print(" " + player1 + " ");
          System.out.println(" " + player2);
          System.out.print(" " + player3 + " ");
          System.out.println(" " + player4 + " ");
          System.out.println();

          // Only two players can battle
          // if (round % 2 == 0) {
          // player1.hit(player2.attack());
          // } else
          // player2.hit(player1.attack())

          // All players randomly attack each other
          Random rand = new Random();
          int turn = rand.nextInt(12);
          switch (turn) {
          case 0:
              if (player1.isAlive() && player2.isAlive())
                  player1.hit(player2.attack());
              break;
          case 1:
              if (player1.isAlive() && player3.isAlive())
                  player1.hit(player3.attack());
              break;
          case 2:
              if (player1.isAlive() && player4.isAlive())
                  player1.hit(player4.attack());
              break;
          case 3:
              if (player1.isAlive() && player2.isAlive())
                  player2.hit(player1.attack());
              break;
          case 4:
              if (player3.isAlive() && player2.isAlive())
                  player2.hit(player3.attack());
              break;
          case 5:
              if (player4.isAlive() && player2.isAlive())
                  player2.hit(player4.attack());
              break;
          case 6:
              if (player1.isAlive() && player3.isAlive())
                  player3.hit(player1.attack());
              break;
          case 7:
              if (player3.isAlive() && player2.isAlive())
                  player3.hit(player2.attack());
              break;
          case 8:
              if (player3.isAlive() && player4.isAlive())
                  player3.hit(player4.attack());
              break;
          case 9:
              if (player1.isAlive() && player4.isAlive())
                  player4.hit(player1.attack());
              break;
          case 10:
              if (player4.isAlive() && player2.isAlive())
                  player4.hit(player2.attack());
              break;
          case 11:
              if (player3.isAlive() && player4.isAlive())
                  player4.hit(player3.attack());
              break;
          }

          if (!player1.isAlive()) {
              System.out.println(player1.getName() + " is dead!");
              // player.remove(0);
              // player1 = null
          }
          if (!player2.isAlive()) {
              System.out.println(player2.getName() + " is dead!");
              // player.remove(1);
              // player2 = null
          }
          if (!player3.isAlive()) {
              System.out.println(player3.getName() + " is dead!");
              // player.remove(2);
              // player3 = null
          }
          if (!player4.isAlive()) {
              System.out.println(player4.getName() + " is dead!");
              // player.remove(3);
              // player4 = null
          }

          if (!player4.isAlive() && !player2.isAlive() && 
              !player3.isAlive()) {
              System.out.println(player1.getName() + " is the 
           winner!");
              break;
          }
          if (!player4.isAlive() && !player1.isAlive() && 
             !player3.isAlive()) {
              System.out.println(player2.getName() + " is the 
           winner!");
              break;
          }
          if (!player4.isAlive() && !player2.isAlive() && 
          !player1.isAlive()) {
              System.out.println(player3.getName() + " is the 
         winner!");
              break;
          }
          if (!player1.isAlive() && !player2.isAlive() && 
          !player3.isAlive()) {
              System.out.println(player4.getName() + " is the 
        winner!");
              break;
          }
          
          
          round++;
          System.out.println();
          }
      }
  }

VBA IF cell VALUE LENGTH criteria

I have a code:

IF s LIKE "UZL.*" AND s LIKE "*.ENG" THEN

It evaluates if cell value starts with "UZL." and ends with ".ENG" but I would like to change those second criteria ".ENG" to be cell length =16 symbols. So it's like

If s Like "UZL.*" And cell value length =16 Then

Can someone please say what would be the code for that?

Full code:

Dim vDB As Variant
Dim rngDB As Range
Dim s As String, sReplace As String
Dim i As Long
Dim Ws As Worksheet

Set Ws = Sheets("BOM")

On Error Resume Next
Worksheets("BOM").ShowAllData
 
With Ws
    Set rngDB = .Range("E2", .Range("E" & Rows.Count).End(xlUp))
End With
vDB = rngDB
For i = 1 To UBound(vDB, 1)
    s = vDB(i, 1)
    If s Like "UZL.*" And s Like "*.ENG" Then
        sReplace = Me.LanguageBox.Value
        s = Replace(s, "ENG", sReplace)
        vDB(i, 1) = s
    End If
Next i
rngDB = vDB

Replace phone numbres

I have a list that contains phonenumbers with different formats. Ex.

  • 08542564782
  • 08 25 45 21 45 4
  • +185472654014
  • +1 8547562154
  • +1085458754856

I'm trying to replace the numbers using "-replace"

If ($User.mobilePhone.StartsWith("08")) {

    $AM = $User.mobilePhone -replace "^08", "+1 8"

}

If ($User.mobilePhone.StartsWith("+18")) {

    $AM = $User.mobilePhone -replace "^\+18", "+1 8"

}

If ($User.mobilePhone.StartsWith("+1 08")) {

    $AM = $User.mobilePhone -replace "^\+1 08", "+1 8"

}

After replacing the numbers, I want to compre them to a diffrent list with the same numbers but correct format. EX.

  • +1 8542564784
  • +1 8254521455
  • +1 8547265401
  • +1 8547562154
  • +1 8545875485
if ($test -ne $AM) {
    
    write-host "The number is not equal'

}

The IF statement should be false but for some reason it's true.

How to do an "if" command that is always checked in c# [closed]

i do a brawser and i want that wen i click on cheackbox in other form so the button is be anable and this is not working so i think the if fanction is not calld every time and i think its not work becas becas this.

the terms Code:

private void timer1_Tick(object sender, EventArgs e)
    {
        pictureBox1.Left += 2;
        
        if(ScarchBoutuneEnable == false)
        {
            button6.Enabled = false;
        }

        if (ScarchBoutuneEnable == true)
        {
            button6.Enabled = true;
        }

        if (URL_String.Contains("https"))
        {
            textBox4.Text = "cycurityd";
        }

        else
        {
            textBox4.Text = "not cycurityd";
        }

        
    }

the checkbox code:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        Form1 form1 = new Form1();
        form1.ScarchBoutuneEnable = true;
        if (checkBox1.Checked)
        {
            
        }

        if (checkBox1.Checked != true)
        {
            form1.ScarchBoutuneEnable = false;
        }

If metabox is emty display another content in wordpress

I'm trying to replace or show other content if the metabox is empty but I can't make it work, here is what I have done.

<div class="trailer"><iframe src="<?php echo get_post_meta($post->ID, 'ytvideourl', true);?>

<?php if( ! empty( $ytvideourl ) ) : ?>

  <a href="https://www.youtube.com/embed/<?php echo get_post_meta($post->ID, 'ytembed', true);?>?rel=0"></a>

<?php endif; ?> ?rel=0"></iframe></div>

Autohotkey If Statement makes only one result

I wanted to run a program on working day only, so I wrote a AutoHotKey script to check "today is sunday or holiday"

But my script doesn't work and I didn't get what the problem is. Here is the code.

Result = "WorkingDay"

if(A_Wday = 1) {
Result = "Sunday"
}

HolidayList = 0101|0211|0212|0213|0301|0409|0501|0505|0519|0606|0815|0920|0921|0922|1003|1009|1225
StringSplit,HoliDay,HoliDayList,|
StringLeft,Today,A_Now,8
StringRight,Today,Today,4

Loop %Holiday0%
    {
    CheckDay := HoliDay%A_index%
    ; msgbox, %Today% = %CheckDay%
    if ( %Today% == %CheckDay% ) {
    Result = "Holiday"
    break
    }
}

msgbox, %Today% = %Result%

The problem is that the "Result" variable return only "Holiday"

Please help me out......... Thanks in advance.

I can't figure out this while and if problem

When I input my number or anything else, it just skips the if statement and goes to the else. I can't figure out what's wrong; I've tried every way to change it. Still a total noob here.

arv = input("Sisestage arv: ")
    arv1 = 0
    kordus = 1
    
    
    while kordus <= 10:
        arv = input("Sisestage arv: ")
        if arv == arv.isnumeric():
             arv1 + arv
             print (arv1)
             kordus += 1
        else:
            print (arv)
            break

How to make a Hangman by calling a method

Basically a stickman but it comes in pieces. I was thinking of just adding the strings.

Then put that in an if() statement so that matches the counter. Ex.

    if(count == 6)
    {
        return str1;
    }
    if(count == 5)
    {
        return str1 + "\n" + str2;
    }

But I thought this was inefficient. It would make the code long. So how can I call a method that gives me a stickman in parts?

how to write a python program that can tell whether the numbers entered can form a triangle or not?

i was writing the following code:

def form_triangle(num1,num2,num3):

    success="Triangle can be formed"
    failure="Triangle can't be formed"

    if(num1 < num2 + num3):
        if(num2 < num1 + num3):
            if(num3 < num1 + num2):
                return success
        
    else:
        return failure


num1=3
num2=3
num3=5
result = form_triangle(num1, num2, num3)  
print(result)

but the problem is this code is unable to pass all the test cases. for instance, if num1, num2, num3 have values 1, 2, 3 respectively, then the expected output should be N/A but my output is None. so, what changes should i have to made in my code to have the expected output.

Outputs printed on same line - python

message = str(input())
for i in message:
  if i == " ":
    print(" ")
  else:
    # ord(i) returns the ASCII number for i
    # To get the actual alphabetical position of i, you have to do ASCII of letter - ASCII of A + 1.
    print(ord(i)-ord("a")+1)

This program converts each character of the users input to a letter, based on their alphabetical order (a = 1, b = 2, ect) and prints each number output on a new line. How do I get change this so that when each number is printed, it is on the same line as the last? (eg 123)

While-loop over dataframe running forever

Many apologies for the inane question, but I just can't seem to figure out why one section of my code won't display an output, and runs seemingly indefinitely. Hopefully it is immediately obvious to someone here, and then I can bang my head against my desk at how obvious it was.

Here is the snippet:

i = 0
j = 0

while i < len(data):
    if data['Pos'][i] == 1:
        while j < len(data[i+1:]):
            if data[i+1:]['Close'][j] >= data['High'][i] or data[i+1:]['Close'][j] <= data['Low'][i]:
                print('The position that was opened on date', data.index[i],'was closed on date', data[i+1:].index[j])
        j += 1
    i += 1          

data is a pandas DataFrame with datetime index, and columns Pos, Close, High and Low.

Convert letters to numbers - python [duplicate]

message = str(input())
for i in message:
  if i == "a": i = 1
  if i == "b": i = 2
  print(i)

ect. I am trying to create a code generator where the user inputs a string eg. "hello" and it is converted to a number code by assigning each letter a number, based on their position in the alphabet. 1 = a, 2 = b and so on. The method I am currently using is very long - are there other ways to do this to avoid this issues?

How can I print the answer together, without the numbers being on multiple lines eg. 1 2 3 21 19

I'm trying to make an if statements that sorts different types of values in my array of objects

I want a code that gives me the value of the objects properties value, and then take the if statement that has that value so it gets the correct console.log.

  var i = 0;
if(stoneData[i].hasOwnProperty('type') == "moveTo" || stoneData[i].hasOwnProperty('type') == "lineTo") {
console.log('stoneData[' + i + '].type = ' + stoneData[i].type + ', stoneData[' + i + '].point = ' + stoneData[i].point + ', stoneData['+i+'].axis.x = ' + stoneData[i].axis.x + ', stoneData['+i+'].axis.y = ' + stoneData[i].axis.y);
} else if(stoneData[i].hasOwnProperty('type') == "quadraticCurveTo") {
  console.log('stoneData[' + i + '].type = ' + stoneData[i].type + ', stoneData[' + i + '].point = ' + stoneData[i].point + ', stoneData['+i+'].axis.curveX = ' + stoneData['+i+'].axis.curveX + ', stoneData['+i+'].axis.curveY = ' + stoneData['+i+'].axis.curveY + ', stoneData['+i+'].axis.x = ' + stoneData[i].axis.x + ', stoneData['+i+'].axis.y = ' + stoneData[i].axis.y);
} else {
  return "something went wrong";
}

I have tried different other methods also.

I can't find the correct way of finding (stoneData[index].type == value).

I have done programming less than a year, so I'm not so good with advance answers yet.

Excel COUNTIFS with merged cell

I have excel sheet with 3 subjects: Customer, Data and Product. I want to calculate how many product for each customer, and I used "COUNTIFS" formula, the problem is customer row is merged, so when I use "COUNTIFS" formula it's doesn't work. can you help me please with this. Excel sheet attached.

File link: https://easyupload.io/5h2hou

Image

samedi 27 février 2021

Setting two manual cutpoints in cutpointr (R)?

I've downloaded the cutpointr package in R and want to use oc_manual (cutpoints from the literature) but need to set two manual outpoints depending on another variable (which can take on the value of 0 or 1). I'm having some difficulty doing this. R keeps running various errors whenever I try to add an ifelse statement or stratify. What is a work around for this? Thanks in advance!

Example:

mtcars
library(cutpointr)
data(mtcars)
opt_cut_manual <- cutpointr(mtcars, mpg, vs, method = oc_manual, 
                       cutpoint = 20, boot_runs = 1000)
plot(opt_cut_manual)

I can only set one manual cutpoint, when I'd like to set the cutpoint at 20 for am=0, and 25 for am=1. I've tried to use an ifelse statement:

mtcars
library(cutpointr)
data(mtcars)
opt_cut_manual <- cutpointr(mtcars, mpg, vs, method = oc_manual, 
if (am==0) {
  cutpoint = 20
} else {
  cutpoint =25
}, boot_runs = 1000)
plot(opt_cut_manual)

This is the error I get:

Error: Can't convert a call to a string In addition: Warning message: In if (!(deparse(substitute(subgroup)) == "NULL")) { : the condition has length > 1 and only the first element will be used

How to create a new column based on conditions in R

I have 3 classes of students A, B, and C. My reproducible dataset looks like this:

data <- data.frame(Student_ID =c(1,1,1,2,2,3,3,3,3,3,4,4,4,5,6,6,7,7,7,8,8),
                   Years_Attended = c(1991,1992,1995,1992,1993,1991,1992,1993,1994,1995,1993,1994,1995,1995,1993,1995,1990,1995,2000,1995,1996),
                   Class = c("A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","C","C","C","C","C"))

I want to add a new column (New Student) to my data frame using R. I define “New student” as any student who did not attend in the first year (i.e., minimum year) of any given class. My intended out put looks like this:

Intended_output <- data.frame(Student_ID = c(1,1,1,2,2,3,3,3,3,3,4,4,4,5,6,6,7,7,7,8,8),
                              Years_Attended = c(1991,1992,1995,1992,1993,1991,1992,1993,1994,1995,1993,1994,1995,1995,1993,1995,1990,1995,2000,1995,1996),
                              Class = c("A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","C","C","C","C","C"),
                              New_Student = c("No","No","No","Yes","Yes","No","No","No","No","No","No","No","No","Yes","No","No","No","No","No","Yes","Yes"))

I have tried:

data$New_student <- ifelse(data$Years_Attended != min(data$Years_Attended, "Yes", "No"))

But I keep getting errors which I don't fully understand. I have been going in cycles for some time. I will really appreciate any pointers with this. The solution doesn't necessarily have to use the 'ifelse' statement. Any approach will certainly be appreciated.

Checking if loop logic in calculator program with a click event listener

const press = document.querySelectorAll('input');

counter = 0;

let integers = "";


press.forEach(item => {
    item.addEventListener('click', (e)=>{

        if(counter === 1){
            term1 = input;
            console.log(term1);
            integers = "";
        }
       if(counter === 2){
            term2 = input;
            console.log(term2); 
            integers = "";
        }
        if(e.target.id === "number"){
            let number  = (e.target.value);
            integers += number;
        }
    
    
            if(e.target.id === "operator"){
            input = parseFloat(integers);
            console.log(integers);
            counter++;
            }    
    })

});

I'm new to Javascript and have been working on a simple calculator I'm trying to build. The numbers have a value in html based on the number they are (i.e. the value for 1 is value="1" in html. Operators have an id of "operator" and numbers have an id of "number". In my code, I try to have things set so my integer value is reset to it's initial value of an empty string once an operator is clicked. This is so the input for numbers comes out correctly. Unfortunately, once my counter hits 2, I get a value of NaN logged into the console.

It seems that the value for integers is kept as an empty string rather than being reassigned its value through the number variable like it did initially. I am just trying to find out why this value isn't reassigned through my loops, I'm sure I made a big mistake somewhere but I'm just not seeing it. I know this is a terrible way to make a calculator, but I am working on logic so that I get a good grasp of programming in general, and also to make things on my own so that I'm not stuck copying code and actually learning. Sorry if I made any dumb mistakes, but any help would be appreciated.

Java "Syntax error on token "else", delete this token" error on if else-if else-if clause?

I made a program to order 3 names in lexicographic order. I'm getting the syntax error with the two else if clauses. I can't figure out how I'm supposed to do it without the else-if statements. What is wrong here?

Scanner splitter = new Scanner(names);
    String name1 = splitter.next(); 
    String name2 = splitter.next(); 
    String name3 = splitter.next();



    if (name1.compareToIgnoreCase(name2) < 0 && name1.compareToIgnoreCase(name3) < 0); { 
        namesOrdered = namesOrdered + name1 + " "; 
        if (name2.compareToIgnoreCase(name3) < 0) { 
            namesOrdered = namesOrdered + name2 + " "; 
            namesOrdered = namesOrdered + name3 + " "; 
        }
        else { 
            namesOrdered = namesOrdered + name3 + " "; 
            namesOrdered = namesOrdered + name2 + " ";
        }
        
    }  
    else if (name2.compareToIgnoreCase(name1) < 0 && name2.compareToIgnoreCase(name3) < 0); { 
        namesOrdered = namesOrdered + name2 + " "; 
        if (name1.compareToIgnoreCase(name3) < 0) { 
            namesOrdered = namesOrdered + name1 + " "; 
            namesOrdered = namesOrdered + name3 + " ";
        }
        else {
            namesOrdered = namesOrdered + name3 + " "; 
            namesOrdered = namesOrdered + name1 + " "; 
        }
    }
    else if (name3.compareToIgnoreCase(name2) < 0 && name3.compareToIgnoreCase(name1) < 0); { 
        namesOrdered = namesOrdered + name3 + " "; 
        if (name2.compareToIgnoreCase(name1) < 0) { 
            namesOrdered = namesOrdered + name2 + " "; 
            namesOrdered = namesOrdered + name1 + " "; 
        }
        else { 
            namesOrdered = namesOrdered + name1 + " "; 
            namesOrdered = namesOrdered + name2 + " "; 
        }
    }
    System.out.println(namesOrdered);

Calculate and Distinct count with filter in Power BI

I have a two tables data and report.

Data:

In data table contain item, Qty and Count, in this table the qty column stored always as a text and count column as a number.

There is lot of duplicated row in this table according to the count.

Report:

In Report table the item column is unique.

The item column are common in between two tables.

Result:

I would like to bring the qty from data table into report table according to the item and count=1 only. (Not 0)

Scenario

  1. The same item contain multiple qty (100, 200, 350 ,0) according to the same count number 1, in this scenario the expected result is “XX”. (Please refer in data table the following items- 123456, 567, 116)
  2. The same item contain two different qty which is number and 0 (100 and 0) according to the same count number 1, in this scenario the expected result is number (ignore the 0 here). (Please refer in data table the following items- 67543)
  3. If item contain 0 only in data table then return the same thing in report table according to the item and count number1. (Please refer in data table the following item- 7,8)
  4. If item not available in data table then return blanks in report table according to the item and count number1. (Please refer in data table the following item – 444, 10 ,12)

I am applying the following New calculated column (DAX) in report table REULT FOR QTY = IF(CALCULATE(DISTINCTCOUNT(DATA[QTY]),FILTER(DATA,DATA[COUNT]=1),FILTER(DATA,DATA[ITEM]='REPORT'[ITEM]))>1,"XX",CALCULATE(FIRSTNONBLANK(DATA[QTY],1),FILTER(DATA,DATA[ITEM]='REPORT'[ITEM])))

It's almost working fine expect the scenario No 2. (The same item contain two different qty which is number and 0 (100 and 0) according to the same count number 1, in this scenario the expected result is number (ignore the 0 here). (Please refer in data table the following items- 67543)

I am trying to ignore the 0 were same item contain 0 and same number in my exciting DAX.

Any advice please.

Here is the power bi file for your reference. https://www.dropbox.com/s/810ex5g0b06ubb6/NEW%20QUERY.pbix?dl=0

DATA TABLE:

enter image description here

REPORT TABLE enter image description here

I am new to programing with C# and have a very simple question

I have a function that calculate numbers that the user inputs and that spits out the answer in the console. It is super simple. The user enters a number, then an operator (+,-,/ and*) and then another number. The function takes (number1) and (number2) and adds, subtracts etc and gives back the answer in the console.

And then the console closes. So it's like a one use calculator.

My question is.. How can I make it so once the user have given the 3 inputs, and the program spits out the answer, the program loops back to "Enter a number", and the process starts again.

Here is the enite code:

class Program
{
    static void Main(string[] args)
    {

        Console.WriteLine("Are you in need to calculate some numbers. y/n? ");
        string ifY = Console.ReadLine();

        if (ifY == "n")
        {
            Console.WriteLine("OK! You do not need a calculator");
        }
        else




            Console.Write("Enter a number: ");
        double num1 = Convert.ToDouble(Console.ReadLine());


        Console.Write("Enter operator: ");
        string op = (Console.ReadLine());


        Console.Write("Enter a number: ");
        double num2 = Convert.ToDouble(Console.ReadLine());


        if (op == "+")
        {
            Console.WriteLine(num1 + num2);
        }
        else if (op == "-")
        {
            Console.WriteLine(num1 - num2);
        }
        else if (op == "/")
        {
            Console.WriteLine(num1 / num2);
        }
        else if (op == "*")
        {
            Console.WriteLine(num1 * num2);
        }
        else
        {
            Console.WriteLine("Invalid operator");
        }




    }
}

}

And I'm sorry if what I am reffering to as Function is incorrect. Please correct me. As I said, completely new to this.

I know it is very "nooby" written. But we all have to start somewhere. Pls don't make fun of me 😅

OR operator inside of If statements

else if (!emailGet.endsWith(".com") && !emailGet.endsWith(".info")){ 
            
            errors += "Email should end with .info or .com";
        }

Why is "&&" playing the role of an "OR" statement, but when I use "OR" itself it does nothing, the only way I can get the code to tell me if one or the other statement is true is by using "&&" which evaluates 2 statements unlike "OR, the logic behind using "&&" makes no sense to me, am I missing something?

C# (or any other code because the only needed is the logic) - Condition to permanently disable a previous condition

I need to know a simplified way to have a condition that permanent "disables" the event from a previous condition already met.

Maybe I'm not using the correct terms but I will explain what I need with an example.

Having the condition:

if (a > 10)
{
   print ("Correct");
}

Let's suppose the condition is met and printing the message Correct as should, but later the next new condition is met (important, after the 1st condition is met):

if (a <= 10)
{
   print ("Incorrect");
}

What I need is when the second condition is met then the first message Correct doesn't be displayed anymore even if the a <= 10 again, so I need that Correct be permanent "skipped", permanent "disabled" or the correct way it calls, and now in substitution of Correct, then the new and permanent displayed message be Incorrect. So as you can see, in the situation I describe Incorrect has more weight than Correct because once a <= 10 then the permanent message to be displayed is Incorrect ("forever").

For a while I have been using some different combinations of if + else, and if + else if, and if + and extra separated if, but no positive results for now, because yes, I get the Incorrect message displayed once the 2nd condition is met but for a strange reason what the code does is once the 2nd condition is met it displays both message on screen Correct and Incorrect, both at the same time and I don't understand why it could be happening because both conditions are mutually exclusive, so in theory, when once one of them is met what I think is the other is automatically "disabled". I don't know if the fact about both conditions are into a loop makes any special case because this is happening.

...
// Here is an example of what I'm using. I tried to put the next in 
// around 10 different ways,either in the same part of the code or in 
// different parts and always the same result, it displays as 
// should `Correct` but when the `a <= 10` is met it displays both messages
// `Correct` and `Incorrect`, 
// and what I need is when this happens, only be displayed `Incorrect` permantly.

if (a <= 10)
{
   print ("Incorrect");
}
else if (a > 10)
{
   print ("Correct");
}
...

Note: I think no extra code or context is needed because here we are talking about a very simple logic, for a simple code. By the way I'm using C# but I put the examples with generic code because the main I need is the logic.

How to sort tuples and eliminate similar ones?

I have a list or matrix with tuples M = [(1,4),(1,5),(3,6),(4,5)]. I want to extract those touples in a form that find simlar ones and add them in a specific list inside a new matrix list. The final view should be like this. Final_Matrix = [(1,4,5), (3,6)]

Thank you

Check if field is taken Tic Tac Toe java

Currently i am coding a simple tic tac toe code in java. Everything works fine but i have a problem.

int[] board = new int[9];
        for(int i = 0; i < board.length; i++){
            board[i] = 7;
        }

This is my board.It has 9 fields.

if(zug >= 9 || zug < 0){

                System.out.println("Dieses Feld gibt es nicht! Versuche es erneut!");
                zug1class(player, playerone1, playertwo2, board2,zug1check2 );
            }
            else if (zug < 9 || zug > 0){


                check = zug;
                System.out.println(check);
                meinBoard[zug] = 0;
            }

And this is my statement for setting a fied. But i want to implement that the code checks with the if statement if the field is taken. I tried it with this:

int[] fieldchecker= new int[9];
for(int i = 0; i < board.length; i++){
            board[i] = -1;
        }

And then after choosing a field:

fieldchecker[zug] = zug;

And then it checks in the if statement:

if(zug == fieldchecker[zug]{

   //Do something

}

But this doesnt work for me. :/ I hope you can help me :D

Marvin

Trying to put 2 images to over lap one another

I have two pictures that I need to put together as one. The first one is about a beach with the ocean. The second picture is a cactus with a very bright green screen behind it. I need to find a way to tune down the green screen in the cactus picture so that I can place it over the beach picture and make it look like there is a cactus at the beach. I can change the pixel colors but I can not seem to take out the bright green screen color of the cactus picture. I can also put both pictures together but the green screen of the cactus picture over writes the coloring of the beach picture. Could any please help show me how to tune down the green pixels of the cactus picture or get rid of the green screen part? Here is the code that I am working with. It's in the google docs. I am at a lost. here is a link to see what I need to do. The last picture is how it should look

https://docs.google.com/document/d/1ZYrigN1LXSMq3_llc6eimZqBh2R9ZVeBmmxSUx63__E/edit?usp=sharing

nested if statement within a for loop doesn't work

I have a nested if statement within a for loop but the first if statement seems not to be progressing onto the rest of the for loop.

for i, x in enumerate(S[start:-1], start):
    if i > max(sma_period1, sma_period2, sma_period3):
        j = i-start
        
        if ma1[i] == x:
            w[j+1] = w[j]
            cash[j+1] = cash[j]

        if ma1[i] < x: 
            w[j+1] = cash[j]/x  + w[j]
            cash[j+1] = 0

        if ma1[i] > x:
            cash[j+1] = w[j]*x + cash[j]
            w[j+1] = 0

tf_strategy_ma1 = [a*b for a,b in zip(w,S[start:])]+ cash

Sorry if this is a very basic question, I am new to coding and completely stuck. Thanks for your help.

Doesn't store entered value when runs second time

I made rock,paper,scissor game. It works fine, as I wanted to, but it doesn't store entered value when runs second time, how do I fix that.

import random

tools =["Rock","Scissors","Paper"]
r="".join(tools[0])
s="".join(tools[1])
p="".join(tools[-1])
def computer_predicion():
    computer_pred = random.choice(tools)
    return computer_pred
computer=computer_predicion()
def my_predicion():
my_predicion = input("Choose (R)Rock,(S)Scissors,(P)Paper:")
    if my_predicion=="R" or my_predicion =="r":
       my_predicion = r
       return my_predicion
    elif my_predicion=="S" or my_predicion =="s":
       my_predicion = s
       return my_predicion
    elif my_predicion=="P" or my_predicion =="p":
       my_predicion = p
       return my_predicion
    else:
         print("Debils ir?")
human=my_predicion()
def game():
    message_win = ("You won!")
    message_lose = ("You lost!")
    message = "Computer:%s\nUser:%s"%(computer,human)
    if computer ==r and human==r :
       print(message+"\nIt's draw")
    elif computer == p and human == p:
       print(message + "\nIt's draw")
    elif computer == s and human == s:
       print(message + "\nIt's draw")
    elif computer == r and human==p:
       print(message+'\n'+message_win)
    elif computer == p and human==r:
       print(message+'\n'+message_lose)
    elif computer == r and human==s:
       print(message+'\n'+message_lose)
    elif computer == s and human==r:
       print(message+'\n'+message_win)
    elif computer == p and human == s:
       print(message+'\n'+message_win)
    elif computer == s and human==p:
       print(message+'\n'+message_lose)
    else:
        pass
 c=True
 while c :      //Here code runs second time if user inputs Y or y.
      game()
      h = input("Continue?(Y/N):")
      if h=="Y" or h=="y":
         my_predicion()
         computer_predicion()
         pass
      elif h=="N" or h=="n":
          c=False
      else:
           print("Wrong symbol!")

If you have any further suggestions on how to make code better I would love to hear them out. Thank you!

How to retry x times and put a long sleep with a print

I have been trying to understand how backoff works. My goal is that whenever I reach a status_code etc: 405 5 times. I want to put a sleep of 60000 sec and print out that there has occured status error 405.

Right now I have written:

import time

import backoff
import requests

@backoff.on_exception(
    backoff.expo,
    requests.exceptions.RequestException,
    max_tries=5,
    giveup=lambda e: e.response is not None and e.response.status_code == 405
)
def publish(url):
    r = requests.post(url, timeout=10)
    r.raise_for_status()


publish("https://www.google.se/")

and what happens now is that if it just reaches 405 once, it will raise the status_code and stop the script. What im looking for is how I can make the script to retry 5 times, if the status is 5 times in a row of 405, then we want to put a long sleep and print it out. How can I do that using backofF? Im also up for other suggestions :)

Why useless if statement is improving performance?

I'm writing a small library in rust as a 'collision detection' module. In trying to make a line-segment - line-segment intersection test as fast as possible, I've run into a strange discrepancy where seemingly useless code is making the function run faster.

My goal is optimising this method as much as possible, and knowing why the executable code changes performance as significantly as it does I would imagine would be helpful in achieving that goal. Whether it be a quirk in the rust compiler or something else, if anyone is knowledgeable to be able to understand this, here's what I have so far:

The two functions:

  fn line_line(a1x: f64, a1y: f64, a2x: f64, a2y: f64, b1x: f64, b1y: f64, b2x: f64, b2y: f64) -> bool {
     let dax = a2x - a1x;
     let day = a2y - a1y;
     let dbx = b2x - b1x;
     let dby = b2y - b1y;

     let dot = dax * dby - dbx * day;
     let dd = dot * dot;

     let nd1x = a1x - b1x;
     let nd1y = a1y - b1y;
     let t = (dax * nd1y - day * nd1x) * dot;
     let u = (dbx * nd1y - dby * nd1x) * dot;
     u >= 0.0 && u <= dd && t >= 0.0 && t <= dd
  }
  
  fn line_line_if(a1x: f64, a1y: f64, a2x: f64, a2y: f64, b1x: f64, b1y: f64, b2x: f64, b2y: f64) -> bool {
     let dax = a2x - a1x;
     let day = a2y - a1y;
     let dbx = b2x - b1x;
     let dby = b2y - b1y;

     let dot = dax * dby - dbx * day;
     if dot == 0.0 { return false } // useless branch if dot isn't 0 ?
     let dd = dot * dot;

     let nd1x = a1x - b1x;
     let nd1y = a1y - b1y;
     let t = (dax * nd1y - day * nd1x) * dot;
     let u = (dbx * nd1y - dby * nd1x) * dot;
     u >= 0.0 && u <= dd && t >= 0.0 && t <= dd
  }

Criterion-rs bench code:

  fn criterion_benchmark(c: &mut Criterion) {
     c.bench_function("line-line", |b| b.iter(|| line_line(
        black_box(0.0), black_box(1.0), black_box(2.0), black_box(0.0), 
        black_box(1.0), black_box(0.0), black_box(2.0), black_box(4.0))));
     c.bench_function("line-line-if", |b| b.iter(|| line_line_if(
        black_box(0.0), black_box(1.0), black_box(2.0), black_box(0.0), 
        black_box(1.0), black_box(0.0), black_box(2.0), black_box(4.0))));
  }

Note that with these inputs, the if statement will not evaluate to true.

assert_eq!(line_line_if(0.0, 1.0, 2.0, 0.0, 1.0, 0.0, 2.0, 4.0), true); // does not panic

Criterion-rs bench results:

line-line               time:   [5.6718 ns 5.7203 ns 5.7640 ns]
line-line-if            time:   [5.1215 ns 5.1791 ns 5.2312 ns]

Godbolt.org rust compilation results for these two pieces of code.

Unfortunately I cannot read asm as well as I'd like, but hopefully this may be helpful.
Thank you in advance if you're able to answer this.

Not able to execute the following python code

Code

role = 'admin'

def f():
    del role

if role == 'admin':
    f()
else:
    pass

Output

Traceback (most recent call last):
  File "C:\Users\Hari\PycharmProjects\Card_Prj\ch.py", line 6, in <module>
    f()
  File "C:\Users\Hari\PycharmProjects\Card_Prj\ch.py", line 3, in f
    del role
UnboundLocalError: local variable 'role' referenced before assignment

If a role called admin exists then it should delete the variable role otherwise it should do nothing, that is what the code is doing.

I have tried different ways of executing this code but failed to do so.

Any help is highly appreciated!!!

Is there a way for me to pass parameters from one function to another in an if statement?

I am currently producing a menu-driven program. Here is a code snippet:

    def main():
    intro()
    loop = True
    while loop:
        print("\n<<<<<<<<<<<<<<<<<<<<<<<<< ||| >>>>>>>>>>>>>>>>>>>>>>>>")
        print("\nChoose your option below:")
        print("1 - Patient Registration")
        print("2 - Total Patients")
        print("3 - Total Sales")
        print("Q/q - Quit")
        choice = str(input("Your choice?"))
        print("\n<<<<<<<<<<<<<<<<<<<<<<<<< ||| >>>>>>>>>>>>>>>>>>>>>>>>")
        menu(choice)
        
def intro():
    print("Welcome to CTI System.")
    print("This system is used to track and manage Covid-19 testing")
   
def menu(choice):
    if choice == '1':
        patientRegistration()   
    elif choice == '2':
        testType(pcr,antigen)
    elif choice == '3':
        totalSales()
    elif choice == 'Q' or choice == 'q':
        print("\nThank you for using this program.\n")
        exit()
    else:
        print("\nInvalid choice! Please select from the list of choices.\n")
        loop = False

When choosing the first choice, it will prompt the user to gather information. Afterwards, once the user is done with the first choice, the user will be prompted to continue, if 'N' then it will go back to the main menu.

This is where where problem starts. I want to choose the 2nd choice in the menu which is the total number of patients. How can I pass the parameters from the first condition to the second?

Your help is greatly appreciated. Thank you!

How to create conditionals based on output of print statement in Python? [closed]

I am utilising a specialised collection of tools in Python to retrieve content from a graph database based on a query provided by the user - the query is mycode. Here, when I execute the print() statement like this-

  print(graph.run(mycode).to_table())

There can be occasions when there is nothing printed on the console at all (i.e. a blank output), while on other occasions, the print() statement has values printed onto the output console. I was wondering if there is a way to create conditionals that - when there is no output produced by the print() statement displays to the user No content found in the DB. Else, if content is found in the database, it just shows the usual print() output.

Something of this sort (in terms of pseudo-code) -

if(output of print(graph.run(mycode).to_table()) is blank/empty):
   print("No content found in the DB)
else:
   print("Content found in the DB! \n")
   print(graph.run(mycode).to_table()

Any help and suggestions to achieve this would be much appreciated.

Javascript - Uncaught SyntaxError: Unexpected token 'else'

Its my first time learning to program Javascript and been working on this program to take 99 drinks on the wall till it reachs zero.. I been working on this program since 12am learning JS... its now 3am and im going bonkers and unable to see my mistake.

Where did i go wrong? How can i prevent this in the future?

Its my first crack at making a JS program so please dont rip into me too bad i litterly just opened a book and started at 11:30pm till now asking at 3am..

Thanks guys or girls!

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My First JavaScript</title>
</head>
<body>
<script>
var drinks = "Energy Drink";
var lyrics = "";
var cans = 99;
    while (cans > 0) {

      lyrics = lyrics + cans + " cans of " + drinks + " on the 
      wall <br>";
      lyrics = lyrics + cans + " cans of " + drinks + "<br>";
      lyrics = lyrics + " Take on down pass it around, <br>";
      
      if (cans > 1)
        {
        lyrics = lyrics + (cans-1) + " cans of " + drink + " on 
        the wall <br>"
        }

     ** else *This is where my error seems to come from????*
        {
        lyrics = lyrics + "No more cans of " + drink + " on the 
        wall <br>";
        }
      cans = cans - 1;
    }
    document.write(lyrics);
</script>

</body>
</html>

vendredi 26 février 2021

IF FUNCTIN IN VBA

If TextBox2.Text = "" Then UserForm7.Show Else

USERORM7.UndoAction End If End Sub

USERFORM7. Undo Action is not working, what else i can use to avoid the opening of userform7

How to double jump in checkers JAVASCRIPT

So I just finished coding my first big program(Im a beginner so for me this is big :/) and I'm having a hard time figuring out the logic for double jumping. I have my checker game set up right now to to do single jumps & then it switches the turn. Any advice on how to implement a double jump feature would be appreciated. https://andrewdimes.github.io/Checkers/ << this is the link to the game.

    let index = parseInt(e.target.id);
    let row = parseInt(e.target.className);
    let desiredSpace = board[row][index];
    console.log(desiredSpace)
    if (!desiredSpace) {
        //red normal move
        if (turn === 'red' && row === pieceSelected[1] + 1 && index === pieceSelected[2] - 1 || turn === 'red' && row === pieceSelected[1] + 1 && index === pieceSelected[2] + 1) {
            board[row][index] = pieceSelected[0];
            board[pieceSelected[1]][pieceSelected[2]] = null;
            playerTurn();
            //black normal move
        } else if (turn === 'black' && row === pieceSelected[1] - 1 && index === pieceSelected[2] - 1 || turn === 'black' && row === pieceSelected[1] - 1 && index === pieceSelected[2] + 1) {
            board[row][index] = pieceSelected[0];
            board[pieceSelected[1]][pieceSelected[2]] = null;
            playerTurn();
            //red jump black
        } else if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'black' || turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'blackking') {
            board[row][index] = pieceSelected[0];
            board[pieceSelected[1]][pieceSelected[2]] = null;
            if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'black' || turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'blackking') {
                board[row - 1][index + 1] = null;
                redPoints++;
            }
            if(board[row-1][index+1] === 'black' || board[row-1][index+1] === 'blackking'){
                turn = 'red'
            }
    
                playerTurn()
            
            
        } else if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'black' || turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'blackking') {
            board[row][index] = pieceSelected[0];
            board[pieceSelected[1]][pieceSelected[2]] = null;
            if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'black' || turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'blackking') {
                board[row - 1][index - 1] = null;
                redPoints++;
            }
            playerTurn()
            //black jump red
        } else if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'red' || turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'redking') {
            board[row][index] = pieceSelected[0];
            board[pieceSelected[1]][pieceSelected[2]] = null;
            if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'red' || turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'redking') {
                board[row + 1][index - 1] = null;
                blackPoints++;
            }
            playerTurn()
        } else if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'red' || turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'redking') {
            board[row][index] = pieceSelected[0];
            board[pieceSelected[1]][pieceSelected[2]] = null;
            if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'red' || turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'redking') {
                board[row + 1][index + 1] = null;
                blackPoints++;
            }
            playerTurn()
        } else if (pieceSelected[0] === 'blackking') {
            if (turn === 'black' && row === pieceSelected[1] + 1 && index === pieceSelected[2] - 1 || turn === 'black' && row === pieceSelected[1] + 1 && index === pieceSelected[2] + 1) {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                playerTurn();
            } else if (turn === 'black' && row === pieceSelected[1] - 1 && index === pieceSelected[2] - 1 || turn === 'black' && row === pieceSelected[1] - 1 && index === pieceSelected[2] + 1) {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                playerTurn();

            } else if (turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'red' || turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'redking') {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'red' || turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'redking') {
                    board[row - 1][index + 1] = null;
                    blackPoints++;
                }
                playerTurn()
            } else if (turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'red' || turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'redking') {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'red' || turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'redking') {
                    board[row - 1][index - 1] = null;
                    blackPoints++;
                }
                playerTurn()
            } else if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'red' || turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'redking') {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'red' || turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'redking') {
                    board[row + 1][index - 1] = null;
                    blackPoints++;
                }
                playerTurn()

            } else if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'red' || turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'redking') {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'red' || turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'redking') {
                    board[row + 1][index + 1] = null;
                    blackPoints++;
                }
                playerTurn()
            }

        } else if (pieceSelected[0] === 'redking') {
            if (turn === 'red' && row === pieceSelected[1] + 1 && index === pieceSelected[2] - 1 || turn === 'red' && row === pieceSelected[1] + 1 && index === pieceSelected[2] + 1) {
                board[row][index] = 'redking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                playerTurn();
            } else if (turn === 'red' && row === pieceSelected[1] - 1 && index === pieceSelected[2] - 1 || turn === 'red' && row === pieceSelected[1] - 1 && index === pieceSelected[2] + 1) {
                board[row][index] = 'redking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                playerTurn();

            } else if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'black'|| turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'blackking') {
                board[row][index] = 'redking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'black'|| turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'blackking') {
                    board[row - 1][index + 1] = null;
                    redPoints++;
                }
                playerTurn()
            } else if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'black' || turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'blackking') {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'black' || turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'blackking') {
                    board[row - 1][index - 1] = null;
                    redPoints++;
                }
                playerTurn()
            } else if (turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'black' || turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'blackking') {
                board[row][index] = 'redking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'black' || turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'blackking') {
                    board[row + 1][index - 1] = null;
                    redPoints++;
                }
                playerTurn()

            } else if (turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'black' || turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'blackking') {
                board[row][index] = 'redking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'black' || turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'blackking') {
                    board[row + 1][index + 1] = null;
                    redPoints++;
                }
                playerTurn()
            }
        } else if (turn === 'red' && pieceSelected[3] === true) {
            if (turn === 'red' && row === pieceSelected[1] + 1 && index === pieceSelected[2] - 1 || turn === 'red' && row === pieceSelected[1] + 1 && index === pieceSelected[2] + 1) {
                board[row][index] = 'redking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                playerTurn();
            } else if (turn === 'red' && row === pieceSelected[1] - 1 && index === pieceSelected[2] - 1 || turn === 'red' && row === pieceSelected[1] - 1 && index === pieceSelected[2] + 1) {
                board[row][index] = 'redking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                playerTurn();

            } else if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'black' || turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'blackking') {
                board[row][index] = 'redking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'black' || turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'blackking') {
                    board[row - 1][index + 1] = null;
                    redPoints++;
                }
                playerTurn()
            } else if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'black' || turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'blackking') {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'black' || turn === 'red' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'blackking') {
                    board[row - 1][index - 1] = null;
                    redPoints++;
                }
                playerTurn()
            } else if (turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'black' || turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'blackking') {
                board[row][index] = 'redking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'black' || turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'blackking') {
                    board[row + 1][index - 1] = null;
                    redPoints++;
                }
                playerTurn()

            } else if (turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'black'|| turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'blackking') {
                board[row][index] = 'redking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'black' || turn === 'red' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'blackking') {
                    board[row + 1][index + 1] = null;
                    redPoints++;
                }
                playerTurn()
            }
        } else if (turn === 'black' && pieceSelected[3] === true) {
            if (turn === 'black' && row === pieceSelected[1] + 1 && index === pieceSelected[2] - 1 || turn === 'black' && row === pieceSelected[1] + 1 && index === pieceSelected[2] + 1) {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                playerTurn();
            } else if (turn === 'black' && row === pieceSelected[1] - 1 && index === pieceSelected[2] - 1 || turn === 'black' && row === pieceSelected[1] - 1 && index === pieceSelected[2] + 1) {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                playerTurn();

            } else if (turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'red' || turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'redking') {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'red' || turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] - 2 && board[row - 1][index + 1] === 'redking') {
                    board[row - 1][index + 1] = null;
                    blackPoints++;
                }
                playerTurn()
            } else if (turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'red' || turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'redking') {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'red' || turn === 'black' && row === pieceSelected[1] + 2 && index === pieceSelected[2] + 2 && board[row - 1][index - 1] === 'redking') {
                    board[row - 1][index - 1] = null;
                    blackPoints++;
                }
                playerTurn()
            } else if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'red' || urn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'redking') {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'red' || urn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] + 2 && board[row + 1][index - 1] === 'redking') {
                    board[row + 1][index - 1] = null;
                    blackPoints++;
                }
                playerTurn()

            } else if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'red' || turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'redking') {
                board[row][index] = 'blackking'
                board[pieceSelected[1]][pieceSelected[2]] = null;
                if (turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'red'|| turn === 'black' && row === pieceSelected[1] - 2 && index === pieceSelected[2] - 2 && board[row + 1][index + 1] === 'redking') {
                    board[row + 1][index + 1] = null;
                    blackPoints++;
                }
                playerTurn()

            }
        }


    }
    render();
};```

rearranging a char array with strncpy in C

I am trying to change the sorting of a the arr list which could consist of zero, one, two as the inputted and stored values for arr. The stringreplace function is meant to shift every single element by one so the new sorting would be one, two, zero. I am trying to replace the elements with one another by using the strncpy function but I think it is a bit faulty, how could i fix this?

strncpy function

char stringreplace( char a[], int b){
    for(int j = 0; j > b -1; j++){
        strncpy(a[j], a[j+1], sizeof(a));}
    for(int j = 0; j > b; j++){
        printf("%s",a[j]);}
}

main function

int main()
{
    char input[100];
    char arr[100]= {0};
    int number;
    printf("Input the number of strings: ");
    scanf("%d", &number);
    for(int i= 0; i < number; i++){
        printf("Input the number of strings: ");
        scanf("%s", input);
        arr[i] = input;
    }
    stringreplace(arr, number);
    return 0;
}    

Powershell to find folder/subfolder and then write if condition to perform action only if folder A is greater than folder B

Basically need to write powershell which give me list of sub directory's. in my sub directory my folder structure is like 101.10.1 , 101.10.2 , 101.10.3 now want to write if condition which take a higher directory from folder (101.10.3) and rhen remove ms sql 2005 application.

something like this

    ****$path = "C:\abc\xyzh\Versions"
$contents = Get-ChildItem -Path $path | sort | Select-Object -Last 10
$contents.Name
$condition = $contents.Name
if ( $condition -gt "$path/$condition" )
{
        # do something"
    }****

How to change the textview height if it contains more than 10 words in Kotlin (Code)

it's a very simple question but I can't find a good solution (in Kotlin) for this problem.

The textview height should change if the textview contains more than 10 words.

Change size from 10dp to 20dp.

Thanks in advance

If firestore doc.exists how do I stop execution of parent function?

I'm trying to stop the async function if a username is found in the database. I can find existingUsername = true, but handleSignup continues to execute and overwrites existing user data.

async function handleSignup {

    var docRef = db.collection("users").doc(username);
    var existingUsername = false

    docRef.get().then((doc) => {
        if (doc.exists) {
            existingUsername = true
        }
        else {
            existingUsername = false
        }
    })

    if (existingUsername == true) {
        return setError("Username exists") // How do I stop the function handleSignup?
    }

    }
//database code to create user
}

My code is running its course without user input

For my class online I have to make a Interactive story/Game in java and I am almost done, but something I did to change it is causing all of the dialogue and story to be put on the screen after just the first choice. I am using else ifs and ifs because That is all we have learned so far. Also sorry if it is messy I am still learning it for the most part. Please try to dumb your answers down some. After typing in "Listen" for the first option the entire rest of the story is put in.

import java.util.Scanner;

public class Homework021 {

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);

    String Go = "", Listen, Speak, Fight, A = "", B, C, D;

    System.out.println(" WELCOME TO THE DUNGEON CRAWLER!");
    System.out.println("  ");
    System.out.println(" You are woken up by a large man kicking you in the stomach.\n"
            + "You let a large gasp of air out before proptly getting up in a blurry state.\n"
            + "What will you do?\n" + "(------------------------------------------)\n"
            + "1)Listen to the man (Listen)\n" + "2)Speak to the man (Speak)\n"
            + "3)Throw a punch at the man(Attack) ");
    System.out.print("> ");
    Go = keyboard.next();

    if (Go.equalsIgnoreCase("Listen")) {
        System.out.println(
                "The large man tells you to get ready for your hearing in 2 minutes.\n" + "What will you do?\n"
                        + "(---------------------------------------------------------------------)\n"
                        + "1)Attack(1)\n" 
                        + "2)Sit Down(2) ");
    }
    else if (Go.equalsIgnoreCase("Attack")) {
        System.out.println("While in a bout of confusion you charge the large man to attack.\n"
                + "He grabs you by the throat, picks you up and slams your head into the wall and then onto the ground.\n"
                + "He stomps his massive boot into your skull and then the back of your neck making you fade into a the eternal darkness."
                + "////YOU HAVE DIED. RESART THE GAME.////");
    }
    else if (Go.equalsIgnoreCase("Speak")) {
        System.out.println("You open your mouth to start speaking to the large man.\n"
                + "As you make a sound he balls his fist up and sucker punches you in the stomach dropping you to the floor.\n"
                + "He states 'You speak when spoken to you filthy mutt.' Then tells you to get ready for your hearing\n"
                + "You spit out blood onto the floor and get on all fours. The large man kicks your head into the toilet and your vision gets fuzzy\n"
                + "You slowly start to fade into an unconcious state. As you start to see black the man says 'That's one less piece of trash we have to feed now.'");
        System.out.println("////YOU HAVE DIED. RESTART THE GAME.////");

        A = keyboard.next();

        if (A.equalsIgnoreCase("1"));
        
        System.out.println("The man turns his back to walk out of your cell.\n"
                + "As the man begeins to walk out you grab your blanket and rush him.\n"
                + "You wrap the blanket around his neck and start to strangle him.\n"
                + "The large man begins to turn purple and blue and you keep pulling tighter and tighter.\n"
                + "The man finally falls to his knees then onto his belly.\n"
                + "As the large man lies lifeless on the floor you grab his baton and keys and run out of the cell.\n"
                + "Do you run to the Left or to the Right?\n"
                + "(--------------------------------------------------------------------------)\n"
                + "1)Left\n"
                + "2)Right");
    }
    
    else if (A.equalsIgnoreCase("2"));
    
    System.out.println("You sit down to think about how you ended up there but you are drawing blanks.\n"
            + "You don't even know your name.\n"
            + "You sit on the floor of the cell waiting for the Large man to come back and retreive you.\n"
            + "*2 minutes pass by*\n" + "The large man appears again and tells you to follow him.\n"
            + "As you follow the large man down the hallway of the dungeon you see all the other starving prisoners rotting away in their cells.\n"
            + "You finally arrive to a large room filled with torches and skulls with a man sitting on a throne made of bones\n"
            + "'AHHHHH! My newest warrior!' The man exclaims! 'I cannot wait to see what you can do in the arena!'\n"
            + "'We have your first round tomorrow! Please eat and rest up for your fight! I cant wait to see you in action!'"
            + "What do you do?\n"
            + "(---------------------------------------------------------------------------------------------------------------------)"
            + "1)Go back to your cell to eat and rest(1)\n"
            + "2)Speak(2)"); 
            
    if (A.equalsIgnoreCase("1"));
    System.out.println("You go back to your cell where a tray of food is waiting on you.\n"
            + "You sit down and think about the new life that you now have to pursue.\n"
            + "As you sit eating and thinking the large man comes back and tells you about your new bout."
            + "'Tomorrow you will be fighting Jeebuz, Be ready hes a worthy apponent.'");;
            System.out.println("What will you do?"
                    + "(--------------------------------------------------------------------------------------------------------------)"
                    + "1)Go to sleep(1)"
                    + "2)Beg for forgiveness, and to let you go(2)");
            
            B = keyboard.next();
            
            if (B.equalsIgnoreCase("1"));
            System.out.println("You go to sleep and wake up the next morning.\n"
                    + "The large man comes to your cell and walks you to the preparation room.\n"
                    + "You walk into the room and pick up the all the weapons to inspect them and decide which you want to use."
                    + "You decide to stick with a sword and a shield."
                    + "The large man tells you to enter the arena."
                    + "You enter the arena and find a small man across the way from you. He looks feeble and weak\n"
                    + "You begin to look around and notice hundreds of people chanting and yelling. There are bright lights and flags hanging up\n"
                    + "There are skulls hanging from the ceiling as well as human spines\n"
                    + "What do you do?"
                    + "(--------------------------------------------------------------------------------------------------------------)"
                    + "1)Charge the man across the arena.(Attack)\n"
                    + "2)Wait to see what your oppnent does.(Wait)");
            
     if (A.equalsIgnoreCase("2"));
    System.out.println("You begin to think of your new life you're about to take on.\n"
            + "You open your mouth to speak to the king you get the word 'Where'\n"
            + "As soon as this word comes out of your mouth the large man hits the back of your head with his baton.\n"
            + "You fall onto your face. As you start to see the darkness you hear\n"
            + "'What a shame, I really wanted to see what this man could do."
            + "////YOU HAVE DIED. PLEASE RESTART////");
    
    
    
    
}


}

Transform IF statement into IF NOT statement (Java)

How to transform this IF statement to IF NOT statement?

The purpose of the code is to ignore lines starting with "//" and empty lines.

if (lineOfText.contains("//") || lineOfText.trim().length() == 0)
continue; 

FILE TO BE READ


// this is a comment, any lines that start with //
// (and blank lines) should be ignored


// data is title, itemCode, cost, timesBorrowed, onLoan
item 1, LM002411,3989,781,true
item 2, LM002711,599,0,FALSE
item 3, LM002876,4599,45,TRUE
item 4, LM002468,6395,0,TRUE
item 5, LM002153,4554,0,FALSE

accessing updated variables outside of .then [duplicate]

I have the code below:

let auth = '';
Data.loginRedirect(auth)
        .then(response => {
        this.var = response.data;   
        auth= this.var;
        console.log(auth); //outputs array
        })
      console.log(auth); //outputs nothing ''

      if ((auth) != '') {
        alert('Email already used!');
      }

In this code, I need auth to be updated with the array value after LoginRedirect runs to use in the if statement. How can I do this?

DiceRoll Switch statement / if statement working, but output only returning zeroes

So my last question got a reply that really helped, and I was able to work out why my class was not working. Here is my revised code for the Dice Class:

import java.util.Random;

public class Dice {
  public int die1;
  public int die2;
  public int total;
  public String name;
  public boolean doubles = false;

  Random random = new Random();

  public void setDie1() {
    die1 = random.nextInt(6) + 1;
  }

  public void setDie2() {
    die2 = random.nextInt(6) + 1;
  }

  public void setTotal() {
     total = die1 + die2;
  }

  public int getDie1() {
    return die1;
  }

  public int getDie2() {
    return die2;
  }

  public int getTotal() {
    return total;
  }

  public boolean checkDouble() {
    if (die1 == die2) {
     doubles = true;
   } else {
      doubles = false;
    } 
    return doubles; 
  }

  public String getName() {
    if (checkDouble() == true) {
      if (die1 == 1 && die2 == 1) {
        name = "Snake Eyes";
      }
      if (die1 == 2 && die2 == 2) {
        name = "Ballerina";
      }
      if (die1 == 3 && die2 == 3) {
        name = "Brooklyn Forest";
      }
      if (die1 == 4 && die2 == 4) {
        name = "Square Pair";
      }
      if (die1 == 5 && die2 == 5) {
        name = "Puppy Paws";
      }
      if (die1 == 6 && die2 == 6) {
        name = "Boxcars";
      } 
    } else {
       switch (getTotal()) {
        case 3:
          name = "Acey-Deucy";
          break;
        case 4:
          name = "Easy Four";
          break;
        case 5:
          name = "Fever Five";
          break;
        case 6:
          name = "Easy Six";
          break;
        case 7:
          name = "Benny Blue, You're All Through";
          break;
        case 8:
          name = "Easy Eight";
          break;
        case 9:
          name = "Nina";
          break;
        case 10:
          name = "Easy Ten";
          break;
        case 11:
          name = "Yo-Eleven";
          break;
        default:
          name = "Error - Something went wrong";
      }
     } 
   return name;
   }
}

And my code for the actual class that prints out the dice rolls:

import java.util.Scanner;

public class RollSC {
  public static void main(String []args) {

    Dice roll = new Dice();
    Scanner input = new Scanner(System.in);

    System.out.println("Roll 'Em!" + "\n~~~~~~~~~");
    System.out.println("\nYou get to roll the dice two times.\nThe value of both rolls will be added 
    to calculate a total.");

    System.out.println("\nPress enter to roll the die... ");
    input.nextLine();

    System.out.println("Roll #1: " + roll.getDie1());

    System.out.println("\nPress enter to roll the die... ");
    input.nextLine();

    System.out.println("Roll #2: " + roll.getDie2());

    System.out.println("\n\n" + roll.getDie1() + " + " + roll.getDie2() + " = " + roll.getTotal());

    System.out.println(roll.getName() + "!");

  }
}

Now, the only problem that I am getting is that my output only returns zero for the random number. Here is the output I get every single time:

Roll 'Em!
~~~~~~~~~

You get to roll the dice two times.
The value of both rolls will be added to calculate a total.

Press enter to roll the die... 

Roll #1: 0

Press enter to roll the die... 

Roll #2: 0


0 + 0 = 0
null!

I just need some help as to how to fix this output. Thanks!

If Statements Overwriting Previous Setter

This is probably something really simple but I've tried a few things and cant get my head around how to prevent overwriting of a value in a foreach -> if statement.

I have a file which consists of Entries which have individual Entry inside of it. I am trying to set a different value for each individual Entry but currently it is setting them correctly but overwrites on each iteration.

var inputdoc = _service.ConvertToDocument(input);
var journal = _service.ConvertFromLedger(ledger);

foreach (var i in inputdoc .Body)
{
            
        foreach (var doc in journal.Entries)
        {
            doc.Entity = entityCode;

            if (doc.Entity == 23380)
            {
                if (i.Number == "VALBEU1") { doc.BankAccount = "435345345"; }
                if (i.Number == "VALBGB1") { doc.BankAccount = "324234234"; }
                if (i.Number == "VALBHU1") { doc.BankAccount = "45342123123"; }
                if (i.Number == "VALBMX1") { doc.BankAccount = "45546231"; }
                if (i.Number == "VALBSE1") { doc.BankAccount = "2344353123"; }
                if (i.Number == "VALBUS1") { doc.BankAccount = "234435645"; }
                if (i.Number == "VALBNO1") { doc.BankAccount = "234233123"; }
            }
        }
  }

So the issue is the end result of the single Entry end up having the same BankAccount value when it should be different depending on the i.Number.. so how is it that i can make it so that when I go through my Entries and set my Entry value that BankAccount number remains the same and moves onto the next Entry..sets that value and so on..

Conditional statement shortcut (python)

I cannot find where my professor taught us to do this. For a conditional statement, if there are multiple numbers ("if x = 1 or 3 or 5 or 9 or ......), how do I make it shorter so I dont have to type every single one? I thought it was the in function???

this is what exactly im trying to do:

elif month == 1 and day == in[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 24, 25, 26, 27, 28, 29, 30]: print("January", day + "th", year, "is a valid date")

Python Error Message - IF STATEMENT SYNTAX ERROR [closed]

Really Confused, as I cant seem to get this Code to Work - It keeps on giving me an "Invalid Syntax" on an IF statement and i have checked the Indentation ...

enter image description here

Problems with If and Switch Statements in a DiceRoll project I am making

One of the classes I am currently working on is a DiceRoll project. One of the requirements of the project is to use nested if else statements and at least one switch statement. Another requirement is to give the slang for the dice roll as per this image Dice Roll Slang

Here is my current code, with an explanation at the bottom:

import java.util.Random;

public class Dice {
 public int die1;
 public int die2;
 public int total;
 public String name;
 public boolean doubles = false;

 Random random = new Random();

  public void setDie1() {
   die1 = random.nextInt(6) + 1;
  }

  public void setDie2() {
    die2 = random.nextInt(6) + 1;
  }

  public void setTotal() {
    total = die1 + die2;
  }

  public int getDie1() {
    return "Roll #1: " + die1;
  }

  public int getDie2() {
    return "Roll #2: " + die2;
  }

  public int getTotal() {
    return die1 + "plus" + die2 + "=" + total;
  }

  public boolean checkDouble() {
    if (die1 == die2) {
      doubles = true;
      return " ";
    } else {
      doubles = false;
      return " ";
    }
    return " ";
  }

  public String getName() {
    if (doubles = true){
      name = "1";
    } else if (total = 7) {
      name = "7";
    } else if (total = 5) {
      name = "5";
    } else if (total = 9) {
      name = "9";
    } else if (total = 11) {
      name = "11";
    } else if ((die1 = 1 && die2 = 2) || (die1 = 2 && die2 = 1)) {
      name = "2";
    } else if ((die1 = 4 && die2 = 2) || (die1 = 2 && die2 = 4)) {
      name = "6";
    }
  }
}

So my original idea was to create nested if else statements in getName. These would correspond to numbers and then I would use these numbers to make a switch statement - also in getName - that would return the dice slang depending on what number was rolled. The only problem I found with this is that since there are multiple ways to roll each number.

If the number is a six for example, you can roll a double 3, or a 2 and a 4. That means I will have to create a lot of different cases and create a very long switch statement. I also end up getting an error with the name = "2"; and name = "6"; statements where it is expecting a <= in place of the = for the conditions after the && .

I think that there is definitely a better way to do this, but I just cannot figure it out. I am going to keep trying and working at it, but I greatly appreciate any help. Thank you.

How to generate an array of pseudo-random, unique, sorted integers without using an if statement?

I need to create an array of pseudo-random unique integers that are already in an ascending order without using an if statement. For example:

[3,5,7,12]

So far I was able to come up with this code, which repeats some numbers and doesn't put the integers in sorted order.

int[] arr = new int[r.nextInt(10)];
for (int i = 0; i < arr.length; i++) {
    int randInt = r.nextInt(arr.length);
    arr[i] = randInt;
}

What is the best way to work around this? Note: I have to not use the ArrayList and sort method.

Multiple conditions inside IF statement refactoring

I need to provide validation for some things and this validation contains tons of conditions inside single If statement.

I'm looking for a possible way to refactor If statement below to make it more compact or just look nicer.

            if ((GetAverage(params1) / GetAverage(params2) >= 1.3
                && GetAverage(params3) / GetAverage(params4) >= 1.3
                && GetAverage(params5) / GetAverage(params6) >= 1.3
                && GetAverage(params7) / GetAverage(params8) >= 1.3
                && GetAverage(params9) / GetAverage(params10) >= 1.5
                && GetAverage(params11) / GetAverage(params12) >= 1.5
                && GetAverage(params13) / GetAverage(params14) >= 0.5
                && GetAverage(params15) / GetAverage(params16) >= 0.5
                && GetAverage(params17) / GetAverage(params18) >= 0.5
                && GetAverage(params19) / GetAverage(params20) >= 0.5)
                || 
                (val1 > val && GetAverage(params1) / GetAverage(params2) >= 1.5
                && GetAverage(params3) / GetAverage(params4) >= 1.25
                && GetAverage(params5) / GetAverage(params6) >= 0.75
                && GetAverage(params7) / GetAverage(params8) >= 0.75)
                ||
                (val2 > val1 && GetAverage(params1) / GetAverage(params2) >= 1.75
                && GetAverage(params3) / GetAverage(params4) >= 1.75
                && GetAverage(params5) / GetAverage(params6) >= 0.75
                && GetAverage(params7) / GetAverage(params8) >= 0.75
                && GetAverage(params9) / GetAverage(params10) >= 0.20)
                ||
                (val1 > val2 && GetAverage(params1) / GetAverage(params2) >= 0.75
                && GetAverage(params3) / GetAverage(params4) >= 0.80
                && GetAverage(params5) / GetAverage(params6) >= 0.20)
                ||
                (val2 > val1 && GetAverage(params1) / GetAverage(params2) >= 0.75
                && GetAverage(params3) / GetAverage(params4) >= 0.80
                && GetAverage(params5) / GetAverage(params6) >= 0.20)
                ||
                (val1 > val2 && GetAverage(params1) / GetAverage(params1) >= 0.75
                && GetAverage(params3) / GetAverage(params4) >= 0.20)
                ||
                (val2 > val1 &&  GetAverage(params1) / GetAverage(params2) >= 0.75
                && GetAverage(paramsparams3) / GetAverage(params4) >= 0.20))
            {
                /// result of validation.
            }

there could be different set of parameters for getting average. is it possible to run these checks in foreach somehow???

thanks for any advice.