lundi 30 novembre 2020

[Beginner]How do you make the game start again when the user exit by entering -1?

I'm trying to make a Hi-Lo guessing game, and I've been struggling to find a way to make the game start again when the user enters '-1'.

I have just started to learn java by myself, so please let me know if you have any suggestions or advice to improve the code I made. I would really appreciate your help.

Game explanations

1)The game generates a random number between 0 and 100, and the user has to guess it. If the guess is bigger or smaller than the random number, it displays messages.

2)If the user enters a value out of range, the game displays a warning message.

3)If the guess is correct, the game gives an option asking if the user wants to play it again.

★★4)Here, when the user enters a certain value (I set it to -1), I want the game to end, but also want to give an option to start the game again.★★


//import random number generator and scanner
import java.util.Random;
import java.util.Scanner;

    public class HighLowGame {

    public static void main(String[] args) {

    //create scanner, variables and a random number
    Scanner scanner = new Scanner (System.in);
    Random generator = new Random();
    int number =generator.nextInt(100) + 1;
    int count = 0;
    boolean game = true;

    //prompt user to enter a number
    System.out.println("Please guess the number.(Enter -1 to quit): ");

    while(game){

        //user enters a number
        int guess = scanner.nextInt();

        //if user enters -1, the game ends
        if(guess == -1){
            break;
        }

        //guessed number is out of range
        if(guess>100 || guess<0){
            System.out.println("The number should be between 0 and 100.");
        }

        //guessed number is smaller than the random number
        if(guess < number && 0 <= guess && guess <= 100 ){
            count++;
            System.out.println("That is too low. Please try again.(Enter -1 to quit):");
        }

        // guessed number is bigger than the random number
        else if(guess > number && 0 <= guess && guess <= 100){
            count++;
            System.out.println("That is too high. Please try again.(Enter -1 to quit):");
        }

        //guessed number is the same as the random number
        else if(guess==number) {
            count++;

            //displays the message and the attempt count
            System.out.println("Congratulations! You got the correct number.");
            System.out.println("Your attempt was " + count + " tries.");

            // ask the user if they want to play the game again
            count = 0;
            System.out.println("Would you like to play the game again?(yes/no): ");
            String another = scanner.next();

            // if the user wants to end the game, it ends
            if (another.equalsIgnoreCase("no")) {
                break;
            }

            // if the user wants to play the game one more time, it starts again
            else {
                number = generator.nextInt(100) + 1;
                System.out.println("Please guess the number(Enter -1 to quit): ");
                }
            }

       }

    }

 }

R loop to copy content from two columns, according a third column, and output into a fourth column

I am aware of the solutions on similar problems and have read through all I found (hence the code provided below), but unfortunately couldn't make them work properly. Also, I am very unfamiliar with loops...

What I'm trying to do: I have a dataset data and am trying to input values in column Cov_length from either column length_L1 or column length_L2, depending on the values in yet a third column: Language: A) If Language states in a specific row L1, then I input the according row value from column length_L1 into Cov_length. B) And correspondingly if value in Language is L2, input the corresponding row value of length_L2 into Cov_length.

Here is some example data:

data111 <- data.frame(Language = c("L1","L1", "L2", "L1", "L2", "L2", "L2", "L1"),
                      Length_L1 = c(4, 7, 3, 12, 10, 5, 5, 7),
                      Length_L2 = c(5, 2, 9, 7, 3, 3, 4, 10),
                      Cov_length = c(0, 0, 0, 0, 0, 0, 0, 0))
> data111
  Language Length_L1 Length_L2 Cov_length
1       L1         4         5          0
2       L1         7         2          0
3       L2         3         9          0
4       L1        12         7          0
5       L2        10         3          0
6       L2         5         3          0
7       L2         5         4          0
8       L1         7        10          0

Here are two solutions I have tried. The first one just runs without error but doesn't do anything (values remain zeros in Cov_length).

for (i in 1:length(data$Language)) {
  if (i == "L1") {data$Cov_length [i] <- data$length_L1 [i] }
  else if (i == "L2") {data$Cov_length [i] <- data$length_L2 [i] }
  else {}
}

And this second solution just takes all the values from column length_L1 instead of actually selecting values between the two columns.

require(base)  
data %>% 
  mutate (Cov_length = ifelse(Language == "L1", paste(length_L1), paste(length_L2))) 

There are a number of cases in my data I'd have to do the above, and it is a 8000-observation piece, with random order of the L1/L2 values (I couldn't efficiently do it by hand). So any advice would be helpful. Thanks!

crossing if statement function in python

I am trying to make an if statement that only goes through when the green line is crossed by the black line or if the red line crosses the black line. Note that the green and red line values are not equivalent to black_line values so i cannot use the <=, >= or == functions when defining the if statement.

black_line = [*black line values]
green_line = [*green line values]
red_line = [*red line values]
for i in range(len(black_line)):
    if green_line [i] crosses black_line[i]:   
        print("green line crossed")
    elif red_line [i] crosses black_line[i]:   
        print("red line crossed")

enter image description here

I have this problem with my code in java How to solve it? [duplicate]

My college professor told me to make a program that calculates if two lines are parallel or not using the equation a1b2=a2b1 and If they are parallel it will print the lines are parallel but if they are not I have to use the equation (𝑥𝑖,𝑦𝑖)=(𝑏1𝑐2−𝑏2𝑐1/𝑎1𝑏2−𝑎2𝑏1 , 𝑐1𝑎2−𝑐2𝑎1/𝑎1𝑏2−𝑎2𝑏1) to find the intersection but I get this error The local variable x may not have been initialized and I don't know how to solve It My questions are

1- Why did I get this error?

2- Did I typed the equations wrong In my code?

3- Is there a better way to write this program?

4- How to find which quadrant the lines lie?

Scanner input = new Scanner(System.in);
double a1 , b1 , c1 , a2 , b2 , c2, X ,Y;
System.out.print("enter line 1 coefficient");
a1 = input.nextDouble();
b2 = input.nextDouble();
c1 = input.nextDouble();
System.out.print("enter line 2 coefficient");
a2 = input.nextDouble();
b1 = input.nextDouble();
c2 = input.nextDouble();
if (a1 * b2 == a2 * b1)
System.out.print("the lines are parallel");
else if (a1 * b2 != a2 * b1)
X = ((b1*c2) - (b2*c1) /(a1*b2) - (a2*b1));
Y = ((c1*a2) - (c2*a1) / (a1*b2) - (a2*b1));
System.out.printf( "intersected straight lines in point %.2f , %.2f  that lies in first quadrant" , X ,Y);

ValueError: The truth value of a Series is ambiguous. When using for loop over a dataframe

I am a newbie in the world of python. I have a dataframe that holds ETF Fund "Score" values, updated every day for the past ten years. I am trying to group these together, by collecting the day when the score first passes above a certain value, say 4, and then the day before it passes below 4. I get an error that says the truth value of a series is ambiguous. Please let me know what I am doing wrong.

Here is an example of the dataframe:

Date(index)     Score
1/20/2010       1.489
1/21/2010       1.9
1/22/2010       4
1/23/2010       4.333
1/24/2010       4.6
1/25/2010       3.9

Here is the code I wrote:

csv.columns =['Date', 'Score']

csv['Date'] = pd.to_datetime(csv['Date'])

csv = csv.set_index('Date')
csv = csv.sort_index().asfreq('D', method='pad')
csv['Score'] = csv['Score'].astype(int)

for val in csv.Score:
    if csv.Score >= 4:
        if csv.Score.shift(-1) <4 or csv.Score.shift() <4:
            print(val)
        else:
            continue
    else:
        continue

This code returns a "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."

The output I would like to achieve is a dataframe consisting of even (including zero) index values being the start date of Score > 4 and the odd index values the end date of Score > 4. Please help.

Can anyone please help me to solve these questions? [closed]

The requested project is dealing with some analysis of 2D straight line geometric shapes. As you studied in your earlier stages, a straight line has many defining equation forms in 2D geometry. One famous equation for defining straight line is: while a, b and c are real numbers. Any 2 straight lines in the plane are either parallel (have no intersection point) or intersected in a point in the plane. If the two straight lines are defined as: The two straight lines are considered parallel if: a1b2 = a2b1. The two straight lines are considered not parallel and intersected in an intersection point (xi, yi) where a1b2 ≠ a2b1 and in this case the coordinates of the intersection point and are defined as: Implement a Java program that reads from the user the 6 coefficient values of the 2 straight lines a1,b1,c1 and a2,b2,c2 (for minimum 20 pairs of straight lines.)  The program checks, for each pair, if they are parallel or intersected.  If, for each pair, they are intersected, the program has to computer the coordinates of the intersection point as given in equation 3.  Finally, the program should print the number and percent ratio (rounded to 2 decimal places) of: o Parallel straight line pairs. o Intersected straight line pairs. o Intersected straight line pairs with intersection point on x-axis or y-axis. o Intersected straight line pairs with intersection point in first plane quadrant. o Intersected straight line pairs with intersection point in second plane quadrant. o Intersected straight line pairs with intersection point in third plane quadrant. o Intersected straight line pairs with intersection point in fourth plane quadrant. Note: You may use digital library or internet to check each case of intersection point coordinates.  The program should works EXACTLY as given sample run Sample Run:

Enter number of straight line pairs: 12 Minimum accepted number of straight line pairs is 20 Enter number of straight line pairs: 27 Enter pair 1 straight line 1 coefficient: 1 3 4 Enter pair 1 straight line 2 coefficient: 2 1 3 Intersected straight lines in point (-1.00,-1.00) that lies in third quadrant Enter pair 2 straight line 1 coefficient: 2 5 1 Enter pair 2 straight line 2 coefficient: 3 1 3 Intersected straight lines in point (-1.08,0.23) that lies in second quadrant Enter pair 3 straight line 1 coefficient: 2 2 2 Enter pair 3 straight line 2 coefficient: 3 1 4 Intersected straight lines in point (-1.50,0.50) that lies in second quadrant. Enter pair 26 straight line 1 coefficient: 4 3 2 Enter pair 26 straight line 2 coefficient: 1 2 3 Intersected straight lines in point (1.00,-2.00) that lies in fourth quadrant Enter pair 27 straight line 1 coefficient: 1 1 1 Enter pair 27 straight line 2 coefficient: 2 2 2 Parallel straight lines Program Statistics >>>>>>>>>>>>>>>>>>>>>>> Number of entered pairs of straight lines: 27 Number of parallel pairs of straight lines: 5 with 19% of the given pairs Number of intersected pairs of straight lines: 22 with 81% of the given pairs Number of pairs of straight lines with intersection point on x-axis or y-axis: 4 with 18% of the intersected pairs Number of pairs of straight lines with intersection point in the first quadrant: 8 with 36% of the intersected pairs Number of pairs of straight lines with intersection point in the second quadrant: 5 with 23% of the intersected pairs Number of pairs of straight lines with intersection point in the third quadrant: 2 with 9% of the intersected pairs Number of pairs of straight lines with intersection point in the fourth quadrant: 3 with 14% of the intersected pairs

If cell value in table range equals "New" copy entire row and paste as values in sheet 1 in the next empty cell

I am trying to do a basic thing but cannot get it right.

I want to evaluate the cells on sheet 2(New Roster) in a table column(OldNew) for the value "New". If it has the value, copy the entire row and add it to the table(CurrentRoster) on sheet 1(Current Roster).

Here is the code I am using:

For Each c In wb.Names("OldNew").RefersToRange.Cells
    If c.Value Like "New" Then
        On Error Resume Next
        Set SourceTable = Worksheets("New Roster").ListObjects("NewRoster").DataBodyRange
        Set DestinationTable = Worksheets("Current Roster").ListObjects("CurrentRoster").ListRows.Add
        SourceTable.Copy
        DestinationTable.Range.PasteSpecial xlPasteValues
    End If
Next

This endlessly loops and does not do what I want.

Here is the entire code for context: Sub TableData()

Dim tbl As ListObject Dim cell As Range Dim rng As Range Dim RangeName As String Dim CellName As String Dim wb As Workbook, c As Range, m Dim ws1 As Worksheet Dim lr As Long Dim lo As ListObject Dim SourceTable Dim DestinationTable

Worksheets("New Roster").Activate Range("A1").Select

If Range("A1") = "" Then
     MsgBox "No Data to Reconcile"
     Exit Sub
    Else
 End If

Application.ScreenUpdating = False  '---->Prevents screen flickering as the code executes.
Application.DisplayAlerts = False  '---->Prevents warning "pop-ups" from appearing.

 ' Clears hidden columns from previous user
Worksheets("Current Roster").Activate
Range("A1").Activate
Columns.EntireColumn.Hidden = False

On Error Resume Next
 Sheet1.ShowAllData
On Error GoTo 0

' Tables the New Roster
Worksheets("New Roster").Activate
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes).Name _
= "NewRoster"
Range("NewRoster[#All]").Select
ActiveSheet.ListObjects("NewRoster").TableStyle = ""

' Name Ranges for Reference, New Name List From New Roster
ActiveSheet.Range("F2").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWorkbook.Names.Add Name:="NewNameList", RefersToR1C1:= _
"=NewRoster[Member AHCCCS ID]"
ActiveWorkbook.Names("NewNameList").Comment = "Contains New list to compare old list to"


' Compares CurrentNameList Values to NewNameList Values to verify if current names are still active
Set wb = ThisWorkbook
For Each c In wb.Names("CurrentNameList").RefersToRange.Cells
    m = Application.Match(c.Value, wb.Names("NewNameList").RefersToRange, 0)
    c.Offset(0, 26).Value = IIf(IsError(m), "InActive", "Active")
Next c

' Adds Column to New Roster Table and place Old/New in header cell
Worksheets("New Roster").Activate
Worksheets("New Roster").Range("AF1").Value = "Old/New"

' Names Old/New Range
ActiveSheet.Range("AF1").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWorkbook.Names.Add Name:="OldNew", RefersToR1C1:= _
"=NewRoster[Old/New]"
ActiveWorkbook.Names("OldNew").Comment = ""

' Compares CurrentNameList Values to NewNameList Values to determine if New Name, If so, Add to Current 
Roster
For Each c In wb.Names("NewNameList").RefersToRange.Cells
    m = Application.Match(c.Value, wb.Names("CurrentNameList").RefersToRange, 0)
    c.Offset(0, 26).Value = IIf(IsError(m), "New", "Old")
Next c
    
' Move Rows with "New" from New Roster to Current Roster Worksheet
Worksheets("New Roster").Activate

For Each c In wb.Names("OldNew").RefersToRange.Cells
    If c.Value Like "New" Then
        On Error Resume Next
        Set SourceTable = Worksheets("New Roster").ListObjects("NewRoster").DataBodyRange
        Set DestinationTable = Worksheets("Current Roster").ListObjects("CurrentRoster").ListRows.Add
        SourceTable.Copy
        DestinationTable.Range.PasteSpecial xlPasteValues
    End If
Next
    
 ' Clear New Roster Data
Worksheets("New Roster").Activate
Columns("A:A").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Delete Shift:=xlToLeft
ActiveWorkbook.Names("NewNameList").Delete
ActiveWorkbook.Names("OldNew").Delete
Worksheets("Current Roster").Activate
Range("A1").Activate
ActiveSheet.Range("CurrentRoster[#All]").RemoveDuplicates Columns:=Array(1, 2, _
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 
30, 31 _
, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55), _
Header:=xlYes



Application.DisplayAlerts = True   '---->Resets the default.
Application.ScreenUpdating = True  '---->Resets the default.


End Sub

How to transform values in a Matrix when condition is met in R?

I have a 40x18 matrix. What I want to do is to check (for loop) every value "x" in this matrix and then if >=0, the x should be transformed to x^alfa. If x<0, then transform it in the way -lamda*(-x)^beta.

At the end, I want to have a new matrix with the transformer values.

I tried this way but it doesn't work. Can anyone help?

Here is a part of my data:

V1 = c(-0.0488238351305964, -0.0365464622704548, -0.023110113947345, -0.00936478818716672, -0.0014143836369377, 0.0136298911422536), V2 = c(-0.0440798156253931, -0.0290469503666371, -0.0184194158583475,-0.00659023901355601, 0.0104814403440645, 0.02050543245721), df[1:40,18) V3 = c(-0.0500446221600135, -0.0310561032780763, -0.0202547384070556, -0.00900829333252385, 0.0179628052483861, 0.024328936936393))

for (h in 1:18) { if df[,h] >= 0,

df1[,h] <- df[,h]^alfa` else df1[,h] <- df[,h]^beta`

}

Returning dates in different format in python

I have made a function in the format: day/month/year. I would like to make another function that asks the user for example: "When do you want to come?" and depending on what month the user say I want to print out a answer.

The problem: I don't know how to make the function that asks the user for the format: day/month/year without limit the years, I would like the user to enter any year and still be able to get the same answers as another any year (but different month).

enter code here
import datetime 

def dateformat(date):
    return datetime.datetime.strptime(datumet, "%d/%m/%Y")

def ask_user():
    winter = dateformat('1/1/2020') <= dateformat('31/3/2020')
    spring = dateformat('1/4/2020') <= dateformat('31/5/2021')
    summer = dateformat('1/6/2020') <= dateformat('31/9/2021')
    autumn = dateformat('1/10/2020') <= dateformat('31/12/2021')
    
    a = dateformat(input("When do you want to come"))
    if a == winter:
        print("Hi")
    if a == spring:
        print("bye")
    if a == summer:
        print("ok")
    if a == autumn:
        print("no")

My question: How can I make this code work for any year? I would like to be able to type any year but inside the month and get the same output. If I only return %d/%m in the dateformat-function the user will not be able to type: day/month/year. Is there maybe a better way of returning the format?

How can I change a global variable's value from inside a function?

I have a @State boolean in my code inside the struct which I have a button that toggle()s it. However, I want to use that variable in my other views as well. So I need to have it outside struct so I can use it another place. My question is that how can I now change its value? Previously my button's action toggled it. How can I change it now?

Here is my code:

struct myView: View {
@State var checked:Bool = false

var body: some View {
HStack {
                                Button(action: {checked.toggle()}) {
                                    Image(systemName: checked ? "checkmark.square": "square")
                                        .resizable()
                                        .aspectRatio(contentMode: .fit)
                                        .scaledToFit()
                                        .foregroundColor(.black)
                                        .frame(height: 20)
                                }
                                Text("I agree")
                                    .fontWeight(.bold)
                                Spacer()
                            }
                            .padding(.horizontal, 20)
                            Spacer()
}
}

However, I want this to work:

var checked:Bool = false
struct myView: View {

var body: some View {
HStack {
                                Button(action: {checked.toggle()}) {
                                    Image(systemName: checked ? "checkmark.square": "square")
                                        .resizable()
                                        .aspectRatio(contentMode: .fit)
                                        .scaledToFit()
                                        .foregroundColor(.black)
                                        .frame(height: 20)
                                }
                                Text("I agree")
                                    .fontWeight(.bold)
                                Spacer()
                            }
                            .padding(.horizontal, 20)
                            Spacer()
}
}

String list from a txt file doesn't recognize other word as the same when i compare it

I'm making a game where you get a lyric and you have to guess the artist or the song. The thing is that when I try to see if the input of the player is in the list where the Artist and song are located just doenst works, i tried it with the same words but python just tell print me "no" every time.

This is just a part of big code so if something doesn't make sense is because I write it in a way that you could understand what I want to do:

def reading(file, lycris, artistandsong): 
    firstline = file.readline()
    artistandsong=(firstline.split(";"))
    return artistandsong

file=open("E:\\Documents\\TP IP 2do 2020\\letras\\1.txt","r")
lycris=[]
artistandsong=[]
wordsfromuser=[""]
artist=reading(file,lycris,artistandsong)

for word in artist:
    if word in wordsfromuser:
     print("yes")
    else:
     print("no")
file.close()

I have also tried if word == words

Why does this if condition not work when I add parentheses around the left hand side of the inequation?

I was trying out a problem, and my code failed one of its test cases. I traced back the error, and it can be summarized by the following code:

#include <stdio.h>

int main(void)
{
  int a = 90000;
  int b = 80000;

  if (a * b <= a + b)
  {
    printf("YES\n");
  }
  else
  {
    printf("NO\n");
  }
}

I would expect the output to be a "NO" (since 90000 * 80000 > 90000 + 80000). But turns out, when compiled and run, the above program outputs "YES".

I suspect this has something to do with the range of an int in C. The range of an int on a 64-bit OS (the one I have) is 4 bytes, thus all the integers from -2,147,483,648 to 2,147,483,647 can be represented by an int. But a * b in the above code is 7200000000, which is well beyond the bounds of an int. So I tried casting the value of a * b to a long long int as follows

#include <stdio.h>

int main(void)
{
  int a = 90000;
  int b = 80000;

  if ((long long int) a * b <= a + b)
  {
    printf("YES\n");
  }
  else
  {
    printf("NO\n");
  }
}

But still the output stays the same, "YES". I can't seem to figure out how I can make the program return the correct output. How can I do it? This has been solved. The above code works perfectly fine.


Like MathewHD pointer out in the comments that declaring a and b as longs rather than ints solves the issue. Then why does casting not work? Casting works (refer the above code). Also, where is this temporary variable having the value of a * b stored, and how can I change the data type of that temporary variable?


Turns out I was using a slightly different code when the error was generated. Using the above code (the one which includes casting to a long), does give the expected output, however adding parentheses around the left hand side of the condition, makes the program return the wrong output i.e. "YES". The code follows

#include <stdio.h>

int main(void)
{
  int a = 90000;
  int b = 80000;

  if ((long long int) (a * b) <= a + b)
  {
    printf("YES\n");
  }
  else
  {
    printf("NO\n");
  }
}

The main reason why I initially thought of adding the parentheses around the left hand side of the inequation, was to ensure that the compiler does not misinterpret the casting to be for only one of the involved integers rather than their product. So I just wanted their product to be casted. I would love an explanation as to why adding the parentheses does more harm than good, i.e. why doe it make the program return wrong outputs?

One of my previous question also remains: Where is this temporary variable having the value of a * b stored, and how can I change the data type of that temporary variable?

How to allocate using a loop in macro VBA?

I have a dataset that i would like to perform allocation on, below are the constraints:

  1. Each container can only contain 310 pieces
  2. We can mix colours, but the point is the maximise the 310

The code below is able to loop through every colour and split them into multiples of 310. however, when it reaches white and chalk, the code breaks.

For the code to work correctly, we should put 160 white, 120 chalk and 30 red in 1 container (in the same row).

As the code below iterates by columns, it does not work when the column next to it is a 0, and the container has not reached maximum capacity. It pushes the next available value to the next container

Sub sum_of_substract()
Dim i, r As Integer
Dim another As Integer
Dim LastRow As Long
LastRow = ActiveSheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
r = 5

Cells(LastRow + 1, 2).Formula = "=SUM(C" & LastRow + 1 & ":CO" & LastRow + 1 & ")"
For i = 3 To 93
While (Cells(4, i).Value) > 0
    If IsEmpty(ActiveSheet.Cells(4, i)) = False And Cells(4, i).Value < 310 And Cells(LastRow + 1, Value + Cells(4, i + 1).Value <= 310 Then
        Cells(LastRow + 1, 2).Formula = "=SUM(C" & LastRow + 1 & ":CO" & LastRow + 1 & ")"
        Cells(LastRow + 1, i).Value = Cells(4, i).Value
        Cells(4, i).Value = Cells(4, i).Value - Cells(4, i).Value
        Cells(LastRow + 1, i + 1).Value = Cells(4, i + 1).Value
        Cells(4, i + 1).Value = Cells(4, i + 1).Value - Cells(4, i + 1).Value
    
    
    
    ElseIf ActiveSheet.Cells(4, i) <> 0 And Cells(4, i).Value < 310 And Cells(LastRow + 1, 2).Value + Cells(4, i + 1).Value > 310 Then
        Cells(LastRow + 1, i + 1).Value = Cells(LastRow + 1, 2).Value - Cells(4, i + 1).Value
        Cells(LastRow + 1, 2).Formula = "=SUM(C" & LastRow + 1 & ":CO" & LastRow + 1 & ")"

    
    Else
        Cells(LastRow + 1, i).Value = 310
        Cells(4, i).Value = Cells(4, i).Value - 310
        Cells(LastRow + 1, 2).Formula = "=SUM(C" & LastRow + 1 & ":CO" & LastRow + 1 & ")"

    
End If
    LastRow = LastRow + 1

Wend

Next i

End Sub

Dataset

R - Add New column based on days in between dates

I have a data set with ID, multiple dates for COVID test for that ID, results, and a new column called CaseID.

ID      DATE            Results         CASEID
1       01/01/2020     POSITIVE           ...
1       02/12/2020     NEGATIVE           ...
1       03/01/2020     POSITIVE           ...

My question is: is there a way to say: if from the first positive for an ID (so 01/01/2020 for ID 1) is approximately 60 days, 90 days or 120 days between two positive test, then put the category "60days" or "90days" or "120days" in th column CaseID.

In this case it will be 60 days.

Is that possible?

Translate these multiple conditional from R to Python

I would appreciate if you could help me on this one, please.

The Problem

ifelse(df2$Status=="Completion", "Completed",
    ifelse(df2$Status=="Declined"|df2$Status=="DIP Declined","Declined",
        ifelse(df2$Status=="Withdrawn"& df2$Decision == "Decline" | df2$Decision == "Refer" | df2$Decision == "Decline"),"Declined - Withdrawn",
             ifelse(df2$Status=="Withdrawn","Withdrawn", "In-Flight"))))

My Attempt

np.where(df2["Status"]=="Completion", "Completed",\
    (np.where(np.logical_or(df2.Status=="Declined",df2.Status=="DIP Declined"),"Declined",\
        (np.where(np.logical_and(df2.Status=="Withdrawn",np.logical_or(np.logical_or(df2["Decision"]=="Decline",df2["Decision"]=="Refer"),df2["Decision"]=="Decline"),"Declined - Withdrawn",
            (np.where(df2.Status=="Withdrawn","Withdrawn","In-Flight")
 )))))))

Error message

TypeError: ufunc() takes from 2 to 3arguments but 4 were given

Thank you!

PHP code is not being executed but is shows no errors [closed]

The rest of the code works fine but this particular area is not being executed. Also, I'm not getting any errors.

/ ---------- DRAGON FORCE ---------
public function dragonF()
{
    echo $this->character1 . "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa uses " . "<br />";
    $this->damage = $this->damage * 2;
}

// ------ GET & SET SPECIAL SKILLS ------

public function getSpecialSkill1($name)
{
    foreach((array) $this->specialSkill1 as $skill1){
        if ($skill1['name'] == 'skilldragonForce' && $skill1['name'] == $name)
        {
            $randomChance = rand(0, 100);
            if ($randomChance <= $skill1['chance'])
            {
                $this->dragonF();
            }
        }
    }
}

public function setSpecialSkill1()
{
    $this->specialSkill1 = array (
        'attack'  => array (
                'name'     => 'skilldragonForce',
                'chance'   => 90
            ),
    );        
}

This is the condition, I've tried to echo something and it works, that's why I think the problem comes from the code above

     if($this->attacker->getType() === 1 && $this->attacker->getDamage())
     {           
         $this->attacker->getSpecialSkill1('skilldragonForce');
     }

Problems while comparing years and sizes of file in batch

I've a doubt for doing a comparison (if statement's) inside a for loop: I've a lot of files inside a folder, and I want to make two comparisons:

  1. If the file was created at the current year (!dateFile:~6,4! equ %date:~6,4%)
  2. If the size of the file is 0 bytes (%%~Za equ 0)

When I find a file that complies these conditions, I want to show "ok".

I've the next line of code, but it doesn't work:

    for /f "tokens=* delims= " %%a in ('dir /s/b/a-d "FOLDER\"') do set dateFile=%%~ta if ((!dateFile:~6,4! equ %date:~6,4%) & (%%~Za equ 0)) echo "ok"

Some help? Thanks :)

if else on windows batch

I tried to create a script with c++ which will active a batch code if user tries to shutdown his computer.

if(system("shutdown -s")){ runs batch code }

But I failed so then I attempted (did not try because I dont how to and couldn't found anythink helpful on google so I ask you guys now) to create a bath code which will be active for 30 minutes and if user tries to shutdown his computer it will run another batch code which I used on my c++ project I mentioned in the beginning. So can you guys help me with this? You can tell me how to write this full on batch , or use c++ 's if else statement then run the batch code. Thanks.

Method for returning the mode that occurs most frequently

I need help on this problem:

Write the method mode that accepts an array of test grades(0 – 100) and return the mode, the grade that occurs most frequently. If there are multiple modes, return the smallest.

My code does not work: Please help, thanks!

public static int mode(int[] marks) {
    int count = 0;
    int count0 = 0;
    int mostFrequent = marks[0];
    for (int x = 0; x < marks.length; x++) {
        if (marks[x] == mostFrequent) {
            count++;
        }
    }
    if (count>count0) {
       count0  = count;
       mostFrequent = marks[count];
    }
    return mostFrequent;
}

E.g:

If marks = {1,2,4,6,1,1,1}, it works

if marks = {1,2,4,1,3,2,3,5,5}, it does not work

dimanche 29 novembre 2020

How can I change a variable based on different booleans?

Can I know how to shorten this code?

I am trying to change the value of my Text only and I have written so many lines. Can I know how to change it and make it short?

if (selectedPage == OnboardingCard.last?.id) {
                                        Text("Get Started!")
                                            .foregroundColor(Color.white)
                                            .fontWeight(.bold)
                                            .padding(10)
                                            .padding(.horizontal)
                                            .background(Color.blue)
                                            .clipShape(Capsule())
                                    } else if (selectedPage == OnboardingCard.first?.id) {
                                        Text("Let's go!")
                                            .foregroundColor(Color.white)
                                            .fontWeight(.bold)
                                            .padding(11)
                                            .padding(.horizontal)
                                            .background(Color.blue)
                                            .clipShape(Capsule())
                                    } else {
                                        Text("Next")
                                        .foregroundColor(Color.white)
                                        .fontWeight(.bold)
                                        .padding(10)
                                        .padding(.horizontal)
                                        .background(Color.blue)
                                        .clipShape(Capsule())
                                    }

How to write to function to check how long input from user is

I need to write function to check if my number from user prompt number and if is he 13 charachers long. My idea was to set 2 condition, but it doesn't seem to work.

var num =parseInt(prompt("Write your number"));

if( typeof(num) ==="number" && num.length ==13){
console.log("It's number 13 chars long");
}
else{
console.log("It's not number or it's not 13 chars long");
}

If i use 2 separated condiotions its work :O I dont know do that with regex cuz im am begginer :)

Calculating test grade averages without using arrays or min/max in C++

I am currently very sleep deprived, mashing buttons into my keyboard , on an assignment that i procrastinated. Which, obviously, is my own fault, but if anyone on here could give some pointers of the use of functions here, i'd greatly appreciate it. The assignment is as follows:

"Write a program that calculates the average of a group of test scores, where the lowest score in the group is dropped. It should use the following functions:

void getScore() should ask the user for a test score, store it in a reference parameter variable, and validate it. This function should be called by main once for each of the 6 scores to be entered. Use a local static variable for which score is to be entered.

void calcAverage() should calculate and display the average of the five highest scores. This function should be called just once by main and should be passed the six scores. Include 2 decimal places on the result. This is passed data by value.

double findLowest() should find and return the lowest of the six scores passed to it. It should be called by calcAverage, which uses the function to determine which of the six scores to drop. This is passed data by value.

Do not use the min or max C++ functions."

What i'm failing to discover is how i can use a void function to pass data back to int main. My code so far is a stringy mess of errors, but i'm not sure how else to approach this one.



#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double getScore(double);
double calcAverage(double);
double findLowest(double);
int main()
{
    
    double score = 0;
    double combinedScore = 0;


    getScore(score);

    calcAverage(combinedScore);

    findLowest();

}

double getScore(double score)
{
    double grade;
    int testNum = 1;

    cout << "Enter the test " << testNum << " grade :";
    cin >> grade;
    while (grade < 0)
    {
        cout << "Invalid entry! Must be at least zero.";
        cin >> grade;
    }
    while (testNum <= 6)
    {
        cout << "Enter the test " << testNum << " grade :";
        cin >> grade;
        if (grade < 0)
        {
            cout << "Invalid entry! Must be at least zero.";
            cin >> grade;
        }
        else
        testNum++;
        cout << "Enter the test " << testNum << " grade :";

        return (grade);
    }
}

void calcAverage()
{
    
}

double findLowest()
{

}

Thanks in advance for anything that points me in the right direction.

How do I check for the smallest array value every time?

So there is a 2d array. In every row of the first column, there are 4 pieces. Every space on the 2d array is a stack of pieces, whether it be 0 or more. Every piece in the first column has to be moved to the second column, but they can only be moved one at a time, and they have to fill up the smallest stack in that second column first. For example, if every row in column 2 has a stack size of 1, then you can place a piece anywhere. But if there is one stack size of 2 while every other stack size is 1, then you can place it anywhere other than that stack of size 2. I am having a hard time implementing this. So far, it allows me to move one piece to the second column without stacking, then it no longer lets me move any pieces to the second column. I assume this is because of the smallestStackSize value not updating. I have also tried using a greatestStackSize value to see if that would help, and I am having similar issues. This method is being called every time someone clicks on a piece to move it. Could really use some help!

private int smallestStackSize_ = 0;
private int greatestStackSize_ = 1;
/**
     * Allows the players to place their pieces on the grid
     */
    public boolean setupPiece () {
        
        // board_.getHeight returns the number of rows on the board
        int[] numPieces = new int[board_.getHeight()];

        // initialize numPieces to contain the number of pieces in each row of
        // column 1. pieceHolderGrid_[][] is the array that holds all of the 
        // stacks of pieces. 
        for ( int i = 0 ; i < numPieces.length ; i++ ) {
            numPieces[i] = pieceHolderGrid_[i][1].getSize(); //all rows of column 1
        }
        
        // update smallestStackSize and greatestStackSize_
        smallestStackSize_ = numPieces[0];
        for ( int i = 1 ; i < numPieces.length ; i++ ) {
            if (numPieces[i] > greatestStackSize_) {
                greatestStackSize_ = numPieces[i];
            }
            if (numPieces[i] < smallestStackSize_) {
                smallestStackSize_ = numPieces[i];
            }
        }
        
        // check if move is to the smallest stack size
        if ( numPieces[1] == smallestStackSize_ ) {
            return true;
        } else {
            return false;
        }

    }

Array not finding value [duplicate]

I'm trying to write a program that takes DNA string value and converts to RNA. Whenever I assign values to specific indexes in my array, It won't see the value in my if statements. It doesn't see the letters at all. I've tried using sc.nextLine() instead of sc.next() in line 30 and that doesn't work at all. Any idea what might be going on?

import java.util.Arrays;
import java.util.List;


class Main {

  String[] dna;
  public Scanner sc = new Scanner(System.in);
    
    
  public static void main(String[] args) {
    Main obj = new Main();

    obj.takeUsr();

  }
  public void takeUsr(){
    System.out.print("How many letters: ");

    int count = sc.nextInt();
    
    int value = 0;
    
    dna = new String[count];
    while(count>0){
      
      
      System.out.print("Input letter:");
      dna[value] = sc.next();
      System.out.println("");
      value++;
      count--;
    }
    value = 0;
    int count2 = dna.length;
    while(count2 > 0){
      System.out.println(dna[value]);
      
      if(dna[value] == "A"){
        //dna[value] = "U";
        System.out.print("U");
        

      }

      else if(dna[value] == "U"){
        //dna[value] = "A";
        System.out.print("A");
      }

      else if(dna[value] == "C"){
        //dna[value] = "T";
        System.out.print("T");
      }

      else if(dna[value] == "G"){
        //dna[value] = "C";
        System.out.print("C");
      }
      else{
        break;
      }
      System.out.println("Success!");
      value++;
      count2--;
    }
  }
}

how to put multiple variables in if statement in java?

I'm super new to programming , I'm making a program to calculate If two lines are parallel or not, the lines are considered parallel if a1 b2 = a2 b1 but I don't know how to put multiple variables in one if statement I have searched but I didn't find the answer can you help me please?

here is my code

double a1, b1, a2 , b2 ;
System.out.print("enter the first numbers");
a1 = input.nextDouble();
b2 = input.nextDouble();
System.out.print("enter the second numbers");
a2 = input.nextDouble();
b1 = input.nextDouble();
if (a1 && b2 == a2 && b1)
    System.out.print("the lines are parallel");
else System.out.print("the lines are not parallel");

filter on a value in a column and remove rows that dont meet condition

I'm relatively new in R. I have this problem. I have data of dogs example of useful part of data (columns age_month and rasnaam (breed) are used)

I have to look for all the breeds if they are small, medium, large etc. And if they are a small breed then all the rows where age_month is lower than 9 have to be removed, if they are a medium sized breed rows where age_month is lower than 13 have to be removed, (large, age_month < 24). I've tried some things but it won't work. I've added all dogs to a list (also tried it with vector) like this: (only for small dogs here)

small_dogs <- list("Affenpinscher", "Bichon frisé", "Bolognezer", "Chihuahua",
            "Dandie Dinmont Terrier", "Dwergkeeshond", "Japanse Spaniel",
            "Griffon belge", "Griffon bruxellois", "Kleine Keeshond", 
            "Lhasa Apso", "Maltezer", "Mopshond", "Pekingees", "Petit Brabançon",
            "Shih Tzu", "Tibetaanse Spaniel", "Volpino Italiano", "Yorkshire Terrier")

I tried this:

for (i in 1:nrow(brachquest2)){
     ifelse((brachquest2$rasnaam %in% small_dogs), (brachquest2 <- brachquest2[!(brachquest2$age_month < 9), ]), 
     ifelse((brachquest2$rasnaam %in% medium_dogs)), (brachquest2 <- brachquest2[!(brachquest2$age_month < 13), ]), 
     (brachquest2 <- brachquest2[!(brachquest2$age_month < 24), ]))
            }

But then I get an unused arguments error. Then I tried to use case_when(), but I'm not familiar with this function, so maybe I'm using it awfully wrong:

brachquest2 <- case_when(
  brachquest2$rasnaam %in% small_dogs ~ brachquest2[!(brachquest2$age_month < 11), ],
  brachquest2$rasnaam %in% medium_dogs ~ brachquest2[!(brachquest2$age_month < 13), ]
  )

Then I get an error: must be length 66 or one, not 18.

(the number of rows is 66)

I hope I explained it okay. Does someone have some useful tips for me? Or maybe it could be much simpler, every help is appreciated!! Thanks in advance

in VHDL how to check if UNSIGNED(8 downto 0) is UNINITIALIZED or UNDEFINED?

I am not able to check if an Unsigned(8 downto 0) data type is "XXXXXXXX" or even "UUUUUUUU"

Inside a process as a variable or even checking an input im not able to get it to work.

Any solution to it?

How to add Results into a Vector within a Loop in R

I was prompted a question and am ever so close to solving what I need. The question is as follows-

"Write a while loop that computes and stores as a new object, the factorial of any non-negative integer mynum by decrementing mynum by 1 at each repetition of the braced code."

Another factor was that if 0 or 1 was entered, the output would be 1.

The code that I wrote as follows-

factorialcalc <- function(i){
  factorial <- 1
  if(i==0 | i==1){
    factorial <- 1
  } else{
    while(i >= 1){
      factorial <- factorial * i
      i <- i-1
    }
  }
  return (factorial)
}

with inputs-

mynum <- 5
factorialcalc(mynum)

and output-

[1] 120

You may be wondering, "your code works perfect, so what's the issue?" My issue lies in the part of the question that says "computes AND stores."

How can I modify my code to put the answers of factorialcalc into a vector?

Example- I input

mynum <- 5
factorialcalc(mynum)

and

mynum <- 3
factorialcalc(mynum)

and

mynum <- 4
factorialcalc(mynum)

When I call this new vector, I would like to see a vector with all three of their outputs (so almost like I made a vector c(120,6,24))

I'm thinking there's a way to add this vector somewhere in my function or while loop, but I'm not sure where. Also, please note that the answer must contain a loop like in my code.

The answer I would be looking for would have an empty vector say answers <- c(), and every time I were to run the function factorialcalc, during the function, I would add the return results from factorial into this new answers vector.

I've tried putting in something like this-

factorialcalc <- function(i){
  factorial <- 1
  answers <- c()
  answers[i] <- answers[factorial]
  if(i==0 | i==1){
    factorial <- 1
  } else{
    while(i >= 1){
      factorial <- factorial * i
      i <- i-1
    }
  }
  return (factorial)
}

This doesn't seem to work, but I think the idea is there.

Thanks in advance for any help.

Flutter- Creating multiple scaffold containers with if statement

I would like to create several containers in a scaffold.

Do I have to create them manually or can I reduce the code by using an if with counter statement to generate them?

If I can use an if statement could you provide a simple example?

Thanks.

Does “if” have implicit access to a class’s special methods even when they are not directly called?

I don’t understand how the code in the for loop knows whether the instance of the class is truthy or not. My understanding is probably faulty but what I think is happening is this: the call to bool calls the altered special method bool which has been modified to use the len built in on the instance. But outside of the class, when we get to the for loop and the if conditional I don’t know how “if” knows whether the order is truthy unless it is calling the special method bool(behind the scenes).

I apologise if this is not the forum for such a question but I don’t know enough of the required terminology to find an answer to this on google or a good book to get my head around OOP with a python bias.

Code

class Order:
    def __init__(self, cart, customer):
        self.cart = list(cart)
        self.customer = customer

   # def __bool__(self):
          #print("\'__bool__ got called\'")
          #return len(self.cart) > 0
        
order1 = Order(['banana', 'apple', 'mango'], 'Real Python')
order2 = Order([], 'Python')


for order in [order1, order2]:
    if order:
        print(f"{order.customer}'s order is processing...")
    else:
        print(f"Empty order for customer {order.customer}")


print(bool(order2))

While loop continues infinitely even after condition is satisfied

Here is a loop to make sure players of my small game input valid answers but the while loop conintues infinitely, even when the conditions are satisfied to break the loop:

initialize = ''
    while initialize != 'yes' or initialize != 'no':
        print('\nWould you like to play?')
        initialize = input('Yes or No? ').lower().strip()
        if initialize == 'yes':
            print('\nHappy to see you.\n')
        elif initialize == 'no':
            print('\nNo worries.\n\nThanks for stopping by!') 
        else:
            print('\nSorry, I didn\'t catch that')
print('please wait as game loads')
print('\nYou\'re very important to us\n')    

if 'yes' or 'no' is typed in the correct if statement runs but the loop continues: Would you like to play? Yes or No? yes

Happy to see you.

Would you like to play? Yes or No?

I want to convert if to switch. Can anyone help me?

I want to change if to switch...can someone help me with that? I ve been trying but nothing worked... please help me with this Please please please please

I want to change if to switch...can someone help me with that? I ve been trying but nothing worked... please help me with this Please please please please

    if(choose==1){
            System.out.println("Milk");
            System.out.print("How many items do you want to add? :");
            quantity =input.nextInt();
            total = total +(quantity*1);
            
            System.out.println("Continue? ");
            System.out.println("Type in Yes or No : ");
            again = input.next();
            if(again.equalsIgnoreCase("Yes")){
                add();//call the method you to create 
            }else{
                System.out.println("Payment (add amout of money you give)");
                pay = input.nextDouble();
                if(pay <=total){
                  System.out.println("Payment failed");
                }else{
                System.out.println("Total price is " + total);
                total = pay-total;
                System.out.println("The change is " + total);
                }
            }
        }else if(choose==2){
            System.out.println("Tea");
            System.out.print("How many items do you want to add? :");
            quantity =input.nextInt();
            total = total +(quantity*2.78);
            
            System.out.println("Continue?");
            System.out.println("Type in Yes or No");
            again = input.next();
            if(again.equalsIgnoreCase("Yes")){
                add();//call the method you to create 
            }else{
                System.out.println("Payment (add amout of money you give)");
                pay = input.nextDouble();
                if(pay <=total){
                  System.out.println("Payment failed");
                }else{
                System.out.println("Total price is " + total);
                total = pay-total;
                System.out.println("The change is " + total);
                }
            }
          }

                
            }
      
  

How to prevent using multiple else if statement in JS?

I have this script that go through my page and looking for any tooltip to fill with the right ingredient. But I would like to know if there is a way to optimize it as it goes like this :

var indiv = document.getElementById("ingredients");
var s = indiv.getElementsByTagName("SPAN"); 
var i;
    
for (i = 0; i < s.length; i++) {
  var ss = s[i].parentElement.textContent;
      
  var ingredient1 = ss.includes("test1");
  var ingredient2 = ss.includes("test2");
 
  if (ingredient1) {
    s[i].textContent = "this is the number 1 ingredient";
  } else if (ingredient2) {
    s[i].textContent = "this is the number 2 ingredien";
  } else {
    s[i].textContent = "unknown ingredient!";
  }
}

And it keeps going with else if (ingredient 3) , else if (ingredient 4) etc.. I know that in Python there is a dictionnary to use but I can't find a good way to do that in JS

Thanks in advance and have a nice day !

How to use an if function with a range of two float numbers [duplicate]

Could someone help me on making a range between two decimal numbers say 18.5 to 24.9? So basically what I wanted to do is this

If BMI in range(18.5, 24.9) print("good you are healthy")

Yet it would not allow me to do this. When I tried to do this it said expected int got float instead. Do note I am a beginner here so do bear with me. Any help would really be appreciated. Thanks.

samedi 28 novembre 2020

If else statement does not procced to else when condition is false in PHP?

why my if else statement does not procced to else when my condition is false? help me what is wrong with my code. the first sql statement work to verify the username is already register but the second sql statement does not work which is to insert the data if the condition are false. here is my code:

<?php

            if (isset($_POST['btn_add'])) 
            {
                $docFname = $_POST['docFname'];
                $docMname = $_POST['docMname'];
                $docLname = $_POST['docLname'];
                $docGender = $_POST['docGender'];
                $docType = $_POST['docType'];
                $docAge = $_POST['docAge'];
                $docNationality = $_POST['docNationality'];
                $docAddress = $_POST['docAddress'];
                $docContact = $_POST['docContact'];
                $docDateAdded = date('Y-m-d');
                $docUsername = $_POST['docUsername'];
                $docUserpass = $_POST['docUserpass'];

                $vald = "SELECT docUsername FROM doctors WHERE docUsername='" . $docUsername . "'";
                $result = $conn->query($vald);
                if($result->num_rows>0)
                {
                    while($row = $result->fetch_assoc())
                    {
                        $rigestered = $row['docUsername'];
                    }
                    if ($docUsername == $rigestered) 
                    {
                        echo "username already taken!";
                    }
                    else
                    {
                        $ins = "INSERT INTO doctors (docFname, docMname, docLname, docGender, docType, docAge, docNationality, docAddress, docContact, docDateAdded, docUsername, docUserpass) VALUE ('$docFname','$docMname','$docLname','$docGender','$docType','$docAge','$docNationality','$docAddress','$docContact','$docDateAdded','$docUsername','$docUserpass')";
                        if($conn->query($ins)===TRUE)
                        {
                            header('location:blank_page.php');
                        }
                        else
                        {
                            echo "SQL Query: " . $ins . "->Error: " . $conn->error;
                        }
                    }
                }

            }

            ?>

Question finding matching numbers in a list

I am new to python and was messing with lists and loops. I want to make a dice game and roll the dice 5 times, store it in a list then find numbers that match in said list. but the out put ends up just giving me the value of the the list length.


import random
        
#I start with an empty list
            
dice = []
            
#Roll 5 random numbers
            
for x in range(0, 5):
    x = random.randint(1,6)
    dice.append(x)
            
#find how many time a number in the list was rolled
            
count = 0
for x in range(6):
    count = dice.count(x)
                
print(“Player rolled:”, dice)
print(count)
        
#The output ends up this:
#Player rolled: [3, 3, 3, 1, 3]
        
#[5]
        ```
#output value I'm looking for is 4
        
#output next run
#Player rolled: [2, 6, 5, 6, 6]
        
#[5]
# output value should be 3
#How do I find and store the matches in the list and store them in count? Sorry #I’m really trying to understand lists and loops but I just can’t figure this out

Guessing game with 5 chances in python [closed]

This is my code:

import random

letters = ['a','g','s','s','c','v','e','g','d','g']

random_letter = random.choice(letters)

guesses_left = 5
while guesses_left > 0:
  guess = input("Your guess: ")
  if guess == random_letter:
    print ("You win!")
    break
  guesses_left -= 1 
else:
  print ("You lose.")

My question: Why am I able to type other types than strings? For example, if I run the code and answer with an integer I don't get error. If this problem is not fixable, is there a better way to create this type of game?

why can't my java code read the condition?

first of all, sorry for bad english. I'm a university student studying computer science.

what I attend to do is when the array(from 0 to n-1) is given, to sum the array values with the index minus multiple of 3 start from the end. for example, when 7 arrays are given, I want to sum a[0] a[2] a[3] a[5] a[6].

below is error part of the code I programmed.

        int j = 0;

        for(int i=0; i<n; i++){
                j = i*3;

                if(i!=n-j)
                        r += array[i];
        }

my code can't read the condition and just sum all the array values. I don't know why. can someone help me ?

java if/else statements always runs else statement [duplicate]

I have to make a program for class and for some reason my if/else statements will always skip straight to the else despite fitting inside the parameters to run the if or else if statements. For example, in the code below, when given the input "Yes" or "yes" it always returns "Bad input".

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Do you want to continue? ");
        String ans = s.nextLine();
        ans = ans.toLowerCase();
        if(ans=="yes"||ans=="y"||ans=="ok"||ans=="sure"||ans=="why not") {
            System.out.print("OK");
        } else if(ans=="n"||ans=="no") {
            System.out.print("Terminating");
        } else {
            System.out.print("Bad input");
        }
    }
}

Writing a thresholding function in R

I'm trying to make a function so that every value x in a dataframe df is replaced by 1 if above y, otherwise it's replaced by 0.

I tried

threshold <- function(x, y) if (x < y) {
  x <- 0 
  } else {
    x <- 1
}

using it, returns a warning:

> threshold(calcium, calcium.threshold)
Warning message:
In if (x < y) { :
  the condition has length > 1 and only the first element will be used

And I'm not sure why?

Cheers.

How do i refrence my validation method (true or false) when i makeing a conditional statment?

so i have an ArryList called "files" and ive created a validation method for validating if its when used you are callling on a valid index refrence:

// validation method of an ArrayList called "files"
public boolean validIndex(int index){
    if(index >= 0 && index < files.size()){
        return true;
    }
    else{
        return false;
    }
}

The insted of just calling on the get method i want to be able to refrence "validIndex" method when calling an on an item from the arrayList.

// Trying to make this one work:
Public void listFile(int index){
    if(validindex(index) = true){
        file.get(index);
    }
    else{
        System.out.println("Index: " + index + "is not valid!");
    }
}

please help

Typo3. How to change fluid tempate with language condition

I use Typo3 1.4.10, using the Bootstrap package

I try to change a Typo3 fluid template based on the current front-end language being used. I have tried various "if conditions". I just cannot figure it out. I have tried using siteLanguage, language and sys_language_uid. In the TSsetup siteLanguage works for me as in:

[siteLanguage("locale") == "en_US.UTF-8"]
 ...

[global]

I cannot figure out is how to do something similar in the fluid templates. I tried tons of different ways. How can I correct the below example taken from one of my many attempts?

<f:if condition="{siteLanguage} == {siteLanguage.locale}">
<f:if condition="{siteLanguage.locale} == en">
 <f:then>
    language 1
</f:then>
<f:else>
    language 0
</f:else>
</f:if> </f:if>

Removing elements from list using if condition

I have tried to remove an element by using if condition in a list, if the list is like this

list1 = ['a','1','c','2','d','3']

for i in list1:
    if i == 'a' :
        list1.pop(list1.index(i) - 1)
        list1.remove(i)

print(list1)

Output : ['c', '2', 'd', '3']

It removes all 'a' in the list but when 'a' is near another 'a', its not removing the second 'a',

list1 = ['a','1','a','2','d','3']

for i in list1:
    if i == 'a' :
        list1.pop(list1.index(i) + 1)
        list1.remove(i)

print(list1)

Output : ['a', '2', 'd', '3']

Why is that ? I want to remove both 'a'. Any ideas ?

vendredi 27 novembre 2020

Continue to Checkout when 'if' conditions are met

I am using the below snippet to check the order total. If the total is less than 100, then the error message "click on coupon" must show, but if the total is zero(coupon applied) or 100 (to pay by credit card), then I want the if loop to end and allow checkout to complete. I have tried using break; and continue with else if, but I believe my syntax is wrong. This is what I have, where $minimum is 100:

if ( WC()->cart->total < $minimum1 ) {

    if( is_cart() ) {

        wc_print_notice( 
            sprintf( 'Click on a Coupon' , 
                wc_price( WC()->cart->total ), 
                wc_price( $minimum )
            ), 'error' 
        );

    } else {

        wc_add_notice( 
            sprintf( 'Click on a Coupon' , 
                wc_price( WC()->cart->total ), 
                wc_price( $minimum )
            ), 'error' 
        );

    }
}

Nested if else statements only works on first statement

I am having an issue with nested if else statements. In this issue, it only executes the first if statement and skips all of the rest, when I want every statement to be executed. The else if statement works fine when there is nothing nested inside it, but when I nest additional if else statements only the first one seems to work. Here is my javascript code:

const apiURL2 = "https://api.openweathermap.org/data/2.5/forecast?id=5604473&appid=6d1d830097a2c0bac1aba2337d0139e6";

fetch(apiURL2).then((response) => response.json()).then((jsonObject) => {
const list = jsonObject['list'];
console.log(jsonObject);
for ( let i = 0; i < 5; i++){

    let divForecastData = document.querySelector('div.weather-forecast-wrapper');
    let temp1 = document.createElement("div");
    let tempday = document.createElement("p");
    let temperature = document.createElement("p");
    let icon = document.createElement("i");
    
    temperature.className = "temp";
    tempday.className = "weekday";
    temp1.className = "day";

    if (i == 0){
      tempday.textContent = "Sat";
      temperature.textContent = list[i].main.temp;
      if (list[i].weather[i].main = "Clear"){
        icon.className = "worked"
      }
      else {
        icon.className = " still worked"
      }
      
    }
    else if (i == 1){
      tempday.textContent = "Sun";
      var far = list[i].main.temp
      var kel = far * (9/5) - 459.67;
      temperature.textContent = Math.round(kel) + "℉";
      if (list[i].weather[i].main = "Clear"){
        icon.className = "worked"
      }
      else {
        icon.className = " still worked"
      }
      
    }
    else if (i == 2){
      tempday.textContent = "Mon";
      temperature.textContent = list[i].main.temp;
    }
    else if (i == 3){
      tempday.textContent = "Wed";
      temperature.textContent = list[i].main.temp;
    }
    else{
      tempday.textContent = "Thu";
      temperature.textContent = list[i].main.temp;
      
    }


    divForecastData.appendChild(temp1);
    temp1.appendChild(tempday);
    temp1.appendChild(icon);
    temp1.appendChild(temperature);
    

}






  });

any suggestions?

python 3 if..elif won't print

For some dumb reason, I can't get my if..elif to print in python 3 but it somehow works in python 2. I'm not sure what I missed.

This is my if, elif

def encdec(userinput, machine, plaintext):
    if userinput == 1:
        print("-----------------------------------")
        print("Encoded:")
        enc = machine.encrypt(plaintext)
        print(enc)
        
    elif userinput == 2:
        print("-----------------------------------")
        print("Decoded:")
        dec = machine.decrypt(plaintext)
        print(dec)

This is my main using python 3's input function.

class main():

    print("Cryptography")
    print("[1] Encode")
    print("[2] Decode")


    userinput = input("Enter your choice: ")
    plaintext = input("Plaintext: ")
    
    
    rightkey = "SGLBIZHJMFTRXAVKNQPDWYCUOE"
    leftkey = "XLEMFHIWOVNYRUDQCJPASGBTKZ"

    if rightkey.isupper()==True:
        rightkey = rightkey.lower()

    if plaintext.isalnum()==True:
        import re
        plaintext = re.sub("[^a-zA-Z]+","",plaintext)

    
    cm = SaveSpaces(UpperCase(CryptMachine(Chao(), leftkey)))
    cm.set_alphabet(rightkey)
    encdec(userinput, cm, plaintext)
    
    

if __name__ == "__main__":
    main()

How to solve a malfunctioning in a life system? [duplicate]

So I made a game with a life system in Python, that everytime you get a wrong answer you loose one life, and have the opportunity to try again. It worked properly with questions wiht a single answer, but then I had the neccessity to create questions with more than one answer. Now it keeps working until you reach 0 lifes, but at that moment no matter the input it takes it as right answer and let's continue to the next question. I tried to recreate this problem in a simpler code, and the error still persists. Here's the code. If there's any way to make this code work, I would really apreciate it.

import random
Dificulty_levels={"easy" : 3, "normal" : 2, "hard" : 1}
Dificulty=input("Choose the dificulty, this will determine the amount of lvies you have (easy / normal / hard): ")
lives=Dificulty_levels[Dificulty]
num1=random.randint(1, 12)
num1_square=num1*num1 
print("What is the square root of "+str(num1_square))
answer=int(input("Your answer is: "))
while answer != num1 and answer != -num1 and lives >= 1:
    lives = lives - 1
    print("Wrong answer, you have "+str(lives)+" left")
    answer=int(input("Try again: "))
if answer==num1 or -num1:
    print("Correct!")
else:
    print("Game Over") 

Should I be using a case statement or an if/else

I am making a script in unix that will read a text file and each record has six fields separated by a pipe. I don't know if I should use a case statement or an if/else statement.

  • If the $JOB has a value of P then NEW_NICE should be set to 3.
  • If the $JOB has a value of S then NEW_NICE should be set to 6.
  • All other values of $JOB should set NEW_NICE to 7.

I kinda wanna use a case statement because it would be simpler, but I also am not sure on how that would look.

Laravel 8: Construct Table

how can i improve this code? The result is putting the number 1 at the end.

Alternative approach for checking data types to build an object

I'm trying to build an object, which uses different methods based on different data types. I.e. it differs from withBooleanValue,withStringValue and withDateValue depending on the data type. What I have is a string, and depending on what that string is (boolean, string or date), I need to build this object. Below is how I went about it.

private List<Answer> getAnswers(Set<Question> questions) {
        List<Answer> answers = new ArrayList<>();
        questions.forEach(question -> {
            Answer.Builder answer = Answer.builder()
                    .withQuestion(question.question());
            if (BooleanUtils.toBooleanObject(question.value()) != null) {
                answer.withValue(AnswerValue.builder()
                        .withBooleanValue(BooleanUtils.toBoolean(question.value()))
                        .build());
            } else {
                try {
                    Date dateValue = DateUtils.parseDate(question.value(), new String[]{"dd-MM-YYYY"});
                    answer.withValue(AnswerValue.builder()
                            .withDateValue(dateValue)
                            .build());

                } catch (ParseException e) {
                    answer.withValue(AnswerValue.builder()
                            .withStringValue(question.value())
                            .build());
                }
            }
            answers.add(answer.build());
        });
        return answers;
    }

Is there a better way to do this in Java8? Somehow the ifs, and try-catch statements make it look very complicated and I'd like to reduce the lines and complexity with a better way. Any advice would be much appreciated.

R to create a tally of previous events within a sliding window time period

Any one able to assist me with a problem using R to create a sum of previous events in a specific time period please? I apologise if I do not follow protocol this is my first question here.

I have a df of IDs and event dates. In the genuine df the events are date times but to keep things simpler I have used dates here.

I am trying to create a variable which is a tally of the number of previous events within the last 2 years for that ID number (or 750 days as Im not too concerned about leap years but that would be nice to factor in).

There is an additional issue in that some IDs will have more than one event on the same date (and time in the genuine df). I do not want to remove these as in the real df there is an additional variable which is not necessarily the same. However, in the sum I want to count events happening on the same date as one event i.e. if an ID had only 2 events but they were on the same day the result would be 0, or there may be 3 rows of dates within the previous 2 years for an ID - but as two are the same date the result is 2. I have created a outcome vector to give an example of what I have after ID 7 has examples of this.

If there were 3 previous events all on the same day the result sum would be 1 and any subsequent events in 2 years

ID <- c(10,1,11,2,2,13,4,5,6,6,13,7,7,7,8,8,9,9,9,10,1,11,2,11,12,9,13,14,7,15,7)
event.date<-c('2018-09-09','2016-06-02','2018-08-20', '2018-11-03', '2018-07-10', '2017-03-08', '2018-06-16', '2017-05-20', '2016-04-02', '2016-07-27', '2018-07-15', '2018-06-15', '2018-06-15', '2018-01-16', '2017-10-07', '2016-08-17','2018-08-01','2017-01-22','2016-08-05', '2018-08-13', '2016-11-28', '2018-11-24','2016-06-01', '2018-03-26', '2017-02-04', '2017-12-01', '2016-05-16', '2017-11-25', '2018-04-01', '2017-09-21', '2018-04-01')
df<-data.frame(ID,event.date)

df<-df%>%
  arrange(ID,event.date)

The resulting column should look something like this.

event.count <- c(0,1,0,0,1,0,0,0,1,0,1,1,2,2,0,1,0,1,2,3,0,1,0,1,2,0,0,1,1,0,0)
df$event.count<-event.count

I have tried various if else and use of lag() but cannot get what I am after

thank you.

I'm trying to get Slide.Get_Value() to print "Five" whenever it gets the number 5 as a test

package com.company.Iguana;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.InputEvent;

public class MyCPS implements ChangeListener {
    JSlider Slider;
    JPanel panel;
    JLabel label;
    JFrame frame;
    JComboBox Combo;

    MyCPS() {
        frame = new JFrame("CPS");
        panel = new JPanel();
        label = new JLabel();
        Slider = new JSlider();
        String[] Buttons = {"Left Click", "Right Click"};
        JComboBox combo = new JComboBox(Buttons);
        ImageIcon image = new ImageIcon("BOAROR.png");
        frame.setIconImage(image.getImage());
        frame.getContentPane().setBackground(Color.YELLOW);
        frame.setTitle("Iguana.exe");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(420, 420);
        Slider = new JSlider(0, 23, 12);
        Slider.setPreferredSize(new Dimension(400, 200));
        Slider.setPaintTrack(true);
        Slider.setMajorTickSpacing(4);
        Slider.setPaintLabels(true);
        Slider.setOrientation(SwingConstants.VERTICAL);
        label.setText("CPS" + Slider.getValue());
        label.setIcon(image);
        Slider.addChangeListener(this);
        panel.add(combo);
        panel.add(Slider);
        panel.add(label);
        frame.add(panel);
        frame.setSize(420,420);
        frame.setVisible(true);
        frame.pack();


    }

    @Override
    public void stateChanged(ChangeEvent e) {
        label.setText("CPS" + Slider.getValue());
        if(e.equals(Slider.getValue()));              <<<<<<<< Problem
        System.out.println("Five");

}

}

Whenever I try putting if(e.equals(Slider.getValue())); == 5 It says Operator '==' cannot be applied to 'java.lang.Object', 'int'

I'm just trying to get it whenever I put the CPS as 5 It would print "Five" Back as a test I'm quite new so I probably did some silly mistake

Ties are still running win messages?

I've been messing around with a rock, paper scissors project that codecademy gets you to try, I'm pretty happy with it but I have one problem! When the result is a tie, it logs the tie message (perfect!) but also logs the win message linked with the result! How do I get it to ONLY log the tie message? Here's the code:

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  if (userInput === "rock" || userInput === "paper" || userInput === "scissors" || userInput === "gun") {
    return userInput;
  } else {
    console.log(`Sorry! But ${userInput} is an illegal weapon in the bloodythirsty sport of Rock, Paper, Scissors!`)
  }
}

const getComputerChoice = () => {
  const ranNum = Math.floor(Math.random() * 3);
  switch (ranNum) {
    case 0:
      return "rock";
    case 1:
      return "paper";
    case 2:
      return "scissors";
  }
};

const determineWinner = (getUserChoice, getComputerChoice) => {
  if (getComputerChoice === getUserChoice) {
    console.log("It seems it's a tie! You've matched wits!");
  }
  if (getUserChoice === "rock") {
    if (getComputerChoice === "paper") {
      return "The computer wins! It has gift wrapped your weapon.";
    } else {
      return "You beat the computer! They immediately begin crafting bigger scissors.";
    }
  }

  if (getUserChoice === "paper") {
    if (getComputerChoice === "scissors") {
      return "The computer wins! They claim arts and crafts time as a reward."
    } else {
      return "You beat the computer! Their puny stone was no match for your paper aeroplane to the eye!"
    }
  }

  if (getUserChoice === "scissors") {
    if (getComputerChoice === "rock") {
      return "The computer wins! You won't be cutting straight lines any time soon..."
    } else {
      return "You beat the computer! You cause emotional damage by destroying their robot child's drawing. You're a monster."
    }
  }

  if (getUserChoice === "gun") {
    if (getComputerChoice === "rock" || getComputerChoice === "paper" || getComputerChoice === "scissors") {
      return "You win. But at what cost?"
    }
  }
  if (getUserChoice === undefined) {
    return "Come back when you're ready to take this game seriously."
  }
}
//Enter your choice below in getUserChoice brackets
const playGame = () => {
  let userChoice = getUserChoice("rock");
  let computerChoice = getComputerChoice();
  if (userChoice !== undefined) {
    console.log(`You have chosen ${userChoice} as your weapon.`);
  }
  if (userChoice !== undefined) {
    console.log(`The computer has brought ${computerChoice} to a ${userChoice} fight.`);
  }
  console.log(determineWinner(userChoice, computerChoice))
}

playGame();

Using the IF function in Excel Powerpivot with DAX

I am trying to use an if statement in excel measures for powerpivot tables. I am trying to calculate revenue per unit but I have one Product Line that calculates revenue differently than all the other Product Lines. The equation I am trying to use is =IF(tableA column = "certain Product Line", calculated revenue for PL/calculated units for PL, calculated revenue for all other PLs / Calculated units for all other PLs). For some reason I keep getting the error "Calculation error in measure, a single value for column 'PRODUCT_LINE' in table 'A' cannot be determined. This can happen when a measure formula refers to a column that contains many values without specifying an aggregation such as min, max, count, or sum to get a single result".

C# how many brackets do you need for an if x or y statement?

If I have an if statement, like so, that is fully fuctional;

if (condition1 == 1 || condition2 == 2)

Why do so many people do it like this? Is there some reason for this other than just their code style?

if ((condition1 == 1) || (condition2 == 2))

Error message displayed even if entered value is valid in Java

I have this method to validate an email entered by user.

Now the method is printing the error even if the email is blank.

I don't want that behavior. I just want the error message to be printed when the email is not alpha because the empty email is accepted has a valid value.

 public static String validateEmail() {
            String email;
            boolean isAlpha;
            boolean isValid = false;
    
                do {
                    email = validateString(MSG_SOLL_EMAIL, MSG_ERR_EMAIL, 5, 50,
                            false);
    
                        isAlpha = Tp2Utils.isAlphaNumPlus(email, "@,.,_")
                                && Tp2Utils.hasNCar(email, '.') >= 1
                                && Tp2Utils.hasNCar(email, '@') == 1;
                       
                       if (email.isBlank()) {
                           isValid = true;
                       }
                        if (!email.isBlank() && isAlpha) {
                            isValid = true;
                        } else {
                            System.out.println(MSG_ERR_EMAIL);
                        }
    
                } while (!isValid && !isAlpha);
    
            return email.trim();
        }

I would appreciate some help to make my method work as I want it to.

Thank's

Ruby if statements is always else

puts "Commands: /startEngine, /upgrade"
command = gets
if command.include? "/"
    command.slice! "/"
    isStartEngine = command <=> "startEngine"
    if isStartEngine == 0
        puts "Starting engine"
        sleep(1)
        print "3"
        sleep(1)
        print "2"
        sleep(1)
        print "1"
        sleep(1)
        print "GO!"
    else
        puts "Unknown"
    end
end

That is my code but it always returns else on if isStartEngine. Using a case doesn't work and I don't know what will and I am new to ruby. Sorry if it is a newbie question. Thank you!

awk syntax '||' without 'if' - how does it work and why does it loop?

I've been doing this university class and we got an assignment about awk. One exercise was to find the lowest value of a column, and I stumbled upon this line of code:

awk 'NR == 1 || $3 < min {line = $0; min = $3}END{print line}' file.txt

If number of lines read = 1 OR Element in third column is smaller than min, set line = line being read and min = Element from third column STOP print line.

I only know some basic python so far and I do not understand how the || works in this context. I know that it is a logical OR, but why is there no if?

Why does it loop without explicit commands like while, until or for?

Does END equals something like else in an if statement?

Check if button has been pressed

I want to add an if statement that checks if the user is undefined for my program. It should alert: "no more profiles". The problem is that my "likeId" is undefined to start with and I will get the alert first time i run the function. I would like to know that I can make an if statement that checks if a certain button has been pressed exactly one time.

This is my code:

if (localStorage.getItem('likeId') == "undefined"){
    alert("no more profiles to swipe")
}

My code should look something like this:

if (localStorage.getItem('likeId') == "undefined" && Button has been clicked exactly one time){
        alert("no more profiles to swipe")
    }

VBA takes wrong branch at If-statement - Severe Compiler Bug?

The question mark in the title is only there because I'm very reluctant to call anything a compiler bug, but in this case, I'd be surprised if anyone could explain this behavior in any other way.

The code to reproduce the problem is very, very simple. In a standard module we have the following:

Sub CompilerBug()
    Dim oClass As cClass
    Set oClass = New cClass
    
    If False Then
        Debug.Print "This doesn't print, as it shouldn't."
    End If
    
    If Falsee(oClass.Clone) Then
        Debug.Print "This does print, although it shouldn't!"
    End If
End Sub

Public Function Falsee(oClass As cClass) As Boolean
    Falsee = False
End Function

And we have a class (cClass) defined in a class module named cClass, containing the following code:

Public Function Clone() As cClass
    Dim oClass As cClass
    Set oClass = New cClass
    Set Clone = oClass
End Function

Private Sub Class_Terminate()
End Sub

The code is pretty self-explanatory, the second if statement gets entered in spite of the aptly named function Falsee returning False, no matter the input! The same result can be observed when the function in the class is replaced by a similar Public Property Get.

For the purpose of reproduction, I'm getting this behavior in my Office 365 Excel, 64bit, Version 2011 (Build 13426.20274) which is the current up-to-date version of excel. I also tested this exact code in my Word VBA IDE with exactly the same results.

"Proof": "Proof"

I have no idea what causes this behavior, but here are a few clues:

If we rewrite the code in our sub to:

Sub CompilerBug()
    Dim oClass As cClass
    Set oClass = New cClass

    Dim bFalse As Boolean
    bFalse = Falsee(oClass.Clone)
    
    If bFalse Then
        Debug.Print "This doesn't print, as it shouldn't."
    End If
End Sub

(First if statement omitted for the sake of brevity) The code gets executed as expected, so it is crucial that the function is called directly in the condition for the if statement (not something that should usually make a difference)

And the next interesting clue is the following (assume we use the buggy sub code again with If Falsee(oClass.Clone) Then): If we remove the following from our class module:

Private Sub Class_Terminate()
End Sub

The if statement works as expected and nothing gets printed! So somehow the Terminate event being executed during evaluation of the If-statement messes things up, but the Class_Terminate() sub doesn't even contain any code! That's the next thing that shouldn't make a difference, yet does! This idea is further supported by the fact, that when we declare a public variable in the module by adding Public poClass As cClass at the top and rewrite the function code to:

Public Function Falsee(oClass As cClass) As Boolean
    Set poClass = oClass
    Falsee = False
End Function

Now the Terminate event doesn't get called during execution of the If-statement, because the instance of the class doesn't go out of scope during the execution of the If-statement and as a result, the If-statement evaluates properly - the Line doesn't get printed.

Obviously, the Terminate-event being executed during evaluation of the If-statement can't be the whole story, because this happens all the time. It also seems to have something to do with the scope of the object that gets terminated and the way the parameter is passed to the function. For instance, the following does NOT produce the same behavior:

Module code:

Sub CompilerBug()
    Dim oClass As cClass
    Set oClass = New cClass

    If Falsee(oClass.CreateAndDestroyObject) Then
        Debug.Print "This doesn't print, as it shouldn't."
    End If
End Sub

Public Function Falsee(lng As Variant) As Boolean
    Falsee = False
End Function

And in the class module:

Public Function CreateAndDestroyObject() As Long
    Dim oClass2 As cClass
    Set oClass2 = New cClass
    Set oClass2 = Nothing
End Function

Private Sub Class_Terminate()
End Sub

To sum everything up, the behavior occurs when:

A method of a class returns an instance of the same class, and this method is called inside an If-statement as an argument for a function, and this instance of the class (that was created by the method) then goes out of scope inside that function and the terminate event of the class gets called (and exists as code). In this case, the if statement gets entered, regardless of the return value of the function.

To me, many questions remain... Why does the Terminate event make a difference in this case? Is any of my code supposed to produce undefined behavior or is this actually a bug? Are there other cases where If-statements don't work the expected way? What exactly causes this bug?

Weird Behaviour in R if else Statement

I'm quit new to R programming. While I was trying to write my first if else statement I came across a weird behaviour which I don't understand.

When I run below code:

x = 4;
y=4;
        if (x==y) {
      print('they are equal');
    } else {
      print('they are not equal');
    }

I get no error and I get the expected output. However when I change the indentation of the same exact code as below:

if(x==y){print('they are equal');}
else{print('they are not equal');}  

I get an error message saying that 'Error: unexpected 'else' in "else"'.

So does this means that R is an indentation sensitive language like Python?

Loop computation - Sum of integers that are devidable

I am looking for a way to compute the sum of integers between 1 and 20 that can be divided by 2, 3 or 5.

I created an array with the integers from 1 to 20. Y= np.arange(1, 21, 1)

However I am not sure how to check if the integers can be divided by 2, 3 or 5. If I try the following I get a float and cannot convert it to an integer: X = Y/2

I know the computation and checking should be done in loop, potentially if loop that checks if Y can be divided by 2, 3 or 5 and then if the statement is true make the true statements add up. How can I do that?

Much thanks in advance!

CMake IF with multiple conditions

How to make if function with multiple conditions? I know CMake support if with 2 conditions, but how to make more than 3? I need something like this:

if(WIN32 OR APPLE OR IOS)
    set(LIBS)
endif()

Thanks

How can I check if the querySelector of a clicked element is correct using if statement?

first post here. I was trying to make some tests using the if statement to fire an Alert, for example, when there's a lot of whatsApp buttons on website, but with differents specifications on it. So i tried to run this code:

window.addEventListener('click', function(event){
    if(event.target.querySelector('a[href*="whatsapp.com"]')){
       console.log('Hey WhatsApp!')
    }
})

But this code isn't works, it does not return an error on Console, but it does not fires the console.log

You guys knows what is wrong with this code or if there's a way to validate on the if statement the querySelector of a clicked button?

Button1 changes function button2 - JS

sorry for my English. I am a Javascript programmer beginner.

My assignment is:
I have 2 buttons (button1, button2)
I need to create a condition (if / else).
If I click on button 1 it will play me song1
But if I click on button2, it changes the soundtrack on button1 from song1 to song2.

Please help me or write me if it is even possible to do it in JS. If this is not possible, please for some alternative to this assignment.
Thanks for the answers.

Check if running script is in array

I'm trying to run a function but only on specific pages. I thought this would be fine...

$allowed_pages = array('/admin/update.php', '/admin/system.php', '/admin/install.php');
if($_SERVER['SCRIPT_NAME'] == $allowed_pages) {
    myCoolFuntion();
}

...but it doesn't seem to work as expected and the myCoolFuntion() runs regardless of what page I am on.

If I echo $_SERVER['SCRIPT_NAME'] on any given page, I can see it does match up correctly (it matches a page specified in the array, for example, /admin/update.php as expected) and so I know the values in the array are in the correct format.

What am I doing wrong?

C# DataGrid Cell - Change row forecolor IF

I'm trying to change the forecolor of a specific row within a datagrid if a cell within that row contains the word "WARNING".

 foreach (DataGridViewRow row in inclog.Rows)
        {
            if (inclog.SelectedCells[5].Value.ToString() == "WARNING")
            {

                inclog.SelectedRows[1].DefaultCellStyle.ForeColor = Color.Red;

            }
        }

I'm trying to change the code, add and remove bits but can't seem to be able to do it.

How can I make a long if else and strings generic?

I have a value_list which is created generic and this value_list includes something like this:

['C','E','F'] # this always changes

Now I have to write into a file which of these rules where attached in value_list.

I saved all my rules in all rules.

all_rules = ['A', 'B', 'C', 'D', 'E', 'F'] #this can also change so thats why i have to do it generic

First I did something like this and this works but I want to do it generic:

marked_rule = ["-", "-", "-", "-", "-", "-"]

        for value in value_list:
            if value == "A":
                marked_rule [0] = "X"
            elif value == "B":
                marked_rule [1] = "X"
            elif value == "C":
                marked_rule [2] = "X"
            elif value == "D":
                marked_rule [3] = "X"
            elif value == "E":
                marked_rule [4] = "X"
            elif value == "F":
                marked_rule [5] = "X"

new_line= "{:-<1} {:-<1} {:-<1} {:-<1} {:-<1} {:-<1}".format(*marked_rule)

Here it write into file

Output:

A B C D E F  
- - X - X X #marked_rule should look like this ["-" "-" "X" "-" "X" "X"].

TODO: make it generic:

first I want to do these lines as often as my all_rules list is

marked_rule = ["-", "-", "-", "-", "-", "-"]

Next I want to add without writing these hard coded If clauses

Frist try, but does not work:

        for index, value in enumerate (value_list):
            if value == all_rules [index]:
                marked_rule[index] = "X"

Next also want to do the string formatting generic, so it shoud contain so many {:-<1} as much as the index of all_rules. The problem is I add somethig before and after (these are fix) . In real case it looks like this:

" *  {:<10} {:-<1} {:-<1} {:-<1} {:-<1} {:-<1} {:-<1} {:<23} {:<3}"

jeudi 26 novembre 2020

How do I tell if exactly N conditions in a set of M conditions are true in Python?

The title is a bit confusing, so I'll give an example. Say I have a set of 4 conditions, [A,B,C,D], where each condition can either be true or false. For example, condition A can either say

A[i,j+1] == 0 

or

A[i,j+1] != 0

I want an if statement that essentially says the following:

if (in [A,B,C,D], any 2 are true and any 2 are false):
    do something
else:
    do something else

I could hard-code each individual case if necessary. For example:

if ((A and B are true) and (C and D are false)) or  ((A and C are true) and (B and D are false)) or...

and I can just continue that for every possible case. However, that seems wildly inefficient and not pythonic.

What's the best method to do this? Should I just hard-code it? Thanks in advance.

Excel formula - Get the sum of each variable every 6 days

enter image description here

I have the following dataset where I want to get the sum of each variable every 6 days. I can get the total sum of every 6 days using

=SUM(OFFSET($A$2,,(COLUMNS($A$5:A5)-1)*6,,6))

And I can get the total sum of each variable using

=SUMIF(A1:S1,A1,A2:S2)

But I cant get the total sum of each variable within the block of 6 days. It won't increment when I drag the formula. So the results should be

      First batch      Second batch         Third batch
A      B       C      A      B       C      A      B       C
2      2       2      4      4       4      6      6       6

Problem producing a new random number at the end of HiLo guessing game

I'm creating a HiLo guessing game in Java. Everything I have so far works as intended except at the end when I prompt a user to play again, the random number remains the same from the previous game. How do I make it so the code produces a new random number when the user chooses to play a new game?

    int answer  = (int)(Math.random() * 100 + 1);
    int guess = 0;
    int guessCount = 0;
    boolean playGame = true;
    String restart;
    Scanner scan = new Scanner(System.in);
    
while(playGame == true)
{
    while (playGame == true) 
    {
        System.out.println("Enter a number between 1 and 100: ");
        guess = scan.nextInt();
        guessCount ++;
        
        System.out.println(answer);
        
        if (guess < 1 || guess > 100) 
        {
            System.out.println("You have entered an invalid number.");
            guessCount --;
        } else if (guess == answer) 
        {
            System.out.println("Correct! Great guess! It took you " + guessCount + " tries!");
            break;
        } else if (guess > answer) 
        {
            System.out.println("You've guessed too high! Guess again: ");
        } else if (guess < answer)
        {
            System.out.println("You've guessed too low! Guess again: ");
        }
    }
    
    System.out.println("Would you like to play again? Y/N");
    restart = scan.next();
    
    if (restart.equalsIgnoreCase("Y")) 
    {
        playGame = true;
    } else if(restart.equalsIgnoreCase("N"))
    {
        System.out.println("Thank you for playing!");
        break;
    }
}

iteration of comparation values in list

I have a list which could change of number of elements

list = ['sp', 'gb', 'fr']

And I have 3 dictionaries where i can find some information about each country.

dic_old_price = {'sp':3355, 'gb': 3000, 'fr':3500}
dic_new_price = {'sp':3005, 'gb': 2500, 'fr':3000}
dic_discount = {'sp': 0.20, 'gb': 0.15, 'fr':0.20}

Well, now I want make a condition if where value (old_price*dicount < new_price) then enter the loop, but it must be true for 3 countries (or all we have). Now, I have "if .... and .... and .... :" and I comment conditions if I have only 2 countries, but I can´t do that always.

if (dic_old_price[list[1]]*dic_discount[list[1]]) < dic_new_price[list[1]] and (dic_old_price[list[2]]*dic_discount[list[2]]) < dic_new_price[list[2]]: #and (dic_old_price[list[3]]*dic_discount[list[3]]) < dic_new_price[list[3]]:

... could be more than 3 countries...

How could I do that? thanks

Python using tkcalendar and getting the results from textfile

My question: is it possible to make a calendar by using tkcalendar that when I press the button on a specific date information from a textfile appears?

The text-file before splitted into many text-files:

days.txt:

Today is 2020/11/26

Soccer :

Today is 2020/11/27

Basketball :

...

Today is 2021/11/26

Run

:

The different textfiles after splitted:

day1.txt:

Today is 2020/11/26

Soccer

day2.txt:

Today is 2020/11/27

Basketball

...

day364.txt:

Today is 2021/11/26

Run

enter code here

from tkinter import *
from tkcalendar import *
import datetime

#Function that makes a textfile turn into 365 textfiles one for each day:
with open('days.txt', 'r') as f:
    split_alph = f.read().split(':\n')
    for i in range(len(split_alph)):
        x = open(f"day{i}", "w")
        x.write(split_alph[i])
        x.close()

root = Tk()
root.title('Hi')
root.geometry('500x400')

cal = Calendar(root, date_pattern="d/m/y", year = 2020, month = 11, day =1)
cal.pack(pady=20)

def grab_date():
    my_label.config(text = cal.get_date())
    d = cal.get_date()

#Some statement that when pressing date I want the label appear with 
#information 
#from the textfiles depending on what I press on.
#I want it to appear once. For example: if I press on the button with date 
#2020/11/26 I only want the information from day0.txt to appear once.

my_button = Button(root, text = 'Get date', command = grab_date)
my_button.pack()

my_label = Label(root, text = ' ')
my_label.pack(pady = 20)

root.mainloop()