mardi 30 novembre 2021

java: too many cases makes performance drop [closed]

So for example I have code like this

String input;

switch(input){
   case "a": // do a process break;
   case "b": // do a process break;
   ... until around 40 functions
}

each process is unique. Simple example of the file

a
b
c
a
b

so the problem with performance is like this I use that function to read a file (that function run 20000 times).

when I run switch for 30 cases (comment 10 cases) the time is (assume) 30s
when I run switch for 35 cases (comment 5 cases) the time become 50s
when I run switch for 40 cases the time also become 50s
all of the 3 use same input that 10 commented cases is not exist in input

I am curious why there is a jump in that processing time and actually I also tried by using 30 cases which is 30s I added this code

// after the code above    
boolean temp = false;
if(temp){ // do nothing }

and the processing time is jump into 50s so the processing time is always jump from 30s to 50s when I add any if function except if(true){} or if (false){} but after it jump into 50s, it become stable in 50ish again

I wonder if java has some kind of memory allocation that affect this behaviour I tried to increase heap memory -Xmx but the result is still the same

I am trying to simplify my multiple array method calls into an if statement or something much more simple based on a condition

I would like to simplify my code and have one array filtering method and then assign the const Alerts based upon the corresponding conditions, instead of 5 array filtering methods. Perhaps an if statement or something of the like would do the trick?

    const pendingAlerts = array.filter((a) => a.approval_status === approvalStatuses.pending && !a.canceled_at).sort(sortCommunicationsByDateRule);
    const deniedAlerts = array.filter((a) => a.approval_status === approvalStatuses.denied && !a.canceled_at).sort(sortCommunicationsByDateRule);
    const upcomingAlerts = array.filter((a) => isApproved(a) && !a.canceled_at && a.begin_at > today).sort(sortCommunicationsByDateRule);
    const activeAlerts = array.filter((a) => isApproved(a) && !a.canceled_at && a.begin_at <= today && a.end_at > today).sort(sortCommunicationsByDateRule);
    const expiredAlerts = array.filter((a) => (a.canceled_at || a.end_at < today)).sort(sortCommunicationsByDateRule); 

    
        <div className="comm-communication-list comm-alert-list wrapper">
          {this.renderNotificationUI()}
          {this.renderDefinitionList(pendingAlerts)}
          {this.renderDefinitionList(upcomingAlerts)}
          {this.renderDefinitionList(activeAlerts)}
          {this.renderDefinitionList(deniedAlerts)}
          {this.renderDefinitionList(expiredAlerts)}
        </div> 

  //The ReactJS list above is rendering the Alert variables  i.e.(pending, upcoming, active, denied, and expired)  based upon the robust multiple filter methods 

I'm trying to create a conditional PHP script that depends on whether an array is NOT empty. Is my logic here correct?

I had a CSS minifier written in PHP (it takes a *.css file, or files, and strips out a bunch of stuff). Today, I learned that if, for whatever reason my webhost disables allow_url_fopen, my script stops working if an absolute URL is specified (and I need an absolute URL here because different pages call this script as an include from different locations).

I decided to write a fallback using a simple if-else condition: because I read my CSS file(s) into an array, the script checks whether an array is not empty; if so, it does its thing; if the array happens to be empty, it outputs a conventional link to the un-minified stylesheet.

I'm not entirely confident in my logic here. Does the following make sense?

<?php
// CSS MINIFIER
// Read the CSS file
$cssFiles = array("https://foobar.com/styles.css");

if (!empty($cssFiles)) {
  // Cycle through the files
  $buffer = "";
  foreach ($cssFiles as $cssFile) {
    $buffer .= file_get_contents($cssFile);
  }

  // Remove comments
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);

  // Remove spaces after colons
  $buffer = str_replace(': ', ':', $buffer);

  // Remove whitespace
  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);

  // Output the minified CSS string
  echo "<style>" . $buffer . "</style>";

} else {

  // If the array is empty, output a conventional CSS line
  echo '<link rel="stylesheet" href="https://foobar.com/styles.css">';

}
?>

How to create return to x?

while True:
        print("Welcome to this BMI calculator")
        x = str(input("Are you using Pounds or Kg, if you are using Kg press K if you are using Pounds press P:"))
        if x in ['P', 'p']:
            h = float(input("Key in your weight:"))

        elif x in ['K', 'k']:
            h = float(input("Key in your weight:"))

        else:
            **return(x)**
            print(x)
   

Bold indicates error and how to return if the user does not key in any of the characters (P/p/K/k)

Finding the high score for each student in a column in Google Sheets with multiple attempts turned on

I give students a quiz in Google Forms and allow multiple attempts. I create a Google Sheets file from the results. Now I want to find the high score for each student and match the score to a master list of email addresses returning a value of zero for any students that did not take the quiz.

How to add the conditional if in file text in java [closed]

I have a text file that includes several temperatures, but I only wanna print out the ones that are above 20. How can I make that possible? I know how to print and reach the text file but how can I make the program print only the temperatures higher than 20 or so. Basically what I am looking for is how to use if statement on a java text so I can print out only the required info.

public static void main(String[] args) throws Exception {




File f = new File ("C:/packages.txt");
Scanner sc = new Scanner (f);
String s;
while (sc.hasNextLine()){

s = sc.nextLine(); 
System.out.println(s);

    
    }
sc.close();
}
}

This is what I have worked on so far

If else not working as intended, is there something wrong with my logic?

I'm trying to loop through an array and if there are any matching elements, it should push true to a new array else return false.

const wordPerformance = []
const wordsReviewed   = "candy, cattle, cat, call, cheat";
const wordsIncorrect  = "candy, cattle, call, cheat";

wordsReviewed.split(/,\s?/).forEach((word) => {
  if (wordsIncorrect.includes(word)) {
    wordPerformance.push(false);
  } else {
    console.log(word) //unreachable, though 'cat' should be logged
    wordPerformance.push(true);
  }
});

console.log(wordPerformance);

By this logic, wordPerformance should return

[false, false, true, false, false]

however, it is returning

[false, false, false, false, false]

Maybe there is something I'm not seeing?

Writing a program in OAM Assembly Code which gets seven positive numbers and prints the highest one

Title really says it all. I need to write a program in OAM Assembly Code which gets seven positive numbers and prints the highest one. I am using OAMulator. The pseudocode I am supposed to follow is

Set highest to 0
Set count to 7
While count > 0
     Get newScore
     Print newScore
     If newScore > highest
            Set highest to newScore
     Set count to count - 1
Print highest
Stop

I was able to get it to where it prints all the numbers but I can't figure out how to get it to print the highest. Here is that code:

SET 7
STA 12
loopStart, LDA 0
STA 0
LDA 12
DEC
STA 12
BRP loopstart
HLT

Please help.

How to convert if else shorthand to normal if else case

Below code, I update the react hook with if-else shorthand condition. To understand exactly this, I try to write it in normal if-else condition, but I couldn't. What is the equal case of this shorthand conditions?

This is working code.

const [array, setArray] = useState([]);

function addProduct(product){
  const ProductExist = array.find((item) => item.id === product.id);
  setArray(
   array.map((item) =>
   item.id === product.id
   ? { ...ProductExist, quantity: ProductExist.quantity + 1 }
   : item
   )
 );
}

This is my try according to the solutions of other topics. But it gives error.

setTestArray(array.map((item) => {
  return if(item.id === product.id){
   return { ...ProductExist, quantity: ProductExist.quantity + 1 }
  }else{
   return item
  }
}

How to write else if as logical statement?

I want to write an if-else statement as a logical statement. I know that:

if (statement1){
   b=c
}
else{
   b=d
}

can be written as:

b=(statement1 && c)||(!statement1 && d)

But how do I write the following if-else statements as logical?:

if (statement1){
   b=c
}
else if (statement2){
   b=d
}
else{
   b=e
}

I'm sorry if there is already a post about this. I have tried, but couldn't find anything similar to my problem.

is there a simpler way to generate random password [duplicate]

import string
import random
characters = list(string.ascii_letters + string.digits + "!@#$%^&*()")

i = input('Please enter confirm (input 1) to proceed with password creation (or any to quit):\n')
if i == 1:
  print("Generating username and password....") 
  length = int(input("Enter password length: "))
  random.shuffle(characters)


  password = []
  for i in range(length):
    password.append(random.choice(characters))


  random.shuffle(password)



  print("".join(password))

else:
   exit

Is there a simpler way to generate a random password, also generating a password doesn't work in the if statement how do i fix this. I also want to be able to call out my password so how do i put it in a variable after ive generated one.

Count repeated elements in Java without using loops or imports

for training purposes i tried to code a programm wich counts how often a given number appears in an given int array. Then checks if the number is even or odd. Without using any imports or loops. I tried to solve it recursive. For Example:

(3, new int[]{3,3,4,5,3,3,2,1})

There are 4 threes, so the Programm should check if 4 is even or odd.

public static int evenNumberOf(int num, int[] numarr) {

After days of coding and not working code i decieded to ask here: any Solutions?

int i = 0 ;
        int counter = 0;
        if(a == null || a.length == 0) {
            return false;
        } else {
            if(a[i] == a.length -1 ) {
                if(counter % 2 == 0) {
                    System.out.println("true");
                    return true;
                    
                } else System.out.println("false");
                    return false;
                
            } else {
            if(a[i] == n) {
                counter++;
                i++;
                return evenNumberOf(n,a) ;
            } else {
                i++;
                return evenNumberOf(n,a) ;

Returning output as a matrix with required info

So I have here with me that is a function that calculates an employee's net salary. It includes the basic salary, overtime rate, deduction. It has two inputs ( basic salary and hours of overtime pay ).

def Net_salary(basic,overtime):
    if (basic < 3000):
        deduction = 0.85
        otrate = 20
        netsalary = basic * deduction + (overtime * otrate)
    elif (basic < 5000):
        deduction = 0.79
        otrate = 40
        netsalary = basic * deduction + (overtime * otrate)
    elif (basic < 8000):
        deduction = 0.73
        otrate = 60
        netsalary = basic * deduction + (overtime * otrate)
    else:
        deduction = 0.67
        otrate = 80
        netsalary = basic * deduction + (overtime * otrate)
    return netsalary    

My question is how do I return the info as a 5 by 6 matrix where 1st column is the employee number (1-5), 2nd column is the respective basic salary, 3rd column is the deduction amount (basic * deduction), 4th column is the hours worked overtime, 5th column is overtime pay( otrate * overtime) and 6th column is their net salary

excel if date range is between date range return value

Hi I am looking for some help with a spreadsheet im working on. I have a list of locations with a start and end date and I want to seperate these locations into tax years.

The end result will be a number of tables showing journeys completed within tax years. If a location falls into a tax year for instance 20/21 the entry should have a start date of the later of the actual start date or 06/04/2020.

Im self taught in excel and am comfortable with formulas or VBA so any help would be appreciated.

I have included a picture below of the sample data and also the desired outcome.

Sample data and desired result

How to use an ifelse statement to take means by groups with data.table syntax?

I use a data.table code that works fine but that I fail to transform to include an ifelse statement. I use the following reprex:

set.seed(1645)
Place <- c(rep("Copenhagen",7),rep("Berlin",11),rep("Roma",12))
Year <- c(rep("2020",4),rep("2021",3),rep("2020",6),rep("2021",5),rep("2019",4),rep("2020",4),rep("2021",4))
Value1 <- c(runif(3),NA,runif(8),NA,runif(9),NA,runif(7))
Value2 <- c(runif(4),NA,runif(2),runif(6),NA,NA,runif(11),NA,NA,runif(2))
df <- data.frame(Place,Year,Value1,Value2)

> df
        Place Year     Value1      Value2
1  Copenhagen 2020 0.10517697 0.865935100
2  Copenhagen 2020 0.96597760 0.579956282
3  Copenhagen 2020 0.47262307 0.346569960
4  Copenhagen 2020         NA 0.478763951
5  Copenhagen 2021 0.90030423          NA
6  Copenhagen 2021 0.14444142 0.280377315
7  Copenhagen 2021 0.73801550 0.302816525
8      Berlin 2020 0.13961383 0.641314310
9      Berlin 2020 0.40221211 0.756374251
10     Berlin 2020 0.49613139 0.070459347
11     Berlin 2020 0.95190545 0.184497038
12     Berlin 2020 0.40182901 0.407892240
13     Berlin 2020         NA 0.002209376
14     Berlin 2021 0.38310025          NA
15     Berlin 2021 0.76417492          NA
16     Berlin 2021 0.29001287 0.632133629
17     Berlin 2021 0.84478784 0.365406326
18     Berlin 2021 0.55547323 0.493870653
19       Roma 2019 0.44198733 0.067744090
20       Roma 2019 0.50403809 0.847876518
21       Roma 2019 0.85358805 0.952393606
22       Roma 2019 0.74996137 0.887583928
23       Roma 2020         NA 0.631937527
24       Roma 2020 0.08303509 0.993400333
25       Roma 2020 0.74205719 0.589183185
26       Roma 2020 0.27552659 0.522451407
27       Roma 2021 0.39518410          NA
28       Roma 2021 0.38390124          NA
29       Roma 2021 0.36605674 0.942102065
30       Roma 2021 0.32014949 0.375689863

I would like to calculate the mean by Place and Year if there are <= 25% NA in the group. Without my condition, this works fine:

setDT(df)
df_means <- df[,.(Value1_mean = mean(Value1),Value2_mean = mean(Value2)), by = .(Place,Year)]

> df_means
        Place Year Value1_mean Value2_mean
1: Copenhagen 2020          NA   0.4257258
2: Copenhagen 2021   0.3581245          NA
3:     Berlin 2020          NA   0.3935807
4:     Berlin 2021   0.3729461          NA
5:       Roma 2019   0.4572996   0.3956536
6:       Roma 2020          NA   0.6494491
7:       Roma 2021   0.4142637          NA

I fail to include the ifelse statement, this does not work:

df_means2 <- df[,.(Value1_mean = ifelse(sum(is.na(Value1))/length(Value1)>=0.25,NA,mean(Value1,na.rm=TRUE)),
                   Value2_mean = ifelse(sum(is.na(Value2))/length(Value2)>=0.25,NA,mean(Value2,na.rm=TRUE))), 
                by = .(Place,Year)]

I checked these posts 1, 2, and 3 without solving my issue. My expected result should be this:

> df_means2
       Place Year Value1_mean Value2_mean
1 Copenhagen 2020        mean        mean
2 Copenhagen 2021        mean        <NA>
3     Berlin 2020        mean        mean
4     Berlin 2021        mean        <NA>
5       Roma 2019        mean        mean
6       Roma 2020        mean        mean
7       Roma 2021        mean        <NA>

How can I transform my code?

How do i input any number/alphabet/character in python

while True:
    i = input('Please enter confirm (input 1) to proceed with username and password creation (or any to quit):\n')
    i = int(i)
    if i == 1:
        print("Generating username and password....")
        break

how can i get it to quit if i input any value/character other than 1

Google Spreadsheets: Conditional formating based on text in another sheet

I'm trying to make a conditional formatting statement based on if a cell is filled with text on another sheet.

For example:

Sheet1 needs to change color of the cell A1 to blue if Sheet2 has text in cell A1

I used a couple of techniques as suggested in other stackoverflow questions, such as: Conditional Formatting from another sheet (I cant find out how to do some sort of regexmatch in this statement)

I thought of some sort of line as (as a custom formula in conditional formatting):

A1(REGEXMATCH(INDIRECT(Sheet2!A1), ""),1 ,0))

but that doesnt work.

Hope someone can help me with this!

How can i solve this While Loop code? Is not repeat code [closed]

Hi I have an problem with my code. if i input on my variable again char N, code not repeat again, but if i input Y in again variable code return cout and finish.

#include <iostream>

using namespace std;

int main()
{
    char again = 'N';
    string firstName, lastName;
    while (again == 'n' || again == 'N') {
        cout << "Hello" << endl
             << "Enter You'r First Name: ";
        cin >> firstName;
        cout << "Enter you'r Last Name: ";
        cin >> lastName;
        cout << "You'r name is " << firstName << " " << lastName << endl;
        cout << "Right (Y/N): " << endl;
        cin >> again;
        if (again == 'y' || again == 'Y') {
            cout << "Have a nice day!";
        }
        return 0;
    }
}

Operators in an if-else statement [duplicate]

I want to have a logic that returns a value based on 2 variables: a received value and a current value. I have simplified it from multiple else-if's to an operator.

The code is something like this:

var receivedState = 2;
var currentState = 1;
var allowedState = true;

if(receivedState == 2 && currentState !== 1) { 
  allowedState = 1;
} else if ((receivedState == 3 || 4 || 5) && (currentState !== 2)) { 
    allowedState = 2;
}

console.log(allowedState);

So what I am trying to do is if the received state is "2" AND current state is not "1" then I want to set the value of allowedState to 1.

What happens now is that it sets the value to 2.

For the other it does work. When the state is 3, 4 or 5 and the current state is not 2 then the value of allowedState is set to 2 except when the current state is something else than the value of 2, then the value of allowedState is 2.

How do I change my code so that the logic works as following:

If received value is 2 and current value is not 1 then return 1, else do nothing (return true). If received value is one of 3, 4 or 5 and current value is not 2 then return 2, else do nothing.

Thanks in advance.

pdfplumber | Extract text from separate columns

Attempted Solution at bottom of post.

I have near-working code that extracts the sentence containing a phrase, across multiple lines.

However, some pages have columns. So respective outputs are incorrect; where separate texts are wrongly merged together as a bad sentence.

This problem has been addressed in the following posts:


Question:

How do I "if-condition" whether there are columns?

  • Pages may not have columns,
  • Pages may have more than 2 columns.
  • Pages may also have headers and footers (that can be left out).

Example .pdf with dynamic text layout: PDF (pg. 2).

Jupyter Notebook:

# pip install PyPDF2
# pip install pdfplumber

# ---

import pdfplumber

# ---

def scrape_sentence(phrase, lines, index):
    # -- Gather sentence 'phrase' occurs in --
    sentence = lines[index]
    print("-- sentence --", sentence)
    print("len(lines)", len(lines))
    
    # Previous lines
    pre_i, flag = index, 0
    while flag == 0:
        pre_i -= 1
        if pre_i <= 0:
            break
            
        sentence = lines[pre_i] + sentence
        
        if '.' in lines[pre_i] or '!' in lines[pre_i] or '?' in lines[pre_i] or '  •  ' in lines[pre_i]:
            flag == 1
    
    print("\n", sentence)
    
    # Following lines
    post_i, flag = index, 0
    while flag == 0:
        post_i += 1
        if post_i >= len(lines):
            break
            
        sentence = sentence + lines[post_i] 
        
        if '.' in lines[post_i] or '!' in lines[post_i] or '?' in lines[post_i] or '  •  ' in lines[pre_i]:
            flag == 1 
    
    print("\n", sentence)
    
    # -- Extract --
    sentence = sentence.replace('!', '.')
    sentence = sentence.replace('?', '.')
    sentence = sentence.split('.')
    sentence = [s for s in sentence if phrase in s]
    print(sentence)
    sentence = sentence[0].replace('\n', '').strip()  # first occurance
    print(sentence)
    
    return sentence

# ---

phrase = 'Gulf Petrochemical Industries Company'

with pdfplumber.open('GPIC_Sustainability_Report_2016-v9_(lr).pdf') as opened_pdf:
    for page in opened_pdf.pages:
        text = page.extract_text()
        if text == None:
            continue
        lines = text.split('\n')
        i = 0
        sentence = ''
        while i < len(lines):
            if phrase in lines[i]:
                sentence = scrape_sentence(phrase, lines, i)
            i += 1

Example Incorrect Output:

-- sentence -- being a major manufacturer within the kingdom of  In 2012, Gulf Petrochemical Industries Company becomes part of 
len(lines) 47

 Company (GPIC)gulf petrochemical industries company (gpic) is a leading joint venture setup and owned by the government of the kingdom of bahrain, saudi basic industries corporation (sabic), kingdom of saudi arabia and petrochemical industries company (pic), kuwait. gpic was set up for the purposes of manufacturing fertilizers and petrochemicals. being a major manufacturer within the kingdom of  In 2012, Gulf Petrochemical Industries Company becomes part of 

 Company (GPIC)gulf petrochemical industries company (gpic) is a leading joint venture setup and owned by the government of the kingdom of bahrain, saudi basic industries corporation (sabic), kingdom of saudi arabia and petrochemical industries company (pic), kuwait. gpic was set up for the purposes of manufacturing fertilizers and petrochemicals. being a major manufacturer within the kingdom of  In 2012, Gulf Petrochemical Industries Company becomes part of the global transformation for a sustainable future by committing to bahrain, gpic is also a proactive stakeholder within the United Nations Global Compact’s ten principles in the realms the kingdom and the region with our activities being of Human Rights, Labour, Environment and Anti-Corruption. represented by natural gas purchases, empowering bahraini nationals through training & employment, utilisation of local contractors and suppliers, energy consumption and other financial, commercial, environmental and social activities that arise as a part of our core operations within the kingdom.GPIC becomes an organizational stakeholder of Global Reporting for the purpose of clarity throughout this report,  Initiative ( GRI) in 2014. By supporting GRI, Organizational ‘gpic’, ’we’ ‘us’, and ‘our’ refer to the gulf  Stakeholders (OS) like GPIC, demonstrate their commitment to transparency, accountability and sustainability to a worldwide petrochemical industries company; ‘sabic’ refers to network of multi-stakeholders.the saudi basic industries corporation; ‘pic’ refers to the petrochemical industries company, kuwait; ‘nogaholding’ refers to the oil and gas holding company, kingdom of bahrain; and ‘board’ refers to our board of directors represented by a group formed by nogaholding, sabic and pic.the oil and gas holding company (nogaholding) is  GPIC is a Responsible Care Company certified for RC 14001 since July 2010. We are committed to the safe, ethical and the business and investment arm of noga (national environmentally sound management of the petrochemicals oil and gas authority) and steward of the bahrain  and fertilizers we make and export. Stakeholders’ well-being is government’s investment in the bahrain petroleum  always a key priority at GPIC.company (bapco), the bahrain national gas company (banagas), the bahrain national gas expansion company (bngec), the bahrain aviation fuelling company (bafco), the bahrain lube base oil company, the gulf petrochemical industries company (gpic), and tatweer petroleum.GPIC SuStaInabIlIty RePoRt 2016 01ii GPIC SuStaInabIlIty RePoRt 2016 GPIC SuStaInabIlIty RePoRt 2016 01
[' being a major manufacturer within the kingdom of  In 2012, Gulf Petrochemical Industries Company becomes part of the global transformation for a sustainable future by committing to bahrain, gpic is also a proactive stakeholder within the United Nations Global Compact’s ten principles in the realms the kingdom and the region with our activities being of Human Rights, Labour, Environment and Anti-Corruption']
being a major manufacturer within the kingdom of  In 2012, Gulf Petrochemical Industries Company becomes part of the global transformation for a sustainable future by committing to bahrain, gpic is also a proactive stakeholder within the United Nations Global Compact’s ten principles in the realms the kingdom and the region with our activities being of Human Rights, Labour, Environment and Anti-Corruption

...

Attempted Minimal Solution: This will separate text into 2 columns; regardless if there are 2.

# pip install PyPDF2
# pip install pdfplumber

# ---

import pdfplumber
import decimal

# ---

with pdfplumber.open('GPIC_Sustainability_Report_2016-v9_(lr).pdf') as opened_pdf:
    for page in opened_pdf.pages:
        left = page.crop((0, 0, decimal.Decimal(0.5) * page.width, decimal.Decimal(0.9) * page.height))
        right = page.crop((decimal.Decimal(0.5) * page.width, 0, page.width, page.height))
        
        l_text = left.extract_text()
        r_text = right.extract_text()
        print("\n -- l_text --", l_text)
        print("\n -- r_text --", r_text)
        text = str(l_text) + " " + str(r_text)

Please let me know if there is anything else I should clarify.

Awk if-statement to count the number of characters (wc -m) coming from a pipe

I tried to scratch my head around this issue and couldn't understand what it wrong about my one liner below.

Given that

echo "5" | wc -m 
2

and that

echo "55" | wc -m
3

I tried to add a zero in front of all numbers below 9 with an awk if-statement as follow:

echo "5" |  awk '{ if ( wc -m $0 -eq 2 ) print 0$1 ; else print $1 }'
05

which is correct, however with 2 digits numbers I get the same zero in front.

echo "55" |  awk '{ if ( wc -m $0 -eq 2 ) print 0$1 ; else print $1 }'
055

How come? It should return only 55 instead of 055. Am I constructing the if statement wrong?

I'm not interested in the optimal way to add leading zeros in the command line (there are enough duplicates of that), my question is regarding why the code above is not working.

Thanks!

Issues with "if-else" statement

I have the following dataframe:

df = pd.DataFrame({'y': [4,3,6,1], 'x': [0,0,2,1]})

I would like to compute the ratio of the two columns. However, since there are some 0 in the denominator, I would like to fix if with a if else statement. The condition should be: if in the denominator there is 0, replace it with 1 and compute the ratio, otherwise as usual.

I did this (and other variations) but it doesn't work (see below error):

if df['x'] == 0:
   df['x'] = 1
   df['ratio'] = df['y']/df['x']
else:
   df['ratio'] = df['y']/df['x']

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

Can anyone help me?

Thanks!

Why the answer always go greater in assembly [duplicate]

This is the code that I have I am trying to get a number input and check whether it is greater or smaller than 4. For some reason when I input 3, the code output "Greater". I checked the input, when I input 0 and minus 1, the result is '/', so I can sure if I input number 0 - 9, it must be in range 48 - 57(DEC).

section .data
    ques db "Enter a number:", 10
    queslen equ $- ques

    gt db "Greater", 10
    gtlen equ $- gt

    lt db "Smaller", 10
    ltlen equ $- lt

section .bss
    input resb 2

section .text
    global  _start

_start:
    call    _printQues
    call    _getInput
    mov rax, [input]
    cmp rax, '4'
    jg  _greater

    mov rax, 1
    mov rdi, 1
    mov rsi, lt
    mov rdx, ltlen
    syscall
    jmp _exit

_printQues:
    mov rax, 1
    mov rdi, 1
    mov rsi, ques
    mov rdx, queslen
    syscall
    ret

_getInput:
    mov rax, 0
    mov rdi, 0
    mov rsi, input
    mov rdx, 2
    syscall
    ret

_greater:
    mov rax, 1
    mov rdi, 1
    mov rsi, gt
    mov rdx, gtlen
    syscall
    jmp _exit

_exit:
    mov rax, 60
    mov rdi, 0
    syscall

Ifelse applied to an interval of columns, but keeping all the other columns

I would like to use the ifelse function to attribute new values to a set of columns in a df. The real df has >200 columns, so I can't state the names of the columns, instead, I need to specify the interval of columns (e.g. 2:205).

df <- data.frame(x=c(123, 121, 120, 124, 125), y=c(1, 0, 0, 0, 1), z=c(0,0, 0, 0, 1))
df
    x y z
1 123 1 0
2 121 0 0
3 120 0 0
4 124 0 0
5 125 1 1

However, when I do specify the interval of columns, the first column is skipped. How can I keep the first column unchanged?

df2 <- as.data.frame(ifelse(df[2:3] == 1, 2, 0))
df2
  y z
1 2 0
2 0 0
3 0 0
4 0 0
5 2 2

Thanks.

pdfplumber | if-condition page text has columns

I have written near-working code that extracts the sentence containing a phrase, across multiple lines.

However, some pages may or may not have columns. So current outputs are incorrect; an amalgamation of completely separate sentences.

This problem has been addressed in the following posts:


Question:

How do I "if-condition" whether there are columns?

  • Pages may not have columns,
  • Pages may have more than 2 columns.
  • Pages may also have headers and footers (that can be left out).

Example .pdf with dynamic text layout: PDF (pg. 2).

Jupyter Notebook:

# pip install PyPDF2
# pip install pdfplumber

# ---

import glob
import PyPDF2
import pdfplumber

# ---

def scrape_sentence(phrase, lines, index):
    # -- Gather sentence 'phrase' occurs in --
    sentence = lines[index]
    print("-- sentence --", sentence)
    print("len(lines)", len(lines))
    
    # Previous lines
    pre_i, flag = index, 0
    while flag == 0:
        pre_i -= 1
        if pre_i <= 0:
            break
            
        sentence = lines[pre_i] + sentence
        
        if '.' in lines[pre_i] or '!' in lines[pre_i] or '?' in lines[pre_i] or '  •  ' in lines[pre_i]:
            flag == 1
    
    print("\n", sentence)
    
    # Following lines
    post_i, flag = index, 0
    while flag == 0:
        post_i += 1
        if post_i >= len(lines):
            break
            
        sentence = sentence + lines[post_i] 
        
        if '.' in lines[post_i] or '!' in lines[post_i] or '?' in lines[post_i] or '  •  ' in lines[pre_i]:
            flag == 1 
    
    print("\n", sentence)
    
    # -- Extract --
    sentence = sentence.replace('!', '.')
    sentence = sentence.replace('?', '.')
    sentence = sentence.split('.')
    sentence = [s for s in sentence if phrase in s]
    print(sentence)
    sentence = sentence[0].replace('\n', '').strip()  # first occurance
    print(sentence)
    
    return sentence

# ---

phrase = 'Gulf Petrochemical Industries Company'

with pdfplumber.open('GPIC_Sustainability_Report_2016-v9_(lr).pdf') as opened_pdf:
    for page in opened_pdf.pages:
        text = page.extract_text()
        if text == None:
            continue
        lines = text.split('\n')
        i = 0
        sentence = ''
        while i < len(lines):
            if phrase in lines[i]:
                sentence = scrape_sentence(phrase, lines, i)
            i += 1

Example Incorrect Output:

-- sentence -- being a major manufacturer within the kingdom of  In 2012, Gulf Petrochemical Industries Company becomes part of 
len(lines) 47

 Company (GPIC)gulf petrochemical industries company (gpic) is a leading joint venture setup and owned by the government of the kingdom of bahrain, saudi basic industries corporation (sabic), kingdom of saudi arabia and petrochemical industries company (pic), kuwait. gpic was set up for the purposes of manufacturing fertilizers and petrochemicals. being a major manufacturer within the kingdom of  In 2012, Gulf Petrochemical Industries Company becomes part of 

 Company (GPIC)gulf petrochemical industries company (gpic) is a leading joint venture setup and owned by the government of the kingdom of bahrain, saudi basic industries corporation (sabic), kingdom of saudi arabia and petrochemical industries company (pic), kuwait. gpic was set up for the purposes of manufacturing fertilizers and petrochemicals. being a major manufacturer within the kingdom of  In 2012, Gulf Petrochemical Industries Company becomes part of the global transformation for a sustainable future by committing to bahrain, gpic is also a proactive stakeholder within the United Nations Global Compact’s ten principles in the realms the kingdom and the region with our activities being of Human Rights, Labour, Environment and Anti-Corruption. represented by natural gas purchases, empowering bahraini nationals through training & employment, utilisation of local contractors and suppliers, energy consumption and other financial, commercial, environmental and social activities that arise as a part of our core operations within the kingdom.GPIC becomes an organizational stakeholder of Global Reporting for the purpose of clarity throughout this report,  Initiative ( GRI) in 2014. By supporting GRI, Organizational ‘gpic’, ’we’ ‘us’, and ‘our’ refer to the gulf  Stakeholders (OS) like GPIC, demonstrate their commitment to transparency, accountability and sustainability to a worldwide petrochemical industries company; ‘sabic’ refers to network of multi-stakeholders.the saudi basic industries corporation; ‘pic’ refers to the petrochemical industries company, kuwait; ‘nogaholding’ refers to the oil and gas holding company, kingdom of bahrain; and ‘board’ refers to our board of directors represented by a group formed by nogaholding, sabic and pic.the oil and gas holding company (nogaholding) is  GPIC is a Responsible Care Company certified for RC 14001 since July 2010. We are committed to the safe, ethical and the business and investment arm of noga (national environmentally sound management of the petrochemicals oil and gas authority) and steward of the bahrain  and fertilizers we make and export. Stakeholders’ well-being is government’s investment in the bahrain petroleum  always a key priority at GPIC.company (bapco), the bahrain national gas company (banagas), the bahrain national gas expansion company (bngec), the bahrain aviation fuelling company (bafco), the bahrain lube base oil company, the gulf petrochemical industries company (gpic), and tatweer petroleum.GPIC SuStaInabIlIty RePoRt 2016 01ii GPIC SuStaInabIlIty RePoRt 2016 GPIC SuStaInabIlIty RePoRt 2016 01
[' being a major manufacturer within the kingdom of  In 2012, Gulf Petrochemical Industries Company becomes part of the global transformation for a sustainable future by committing to bahrain, gpic is also a proactive stakeholder within the United Nations Global Compact’s ten principles in the realms the kingdom and the region with our activities being of Human Rights, Labour, Environment and Anti-Corruption']
being a major manufacturer within the kingdom of  In 2012, Gulf Petrochemical Industries Company becomes part of the global transformation for a sustainable future by committing to bahrain, gpic is also a proactive stakeholder within the United Nations Global Compact’s ten principles in the realms the kingdom and the region with our activities being of Human Rights, Labour, Environment and Anti-Corruption

...

Please let me know if there is anything else I can add to post.

How to write cleaner if-else statements and prevent nesting

So I know that nesting code can get ugly very quickly. Therfore I looked up a way to prevent nesting an found out that you can do the following

if (user == null) return;

console.log('Deleting');
user.delete();

Instead of using curly brackezs like that

if (user != null) {
console.log('Deleting');
user.delete();
}

However I can't really see how this is helpful when using an if-else statement. For example: I have this piece of code from my project that I would really like to write in a cleaner way than that. But I am struggling to figure out how this can be done.

               if (parseInt(year) == joinTime.getFullYear()) {
                    if (parseInt(month) == joinTime.getMonth() + 1) {
                        if (parseInt(day) == joinTime.getDay()) {
                            channel.send(message);
                        } else {
                            comparison(day, hour, minute);
                        }
                    } else {
                        comparison(day, hour, minute);
                    }
                } else {
                    comparison(day, hour, minute);
                }

IF-Else condition with SQL statement

declare @RevisionId int =3
declare @ObjectId  int =2

if @RevisionId in(2,3) 
Begin 
    If @ObjectId like '%1%' OR @ObjectId like '%2%' and @RevisionId =2
    Begin 
        If @ObjectId = '1'
        Begin       
            print 'ObjectId1 rev2'
        End    
        else If @ObjectId = '2'
        Begin 
            print 'ObjectId2 rev 2'
        End 
    End 
    else If @ObjectId like '%1%' OR @ObjectId like '%2%' and @RevisionId =3
    Begin
        If @ObjectId = '1'
        Begin   
            print 'ObjectId1 rev3'
        End  
    End 
    else If @ObjectId = '2'
    Begin
        print 'ObjectId2 rev3'
    End   
End 

Expected result:

  • For RevisionId 2 and ObjectId 1 -> ObjectId1 rev2 -- as expected from above solution

  • For RevisionId 2 and ObjectId 2 -> ObjectId2 rev2 -- as expected from above solution

  • For RevisionId 3 and ObjectId 1 -> ObjectId1 rev3 -- result failed and showing command successfully

  • For RevisionId 3 and ObjectId 2 -> ObjectId2 rev3 -- result failed and showing command successfully

There might be issue with the solution - how can I find the solution?

lundi 29 novembre 2021

How to continue an if else statement (?) with another if else statement

A little confused on where to put another if-else statement after one. like do I put it under the if statement ("have you registered to vote yet?" ) or do i put it under the else statement?

I wanted it to answer if yes then it would print out "you can vote" and if no then it would print out "You must register before you can vote"

here's the code

import java.util.Scanner;

public class voting {
  public static void main(String[] args) {
    int yourage, votersage;
    votersage = 18;
    Scanner input = new Scanner(System.in);
    System.out.println("How old are you? ");
    yourage = input.nextInt();
    if (yourage >= votersage) {
      System.out.println("Have you registered to vote?");
    }
    else {
      System.out.println("You are too young to vote");
    }
  }
}

Basic Java HiLow guessing game

I am fully aware this question has been asked many times, it is a classic first year problem in CSC. I am not looking for the solution to the problem itself. I think I have it basically done however I am missing something that I cannot find how to do.

Here is my code:

import java.util.Scanner;
import java.util.Random;

public class HiLow
{
    public static void main (String[] args) 
    {
        Random generator = new Random();
        Scanner scan = new Scanner(System.in);
        int num1,guess;
        int count = 0;
        num1 = generator.nextInt(100) + 1;
        while(true) {
            System.out.print("Enter an integer between 1 or 100 or enter 00 at anytime to quit: ");
            guess = scan.nextInt();
            count++;
            if(guess == num1 || guess == 00) {
                if(guess == 00) {
                    System.out.println("Thanks for playing");
                    break;
                }
                System.out.println("Congrats you've guessed correct and your total guesses is " + count );
                break;
            }
            else if (guess > 100 || guess < 1) {
                System.out.print("I see you cannot follow instructions. I said ");
                count--;
            }
            else if (guess > num1) {
                System.out.println("You have guessed too high. ");
            }
            else {
                System.out.println("You have guessed too low.");
            }
        }
    }
}

My problem is i am required to prompt the user at the point of "if the user quits or successfully guesses the correct number, prompt the user to see if they wish to play again". I am lost and not sure how to continue my while loop from the beginning after my breaks. Is there a way to end the break condition i have from (guess == num1 || guess ==0) and direct my program to start again at the while(true) statement?

Thanks

cmd: Open a browser when a string is output using docker

I'm running a docker command from inside cmd (a .bat script). The command looks like docker run --shm-size=1gb -it --privileged --name test p 8080:8080 -h test thom/test:latest I want to make a loop that waits for a certain string to appear after I invoke this command, or it waits for the port (8080) to be open. The string is "Daemon started!", and when it is output, I want to open a browser:

explorer "http://localhost:8080"

I'm struggling to make a while loop in batch though without restarting the docker command. This is what I have so far.

:loop
timeout /t 5
(docker run --shm-size=1gb -it --privileged --name test p 8080:8080 -h test thom/test:latest | find "proxy Daemon started!")  > nul 2>&1
if find "proxy Daemon started!" goto loop
echo I can go!
explorer "http://localhost:8080

 

Fail Result for if-else condition in sql

if @RevisionId in(2,3) Begin If @ObjectId like '%1%' OR @ObjectId like '%2%' and @RevisionId =2 Begin If @ObjectId = '1' Begin
print 'ObjectId1 rev2' End
else If @ObjectId = '2' Begin

                print 'ObjectId2 rev 2'
                End 
        End 
        else If @ObjectId like '%1%' OR @ObjectId like '%2%' and @RevisionId =3
            Begin
            If @ObjectId = '1'
                Begin   
                print 'ObjectId1 rev3'
                End  
            End 
            else  If @ObjectId = '2'
            Begin
                print 'ObjectId2 rev3'
            End   
    End 
    -----
    Expected Result :
For RevisionId 2 and ObjectId 1 -> ObjectId1 rev2
For RevisionId 2 and ObjectId 2 -> ObjectId2 rev2
For RevisionId 3 and ObjectId 1 -> ObjectId1 rev3
For RevisionId 3 and ObjectId 2 -> ObjectId2 rev3
    ------

how can I search for an input in a char, to replace it

in the function different i want to search for a specific letter which i set in a printf an scanf request in my main function. In the main function i also set the text and the letter which should be insert for the other letter.

#include <stdio.h>
#include <string.h>

int change (char *text, char search, char replace)
{
  int i=0;
  char help[40];

  sprintf(hilf,"%s",text);

  for(i=0; i<= strlen(help); i++) 
  {
    if(help[i]==search)
    {
      help[i]==replace;
    }
  }
}

int main()
{
  char name[40];
  int z, ne;

  printf("\nName: ");
  fgets(name, sizeof(name),stdin);

  printf("\nwhich sign do you want to replace: ");
  scanf("%i", &z);

  printf("\nnew sign: ");
  scanf("%i", &ne);

  change(name, z, ne);

  printf("\nchanged text is: %s", name);
}

TypeError cannot read property url of undefined on strapi

I have a list of items. Some have a download link and some not.

If I try to render a an undefined url, I have this error. So I tried this :

if (spectacle.pdf.url) {
    const pdf = spectacle.pdf.url;
    const flag = `/fl_attachment:dossier${spectacle.slug}`;
    const position = 47;
    const output = [pdf.slice(0, position), flag, pdf.slice(position)].join('');
}

But I now have an other error telling me that output is not defined. Does someone can explain me how to do it well to stop a function to load if undefined ?

[slug].js

const Spectacle = ({ spectacle, spectacles, categories }) => {



  const slideRight = () => {
    const slider = document.querySelector('.gallery');
    console.log(slider);
    slider.scrollBy({
      left: 450,
      behavior: 'smooth'
    });
  }

  const slideLeft = () => {
    const slider = document.querySelector('.gallery');
    console.log(slider);
    slider.scrollBy({
      left: -450,
      behavior: 'smooth'
    });
  }

  useEffect(() => {
    const bigTitle = document.getElementById('big-title');
    const vertTitle = document.getElementById('ver-title');
    const title = spectacle.title;
    if (title.length > 30) {
      bigTitle.style.fontSize = "8vw";
      vertTitle.style.fontSize = "3rem";
    }
  }, []);

  
if (spectacle.pdf.url) {
    const pdf = spectacle.pdf.url;
    const flag = `/fl_attachment:dossier${spectacle.slug}`;
    const position = 47;
    const output = [pdf.slice(0, position), flag, pdf.slice(position)].join('');
}


  return (
    <>
      <div className="spectacle-header">
        <img src={spectacle.image.url} />
        <div className="spectacle-titles">
          <h1 id="big-title" className="big-title">{spectacle.title}</h1>
          <h5 className="subtitle">{spectacle.sousTitre}</h5>
        </div>
      </div>
      <Container className="spectacle-text">
        <Row className="bloc-mob">
          <Col className="ext a">
            <h1 id="ver-title" className="vertical-title red">{spectacle.title}</h1>
            <h2 className="quote shows">{spectacle.citation}</h2>
          </Col>
          <Col className="middle-col">
            <p className="">
              <Moment format="YYYY" className="date">{spectacle.year}</Moment>
            </p>
            <Row className="status">
              <Col>
                <span>{spectacle.status}</span>
              </Col>
              <Col>
                <span>{spectacle.category.name}</span>
              </Col>
            </Row>
            <div>
              <p className="description" id='desc'>
                <ReactMarkdown source={spectacle.description} />
                <a href={output} download="newfilename"><h4>Télécharger le document</h4></a>
              </p>
              <div className="video"
              dangerouslySetInnerHTML= >
              </div>
            </div>
          </Col>
          <Col className="ext b">
            <p className="generic" id="generic">
              <ReactMarkdown source={spectacle.cast} />
            </p>

           
            <div className="scroll-down">
              Scroll down
              <img src="https://res.cloudinary.com/ciefact/image/upload/v1634668021/arrow_0e058f1520.svg"
                className="arrow-down" />
            </div>
          </Col>
          {/* <Col className="illu">
            <img src={spectacle.Illustration.url} />
          </Col> */}
        </Row>

        <Row className="gallery">

          {spectacle.galery.map((item) => (
            <ModalImage
              key={item.id}
              small={item.url}
              large={item.url}
              alt={item.title}
              hideZoom={true}
              hideDownload={true}
            />
          ))}
        </Row>
        <button
          id="slideLeft"
          type="button"
          onClick={slideLeft}
        >
          <img src="https://res.cloudinary.com/ciefact/image/upload/v1634668021/arrow_0e058f1520.svg"
            className="arrow-down" />
        </button>
        <button
          id="slideRight"
          type="button"
          onClick={slideRight}
        >
          <img src="https://res.cloudinary.com/ciefact/image/upload/v1634668021/arrow_0e058f1520.svg"
            className="arrow-down" />
        </button>
      </Container>
    </>
  )
}

export async function getStaticPaths() {
  const spectacles = await fetchAPI("/spectacles")

  return {
    paths: spectacles.map((spectacle) => ({
      params: {
        slug: spectacle.slug,
      },
    })),
    fallback: 'blocking',
  }
}

export async function getStaticProps({ params }) {
  const spectacle = (await fetchAPI(`/spectacles?slug=${params.slug}`))[0]

  const [spectacles, categories] = await Promise.all([
    fetchAPI("/spectacles"),
    fetchAPI("/categories"),
  ])
  return {
    props: { spectacle: spectacle, spectacles, categories },
    revalidate: 1,
  }
}

export default Spectacle 

If else condition is not working for my code [closed]

---the above code is not working for ObjectId like 1 and RevisionId =3 -- for ObjectId like 1 and RevisionId =3 it is select query is appending with where condition in revision 2

if @RevisionId in(2,3) 
        Begin -- 2
            If @ObjectId like '%1%' OR @ObjectId like '%2%' and @RevisionId =2
            Begin --3
                If @ObjectId = '1'
                Begin --4
                    Set @demoquery = @demoquery  + @ColName + ' in (select id from table1  )'
                End    --4
                else  If @ObjectId = '2'
                    Begin --5
                    Set @demoquery = @demoquery + @ColName + ' in ( select id from table2 where status='''+ N'sample' +''' )'
                    End  --5
            End  --3
            else If @ObjectId like '%1%' OR @ObjectId like '%2%' and @RevisionId =3
                Begin --3
                If @ObjectId = '1'
                    Begin --4
                    Set @demoquery = @demoquery  + @ColName + ' in (select id from table1  )'
                    End  --4
                End --3
                else  If @ObjectId = '2'
                Begin --5
                Set @demoquery = @demoquery + @ColName + ' in ( select id from table2 where status='''+ N'sample' +''' )'
                End   --5
        End ---2

Problem with running code and linking parts

def menu():
    print("1. Create new User")
    print("2. View User")
    print("3. Update User")
    print("4. Quit ") 
menu()

selection=input("Select a menu- Input a number:")

if not selection.isdigit():
    print("You have input a non digit value. Select again:")
    selection=input("Select a menu- Input a number:")
else:  
    selection = int(selection)
    if selection==1:
      print("::menu 1::")
      newName = input("Input first name : ")
      newSurname = input("Input last name : ")
    elif selection==2:
      print("::menu 2::")
    elif selection==3:
      print("::menu 3::")
    elif selection==4:
      print("you have logged out")
    else:
      print("There is no menu",end=" ")
      print(selection)
      print()
      menu()
      selection=input("Select a menu- Input a number:")

so when i run the code and input a wrong value first (non integer) then input a number that's not in the menu i want it to be able to let me to then input another number like a right one eg 1 but its seems it doesn't do anything after that and i don't know how to fix it can someone help. It only acknowledges 1-4 only when i do it first but not after any wrong values.

if condition in XSLT for End of Contract date

I want to have if condition in which to use the End of Contract Date as a default value, but if it is empty or not equal the last day of work then use the actual Termination_Last_Day_of_Work?

Would you please help me on how to do that using xsl:if in XSLT?

       <End_Date>
            <xsl:value-of select="ws:Contract/ws:End_Date/text()"/>
        </End_Date>
        
        <Last_Day_of_Work>
            <xsl:value-of select="ws:Status/ws:Termination_Last_Day_of_Work/text()"/>
        </Last_Day_of_Work>

Regards, Eman

How to avoid a terminal prompt in Java

I have a simple Java program that asks a series of questions. At the end I ask the user if they would like to continue with the program or quit. If they say yes, the program asks them the same questions as before. This works, but as soon as they as asked the questions the program seems to stop. This is the function that I am calling. IS it because I don't have anything at the end of the if statement? I'm new to Java and just trying to understand this sequence.

void doMore(){

        System.out.print("Do you want to do anything else? : Yes|No ");
        String answer = keyboard.nextLine();

        if(answer.equals("YES") || answer.equals("yes")|| answer.equals("Y") || answer.equals("y")){
            showInstructions();
        }else{
            System.out.println("Thank you for using the lego manager. Please come back soon!");
            System.exit(0);
        }
}

SQL Query If more than one contact I only want the first listed

I am trying to write a query that joins residents emergency contacts names and phone numbers however we have several types of emergency contacts they can list.

For example: they can list emergency contact, responsible party, Power of Attorney.

I am wanting to pull back Responsible party. But some have 2 responsible parties listed and some have none and only an emergency contact.

How do I get just the first listed Responsible party and or if they do not have a responsible party listed grab the emergency contact but only 1 not several if they list more than one emergency contact.

Resident Name   Contact Name    Phone          Contact Type
----------------------------------------------------------------
Jane Doe        John Smith      999-999-9999   Responsible Party
Jane Doe        Patrick Star    999-888-8888   Responsible Party

I only want one of those Responsible Party not both

Thanks for your help!

Is it possible to reference information that's currently only within a google sheet query?

I have a query (=QUERY(A9:N,"Select C,D,E,F,G,H,I where B contains """&L3&"""")) Which returns a header row and a row where the answers are either true or false - depending on the the tickboxes in the query array.

I am trying to find whichever Column has true and return the header in a TEXTJOIN - so that I get one cell with all the true headers if that makes sense.

My current attempt is with an array formula

=TEXTJOIN(" | ",true ,ArrayFormula(if(QUERY(A9:N,"Select C,D,E,F,G,H,I where B contains """&L3&"""")=true,[HELP],"")))

but I don't know how to return the header or rather return the value of the cell right above the true - it would be easy enough if I let it fill up a 7x2 box but again - would prefer a one-cell answer

https://docs.google.com/spreadsheets/d/1e3FtvRGlefL154GCAYg8LpU_3jJOADZJVFBNBaOrDwQ/edit?usp=sharing The spreadsheet is rather large but sheet in question is "Resource Node Overview"

Any and all help is appreciated!

AWS Quicksight if else with dates

I am trying to merge two date columns together with the ifelse function, my formula is

ifelse(RewardPaidDate = null,rewarddate, RewardPaidDate)

however it only returns the RewardPaidDate column and leaves the nulls in the new calculated field named RewardSentDate. I have tried changing it to

ifelse(RewardPaidDate = '',rewarddate, RewardPaidDate)

but I get the error message: "At least one of the arguments in this function does not have correct type. Correct the expression and choose Create again."

calculated column is RewardSentDate

Selenium Python If-else Statement

i have a little python script which presses some different buttons after 1 sec break (1,2,3 and 4) Everything is working fine but sometimes only Button 4 appears on that website and 1,2,3 not, and my script can't handle that Button 1,2 and 3 are missing :( I tried to make a if-else statement but its not working. I also tryed the try: and finally: solution. Maybe you have a tipp for me I would be very happy ^^


"Without if-else statement when every Button appears

                  "Button 1 appears
    wait.until(EC.element_to_be_clickable((By.XPATH, "//uni-view[@class='btn']"))).click()
    time.sleep(1) "Button 2 appears
    wait.until(EC.element_to_be_clickable((By.XPATH, "//uni-view[@class='btn']"))).click()
    time.sleep(1) "Button 3 appears
    wait.until(EC.element_to_be_clickable((By.XPATH, "//uni-view[@class='btn active']"))).click()
    time.sleep(1) "Button 4 appears
    wait.until(EC.element_to_be_clickable((By.XPATH,"/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-movable-area/uni-scroll-view/div/div/div/uni-view/uni-view[3]/uni-view[2]/uni-view/uni-view/img[2]"))).click()
    time.sleep(1) 

"With if-else statement when only Button 4 appears. If Button 1 appears, go to 2, 3, and 4. If Button 1 not appears just press Button 4 (so my idea ^^) But it doesn't get

    if driver.find_element_by_xpath("//uni-view[@class='btn']"):
        wait.until(EC.element_to_be_clickable((By.XPATH, "//uni-view[@class='btn']"))).click()
        time.sleep(1)
        wait.until(EC.element_to_be_clickable((By.XPATH, "//uni-view[@class='btn']"))).click()
        time.sleep(1)
        wait.until(EC.element_to_be_clickable((By.XPATH, "//uni-view[@class='btn active']"))).click()
        time.sleep(1)
        wait.until(EC.element_to_be_clickable((By.XPATH,"/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-movable-area/uni-scroll-view/div/div/div/uni-view/uni-view[3]/uni-view[2]/uni-view/uni-view/img[2]"))).click()
        time.sleep(1)
    else:
        wait.until(EC.element_to_be_clickable((By.XPATH,"/html/body/uni-app/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-movable-area/uni-scroll-view/div/div/div/uni-view/uni-view[3]/uni-view[2]/uni-view/uni-view/img[2]"))).click()
        time.sleep(1)

Python: I'm looking to append certain numbers to a list using for loop, but I don't understand why 1 works and the other solution doesnt [duplicate]

So I'm looking to iterate through this list [1,2,4,0,0,7,5] and only append the numbers 0 and 7 to make [0, 0, 7].

So below, I included my initial attempt which didn't work.

def spy_game(mylist):
    a = []
    for i in mylist:
        if i == 0 or 7:
            a.append(i)
        else:
            pass
    print(a)

Output: [1,2,4,0,0,7,5]

Below here is the working solution, I'm not sure why the solution below works as opposed to the one above. I'm looking for a explanation for dummies kind of thing, any and all help is appreciated thanks.

def spy_game(mylist):
    a = []
    for i in mylist: 
        if i == 0:    #Removed or 7
            a.append(i)
        elif i == 7:    #added elif statement
            a.append(i)
        else:
            pass
    print(a)

Output: [0,0,7]

Adding values in a list if the are the same, with a twist

I have a question (python) regarding adding of values if the are the same. So for example we have:

Lst1 = [A, A, B, A, C, D]
lst2 = [1, 2, 3, 4, 5, 6]

what I would like to know is how I can add the numbers in lst2 if the strings in lst1 are similar. the end result would thus be:

new_lst1 = [A, B, A, C, D]
new_lst2 = [3, 3, 4, 5, 6]

where

new_lst2[0] = 1+2

So values only get added when the are next to each other.

To make it more complicated, it should also be possible if we have this example:

lst3 = [A, A, A, B, B, A, A]
lst4 = [1, 2, 3, 4, 5, 6, 7]

of which the result has to be:

new_lst3 = [A, B, A]
new_lst4 = [6, 9, 13]

where new_lst4[0] = 1 + 2 + 3, new_lst4[1] = 4 + 5, and new_lst4[2] = 6 + 7.

Thank you in advance!

for a bit of background: I wrote a code that searches in Dutch online underground models and returns the data of the underground of a specific input location.

The data is made up of layers:
Layer1, Name: "BXz1", top_layer, bottom_layer, transitivity
Layer2, Name: "BXz2", top_layer, bottom_layer, transitivity
Layer3, Name: "KRz1", top_layer, bottom_layer, transitivity

etc..

BXz1 and BXz2 are the same main layer however different sublayers. In terms of transitivity I would like to combine them if they are next to each other. so in that way i would get:
Layer1+2, Name: BX, top_layer1, bottom_layer2, combined transitivity Layer3, Name: "KRz1", top_layer, bottom_layer, transitivity

Stopping a Javascript timer function from running multiple times after using an 'in viewport' function to call it?

Creating a website with a timer that counts up once the div is scrolled into view. The problem I'm having is that scrolling away starts the timer again, and I'd like the final value that the timer reaches to remain until the page is reloaded.

I've tried using 'event.handled' and '$.Callbacks("once")' but neither seem to work.

Any guidance would be appreciated - code below!

$(allInView);
$(window).scroll(allInView);

function isScrolledIntoView(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

  return elemBottom <= docViewBottom && elemTop >= docViewTop;
}

function allInView() {
  if (isScrolledIntoView($("#column4"))) {
    /// when 'column4' IS being 'viewed', the timers then begin

    jQuery(function ($) {
      $(".timer").countTo({
        from: 0,
        to: 183,
        speed: 1000,
        refreshInterval: 50,
        onComplete: function (value) {
          console.debug(this);
        },
      });
    });
  }
}

Compare string with slice output not working as expected

I have written one program which will execute if both the remote server reachable, otherwise it will terminate the execution. For that i written below login but it did not produce as expected. Below is code snippet.

 str := "false"
 Comd1 := fmt.Sprintf("ping -c 1 %s  > /dev/null && echo true || echo false", serIP)
 op, err := exec.Command( "/bin/sh", "-c", Comd1 ).Output()
 fmt.Println(string(op))
     if err != nil || str  == string(op) {
        fmt.Println(err)
        return
     }

Whenver server ip not rechable it is expected to enter in if loop and terminate the program but it always skip the condition and execute further which leads panic which is expected as remote server is not rechable.

Any suggestion in code to compare string with []byte output would be highly appreciable.

how to check the ip adress with a yaml file

I would like to check an ip-adress with a yaml-file. Unfortunately I got some syntax errors when trying to run following code:

script:
    - echo "Checking if PXI-Testsystem is running.."
    - |
      exit_code=0
      if [ ping -n 1 10.54.10.10 | grep -q "ms" ]; then
        echo "FOUND"
        exit_code=$?
      else 
        echo "NOT FOUND" 
        exit_code=$?       
      fi

I get this error:

+ if [ ping -n 1 10.54.10.10 | grep -q "ms" ]; then
+   ~
Missing '(' after 'if' in if statement.

What is wrong with the syntax here?

Thanks in advance

dimanche 28 novembre 2021

Why is my if statement working even though it's not supposed to be right? [closed]

I started doing a code some time ago but I got into this problem that I see that It's supposed to not be correct, but for some reason is working.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    ...
    string map1;
    string map2;
    ...
    bool free = true;
    cin >> map1;  
    cin >> map2;   
    int c = 0;
    for (size_t i = 0; i < map1.size(); i++) {
        cout << map1[c] << map2[c];             //starting characters of each string
        if (map1[c] != 0 && map1[c] != 1) {
            cout << free;
            free = false;
            cout << i;
            i = map1.size();
        }
        else if (0 != map2[c] && 1 != map2[0]) {
            cout << free;
            free = false;
            cout << i;
            i = map1.size();
        }
        c++;
    }
    ...
    return 0;
}

Function if/elif/loop giving error message [duplicate]

My code is in a loop, im getting syntax error on the if statement on the last block, the loop ends just before "Game Over":

computer = int(computer)

  if computer == 0:
    print(rock)
  elif computer == 1:
    print(paper)
  elif computer == 2:
    print(scissors)


  print(f"{result1}\n")
  print(f"Score:   Computador: {scorec}   Voce: {scorep}\n")


  if int(scorec) == 3:
    print("O computador ganhou o jogo!")
    replay = (input("Replay? 'Y' ou 'N'").upper()
  elif int(scorep) == 3:
    print("Voce ganhou o jogo!\n")
    replay = (input("Replay? 'Y' ou 'N'").upper()
      
print("Game Over!")

I messed a lot with indention and failed

error message:

> File "main.py", line 93
>     elif int(scorep) == 3:
>     ^ SyntaxError: invalid syntax

Why am I getting an invalid syntax error in this python code? [duplicate]

indexS = 0
indexE = 0
rNumS = 0
rNumE = 0

for i, row in dfPeople.iterrows():
    cityS = "null"
    stateS = "null"
    cityE = "null"
    stateE = "null"
    
    if (dfPeople.at[i,'CityP'] == 1):
        rNumS = dfSaferCities.iloc[indexS]['RelocationNumber']
        
        if (rNumS == 0):
            indexS += 1

        cityS = dfSaferCities.iloc[indexS]['Name']
        stateS = dfSaferCities.iloc[indexS]['State']
        dfPeople.at[i,'CityChosen'] = cityS
        dfPeople.at[i,'StateOfCityChosen'] = stateS
        rNumS -= 1
        
    if (dfPeople.at[i,'CityP'] == 2):
        rNumE = dfEconomicalCities.iloc[indexE['RelocationNumber']
        
        if (rNumE == 0):
            indexE += 1 

        cityE = dfEconomicalCities.iloc[indexE]['Name']
        stateE = dfEconomicalCities.iloc[indexE]['State']
        dfPeople.at[i,'CityChosen'] = cityE
        dfPeople.at[i,'StateOfCityChosen'] = stateE
        rNumE -= 1

I get an invalid syntax error on "if (rNumE == 0):" and I do not know why. It looks correct to me. I don't know what else to say. I really really do not know what else it could be.

ifelse, is.na and replace

I have a big data frame where I am trying to figure out with NA values

q3 times_30
Very easy 18/11/2021
Easy 01/01/2021
NA Not due
NA No answer
NA 01/02/2021

I am using

df$q3<-ifelse (is.na(df$q3), df$times_30,df$q3)

Where gives me

q3 times_30
Very easy 18/11/2021
Easy 01/01/2021
Not due Not due
No answer No answer
01/02/2021 01/02/2021

but I would like instead of replaced with the date at the NA of q3 to give me a "No answer", as the following

q3 times_30
Very easy 18/11/2021
Easy 01/01/2021
Not due Not due
No answer No answer
No answer 01/02/2021

I have a program that just does not work & I need to find the bug

my task is to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. When I run my program it does not repeatedly ask for number, it just does it one time without responding.

`

    try:
        float(num)
    except:
        "invalid input"

    if num > largest:
        largest = num
    
    if smallest == 0:
        smallest= num
    
    if smallest > num:
        smallest = num
    print(num)

`

if condition with differing behaviour depending on a pre-evaluation or not

While doing a leetcode problem, I encountered a strange problem with vectors in C++ : an if-statement went directly to else even if the evaluated expression was evaluated true. Using VS debugger, I verified that this expression was true and really didn't understand why it worked like that. After some tests, I figured out a way to make it work : by evaluating THE SAME expression right before the if-statement and storing it in another variable, the if-statement worked as intended. I disassembled my code with VS debugger and found that that particular if-statement wasn't evaluated at all : at the end of the evaluation, I have a jmp instruction to the else part. Comparing with two other similar if-statements, I noticed they both have "je" or "jns" instead of that simple "jmp". As I don't know which compiler does leetcode use, I can't say if it's specific to Visual C++ compiler.
Does someone know why it works like this ? I'd like to understand better what's happening and what is my mystake even if I solved the code. My comprehension of assembly and compilers isn't good enough for the moment to figure out by myself.

Here is a simple code comparing three similar if-statements. The second one is not working.

#include <iostream>
#include <vector>

int main()
{
    std::vector<int>digits = { 9,9,9 };
    int i = 3;
    if (-1 < 0) {
        int k = 0; 
    }

    if ((digits.size() - 1 - i) < 0) {
        int k = 0;
    }
    else {
        int j = 0;
    }

    int test = digits.size() - 1 - i;
    if (test < 0) {
        int k = 0;
    }
    else {
        int j = 0;
    }
    return 0;
}

Here is the interesting parts in the disassemble ; the "unconditional jmp" I talked about is the instruction 00B83E03.

int i = 3;
00B83DDE  mov         dword ptr [i],3  
    if (-1 < 0) {
00B83DE5  mov         eax,1  
00B83DEA  test        eax,eax  
00B83DEC  je          main+0A5h (0B83DF5h)  
        int k = 0; 
00B83DEE  mov         dword ptr [ebp-30h],0  
    }

    if ((digits.size() - 1 - i) < 0) {
00B83DF5  lea         ecx,[digits]  
00B83DF8  call        std::vector<int,std::allocator<int> >::size (0B81190h)  
00B83DFD  sub         eax,1  
00B83E00  sub         eax,dword ptr [i]  
00B83E03  jmp         main+0BEh (0B83E0Eh)  
        int k = 0;
00B83E05  mov         dword ptr [ebp-3Ch],0  
    }
00B83E0C  jmp         main+0C5h (0B83E15h)  
    else {
        int j = 0;
00B83E0E  mov         dword ptr [ebp-48h],0  
    }

    int test = digits.size() - 1 - i;
00B83E15  lea         ecx,[digits]  
00B83E18  call        std::vector<int,std::allocator<int> >::size (0B81190h)  
00B83E1D  sub         eax,1  
00B83E20  sub         eax,dword ptr [i]  
00B83E23  mov         dword ptr [test],eax  
    if (test < 0) {
00B83E26  jns         main+0E1h (0B83E31h)  
        int k = 0;
00B83E28  mov         dword ptr [ebp-60h],0  
    }
00B83E2F  jmp         main+0E8h (0B83E38h)  
    else {
        int j = 0;
00B83E31  mov         dword ptr [ebp-6Ch],0  
    }

Thank you in advance !

Passing data between functions from endless while loop

Been struggling to get this to work because I can't use return in a while loop that is not going to end.

In a nutshell, I'm receiving a message in a socket client in one function receive() (the endless loop) and need to pass the result of that incoming message to main(). Trying to use yield, since I'm not sure what else would achieve this. I created another function to try and capture the yield in the receive() function.

I know the initial message reaches the server because it outputs the message, and I know the client is receiving the server's confirmation message because it's printing it. I just am having no luck passing that data to main(), so the rest of the code won't work right.

I'm very new to this, so I'm probably doing this horribly wrong. I should be using classes to share data more easily, but don't grasp them enough yet. Hopefully using yield or something else can get around that.

receive function:

def receive():
    while True:
        try:
            incoming = client.recv(2048).decode(FORMAT)
            if 'RECEIVED' in incoming:
                confirmation = 'confirmed'
                yield confirmation
            print(incoming)
        except:
            print("Connection interrupted.")
            client.close()
            break

#------------
# also tried
#------------
def receive():
    while True:
        try:
            incoming = client.recv(2048).decode(FORMAT)
            if 'RECEIVED:COMPLETE' in incoming:
                confirmation = 'confirmed'
            else:
                confirmation = 'unconfirmed'
            yield confirmation
        except:
            print("Connection interrupted.")
            client.close()
            break

return function:

def pass_return(passed_return_value):
    passed_return_value

main function (with various tests)

def main():
    pass_return(receive())
    # Bunch of code
        if something == True:
            send("some message")
            time.sleep(.25)
            try:
                if confirmation == 'confirmed':
                    # do the business here

#------------
# also tried
#------------
def main():
    # Bunch of code
        if something == True:
            send("some message")
            time.sleep(.25)
            pass_return(receive())
            try:
                if confirmation == 'confirmed':
                    # do the business here

#------------
# also tried
#------------
def main():
    r = pass_return(receive())
    # Bunch of code
        if something == True:
            send("some message")
            time.sleep(.25)
            try:
                if r == 'confirmed':
                    # do the business here

#------------
# even tried
#------------
def main():
    # Bunch of code
        if something == True:
            send("some message")
            time.sleep(.25)
            r = pass_return(receive())
            try:
                if r == 'confirmed':
                    # do the business here

I'm declaring the variable confirmation OUTSIDE of main() and receive() (atop the file where my constants are) or else I get an error of confirmation is undefined.

If I print confirmation in main(), it either prints nothing or None, so my guess is that it's just getting the initial empty value of confirmation and not the yield.

# constants above here
confirmation = str()

# code and such
def pass_return(passed_return_value):
    passed_return_value
def receive():
    #code...
def main():
    #code...

if __name__ == '__main__':
    main()

Simple jQuery if else statement

I have a mini script, this script finds within a specific class the link. I basically need a simple if-else-statement. Something like if a is existing, then run the script if not, then do nothing.

Can someone help me with that?

jQuery(document).ready(function() {
  jQuery("body").on("click", ".click-child", function() {
      var href = jQuery(this).find("a").attr('href');
      window.location = href;
  });
});

Conditional statement limiting the number of displayed elements

I'm having trouble implementing the logic that will limit me from adding the same items to my shopping list. When the item is the same, I just want to display the quantity with the existing item.

    <div class="pizzas">
    </div>
    <div class="shoppingCart">
        <p class="totalPrice">Hungry? order our pizzas</p>
    </div>

// js

fetch("https://raw.githubusercontent.com/alexsimkovich/patronage/main/api/data.json")
.then(data => data.json())
.then(data => {
let valueCurrency = 0;
data.forEach(element => {
    const shoppingCart = document.querySelector(".shoppingCart");
    const pizzas = document.querySelector(".pizzas");
    const box = document.createElement("div");
    const img = document.createElement("img");
    const title = document.createElement("h3");
    const ingredients = document.createElement("p");
    const price = document.createElement("h4");
    const btn = document.createElement("button");
    const totalPrice = document.querySelector(".totalPrice");
     
    box.className = "box";
    ingredients.className = "ingredients"
    btn.className = "btn";
    img.src = element.image;
    img.className = "img";
     
    title.innerHTML = element.title;
    ingredients.innerHTML = element.ingredients;
    price.innerHTML = element.price.toFixed(2) + " zł";
    btn.innerHTML = "Dodaj do koszyka";
     
    box.appendChild(img);
    box.appendChild(title);
    box.appendChild(ingredients);
    box.appendChild(price);
    box.appendChild(btn);
    pizzas.appendChild(box);


    btn.addEventListener("click", (e) => {
        valueCurrency = valueCurrency + element.price;

        const pizza = document.createElement("div");
        pizza.className = "pizzaList";
        const pizzasList = document.createElement("li");
        const pizzaPrice = document.createElement("p");
        const btnRemove = document.createElement("button");
        btnRemove.innerText = "X";
         
        pizzasList.innerText = title.textContent;
        pizzaPrice.innerText = price.textContent;

        pizza.appendChild(pizzasList);
        pizza.appendChild(pizzaPrice);
        pizza.appendChild(btnRemove);

        totalPrice.innerText = "Całkowita cena: " + valueCurrency.toFixed(2);

        if(pizzasList.innerText === pizzasList.innerText)
        {
            // don't add another item to the list
            // just add +1 to existing element
        }
        else
        {
            // add an item to the list
            shoppingCart.prepend(pizza);

        }

        btnRemove.addEventListener("click", (e) => {
            pizza.remove();
            valueCurrency = valueCurrency - element.price;
            totalPrice.innerText = "Całkowita cena: " + valueCurrency.toFixed(2);
        })
    })

});
 
})
.catch(err => console.log(err));

My problem is exactly in the conditional statement, I don't know exactly how to implement the counting of the same pizzas option.

Thank you in advance for your help.

How do i change the foreground color of a console in c# with a if statement

I want to change the color of the text in a c# console to blue if a person says their favorite color is blue.

using System;

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

        Console.Title = ("Favorite Color");
       

        Console.WriteLine("What is your favorite color?");

        string favoriteColor = (Console.ReadLine());

        if (favoriteColor == "Blue")
        {
            Console.ForegroundColor = ConsoleColor.Blue;
        }
    
        Console.ReadKey();
    }

}

}

Why I am getting undefined on web page?

I am trying to display user status in the Gantt chart. But it returns undefined.

In this picture it is returning undefined and something else

.

I am using this method to return output

 var stat = groups.push(document.getElementsByClassName('status')); 
 var st = document.write(stat);

But it shows undefined and some server data instead of displaying 'Active' or 'Pause'

function userStatus(online) {
  const element = document.querySelector('.status');
  if (online) {
    element.classList.remove('offline');
    element.classList.add('online');
    element.innerText = 'Activ';
  } else {
    element.classList.remove('online');
    element.classList.add('offline');
    element.innerText = 'Pause';
  }
}
window.addEventListener('load', () => {
  userStatus(navigator.onLine);
  window.addEventListener('online', () => {
    userStatus(true);
  });
  window.addEventListener('offline', () => {
    userStatus(false);
  });
});
.app {
  height: 4.7vh;
  width: 4.7vw;
  display: flex;
  align-items: center;
  background-color: #000000;
  margin-left: 0.4px;
}

.status {
  margin-left: 10px;
  font-size: 15px;
  width: 2.5%;
}

.status.online {
  color: #41a700;
}

.status.offline {
  color: #f15c4f;
}

.app {
  margin-left: 261px;
}

.app {
  position: relative;
  margin-bottom: 5%;
}
<div class="app">
  <h5 class="status">User Status</h5>
</div>

Can't figure out the for loop logic

I am trying to write a code where the user submits a wiki search. If the query is in the given list of entries, the user should be redirected to related entry's page. If the query doesn't match the name of an entry but is a substring of any entry, the user should be taken to a page that lists the related entries. My problem is that I couldn't figure out how to logically implement return statements.

The code below works fine:

def search(request):
    sub_list = []
    entries = util.list_entries()
    search = request.GET.get("q")

    for entry in entries:
        if search.lower() == entry.lower():
            return redirect("entry", title= search)
        elif search.lower() in entry.lower():
            sub_list.append(entry)
    return render(request, "encyclopedia/search.html",{
        "title":search,
        "sub_list":sub_list
    })

But when I try to add another condition for the case where the query doesn't match the name of an entry, either it always returns "Not Found":

    for entry in entries:
        if search.lower() == entry.lower():
            return redirect("entry", title= search)
        else:
            if search.lower() in entry.lower():
                sub_list.append(entry)
                return render(request, "encyclopedia/search.html",{
                    "title":search,
                    "sub_list":sub_list
                })
        return HttpResponse("Not Found")

or returns only the first substring match:

    for entry in entries:
        if search.lower() == entry.lower():
            return redirect("entry", title= search)
        else:
            if search.lower() in entry.lower():
                sub_list.append(entry)
                return render(request, "encyclopedia/search.html",{
                    "title":search,
                    "sub_list":sub_list
                })
    return HttpResponse("Not Found")

error in outer indentation level for IoT device Distance sensor

we are student from college doing our project which is inter and outer counter that count the student who inter the room and leave it and theres problem in line 30 says theres outer indentation and also theres trackback error, so we have two sensor ( sensor1 , sensor2) when sensor1 calculate the distance then sensor2 it means the person is entering and the opposite , also we don't have any idea about indentation

samedi 27 novembre 2021

Radius expansion over time does not effect actual sphere collider

So I'm trying to increase the radius of the sphere collider based on how long the player holds the mouse button down. I've tried a few different things like moving the yield return wait for seconds .1f above the small equations as well as moving some of the if statements around. If something doesn't make sense please ask. This is not the entire script

    private bool IsCasting = false;

    private float CastSpeed = StatBase.CastSpeed; // this = 1
    private float TimeSpentCasting = 0;
    private float spellCooldown = 1f; // to let animation play out

    public SphereCollider col;

    public float MaxAOERange = StatBase.AreaOfEffect + (StatBase.AreaOfEffect * (FinalStatValues.finalIncreaseAreaOfEffect / 100));

    public float AOERangePotential = 0;

    public float ExpansionSpeed = 1;

void Start()
{
        col = GetComponentInParent<SphereCollider>();
        col.radius = 0;
}



    IEnumerator SpellCastPowerBuild()
    {
        while (Input.GetMouseButtonDown(0) && IsCasting == true && TimeSpentCasting < 
        CastSpeed)

        {
            AOERangePotential += MaxAOERange / 10;
            TimeSpentCasting += CastSpeed / 10;

            if(TimeSpentCasting >= CastSpeed)
            {
                AOERangePotential = MaxAOERange;
            }

            yield return new WaitForSeconds(.1f);
        }

        if (IsCasting == false)
        {
            PerformCast();
            yield break;
        }
    }


    private void Update()
    {
        if (Input.GetMouseButtonDown(0) && spellCooldown == 0) // SpellCooldown is set to 0
        {                                                          for testing
            IsCasting = true;
            SpellCastPowerBuild();
        }
    }


    void PerformCast()
    {
        col.radius = AOERangePotential * ExpansionSpeed * Time.deltaTime;

        AOERangePotential = 0;
        TimeSpentCasting = 0;

        IsCasting = false;
    }

Matplotlib animation patch not redrawing patch

I'm trying to run a matplotlib.pyplot simulation which creates a figure in a 10x10 grid with a large circular outline of radius 10 (the container). Inside this container, a ball (and later multiple balls) is drawn, with its position given in initialisation. Then, when I run a method, next_collision(), it will apply other methods, and calculate a new position for the ball. The patch should then be redrawn at this new position.

class Simulation():
    def __init__(self, container = Container()):
        self._container = container
        self._balls = [Ball(np.array([i+1, i+1]), np.random.normal(0, 5, 2)) for i in range(num_particles)]
        print(self._balls)

                
    def next_collision(self):
        for i in range(0, num_particles):
            self.oldpos = self._balls[i].pos.copy()
            self.oldvel = self._balls[i].vel.copy()
            t = self._balls[i].time_to_collision(self._container)
            self._balls[i].pos = self._balls[i].move(t)
            self._balls[i].vel = self._balls[i].collide(self._container)

    def run(self, num_frames, animate=False):
        if animate == True:
            f = pl.figure()
            ax = pl.axes(xlim=(-10, 10), ylim=(-10, 10))
        for i in range(0, num_particles):
            for frame in range(num_frames):
                self.next_collision()
                if animate == True:
                    ax.add_artist(self._container.get_patch())
                    ax.add_patch(self._balls[i].get_patch())
                    pl.pause(0.1)
                    self._balls[i].patch.center = self._balls[i].pos
                    pl.pause(0.1)
                    pl.show()
        
sim = Simulation(con)        

the get_patch() methods in the final if statement is from two earlier classes, Ball and Container (respectively), as follows:

    def get_patch(self):
        self.patch = pl.Circle(self.oldpos, 1, fc = 'r')
        ax = pl.axes(xlim=(-10, 10), ylim=(-10, 10))
        ax.add_patch(self.patch)
        return self.patch
        #pl.pause(1) 
        #self.patch.center = [self.pos[0], self.pos[1]]
        #print('new patch center', self.patch.center)
        #pl.pause(1)
        #pl.show()

#rest of ball class code
#starts container class

    def get_patch(self):
        return pl.Circle([0., 0.], 10, ec='b', fill=False, ls='solid')

when I run the simulation object in the console, sim as follows:

 sim.run(2, True)

it should perform the next_collision() method twice (num_frames determines how many times next collision should be run), and so it should show the patch appearing in its first position, then appearing in its next position, then appearing in its next position. However instead of removing the old patch, and drawing the new patch, it instead keeps the old patches, whilst drawing a new patch in the new position, e.g:

enter image description here

which is not what I am looking for. I have noticed that if I do

sim.run(1, True)

i.e. doing one collision at a time and closing the pop up window that has the figure on it after each collision, it does update the patch position without having the old position also on the figure.

As a slight aside, and this is not as important, is there any way to make my animation more smoother, rather than just having a patch disappear from its old position and appearing at its new position without any motion of the ball between the positions?

Thanks

Why am I getting a value error in excel while using the ifs function?

=IFS(SEARCH("C*",A9),"Cake",SEARCH("K*",A9),"Cookies",SEARCH("B*",A9),"Bread & Bun",SEARCH("Y*",A9),"Pastry")

It works for the first criteria and returns "cake" but won't work for the others. I keep getting a #VALUE error. Can help please??

I think my if statement is returning as false and i am not sure why [duplicate]

My code is returning all the letters with a counter of zero. I am not sure why this problem is occurring.

public class LetterFrequencies {

    public static void main(String[] args) {

        String letters = "abcdefghijklmnopqrstuvwxyz";
        String phrase = "This is a phrase!";

        System.out.println("The following shows the letter frequencies for the phrase");

        /* your code here */
        int counter = 0;
        for (int i = 0; i <= 25; i++) {
            for (int j = 0; j <= 16; j++) {
                if (letters.substring(i, i + 1) == phrase.substring(j, j + 1)) {
                    counter++;
                }
            }
            System.out.println(letters.substring(i, i + 1) + counter);
        }
    }
}

Python: How can I reduce the number of 'if' statements down to a reasonable amount for my game?

Im making a chess game in python and was trying to generate the legal moves of each piece using 'if' statements to see if the space the player wants to move to is free and if the move is actually within the borders of the board. The problem is that there are too many 'if' statements as well as nested 'if' statements. This really makes my file look like spaghetti code and over-complicates the process.

Here is an example:

def valid_moves(self, board):
    i = self.row
    j = self.col

    moves = []

    if i > 0:
        # TOP LEFT
        if j > 0:
            p = board[i - 1][j - 1]
            if p == 0: # checks if space empty
                moves.append((j - 1, i - 1,))
            elif p.color != self.color:
                moves.append((j - 1, i - 1,))

        # TOP MIDDLE
        p = board[i - 1][j]
        if p == 0: # checks if space empty
            moves.append((j, i - 1))
        elif p.color != self.color:
            moves.append((j, i - 1))

        # TOP RIGHT
        if j < 7:
            p = board[i - 1][j + 1]
            if p == 0: # checks if space empty
                moves.append((j + 1, i - 1,))
            elif p.color != self.color:
                moves.append((j + 1, i - 1,))

    if i < 7:
        # BOTTOM LEFT
        if j > 0:
            p = board[i + 1][j - 1]
            if p == 0: # checks if space empty
                moves.append((j - 1, i + 1,))
            elif p.color != self.color:
                moves.append((j - 1, i + 1,))

        # BOTTOM MIDDLE
        p = board[i + 1][j]
        if p == 0: # checks if space empty
            moves.append((j, i + 1))
        elif p.color != self.color:
            moves.append((j, i + 1))

        # BOTTOM RIGHT
        if j < 7:
            p = board[i + 1][j + 1]
            if p == 0: # checks if space empty
                moves.append((j + 1, i + 1))
            elif p.color != self.color:
                moves.append((j + 1, i + 1))

    # MIDDLE LEFT
    if j > 0:
        p = board[i][j - 1]
        if p == 0: # checks if space empty
            moves.append((j - 1, i))
        elif p.color != self.color:
            moves.append((j - 1, i))

    # MIDDLE RIGHT
    if j < 7:
        p = board[i][j + 1]
        if p == 0: # checks if space empty
            moves.append((j + 1, i))
        elif p.color != self.color:
            moves.append((j + 1, i))

    return moves

This example is for just 1 piece out of 6 and so there is a lot of occurring 'if' statements. How can I refractor this to where I don't need to use as many 'if' statements?

Program won't perform this if-branch [closed]

The objective of this program is to be able to change any of the following values using user input: department ID, course number, section, credits, instructor, days, time, max class enrollment, students and student IDs of said students enrolled, and registration status. You should be able to change any of those values and be able to print it all out in the end. Here is the part of my code with the issue:

cout << "Please input \"c\" if you want to make any changes." << endl;
    cin >> makeChanges;

    if (makeChanges == 'c') {
        cout << "Please input which change you would like to make: " << endl;
        cout << "Department ID" << endl;
        cout << "Course Number" << endl;
        cout << "Section" << endl;
        cout << "Credits" << endl;
        cout << "Instructor" << endl;
        cout << "Day(s)" << endl;
        cout << "Time" << endl;
        cout << "Campus" << endl;
        cout << "Building" << endl;
        cout << "Room Number" << endl;
        cout << "Max Class Enrollment" << endl;
        cout << "Students" << endl;
        cout << "Student IDs" << endl;
        cout << "Registration Status" << endl;
    }
    else {
        courseInfo.printInfo();
    }

    getline(cin, changeType);

    if (changeType == "Department ID") {
        cout << "Please input the department ID." << endl;
        getline(cin, department);
        courseInfo.setCourseID(department);
    }

    else if (changeType == "Course Number") {
        cout << "Please input the course number." << endl;
        cin >> classNum;
        courseInfo.setCourseNum(classNum);
    }

    else if (changeType == "Section") {
        cout << "Please input the section number." << endl;
        cin >> section;
        courseInfo.setSectNum(section);
    }

    else if (changeType == "Credits") {
        cout << "Please input the number of credits." << endl;
        cin >> credits;
        courseInfo.setNumCreds(credits);
    }

    else if (changeType == "Instructor") {
        cout << "Please input the instructor." << endl;
        getline(cin, professor);
        courseInfo.setInstructName(professor);
    }

    else if (changeType == "Day(s)") {
        cout << "Please input the day(s): M, T, W, Th, or F." << endl;
        getline(cin, days);
        courseInfo.setDays(days);
    }

    else if (changeType == "Time") {
        cout << "Please input the hour of the start time." << endl;
        cin >> hour1;
        courseInfo.setCourseHour1(hour1);

        cout << "Next please input the minutes of the start time (If it is 0, then put in 00)." << endl;
        cin >> min1;
        courseInfo.setCourseMinute1(min1);

        cout << "Please input the hour of the end time." << endl;
        cin >> hour2;
        courseInfo.setCourseHour2(hour2);

        cout << "Next please input the minutes of the end time (If it is 0, then put 00)." << endl;
        cin >> min2;
        courseInfo.setCourseMinute2(min2);
    }
    
    else if (changeType == "Campus") {
        cout << "Please input the campus your course is held on." << endl;
        getline(cin, campus);
        courseInfo.setCampus(campus);
    }

    else if (changeType == "Building") {
        cout << "Please input the building your course is held in." << endl;
        cin >> building;
        courseInfo.setClassroomBuilding(building);
    }

    else if (changeType == "Room Number") {
        cout << "Please input the classroom number." << endl;
        cin >> roomNum;
        courseInfo.setClassroomNum(roomNum);
    }

    else if (changeType == "Max Class Enrollment") {   
        cout << "Please input maximum students in the course." << endl;
        cin >> maxClass;
        courseInfo.setMaxEnroll(maxClass);
    }

    else if (changeType == "Students") {
        cout << "Please input the number of students enrolled." << endl;
        cin >> numStuds;
        courseInfo.setNumStuds(numStuds);
    }

    else if (changeType == "Student IDs") {
        cout << "Please input the IDs of each student enrolled." << endl;
        courseInfo.inputStudIDs(numStuds);
    }

    else if (changeType == "Registration Status") {
        cout << "Please input the registration status: \"o\" for open, \"c\" for close, or \"x\" for cancelled." << endl;
        cin >> status;
        courseInfo.setCourseStat(status);
    }
    courseInfo.printInfo();

When testing this by attempting to change any value that is more than one word (like Department ID), the program just outputs all of the initial values without following through with the if-branch and actually changing the value. However, this is not an issue for one-word values (like Section). What can I do to fix this error?

Edit: I already included directives and functions and their respective definitions, but they are too long to put here. It still compiles, but it just doesn't follow through with the if-branch.

Edit: Here are the functions and function definitions:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class UMDearborn {
    public:
        UMDearborn();
        void setCourseNum(int courseNum);
        
        void setCourseID(string courseID);
        
        void setSectNum(int sectNum);
        
        void setNumCreds(int numCreds);
        
        void setDays(string courseDays);
        
        void setCourseHour1(int hour1);
        
        void setCourseMinute1(int min1);

        void setCourseHour2(int hour2);
        
        void setCourseMinute2(int min2);

        void setClassroomBuilding(string buildingID);
        
        void setClassroomNum(int roomNum);
        
        void setMaxEnroll(int maxNum);
        
        void setCampus(string campusName);
        
        void setInstructName(string profName);
        
        void setNumStuds(int numStuds);
        
        void inputStudIDs(int numStuds);
        void setStudIDs(int studID);
        int getStudIDs() const;
        void printStudIDs();

        void setCourseStat(char courseStat);

        void printInfo();
    private:
        int classNum;
        string department;
        int section;
        int credits;
        string days;
        int courseHr1;
        string courseMin1;
        int courseHr2;
        string courseMin2;
        string building;
        int locationNum;
        int maximum;
        string campus;
        string professor;
        int students;
        int id;
        char status;
        vector<UMDearborn> idNums;
};

UMDearborn::UMDearborn() {
    classNum = 150;
    department = "CIS";
    section = 4;
    credits = 4;
    days = "M, W";
    courseHr1 = 2;
    courseMin1 = "00";
    courseHr2 = 3;
    courseMin2 = "15";
    building = "SSB";
    locationNum = 2195;
    maximum = 60;
    campus = "Dearborn";
    professor = "Unknown";
    students = -1;
    id = 10101010;
    status = 'n';
}

void UMDearborn::setCourseNum(int courseNum) {
    classNum = courseNum;
}

void UMDearborn::setCourseID(string courseID) {
    department = courseID;
}

void UMDearborn::setSectNum(int sectNum) {
    section = sectNum;
}

void UMDearborn::setNumCreds(int numCreds) {
    credits = numCreds;
}

void UMDearborn::setDays(string courseDays) {
    days = courseDays;
}

void UMDearborn::setCourseHour1(int hour1) {
    courseHr1 = hour1;
}

void UMDearborn::setCourseMinute1(int min1) {
    courseMin1 = min1;
}

void UMDearborn::setCourseHour2(int hour2) {
    courseHr2 = hour2;
}

void UMDearborn::setCourseMinute2(int min2) {
    courseMin2 = min2;
}

void UMDearborn::setClassroomBuilding(string buildingID) {
    building = buildingID;
}

void UMDearborn::setClassroomNum(int roomNum) {
    locationNum = roomNum;
}

void UMDearborn::setMaxEnroll(int maxNum) {
    maximum = maxNum;
}

void UMDearborn::setCampus(string campusName) {
    campus = campusName;
}

void UMDearborn::setInstructName(string profName) {
    professor = profName;
}

void UMDearborn::setNumStuds(int numStuds) {
    students = numStuds;
}

void UMDearborn::setStudIDs(int studID) {
    id = studID;
}

void UMDearborn::setCourseStat(char courseStat) {
    status = courseStat;
}

void UMDearborn::inputStudIDs(int numStuds) {
    UMDearborn currID;
    int i;
    int id;

    for (i = 0; i < idNums.size(); ++i) {
        cout << "ID: ";
        cin >> id;
        currID.setStudIDs(id);
        idNums.push_back(currID);
    }

}

void UMDearborn::printStudIDs() {
    UMDearborn currID;
    
    for (int i = 0; i < (idNums.size() - 1); ++i) {
        currID = idNums.at(i);
        cout << currID.getStudIDs() << ", ";
    }

    currID = idNums.back();
    cout << currID.getStudIDs();
}

void UMDearborn::printInfo() {
    UMDearborn courseInfo;
    cout << "Department ID: " << department << endl;
    cout << "Course Number: " << classNum << endl;
    cout << "Section: " << section << endl;
    cout << "Credits: " << credits << endl;
    cout << "Instructor: " << professor << endl;
    cout << "Day(s): " << days << endl;
    cout << "Time: " << courseHr1 << ':' << courseMin1 << " - " << courseHr2 << ':' << courseMin2 << endl;
    cout << "Campus: " << campus << endl;
    cout << "Building ID: " << building << endl;
    cout << "Room Number: " << locationNum << endl;
    cout << "Max Class Enrollment: " << maximum << endl;
    cout << "Students: " << students << endl;
    cout << "Student IDs: " << courseInfo.printStudIDs() << endl; // Get back to later
    cout << "Status: " << status << endl;
}