lundi 31 août 2020

UIPath. Vb.net? if condition

Im new to uipath and coding in general. I know most of the basics from what was taught but they didnt go through how to form "condition" statements in the "if" activity. or basically any form of conditions. Where can i go about to learning them? is it a specific language?

kinda like: not Months.Contains(ExpenseMonth)

i wouldnt be able to come up with that because i dont know what is acceptable/readable to uipath studio

also regarding those calculations. where can i find more information on those? to learn more about

kinda like: (int32.Parse(row("Value").ToString) * 100 / monthlyTotal).ToString

they didnt really give me details on how to form that

so essentially, if i wasnt spoon fed with those statements, i would be stuck

Can I disregard certain code when certain input is given?

I am building a basic calculator on python to get to know the basics of programming and what not. Basically my issue is that when I am squaring a number with my calculator it will still ask for my second number, while it spits out the correct answer still I would like it to not ask for my second number when the square function is used.

name = input("Enter your name: ")
lastname = input("Enter your last name: ")
print("Welome " + name + " " + lastname + "!")
num1 = float(input("Enter a number to calculate: "))
Component = input("*, /, +, -...?????: ")
num2 = float(input("Enter your last number...: "))
if Component == "*":
    print(num1 * num2)
if Component == "+":
    print(num1 + num2)
if Component == "/":
    print(num1 / num2)
if Component == "-":
    print(num1 - num2)
if Component == "sqr":
    print(num1 ** 2)
    

The value to be entered via if is undefined

test.js

const PatientInfoModal = ({ visible, onCancel, onEditPatient, 
                            setVisible, editid, editname, editgender, 
                            editage, editbirth_date, editkey }) =>{

....

    function onOk(values) {
    const { patient } = values;
    const { id, name, gender, age, birth, editkey } = patient;
    onEditPatient({ name, gender, age, birth_date, editkey });
    if (id == '' ) {
        onEditPatient({id: 'flase'})
    } else if (id !== '') {
        onEditPatient({id: 'true'})
    }
}

When using an if statement, I want to enter'false' if the id value is undefined, and'true' if defined.

However, in all cases the undefined value appears.

It seems that the id value is not defined. How can I put'flase' and'true' in the id value?

It seems that the pid of the if statement cannot read the value of const {pid}. Let me know if you know how

Why is my python function not being executed even if there's no error? [closed]

I'm fairly new to python and I'm trying to create a Season Checker. So far I only have spring, but when I run the code, nothing executes. Am I missing something?

def season_checker(month, day):
    spring = 'March', 'April', 'May', 'June'
    
    if (month == 'March' and 20 >= day >= 31):
        spring = str(month), day, 'is a spring day'
    elif (month == 'April' and 1 >= day >= 30):
        spring = str(month), day, 'is a spring day'
    elif (month == 'May' and 1 <= day <= 31):
        spring = str(month), day, 'is a spring day'
    elif (month == 'June' and 1 >= day >= 20):
        spring = str(month), day, 'is a spring day'
    else:
        spring = str(month), day, 'is an unreconized month and day'

    return spring

   
def main():
    user_month = input("Enter month: ")
    month = user_month.lower()
    user_day = int(input("Enter day: "))
    season = season_checker(user_month, user_day)

main()

how to handle error in cauchy calculation in numpy

i want to calculate the Cauchy matrix with entries a_ij = 1/(x_i-y_j) for two vectors and using numpy

Example:
([1, 2], [3, 4]) --> [[-1/2, -1/3], [-1, -1/2]]

import numpy as np
    
    if len(y) != len(x) :
        raise ValueError ('len(x) and len(y) must be equal')
    else : 
        for i in range (len(x)) :
            for j in range (len(y)):
                if x[i] == y[j] :
                    raise ValueError('error')
                
                else : 
                    cauchym = 1.0/np.array([(x_i-y_j) for x_i in x for y_j in y]).reshape([len(x),len(y)])
                    return cauchym

My code seems to be working with regular input. However i get a few errors with input shown below and I don't know how to get around those

  1. array from difference length :

x = np.array([1, 2]) y = np.array([1.5, 2.5, 3.5, 5.0])

Error message : intro_numpy.py", line 82, in cauchy raise ValueError ('len(x) and len(y) must be equal') ValueError: len(x) and len(y) must be equal

  1. empty list : x = np.array([]) y = np.array([])** *Error message : Your result was in the wrong type:
  • You returned type: NoneType
  • Expected type: ndarray (from numpy)*
  1. 0 array :

x = np.array([0, 1, 2, 3, 4]) y = np.array([4, 3, 8, 1, 0])

error message : ValueError not raised* i don't understand why i need to raise a specific error for this one ? and if so which one

Thanks in advance for your suggestions , comments and advice

Issues with authorisation

I am trying to create an authorisation system, the user must enter their name and it checks an external notepad document for their name. When I enter the correct name it believes it is unauthorised, please can you help. This is the code.

Can I apply vectorization here? Or should I think about this differently?

To put it simply, I have rows of activity that happen in a given month of the year. I want to append additional rows of inactivity in between this activity, while resetting the month values into a sequence. For example, if I have months 2, 5, 7, I need to map these to 1, 4, 7, while my inactive months happen in 2, 3, 5, and 6. So, I would have to add four rows with this inactivity. I've done this with dictionaries and for-loops, but I know this is not efficient, especially when I move this to thousands of rows of data to process. Any suggestions on how to optimize this? Do I need to think about the data format differently? I've had a suggestion to make lists and then move that to the dataframe at the end, but I don't see a huge gain there. I don't know enough of NumPy to figure out how to do this with vectorization since that's super fast and it would be awesome to learn something new. Below is my code with the steps I took:

df = pd.DataFrame({'col1': ['A','A', 'B','B','B','C','C'], 'col2': ['X','Y','X','Y','Z','Y','Y'], 'col3': [1, 8, 2, 5, 7, 6, 7]})

Output:

  col1 col2  col3
0    A    X     1
1    A    Y     8
2    B    X     2
3    B    Y     5
4    B    Z     7
5    C    Y     6
6    C    Y     7

I'm creating a dictionary to handle this in for loops:

df1 = df.groupby('col1')['col3'].apply(list).to_dict()
df2 = df.groupby('col1')['col2'].apply(list).to_dict()
max_num = max(df.col3)

Output:

{'A': [1, 8], 'B': [2, 5, 7], 'C': [6, 7]}
{'A': ['X', 'Y'], 'B': ['X', 'Y', 'Z'], 'C': ['Y', 'Y']}
8

And now I'm adding those rows using my dictionaries by creating a new data frame:

df_new = pd.DataFrame({'col1': [], 'col2': [], 'col3': []})
for key in df1.keys():
    k = 1
    if list(df1[key])[-1] - list(df1[key])[0] + 1 < max_num:
        for i in list(range(list(df1[key])[0], list(df1[key])[-1] + 1, 1)):
            if i in df1[key]:
                df_new = df_new.append({'col1': key, 'col2': list(df2[key])[list(df1[key]).index(i)],'col3': str(k)}, ignore_index=True)
            else:
                df_new = df_new.append({'col1': key, 'col2': 'N' ,'col3': str(k)}, ignore_index=True)
            k += 1
        df_new = df_new.append({'col1': key, 'col2': 'E', 'col3': str(k)}, ignore_index=True)
    else:
        for i in list(range(list(df1[key])[0], list(df1[key])[-1] + 1, 1)):
            if i in df1[key]:
                df_new = df_new.append({'col1': key, 'col2': list(df2[key])[list(df1[key]).index(i)],'col3': str(k)}, ignore_index=True)
            else:
                df_new = df_new.append({'col1': key, 'col2': 'N' ,'col3': str(k)}, ignore_index=True)
            k += 1

Output:

   col1 col2 col3
0     A    X    1
1     A    N    2
2     A    N    3
3     A    N    4
4     A    N    5
5     A    N    6
6     A    N    7
7     A    Y    8
8     B    X    1
9     B    N    2
10    B    N    3
11    B    Y    4
12    B    N    5
13    B    Z    6
14    B    E    7
15    C    Y    1
16    C    Y    2
17    C    E    3

And then I pivot to the form I want it:

df_pivot = df_new.pivot(index='col1', columns='col3', values='col2')

Output:

col3    1   2   3   4   5   6   7   8
col1                                
A   X   N   N   N   N   N   N   Y
B   X   N   N   Y   N   Z   E   NaN
C   Y   Y   E   NaN NaN NaN NaN NaN

Thanks for the help.

Is it ME Or Flutter who is wrong?

hello everyone this thing is driving me crazy i have a button on click it will check a simple condition but the problem is it always gives the opposite result !!

          onPressed: () {
            if(1 == 1){
              return applyDiscount(context);
            }
            return _selectClient(context);
          },

1 is definitely = to 1 but the thing is this condition returns _selectClient method !! even if you print the identifier it will return true ,what the hell is going on ?

i tried many other identifiers and all of them gives back false results

If (no else)-sentences with substring in R

I have a df, I would like to substring the first letters for all columns in the screen_name column, except for the cell with the name 'frank'. All my attempts are ignored by R (substring is executed on all cells). Why?


df <- data.frame("screen_name" = c("august", "berit", "christopher", "david", "erica", "frank"), "rt_name" = c("berit", "august", "david", "erica", "frank", "christopher"))

#IF-sentence with '%!like%' 
'%!like%' <- function(x,y)!('%like%'(x,y))
df$screen_name<- if(df$screen_name %!like% ('frank')) {substr(df$screen_name, 1, 2)}

#IF-sentence with !=
df$screen_name<- if(df$screen_name != 'frank') {substr(df$screen_name, 1, 2)}

I am looking for solution that include %!like% or similar as the names in the df can vary and I am not always having an exact match.

Thanks in advance!

Creating a new List out of a List but without dublicate items?

i have a List

carner_list = ['<a href="/lyric/34808442/Loyle+Carner/Damselfly">Damselfly</a>',
 '<a href="/lyric/37311114/Loyle+Carner/Damselfly">Damselfly</a>',
 '<a href="/lyric/37360958/Loyle+Carner/Damselfly">Damselfly</a>',
 '<a href="/lyric/33661937/Loyle+Carner/The+Isle+of+Arran">The Isle of Arran</a>',
 '<a href="/lyric/33661936/Loyle+Carner/Mean+It+in+the+Morning">Mean It in the Morning</a>']

Now i want to get rid of the dublicated items. The Problem is, the items that are double are only different from each other at a specific point in the string, i[38:].

My idea was to create a for loop:

new_list = []
for i in carner_list:
       if i[38:] in new_list:
           print("found")
       else:
           new_list = new_list + [i]
           print("not")

But this is not working.

Is something in the syntax wrong or am i completely on the wrong track?

Best Russell

How can i take user input and save it permanently in a variable and use that variable in window.open()

I am trying to use javascript to take a url entered in a text box and permanently change a variable. I then want to use that variable in an if statement with window.open() if the condition is true. The code will be a file saved on their computer that they open in chrome. Any ideas?

how to create new column in pandas with if statement?

here I have a dataframe in pandas: df = pd.DataFrame(df), and saved as csv file. I am beginner in python and don't know how to deal with

pandas

as csv file

I want to add a new column in specific two conditions / type 'buy'

1. df['cross'] == up
and
2. df['low'] <= df['mi48change'] # if any value of the last 10 values from df['low'] is less than any 
value of the last 10 values from df['mi48change']
otherwise type 'ok'

for condition 2, in the 2nd attached photo, this happened 3 times (red squares), 3 times that the value of df['low'] is less than df['mi48change'] in the last 10 values, before df['cross'] == up, so new column will type 'buy'.

may be it should be as a function to create this new column?

What is a good way of making usernames case insensitive in Python? (Beginner Level)

I'm still a programming student so this might be very easy for you to answer.

I'm writing some code from the book 'Python Crash Course'. The task I'm on has me 'Make sure my comparison is case insensitive. If 'John' has been used, 'JOHN' should not be accepted. To do this you need to make a copy of current_users containing the lowercase versions of all existing users.'

Which in my code I have. Except it doesn't work.

current_users = ['ted', 'jed', 'red', 'ned', 'dr fred']

new_users = ['ted', 'jed', 'bernard', 'hoagie', 'laverne']

for username in new_users:
    if username in current_users:
        print(f"Username {username} is unavailable. Please choose a different username.")
    else:
        print(f"Username {username} is available for use.")

Output: Username ted is unavailable. Please choose a different username. Username jed is unavailable. Please choose a different username. Username bernard is available for use. Username hoagie is available for use. Username laverne is available for use. [Finished in 0.3s]

If I change 'ted' to 'Ted' or 'TED' it outputs:

Username Ted is available for use. Username TED is available for use.

It shouldn't. Have I missed something? Or did Python lose the function for case insensitivity in a recent update?

EDIT - Thanks to those answered this constructively. It says I shouldn't comment to say thanks so I'll do it here.

Good Design for if else object mapping

I have this logic:

public void method(Boo result, Foo foo, Bar bar) {
   if(foo != null) {
      if(foo.getId() != null){
         result.setId(foo.getId());
      } else {
         result.setId(bar.setId());
      }
      if(foo.getName() != null){
         boo.setName(foo.getName());
      } else {
         result.setName(bar.setName());
      }
      // and many similar attributes
   } else {
      result.setId(bar.setId());
      result.setName(bar.setName());
      // and many similar attributes
   }
}

I find this way ugly, is there any way to make it in better design. I know that is better to use mapstruct, but in this project I can't.

Point System for Hunting Game

Hi friend i have a problem when solving our teacher assignment. Here is the problem:

You are tasked for implementing point system for your company upcoming hunting game. There is a rule for the game:

Point bracket

  1. Bracket total kill 10 point multiplier x1
  2. Bracket total kill 20 point multiplier x2
  3. Bracket total kill 30 point multiplier x3
  4. Bracket total kill 40 point multiplier x4
  5. Bracket total kill 50 point multiplier x5
  6. Bracket total kill above 50 point multiplier x6

Point bracket explanation: *if total kill less or the same than 10, point will be 10 *if total kill between 10 and 20, point will be 2x of total kill between 10 and 20, plus 1x of 10 total kill

  • if total kill between 20 and 30, point will be 2x of total kill between 10 and 20, plus 3x of total kill over 20, plus 1x of 10 total kill
  • if total kill above 30, point will be 2x of total kill between 10 and 20, plus 3x of total kill between 20 and 30, plus 4x total kill over 30, plus 1x of 10 total kill
  • and so on

Ex:

  1. total kill 10, point 10
  2. total kill 27, point 51
  3. total kill 33, point 72
  4. total kill 120, point 570
  5. total kill 60, point 210

I have tried to code it in js, but i think there is some missing logic. can you help me ?

function calculatePoint(totalKill){
    if(totalKill <= 10){
        return 10;
    } else if ( totalKill >= 10 && totalKill <=20){
        return 2*totalKill + 1*10*totalKill;
    } else if ( totalKill>=20 &&  totalKill <=30){
        return 3*totalKill + 1*10*totalKill;
    } else if (totalKill>=30){
        return 2*totalKill + 3*totalKill + 4*totalKill+1*10*totalKill;
    } 
}

Replacing a substring with a space character

I am given a string and I have to remove a substring from it. Namely WUB, and replace it with a space character.

Input:  WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB
Output: WE ARE THE CHAMPIONS MY FRIEND 

Here is my code so far:

#include <iostream>

using namespace std;

int main()
{
    const string check = "WUB";
    string s, p;
    int ct = 0;
    cin >> s;

    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] == 'W' && s[i+1] == 'U' && s[i+2] == 'B')
        {
            i += 2;
            if (p[ct] == '32' || p.empty())
            {
                continue;
            }
            else
            {
                p += ' ';
                ct++;
            }
        }
        else
        {
            p += s[i];
            ct++;
        }
    }

    cout << p;
    return 0;
}

Why is the first if statement never executed?

dimanche 30 août 2020

If-else statement error in Scheme using guile

Total newbie to Scheme here.

I've been stuck on a scheme problem for sometime now. I don't understand how to code this right. I've looked every where on this site and others, and I just can't get this to work.

the problem: define a function Square that squares its parameters. If the parameter is not a number, print the message "invalid_input".

Here is what I have tried:

(define (square x) (cond
                      ((number? x) (* x x))
                      (else (display "invalid_input\n"))
                   )
)

I've also tried this:

 (define (square x) (cond
                       ((number? x) (* x x))
                       ((not (number? x)) (display "invalid_input\n"))
                    )
 )

And this:

(define (square x) (if 
                   (number? x) (* x x) (display "invalid_input\n")
                   )
)

None of these have worked when I call square like this (square h). I keep getting this error on Linux

scheme@(guile-user)> (square h)
;;; <stdin>:44:0: warning: possibly unbound variable `h'
<unnamed port>:44:0: In procedure #<procedure 7fcc7d0a0b60 at <current input>:44:0 ()>:
<unnamed port>:44:0: In procedure module-lookup: Unbound variable: h
Entering a new prompt.  Type `,bt' for a backtrace or `,q' to continue.

Shouldn't it print "invalid_input" since 'h' is not a number? help me out here please. thank you

How to assign a variable to an if statement in a for loop?

I would like to have my for loop and if statement in a line.

Expanded Code:

for  item in number:
    if item['datetime'] not in number:
        print('Not there')

I tried this:

eg = [if item['datetime'] not in number: print('Not there') for item in number]

Code:

                    req = requests.get(url2 + str(page))
                    soup = BeautifulSoup(req.content, 'html.parser')
                    g_data = soup1.find_all('span', {"class": "b-card b-card-mod-hvehicle"})
                    g_price = soup.find_all('div', {"class": "b-card--el-vehicle-price"})
                    g_mile = soup.find_all('p', {"class": "b-card--el-brief-details"})
                    g_name = soup.find_all('p', {"class": "b-card--el-description"})
                    g_user = soup.find_all('a', {"class": "b-card--el-agency-title"})
                    g_link = soup.find_all('div', {"class": "b-card--el-inner-wrapper"})
                    g_sales = soup.find_all('span', {"class": "b-card--el-featured-label"})
                    time = soup.find_all('time', {"class":"timeago b-card--el-agency-time"}) 
                    m_price = [item.text for item in g_price]
                    m_mile = [item.text for item in g_mile]
                    m_user = [item.text for item in g_user]
                    m_name = [item.text for item in g_name]
                    m_link = [item.a["href"] for item in g_link]
                    m_extensions = [('') for item in g_link]
                    m_sales = [item.text for item in g_sales]
                    r_time = [dateutil.parser.parse(item['datetime']).strftime('%m-%d-%Y:%H:%M:%S') for item in time]
                    req2 = requests.get(m_extension + m_link)
                    soup_req2 = BeautifulSoup(req2.content, 'html.parser')
                    number = soup_req2.find_all('a',{"class": "b-seller--el-show-contacts b-line-mod-thin"})
                    test1 = (if item['mobile'] not in item: item = ('Sold') for item in number)

Gives me a syntax error. Thanks!

How to test if an object is a string? [duplicate]

I have a list of objects that I need to remove all strings from, leaving me with only integers in the list.

The problem I'm having is that some of the strings only contain numbers, for example "1" is a string. If I use is in an if statement if (listOfItems[i] is string) will not work on "1" I've also tried GetType() and typeof as shown below but I'm having the same problem.

How do I test if an object is a string, even if that string contain numbers?

public static class Filter
    {
        public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
        {
            for (int i = 0; i < listOfItems.Count; i++)
            {
                if (listOfItems[i].GetType() != typeof(int))
                    listOfItems.RemoveAt(i);
            }
            List<int> listOfInts = new List<int>();
            for (int i = 0; i < listOfItems.Count; i++)
            {
                listOfInts.Add((int)listOfItems[i]);
            }
            return listOfInts;
        }
    }

why my compiler directly jumping to else statement without checking if statment?

class val_brac:
    def bracket(self,str1):
        l=len(str1)
        for i in range(l):
            # print(i)
            if str1[i] == str1[l-1-i]:
               continue
            else:
                return False
        return True
            

print(val_brac().bracket('{[()]}'))

this is my code..

it returning False every time and the loop is running only once

Compare a number to see if it is between the past values

I'm going through a difficulty that I believe is not something so difficult, but for me it is being kkk. I want to compare a number to see if it is between two past values.

My logic is from this example below, but it is not working.

Examples:

$x = 197
$pastValue1 = 300
$pastValue2 = 600

$x = 420
$pastValue1 = 300
$pastValue2 = 600

if ($x >= $pastValue1 && $x <= $pastValue2) {?>
<div class = "detailsProd">
<p> Number <? php echo $x;?> is among the past values </p>
</div>
<? php} else { ?>
<p> Number <? php echo $x;?> is not among the past values </p>
<? php}?>

Program terminates without printing out the coded message [closed]

I tried to run this with a input of 02/29/2001, which ideally should print out the message of You entered an invalid date, but instead, it just terminated after finishing running the program. Where did it go wrong?

  Scanner keyboard = new Scanner(System.in);
        String date;
        String mm, dd, yyyy;
        System.out.print("Please enter a date in mm/dd/yyyy format: ");
        date= keyboard.nextLine();
        mm = date.substring(0, 2);
        
        dd = date.substring(3,5);
    
        yyyy = date.substring(6,10);
    
        int year = Integer.parseInt(yyyy);
        int day = Integer.parseInt(dd);
        int month = Integer.parseInt(mm);
    
        boolean isLeapYear=false;
        if (year % 4 ==0) 
        {
            if (year % 100 !=0)
            isLeapYear=true;
        
        else if (year % 4 ==0 && year % 100 ==0)
            {  if (year % 400 == 0)
                  isLeapYear=true;
            }
        else 
            isLeapYear=false;
        }
        if (isLeapYear=false)
        {
            if(month==2 && day>28)
            System.out.println("You entered an invalid date.");
        }

Creating a trigger to update quantities in T-SQL

I am trying to create a trigger in T-SQL that will be called when an order is placed that will check the quantity in a the product table and see if the the order quantity requested is the product table quantity. If the order is greater than the quantity on hand then the change is not reflected and the the transaction is rolled back. However, I am getting stuck with the if statement and can use some advice on how to do this properly. Any advice is welcomed.

CREATE TRIGGER trg_checkQ
ON product
FOR UPDATE
AS
BEGIN
SET NOCOUNT ON;


IF I.quanitity > product.quanitity
FROM Inserted I
WHERE I.productid = product.productid 
RAISERROR('Transaction denied!!!',16,1);
ROLLBACK TRAN;
END;

UPDATE product SET quanitity = product.quanitity - I.quanitity
FROM Inserted I
WHERE I.productid = product.productid
END

My if else statement only goes to print out the 'if' section [duplicate]

I'm learning python by myself with youtube and I'm playing around with it. It's been about 2 weeks. Then I suddenly wanted to make a silly multi-ending mini game using my brother with if else statement. But it only goes to print out the 'if' section even if I input words like 'no' or anything else.

# Project: Hit & Run David


from time import sleep


def print_slowly(num_fullstop):
    for _ in range(num_fullstop):
        print(".", end='')
        sleep(1)


print("Welcome to Hit & Run Simulator!")
sleep(2)
hit_or_not = input("Would you like to hit David without any reason? ")
if hit_or_not == "yeah" or "yes" or "sure" or "of course" or "okay" or "indeed" or "yup" or "ya":
    sleep(1)
    print_slowly(3)
    print()
    print("David is now angry!")
    sleep(2)
    calm_or_not = input("Would you like to try calming him down? ")
    if calm_or_not == "yeah" or "yes" or "sure" or "yep" or "ok" or "okay" or "yup" or "ya":
        sleep(2)
        print("You said to David: 'I'm sorry bro!'")
        sleep(2)
        print("'It was just a physical friendly greeting! Calm down!'")
        sleep(1)
        print_slowly(3)
        print()
        print("David is calmed down now.")
        sleep(1)
        print_slowly(6)
        print()
        hit_or_not = input("Would you like to hit David again? ")
        if hit_or_not == "yeah" or "yes" or "sure" or "ok" or "yep" or "okay" or "yup" or "ya":
            sleep(2)
            print("You just hit David again!")
            sleep(2)
            print("Now he is so mad that trying to calming him down won't help!")
            sleep(4)
            run_or_not = input("Would you like to run away? ")
            if run_or_not == "yeah" or "yes" or "sure" or "ok" or "yep" or "okay" or "yup" or "ya":
                sleep(2)
                print("You start to run away as fast as you can.")
                sleep(4)
                print("David starts to chasing you but he is much slower than you so you safely escape from him.")
                sleep(8)
                print("HAPPY ENDING")
            else:
                sleep(4)
                print()
                print("So you have chosen death.")
                sleep(4)
                print()
                print("BAD ENDING 2")
        else:
            print("Ok, fair enough")
            sleep(4)
            print()
            print("Normal ENDING")
    else:
        print("David became so angry now that he starts to beat you")
        sleep(4)
        print("You were beaten up to death.")
        sleep(4)
        print("BAD ENDING")
else:
    print("You are so BORING.")
    sleep(4)
    print("KINDA HAPPY ENDING")

JavaScript only run operation if the operation result is < 100

How can I run in JavaScript a operation, ONLY if the operation result is < 100, as an example.

I tried the following code but the += operation got executed twice, but I only want it to be executed after the if statement.

let progress = 0

function earn(howmuch) {
    if (progress += howmuch < 100) {
        console.log(progress) // console.logs 1
        progress += howmuch
        console.log(progress) // console.logs 2
    }
}

document.querySelector('.click-area').addEventListener('click', function() {
    earn(1)
}

Thanks for help

Is there a more concise way to returning words in a specified text with a combination of characters

I need to create a function that accepts a block of text as an argument, then matches and returns any word containing at least one of the strings/combination of characters below:

- tion (as in navigation, isolation, or mitigation)
- ex (as in explanation, exfiltrate, or expert)
- ph (as in philosophy, philanthropy, or ephemera)
- ost, ist, ast (as in hostel, distribute, past)

I have used a for loop to search for and append these patterns to a list:

def f(string):
    string_list = string.split()
    match_list = []
    for word in string_list:
        if "tion" in word:
            match_list.append(word)
        if "ex" in word:
            match_list.append(word)
        if "pht" in word:
            match_list.append(word)
        if "ost" in word:
            match_list.append(word)
        if "ist" in word:
            match_list.append(word)
        if "ast" in word:
            match_list.append(word)
    return match_list

print (f(text))

How could I write this code more efficiently?

samedi 29 août 2020

Cant accurately collate data from list with an integer

#I'm trying to call a search of a list with if statements and then add values to a co-ordinate that I can #call to draw a object in turtle. Similar solutions are welcome, but i really would like to know where I #am going wrong in my thinking here.

fixed_data_set_01 = [['Competitor A', 'Right'],
                     ['Competitor A', 'Down'],
                     ['Competitor A', 'Down'],
                     ['Competitor A', 'Left'],
                     ['Competitor A', 'Up']]


def list_searcher():

    global fixed_data_set_01
    d = len(fixed_data_set_01)
    f = 0 # looping variable to search through index
    y = 0 # defining y coord
    x = 0 # defining x coord
    
    for lister in range(d):
        
        print(fixed_data_set_01[f])
        f = f + 1
        p = fixed_data_set_01[f]
        
        if 'Up' in p:#if up is in the move set add value to y coord for competitor
            y = y + 90
            print(y,x)# testing
                 return y
    
        if 'Down' in p:#if down is in the move set add value to y coord for competitor
            y = y - 90
            print(y,x)# testing
                return y

        if 'Left' in p:#if left is in the move set add value to x coord for competitor
            x = x - 120
            print(y,x)
                return x
        
        if 'Right' in p:#if right is in the move set add value to x coord for competitor  
            x = x + 120
            print(y,x) # testing 
                return x
        
list_searcher()

How to filter MS Access field based on the value of another field

I have an Access query which includes a field for [Month] and another field for [Fiscal_Year]. I would like to filter the Month field to only return [Month] 1 if [Fiscal_Year]= 2021, and return all [Month] if not Fiscal_Year 2021

Run javascript on specific URL load

I want to run javascript on specific URL load, below is my code. It only shows an alert on the home page, not on the URL I have a condition on i.e. https://www.example.com/cart it gives an alert message on the home page only.

<script type="text/javascript">
    var currURL = window.location.href;

   function codeAddress() {

     if (currURL = 'https://www.example.com/cart'){
            alert('We are not shipping to countries that are not listed in shipping country!');
     }
    }
  window.onload = codeAddress;
        </script>

Conditionally compare value of array and set it to a variable

So I am trying to set a flag emoji to the flag variable depending on the value of the passed dishes array of objects.
I have a solution, but I bet this can be improved. I mean just imagine 50 countries ...

let flag = ''
const countryFlags = ['🇩🇪', '🇬🇷', '🇪🇸', '🇮🇹']
const dishes = [
   { dish: 'pizza', origin: 'italian' },
   { dish: 'tzatziki', origin: 'greek' }
]

const chooseFlag = a => {
    if (a === 'german') flag = countryFlags[0]
    if (a === 'greek') flag = countryFlags[1]
    if (a === 'spanish') flag = countryFlags[2]
    if (a === 'italian') flag = countryFlags[3]
}

chooseFlag(dishes.origin)

Anybody got a shorthand solution?

If-then loop for sub-directories, if the lines in the file are more than 2

A directory contains 30 sub-directories (all end with _g). In each sub-directory, a file named report.txt exists. I need to loop for all sub-directories and execute statement one if the lines in the file report.txt are greater than 2, or statement two if less than 2.

I tried using this script, but I am not getting the exact output.

#!/bin/bash
File=report.txt
for g in *_g;
if ((awk 'END{print NR}' $g/"$File" > 2)); then
echo "$g:";
    Statement 1 "$g"/report.txt
echo "------------------";
else 
echo "$g:";
    Statement 2 "$g"/report.txt
echo "------------------";
fi
done

How to use AND to check condition in Assembly language?

I'm trying to check even odd in assembly, using a 32-bit NASM, the code is working fine for odd numbers, but for even numbers it is giving output

Even
Odd
Odd

My code is,

section .data
    even db "Even", 0xa;
    odd db "Odd", 0xa;
    lene equ $-even;
    leno equ $-odd;

section .text
    global _start;

_start:
    mov ax, 0x4;
    and ax, 1;
    jz evenn;
    jnz oddd;
    jmp outprog;

evenn:
    mov eax, 4;
    mov ebx, 1;
    mov ecx, even;
    mov edx, lene;
    int 0x80;

oddd:
    mov eax, 4;
    mov ebx, 1;
    mov ecx, odd;
    mov edx, leno;
    int 0x80;

outprog:
    mov eax, 1;
    int 0x80;

React UseState if else condition won't set result

Ok SO trying to think of the simplest way to ask this first of all the code isn't the most beautiful its the 3rd thing I've ever made in react which I started a week ago and coding maybe a little over 2 months ago. I am making a form that takes in data for COVID simple firstName, lastName, email, and a risklevel The risk level is determined by the count of questions answered yes aka true with if else statements. The count works fine it logs the proper number based off of questions answered true the form information works the only thing it wont do is take my risklevel state and apply it based off of three conditions

function ModalPopUp() {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);

const [FirstName, setFirstName] = useState('');
const [LastName, setLastName] = useState('');
const [email, setEmail] = useState('');
const [riskLevel, setRiskLevel] =  useState(0);
const [dryCough, setDryCough] = useState(null);
const [sob, setSob] = useState(null);
const [Aches, setAches] = useState(null);
const [soreThroat, setSoreThroat] = useState(null);
const [headache, setHeadache] = useState(null);
const [fatigue, setFatigue] = useState(null);
const [exposure, setExposure] = useState(null);
// const [age, setAge] = useState(0)
// const [count, setCount] = useState(0)
// const [patients, SetPatients] = useState([]);

const riskState = () => {
  
  let count = 0;
 if(dryCough === true) {
count++ 
 }
 if(sob === true) {
  count++
 }
 if(Aches === true) {
  count++ 
}
if(soreThroat === true) {
  count++
 
 }
 if(headache === true) {
  count++

 }
 if(fatigue === true) {
  count++
 }
 if(exposure === true) {
  count++
 }
if (count <= 2) {
     setRiskLevel({riskLevel: riskLevel + 1})
 }
 if (count > 2 && count <= 4) {
    setRiskLevel({riskLevel: riskLevel + 2})
 }
  
 if (count > 4) {
   setRiskLevel({riskLevel:  riskLevel + 3})
 }
    console.log(dryCough);
    console.log(count);
    console.log(riskLevel)
}

What is common practice for implementing one-off things in code? [closed]

I'm new to programming and have been using tkinter in python to work on a game. This applies to my game but would also probably apply to many other games and programs too.

For example, if I create a dialogue system in a game and for one specific scenario or for the final boss the dialogue is different (For example the font changes, colour changes, the dialogue has a specific animation or requires a choice made by the player etc), what is the best way to implement it?

I could use a switch statement or if statement, to check if it's that specific scenario but it wouldn't be efficient to have the program check the condition every time, would it be? Is there any better practice for doing such code? Or is there a different problem that leads me into this problem?

unexpected output while using float variable in if statement

//here's my code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int N;
    scanf("%d",&N);
    int i,ct=0;//ct is to count how many given inputs of W & H fulfill the if and else if conditional statements given below.
    float W,H,ratio;//W and H are width and rectangle of rectangle respectively.ratio is ratio b/w W&H.  
    for(i=0;i<N;i++)
    {
        scanf("%f%f",&W,&H);
        ratio=W/H;
        printf("%f\n",ratio);
        if(ratio==1.7)//this statement is not getting executed for some reason
        {
            printf("true\n");
            ct++;
        }
        else if(ratio>1.6)
        {
            if(ratio<1.7)
            ct++;
        }   
    }
    printf("%d",ct);
}

note: when I give input as following

1 
10 1

supposed output is

ct=1

my output is

ct=0 

//ratio is 1.7 but if statement above is not getting executed that's why ct is not getting updated I want to know what is the problem with my above if statement.

Ways to include custom error messages in shorthand if-else sanity checks Discord JS

I am a beginner and probably, this is a stupid question. I am writing a command handler for a discord.js bot. Every time, a user sends a message starting with the correct command prefix, I check whether the invoke is in an Enmap of possible commands. Currently, it looks like this:

const command = client.commands.get(invoke);
if(!command) return;
...

I would like to keep this shorthand way of writing those sanity checks, but I would like to inform the user that there is no command with this name.

Is there an elegant way of doing this or does anyone know where I can find more information about good ways to solve this?

Thanks in advance :D

Clang-Tidy: Repeated branch in conditional chain

I'm trying to get my code clang-tidy clean, and it's complaining that I'm using garbage values. the task is when string_type is equalled to the if statement call the somefunc(n) in some_class function name the same as the if statement name

if (string_type == "somefun0") {
    some_class.somefun0();
} else if (string_type == "somefun1") {
    some_class.somefun1();
} else if (string_type == "somefun2") {
    some_class.somefun2();
} else if (string_type == "somefun3") {
    some_class.somefun3();
} else if (string_type == "somefun4") {
    some_class.somefun4();

this is how it goes it needs some short method

Simplifying Java IF-ELSE

Imagine there is an "if statement" with n conditions:

if (a == b || x == '0' || z == '1' .... || s == 'e') {      // < n conditions 
    result = do_something(); 
}

Can this be re-written as below :

switch (??) {
   case a == b:
   case x == '0':
   case z == '1';
   ...
   case s == 'e':
        result = do_something();
        break;
   default:
        break;
}

It feels more readable, and less cumbersome than multiple conditions separated by OR/AND operators. If another condition needs to be added then we can just add another case.

Is this possible? If yes, then please share an implementation.
OR
Is the original "if statement" itself a result of bad coding and hence, should be taken as a hint that the entire code needs to be revisited and improved?

What is the difference here in between these two python statements?

Can I know what is the difference here ? Assume A is 2d array and B is an int

if(A[i][j] == 2):
   res += B == 0

and

if(B == 0 and A[i][j] == 2):
   res += 1

vba not working with if statement and goto slide

so i am using vba powerpoint, i am trying to go to a slide according to these polls, so i have made this piece of code:

Sub got()
If sun.Caption > rain.Caption And sun.Caption > cloud.Caption And sun.Caption > sn.Caption Then
    ActivePresentation.SlideShowWindow.View.GotoSlide (4)
End If
If rain.Caption > sun.Caption And rain.Caption > cloud.Caption And rain.Caption > sn.Caption Then
    ActivePresentation.SlideShowWindow.View.GotoSlide (5)
End If
If cloud.Caption > sun.Caption And cloud.Caption > rain.Caption And cloud.aption > sn.Caption Then
    ActivePresentation.SlideShowWindow.View.GotoSlide (6)
End If
If sn.Caption > sun.Caption And sn.Caption > cloud.Caption And sn.Caption > rain.Caption Then
    ActivePresentation.SlideShowWindow.View.GotoSlide (7)
End If
End Sub

now, for me this looks like any other vba powerpoint code, but it gives me this:

run time error '438':
object doesn't support this property or method

vendredi 28 août 2020

Getting same output everytime [closed]

This a simple number guessing game. If you guessed the number right, it outputs "You win!!!", but if the number of tries (numberofguesses) is exceeded, it should output "You lose", but it is showing "You win!!!" even though I checked the values of numberofguesses, secretnum and guess after the while loop. Answer in simple words, I'm a beginner.

#include <iostream>
using namespace std;

int main()
{
    int secretnum = 7;
    int guess = 0;
    int numberofguesses = 3;
    while (secretnum != guess && numberofguesses != 0) {
        cout << "enter your guess: ";
        cin >> guess;
        --numberofguesses;
    }
    if (secretnum = guess && numberofguesses != 0) {
        cout << "You win!!!";
    }
    else
    {
        cout << "You lose";
    }
}

How does the following code works printf("%c")?

I wanted to know how the following program is working?

#include <stdio.h>
int main(void) {
    while(1){
        if(printf("%d",printf("%c")))
        break;
        else
        continue;
    }
    return 0;
}

I did not know how the part printf("%c") is working and therefore the whole program.I am aware of writing something like printf("%c", 'a'); like that but how is it working without providing the character to be printed? My question is what does the following program prints and how does it prints so?

I have tried to run the program, sometimes it prints nothing, but sometimes it is printing some random character followed by 1. I am not able to get how it is working, can someone please explain what is going behind the code and how it is printing that random characters, and why there is one at the end?

Here are some output I am getting

Output

Output

please explain what is wrong with the else command? [closed]

def main():
    sides = 6
    while rolling:
        roll_againinput("ready to roll? ENTER = Roll.  Q=Quit")
        if roll_again.lower() != 'q':
            num_rolled = roll(sides)
            print ("you rolled a", num_rolled)
            else:
                
                rolling = false
                
    print("thanks for playing")
     main ()
 File "<ipython-input-21-368344836b58>", line 8
    else:
    ^
SyntaxError: invalid syntax

IF ELSE user input to set a string for printing later, not immediately

I've starting learning JAVA and we have a task but we were given a lot of info and I'm very confused.

We are sequentially taking input details from a user and printing it in a specific format at the end.

The last detail : Age needs to be taken as the number and then later printed in as an Age Bracket (i.e: 20 and under, 21 to 35, 36 - 70, 71 and over) depending on the input.

I have this for when the user enters their age:

    System.out.println("Enter Your Age:");
        age=input.nextInt();
            if (age <= 20) {
                String aB = "20 or under";
            }
            else if (age < 35 && age > 21) {
                String aB = "21-35";
            }
            else if (age < 70 && age > 36) {
                String aB = "36-70";
            }
            else {
                String aB = "71 or Over";
            }

And then this at the end to print it along with the other data collected. The error is stating variable aB cannot be found.

System.out.println( "\n" + fN + ". " + mN + ". " + lastName + "\n" + "\n" + houseNumber + " " + streetName + " " + streetType + "\n" + cityName + "\n" + "Age Bracket: " + aB);

I feel like I am over complicating it and confusing myself. The rest of the print statement works its just aB at the end. So I assume I've done something wrong in the if - else code.

I have found a lot of code on here for printing the answer right away after the user input but not for setting the if else outcome as a sting to be printed later. Not sure if it can even be done.

Trying to Run two functions and two different emails in google scripts

I'm trying to have my sheet trigger an email alert when the last row on certain column matches an if statement after a google form feeds the sheet. it worked the first time but when i try to do a second condition it only acomplishes the second if. so separated the ifs work, but not combined.

can you guys help? here is the function:

function sendEmails() {
  
  var ss  = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Observaciones Diarias IMPRG");
  var lr  = ss.getLastRow();
  
  var currentTemp = ss.getRange(lr, 6).getValue();
  var currentkidName = ss.getRange(lr, 3).getValue();
  var currentTexture = ss.getRange(lr, 15).getValue();
  
  if(currentTemp >39) {
  
  MailApp.sendEmail("alvaroalfredo25@gmail.com","Temperature>39°Alert", currentkidName + " had atemperature of " + currentTemp + "° " +" which is extremely high, please check")
  }
  
  else if (currentTexture = 1){
    MailApp.sendEmail("alvaroalfredo25@gmail.com","Texture Alert", currentkidName + " had a  " + " liquid Evacuation. which indicates an issue, please check")
  }
}

What does the return do at the end of the expression of a PHP condition?

I am analyzing a PHP code but I cannot understand the logic of a condition with a return at the end.

Route::domain('{name}.{domain}.{tls}')->group(function () {
    $settings = App::make(\Common\Settings\Settings::class);
    $appUrl = config('app.url');
    $currentUrl = \Request::url();
    if ($appUrl === $currentUrl || !$settings->get('builder.enable_subdomains')) return; //<- Here
    Route::get('{page?}', 'UserSiteController@show')->name('user-site-subdomain');
});

I need to understand what are the circumstances that line 6 will be executed but apparently the return changes everything.

Any clarification or some more illustrative example will be welcome.

Apache directive to not to redirect REQUEST_URI with IF condition

The Apache directive is working successfully to redirect the web application URL if it contains "/login" string in REQUEST_URI to the help page. This works with a single directive as below.

RedirectMatch 301 "^(.*)" "https://ift.tt/3luZyZJ"

However, I wanted to not to redirect to help page if "REQUEST_URI" contains string "login?next=/scm"

I modified/added directive as below however it's not working as expected, any suggestions are welcome.

    <LocationMatch "^/login">
<If "%{REQUEST_URI} =~ m#/scm#">
#Do nothing
</If>
<Else>
       RedirectMatch 301 "^(.*)" "https://x.y.com/help-url/"
</Else>
</LocationMatch>

The value of iterator not updating inside an if statement in a for loop.. (Check the code for reference)

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        int n, ans = 0;
        scanf("%d", &n);
        int s[n];
        bool flag = false;
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &s[i]);
        }
        for (int i = 0; i < n; i++)
        {
            s[i] -= 1;
            if (s[i] < 0)
                break;
            ans++;
            if (i == (n - 1))
            {
                i=0;
                flag = true;
            }
        }
        printf("\n%d\n", ans);
        printf("%d", flag);
    }

    return 0;
}

I want to know why the value of i is not updating to i=0 when i == n-1, as I have written in the code. The bool flag is just there to check if the if statement was rendering at all or not (It is). Kindly help me out with this.

python infinite loop 'try and if' under a method

  1. executing menu() and go to 1 or 2 or 3 is good to do its work.

  2. but after passing by getproduct(character) and getting back to menu() and then if you choose number 3, it makes a bad loop.

I want to know why, and how to solve this problem...

def menu():

    menu = '1. ice\n2. cream\n3. quit'
    print(menu)
    
    try:
        order = int(input('choose one: '))
        
        if order == 1:
            c = 'ice'
            getproduct(c)
        elif order == 2:
            c = 'cream'
            getproduct(c)
            
        elif order == 3:
            exit()
            
        else: menu()
        
    except ValueError: menu()

def getproduct(character):

    toping = int(input('1. ice or 2. cream?'))
    
    try:
        if character == 'ice' and toping == 1:
            print(character + 'ice')
            menu()
        
        elif character == 'ice' and toping == 2:
            print(character + 'cream')
            menu()
        elif character == 'cream' and toping == 1:
            print(character + 'ice')
            menu()
        elif character == 'cream' and toping == 2:
            print(character + 'cream')
            menu()
        else: getproduct(character)
    except: getproduct(character)
    
        
menu()

Repetitive if statement into one clean if statement inside a for loop

Considering the case of having to check a billion conditions, how could I reduce an ugly, repetitive if statement into a clean, elegant if statement by using a for loop. Example and documentation are very much appreciated!

Here's an example of the monstrosity I'm talking about:

 if (
        x === 0 && y === 1 ||
        x === 2 && y === 3 ||
        x === 4 && y === 5 ||
        x === 6 && y === 7 ||
        x === 8 && y === 9
      ) {
        // do somethig...
      }

if statement and the maximal value in Pascal

Looking at this code:

enter image description here

I thought that the program won't give the right maximal value if z>x and y>x ,but, to my surprise, it did give the correct value. Why is that? Did the program compare Y and Z and gave the biggest value without me ordering it to do so?

Nest if with INDEX, Match Function

I imagine I am closing this last argument out incorrectly which is why I am getting false on the last if statement no matter what it is. All the others before last if statement are working correctly, but below is an example of my problem with fake data.

For some reason, last keeps failing. If I pull it out and put it in a separate cell, it works correctly but failing as part of the complete if statement.

=IF(D7="bread","",
IF(D7="chicken","",
IF(D7="dog","",
IF(D7="bird","",
IF(D7="rat",INDEX('Sheet'!E:E,MATCH(A7,'Sheet2'!B:B),
IF(D7="mouse",INDEX('Sheet'!E:E,MATCH(A7,'Sheet2'!B:B),0),0)))))))

How to make if-statement print required the result?

This code has one problem. The problem is in

Problem in if-statement

if(all_digits(to_find) && strlen(to_find) ==  13)

Whenever I enter 13 characters but not from the file then it gives me a message of else statement but printing Found. Hello World! also. Although Found. Hello World! is in if-statement. It should not be printed. How to make if-statement work correctly?

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

int all_digits(char *s){
  for (; *s!=0; s++){
    if (!isdigit(*s)){
      return 0;
    }
  }
  return 1;
}

Another part of code

int main(){
  FILE * fr = fopen("file.csv", "r");

  char save[500], line[200],  to_find[50];
  int oneByOne = 0, numberOfFields=8;
  char *word = NULL;
  printf("Enter the ID card number: ");
  scanf("%s", to_find);

  if(all_digits(to_find) && strlen(to_find) ==  13){
    while(fgets(line, 200, fr)){
      word = strtok(line, "\n");
      strcpy(save, line);

      if (strstr(save, to_find)){
        char *wordone = strtok(save, ",");
        while (wordone != NULL){
          printf("Here are your details: %s\n", wordone);
          wordone = strtok(NULL, ",");
        }
      }
    }
    fclose(fr);

    printf("Found. Hello World!\n");
  }  
  else {
    printf("enter correclty\n");
  }
return 0;
}

syntax error unexpected toke in if statement in js

I am receiving a syntax error with unexpected token < at line 14 when i try to run this script in my browser. What i am trying to do is open my classes 5 minutes before class and still open when ran all the way up to 5 minutes before the next class.

<script>
//Current time
var date = new Date();
var time = date.getTime();

//Time checker
if(time >= 7:55 && < 8:55){
    window.open('https://classroom.google.com/c/MTIyMjc3NTE0MzEw');
}
if(time >= 8:55 && < 9:55){
    window.open('https://classroom.google.com/c/MTE1MjA4MzM5MDgz');
}
if(time >= 9:55 && < 10:55){
    window.open('https://classroom.google.com/c/MTIyMjk4MzAxMjYx');
}
if(time >= 10:55 && < 11:55){
    window.open('https://classroom.google.com/c/MTIzMjMyNzU4ODk2');
}
if(time >= 11:55 && < 12:55){
    window.open('https://classroom.google.com/c/MTIzMTkzMjU1MjAx');
}
if(time >= 12:55 && < 13:55){
    window.open('https://classroom.google.com/c/MTIyMjk4MzAxMjQx');
}
if(time >= 13:55 && < 14:55){
    window.open('https://classroom.google.com/c/MTIyNDk3Mjk5NDQ2');
}
if(time >= 14:55 && <= 15:00){
    window.open('https://classroom.google.com/c/MTIyNjk1NTQxMzYw');
}
</script>

Python parser.parse combined with if statement

I am working on a calculator project, I am using yacc as a parser and as I have 4 different values to parse I wanted to check what was just parsed. I have a strong feeling it won't work but I don't know what to use else. I Only get this error message: Process finished with exit code -1073741571 (0xC00000FD)

If anyone can help me, I would very much appreciate it.

This is my code, the piece of code I'm talking about would be:

if parser.parse(C1):

t[0] = float(C1)

MwGCalc.MwGCalc(C1)

MwGCalc is this right here, it currently only works for 4*4 but it's just for testing purposes and not very well thought out:

print("Content-type: text/html\n\n")
import numpy as np
import cgitb
import cgi



cgitb.enable()
form = cgi.FieldStorage()
C1 = form.getvalue('C1')
# Defining Variables


#Actual Calculating
if C1 == 256:
    p = C1
    print(p)

And this right here is the Code for the calculator:

import numpy as np
import MwGCalc
#!C:\Users\Letsmoe\Anaconda3\python.exe
print("Content-type: text/html\n\n")
tokens = (
    'NAME', 'NUMBER',
    'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'EQUALS',
    'LPAREN', 'RPAREN', 'POWER', 'FUNC',
)

# Tokens

t_PLUS = r'\+'
t_MINUS = r'-'
t_TIMES = r'\*'
t_DIVIDE = r'/'
t_EQUALS = r'='
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
t_POWER = r'\^'
t_FUNC = r'(sin)|(cos)|(tan)|(ln)|(log)|(sqrt)'


def t_NUMBER(t):
    r'\d+'  # [0-9]+
    try:
        t.value = int(t.value)
    except ValueError:
        print("Integer value too large %d", t.value)
        t.value = 0
    return t


# Ignored characters
t_ignore = r" \t\r"


def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")


def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)


# Build the lexer

lexer = lex.lex()

# Parsing rules

precedence = (
    ('left', 'PLUS', 'MINUS'),
    ('left', 'TIMES', 'DIVIDE'),
    ('left', 'POWER'),
    ('right', 'UMINUS'),
)

# dictionary of names
names = {}


def p_statement_assign(t):
    'statement : NAME EQUALS expression'
    names[t[1]] = t[3]


def p_statement_expr(t):
    'statement : expression'
    if parser.parse(C1):
        t[0] = float(C1)
        MwGCalc.MwgCalc(C1)


def p_expression_binop(t):
    '''expression : expression PLUS expression
                  | expression MINUS expression
                  | expression TIMES expression
                  | expression DIVIDE expression
                  | expression POWER expression'''
    if t[2] == '*':
        t[0] = t[3]**t[1]


def p_expression_uminus(t):
    'expression : MINUS expression %prec UMINUS'
    t[0] = -t[2]


def p_expression_func(t):
    'expression : FUNC LPAREN expression RPAREN'
    if t[1] == 'sin':
        t[0] = np.sin(t[3])
    elif t[1] == 'cos':
        t[0] = np.cos(t[3])
    elif t[1] == 'log':
        t[0] = (np.log(t[3])) / (np.log(10))
    elif t[1] == 'sqrt':
        t[0] = np.sqrt(t[3])
    elif t[1] == 'ln':
        t[0] = (np.log(t[3]))


def p_expression_group(t):
    'expression : LPAREN expression RPAREN'
    t[0] = t[2]


def p_expression_number(t):
    'expression : NUMBER'
    t[0] = t[1]


def p_expression_name(t):
    'expression : NAME'
    try:
        t[0] = names[t[1]]
    except LookupError:
        print("Undefined name '%s'" % t[1])
        t[0] = 0


def p_error(t):
    print("Syntax error at '%s'" % t.value)


if __name__ == "__main__":  # HTML is following
    print()  # blank line, end of headers
    print("<TITLE>CGI script output</TITLE>")

    import ply.yacc as yacc

    parser = yacc.yacc()
    # while True:
    #    try:
    #        s = input('calc > ')   # Use raw_input on Python 2
    #    except EOFError:
    #          break
    #    parser.parse(s)

    import cgi
    import cgitb

    cgitb.enable()
    form = cgi.FieldStorage()
    C1 = form.getvalue('C1')
    if C1 is not None:
        C1 = str(C1)
    C2 = form.getvalue('C2')
    if C2 is not None:
        C2 = str(C2)
    C3 = form.getvalue('C3')
    if C3 is not None:
        C3 = str(C3)
    C4 = form.getvalue('C4')
    if C4 is not None:
        C4 = str(C4)

    for C1 in C1.splitlines():
        parser.parse(C1)
    for C2 in C2.splitlines():
        parser.parse(C2)
    for C3 in C3.splitlines():
        parser.parse(C3)
    for C4 in C4.splitlines():
        parser.parse(C4)```

How do I make an if/else statement in JavaScript that makes it so that when you put in different things in a text box, different things happen?

How do I make an if/else statement in JavaScript that makes it so that when you put in different things in a text box, different things happen? I want to know how to say "if the text is "blank", then it does this, else do this."

Why variables assigning works differently when it is used with conditional statement?

Im wondering if:

s = 'foo bar'
a, b = s.split(' ')

print(a)
'foo'
print(b)
'bar'

so why:

s = 'foo bar'
a, b = s.split(' ') if s else '',''

print(a)
['foo', 'bar']
print(b)
''

Can someone explain me why python behaves like shown at the second example?
Thank you!

Which If statement is faster; comparison operators or in_array?

I'm creating several functions checking values between or in some interval. Since these functions will be called ten thousand of times, which one should I use for the following sample scenario?

Lets consider I have 1..N variables, I want to check whether the input is in N set or not.

Sample case;

Code numbers between 1 to 15 (also sometimes; numbers between 1 to 15 but not 8 etc.)

First option;

if ($num >= 1 && $num <= 15) {
    //..
}

Second option;

if (in_array($num, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], TRUE)) {
    //..
}

IF Else Statement with user input in Python [closed]

sorry to ask this basic question. I am learning python and when i tried running the following code i am not achieving the desired result. Basically when executed, the code has to take 3 inputs from user, compare it then print eg: num1 is greatest. Then it has to print the number.

num1=input("Enter num1:")
num2=input("Enter num2:")
num3=input("Enter num3:")
def max_num(num1, num2, num3):
    if(num1>=num2 and num1>=num3):
        print("num1 is greatest")
        return num1
    elif(num2>=num1 and num2>=num3):
        print("num2 is greatest")
        return num2
    else:
        print("num3 is biggest")
        return num3

print(max_num)

Comparing string variables and ignoring outside whitespace

I have this function (part of a C# .Net DLL) which locates XML elements with a specific value and replaces the text. It uses recursion:

   private bool ReplaceNameInXMLDocument(XElement pElement, string strOldName, string strNewName)
    {
        bool bReplaced = false;

        try
        {
            if (pElement.HasElements)
            {
                foreach (var pSubElement in pElement.Descendants())
                {
                    ReplaceNameInXMLDocument(pSubElement, strOldName, strNewName);
                }
            }
            else if (pElement.Value == strOldName)
            {
                pElement.Value = strNewName;
            }

            bReplaced = true;
        }
        catch (Exception ex)
        {
            SimpleLog.Log(ex);
        }

        return bReplaced;
    }

The only issue I have is related to whitespace. Imagine strOldName is Happy but in the XML data file the value there (for what ever reason) is Happy (it has an extra space). At the moment my comparison method is not locating the match because of the difference with whitepsace.

I realise I could change the else clause like this:

{
    string strExistingValue = pElement.Value.Trim();
    if(strExistingValue = strOldName)
    {
        ...
    }
}

But is there any other way that I can compare strOldName against the string element and automatically ignore outside whitespace? This is because I know that the variable strOldName has already been Trimmed. Is there a simpler comparison beyond my suggested adjustment?

jeudi 27 août 2020

Java menu with table and order number using array

so i have this homework about making a menu using array but i don't seem to understand how to make a table number or order number. however i am able to make the menu but the table number part is really complicated to add and i tried to search but i didn't found any correct code to help me make this so anyone please help so the teacher wants the output to be:

input : 
Number of table : ..2..
Order table(1) : ..2..
Order again? (y/n) ..y...
Order table(1) : ..3..
Order again? (y/n) ..n...

Order table(2) : ..4..
Order again? (y/n) ..y...
Order table(2) : ..5..
Order again? (y/n) ..n...

Any changes? (y/n) ..y.. if "n" --> SUMMARY
Table no : ...1..
Order no:  ..2..
Are you sure? (y/n) ..y..  

if "n" --> Table no : ...... 
              Order no: ......
              Are you sure? (y/n) ..y..  

output (SUMMARY) :
Table 1                   
menu3      price3        
------------------- +
Total      xxxxxx

Table 2        
menu2      price2        
menu3      price3
------------------- +
Total      xxxxxx

GRAND TOTAL XXXXXXXX

and this is the code for the menu that i wrote:

package function;

import java.util.Scanner;

public class Function {

  public static void main(String[] args) {
    Scanner keyB = new Scanner(System.in);  // Create a Scanner object
    String[] menuname  = {"1. fried rice","2. noodle","3. soup","4. meatballs","5. chicken tenders","6. ramen","7. iced tea","8. cola","9. mineral water","10. ice cream"};
    int   [] menuprice = {25000,27000,28000,20000,26000,30000,4000,6000,2000,12000};
    int   [] order     = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    
    System.out.print("\u001B[2J");

    System.out.println("M E N U");
    for (int i=0; i<menuname.length; i++) {
        System.out.println(menuname[i]+": Rp. "+String.valueOf(menuprice[i]));
    }
    System.out.println();

    String orderagain="y";
    int userorder=0, ordernum=0, ordertotal=0;
    while (!orderagain.equals("n")) {
        System.out.print("Enter your menu number: ");
        userorder = keyB.nextInt()-1;
        order[ordernum]=userorder;
        ordertotal=ordertotal+menuprice[userorder];
        ordernum++;
        System.out.print("Order again (y/n): ");
        orderagain = keyB.next().toLowerCase();
        System.out.println();
    }

    System.out.println();
    System.out.println("Your ordered menu:");
    System.out.println();
    for (int i=0; i<ordernum; i++) {
        System.out.println(menuname[order[i]]+": Rp. "+String.valueOf(menuprice[order[i]]));
    }
    System.out.println("------------------------------------------ +");
    System.out.println("The total is: Rp. "+String.valueOf(ordertotal));
    System.out.println();
  }
}

While scrolling tableview not loading properly with if else condition in swift

I am showing all orders in tableview.. if i select row then in next viewcontroller i can cancel the order...

here in the canceled order cell i need to show "Cancelled" label and i need to strike the order name.. here cell adding correctly and if i cancel the order then cancel label coming and order name also striked out..

but the problem is if once i scroll up and down then some random cells also some showing strike mark in the order name? why? whats wrong in my if else condition in cellForRowAt

coreect cancel order

enter image description here

random cell showing strike mark like this

random cells showing strike mark like this

my code in here whats wrong in cellForRowAt if else condition:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell: EventsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EventsTableViewCell") as! EventsTableViewCell
    let order     = orderList!.orders[indexPath.row]
            
    if order.status == "Cancelled" {
        cell.cancelLbl.text = " \(order.status!) "
        let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string:order.orderName!)
        attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
        cell.nameLbl.attributedText = attributeString
    }
            
    else{
        cell.cancelLbl.text = ""

        if order.isAllDayOrer == true{
            
            cell.cancelLbl.text = ""

            cell.tohardcodeLabel.isHidden = true
            cell.fromHardcodeLabel.text = "order Date"
            
            cell.startLbl.text = order.orderDate

            cell.nameLbl.text  = order.orderName
            cell.AddrLbl.text  = order.orderAddress
            cell.orderownerNameLabel.text = order.orderOwnerName as? String

        }
        else {
           
            cell.cancelLbl.text = ""

            cell.tohardcodeLabel.isHidden = false
            cell.fromHardcodeLabel.text = "From Date"

            cell.startLbl.text = order.orderDate + " " + order.orderTime
            
            cell.nameLbl.text  = order.orderName
            cell.AddrLbl.text  = order.orderAddress
            cell.orderownerNameLabel.text = order.orderOwnerName as? String
        }

    }

    return cell
}

please help me with code.

Need to make a list of the outstanding GPA’s from the array Im making (GPA’s over 3.4). Prefer traditional loop solution over some ES6 function

Need help with getting list of GPAs over 3.4. Was able to sort largest to smallest, average, and get min and max GPAs utilizing traditional approaches (not ES6).

<div id ="out"></div>
<script>
var gpas = [];
var thegpas = " ";
var total = 0
while (thegpas != "XXX")
{
    thegpas = prompt("Enter gpas or XXX to Stop");
    if(thegpas != "XXX"){
        gpas.push(thegpas);
    } else  {
        break;
        
    }
    
}

for(var x = 0; x < gpas.length; x++)
{
    a = gpas.sort((a,b)=>b-a);
    total=total + parseFloat(gpas[x]);
    b = total/gpas.length //parseFloat(total)/length;
    var max = gpas[0];
    var min = gpas[0];
    for(var i = 1; i < gpas.length; ++i) {
        if (gpas[i]>max) {
            max = parseFloat(gpas[i]);
        }
        else if (gpas[i] < min) {
            min = parseFloat(gpas[i]);
            
        }
    }
    //need help with this part
    //outstandingGPAs=0;
   outstandingGPAs = [];
   cutoff = 3.4;
   if (gpas[x]>cutoff){
        outstandingGPAs.push(parseFloat(gpas[x])); 
    }

    out= "Largest to smallest " + a + "<br/>" + "GPAs average: " + b + "<br/>" + " Max and Min: " + max + ", " + min + "<br/>" + "Outstanding GPAs (greather than 3.4): " + outstandingGPAs ;
    
   // alert(gpas[x]);
}
    document.getElementById('out').innerHTML=out;

Current Output:outputimage

error syntax on if nesting(intermediate-advance) [closed]

import re,sys
a = input('?\n')
b = re.search('[A-Z]+',a)

if b is not None:
   if len(b.group()) == len(a):
       print('@')
       sys.exit()#if b is not None:
   
 #Thank you
 #what above code should do
#if b is not None:
    #if len(b.group()) == len(a):
        #print('@')
        #sys.exit()

** If b is not None is True,I want to group and compare its length to a to determine if the whole of a is uppercase or not**

If -Else condition in Pandas to create CSV in separate folders

I am new to python and trying to apply if-else condition over a dataframe.

If the ACCOUNT_LOGIN contains any special character create the csv under a ErrorFolder. else create the csv under ValidatedDataFolder

But the below is also creating a file under ValidatedDataFolder alongwith ErrorFolder even . How to acheive this validation of creating csv in different folders based on if-else condition?

dataframe ACCOUNT_LOGIN : [ AL&L@WA, ANGLIND, ASIGAFU ]

def validate(rowsofdataframe):

filename="TestFileSpclCharOp.txt" 

if  rowsofdataframe['ACCOUNT_LOGIN_1'].strip().isalnum()==False : #if any row contains any spcl character
    output_error_file=os.path.join(errorPath,filename)
    rowsofdataframe.to_csv(output_error_file,index=False)
    val="Login contains special character.FAILED"
else :
   
    validated_Files=os.path.join(foramttedPath,filename)
    rowsofdataframe.to_csv(validated_Files,index=False)
    val="All validation passed" 
    
return val

dfwithcolumns['Status'] = dfwithcolumns.apply(validate, axis=1)

How can I use event.key with an else statement?

I want to be able to have an else statement that always default when I hit a key.

var key = event.key;
if(key == "ArrowDown"){
   //do something
} else if(key == "ArrowUp"){
  //do something
} else{
  //do something
}

The problem is that the program stops and waits for event.key, so else only happens when I hit another key, I want else to happen every time through the loop without having to hit a key. I have tried var key = event.key || "asdf" and then switching the else to else if(key == "asdf") but I havent had any luck. This is in javascript. I am not stuck to using event.key, I am open to using something else

Java programming for interchanging two consecutive letters [closed]

Write a program in JAVA that will accept a word of even length and create a new word by interchanging two consecutive letters of the word.

Sample Input: PROGRAMS Sample Output: RPGOARSM

How can I put several if statements into a Tkinter Button

I have tried to put my if statements into a messagebox function and have the button print out a message with a number and the corresponding player. I have tried everything I can think of and it still doesn't work, at the moment it prints out a random number but of course I want it to print the player's name as well, any help will be appreciated :)

    print(number)
    if number == 18:
        print(no_18)
    elif number == 17:
        print(no_17)
    elif number == 16:
        print(no_16)
    elif number == 15:
       elif number == 5:
        print(no_5)
    elif number == 3:
        print(no_3)
    elif number == 2:
        print(no_2)
    elif number == 1:
        print(no_1)
    else:
        print("Player not found")
   

    def generate_number():
        messagebox.showinfo("You got this player!", random.randint(1, 20))
    
    
    root = tk.Tk()
    
    canvas = tk.Canvas(root, height=600, width=600, bg="#f40000")
    canvas.pack()
    
    label1 = tk.Label(root, text="Click for a random player", bg="#f40000", fg="#323648")
    label1.config(font=("", 24))
    label1.place(relx=0.22, rely=0.1)
    
    button1 = tk.Button(root, height=12, width=30, text="Random \n Man United player", 
    command=generate_number, bg="#ef7a85", activebackground="#dd6d11")
    button1.place(relx=0.34, rely=0.4)
    
    root.mainloop()

If statement is not working in python in python 3.6

    a = input('10+1: ')
if a == 11:
    print("correct")
else:
    print('wrong')

The code above is not working in my program.

Its giving me an output of something like this:

10+1: 11
wrong

Process finished with exit code 0

Need help regarding the implementation of logic for multiple conditions

I need some help in identifying the logic to implement the following conditions below:

I have a search criteria request which can can have around 10 possible combinations. Im writing the request validation for it with proper error messages.

These are my conditions :

         if (request.getFullName() == null && request.getFullNameEs() == null && request.getBirthDate() == null && request.getNat() == null &&
                request.getGender() == null) {
            validationErrors.add("Name criteria search is not proper");
        }
        if (request.getPassportNo() != null) {
            if (request.getPassportNationality() == null && request.getBirthYear() == null) {
                errors.reject(NULL_OR_EMPTY_FIELD_ERROR, "Please pass passportNationality or birthYear ");
            }
            if (request.getPassportTypeId() == null || request.getPassportNationality() == null) {
                errors.reject(NULL_OR_EMPTY_FIELD_ERROR, "Please pass passportTypeId and/or passportNationality");
            }
        } else {
            errors.reject(NULL_OR_EMPTY_FIELD_ERROR, "Please pass passportNo");
        }
        if (request.getIdNo() == null) {
            if (request.getIdType() == null || request.getIdNationalityId() == null) {
                errors.reject(NULL_OR_EMPTY_FIELD_ERROR, "Please pass IdType and/or IdNationalityId");
                return;
            }
        } else {
            errors.reject(NULL_OR_EMPTY_FIELD_ERROR, "Please pass idNo");
        }
        if (request.getPersonNo() == null && request.getPersonTypeId() == null) {
            errors.reject(NULL_OR_EMPTY_FIELD_ERROR, ERROR_MESSAGE);
        }
        if (request.getSponsorNo() == null && request.getSponsorTypeId() == null && request.getPpsId() == null) {
            errors.reject(NULL_OR_EMPTY_FIELD_ERROR, ERROR_MESSAGE);
        }
        if (request.getSponsorNo() == null && request.getSponsorTypeId() == null && request.getPpsId() == null) {
            errors.reject(NULL_OR_EMPTY_FIELD_ERROR, ERROR_MESSAGE);
        }
        if (request.getSponsorNo() == null) {
            errors.reject(NULL_OR_EMPTY_FIELD_ERROR, ERROR_MESSAGE);
        }
        if (request.getPersonNo() == null && request.getPersonTypeId() == null) {
            errors.reject(NULL_OR_EMPTY_FIELD_ERROR, ERROR_MESSAGE);
        }

in one request, only of the criteria should be passed and it that particular criteria failed then I want the validation to break and display only that particular error message and not the list of messages.

How can I achieve this behavior?

Else statement to return text if no matches found - average from list

I have a list of people with names, age and gender:

people = [('John', 36, 'M'), ('Rachel', 24, 'F'), ('Deardrie', 78, 'F'), ('Ahmed', 17, 'M'), ('Sienna', 14, 'F')]

I have written some code that pulls back the average age of all males ('M'):

def average_age(members,gender):
    return sum([member[1] for member in people if member[2] == "M"])/2

This returns the expected result:

average_age(people, 'M')
26.5

However, if I was to write average_age(people, 'Z') I would like it to return the result statement to return 'No matches found.' At the moment, it still returns 26.5.

I have tried putting an else statement within the code but nothing seems to work.

Any help would be greatly appreciated.

Thank you

Excel Userform Text field validation

I'm making a userform that has multiple text boxes, for Example Combobox1 = ReasonForRequestField and Combobox2 = Requestnotcreatedfield, if Combobox1 = Reason 1 or Reason 2 then the validation will require the user to select an outcome from Combobox2, but if Combobox1 = Reason 3 or 4 then Combobox2 is not required.

i have tried the validation below but it wont allow me submit with Reason 1 in Combobox1

If Me.ReasonForRequestField.Value = "Reason1" Then

MsgBox " Please select a reason from Drop Down below " , vbExclamation, " Request not created field "

Me.Requestnotcreatedfield.SetFocus

Exit Sub

End If

i found this example on here but couldnt figure out how to adapt the variables to my form

If combobox1.Text = "1 - 2 yr" And (CDbl(textbox2.Value) < 1 Or CDbl(textbox2.Value) > 2) Then MsgBox ("Enter correct value") ElseIf combobox1.Text = And Then... End If

i hope i explained what i'm after ok, Any help would be Greatly appreciated :)

Thanks.

How can I simplify/more readable this by using calls to InOrder (code below)

How can I simplify/more readable this by using calls to InOrder (code below). The aim of the code is to check if a Rectangle contains a Point. Below is the code for firstly the Rectangle class, and further below is the InOrder class. I am having trouble finding a way to make the code more readable and I want to simplify it the best way possible.

// Construct a rectangle from two arbitrary points
public class Rectangle {
private int x1;
private int y1;
private int x2;
private int y2;

public Rectangle(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

public boolean contains(int x, int y) {
if(x1 <= x2) {
    if(x1 <= x && x <= x2) {
    if(y1 <= y2) {
        return y1 <= y && y <= y2;
    } else {
        return y2 <= y && y <= y1;
    }
    }
} else {
    if(x2 <= x && x <= x1) {
    if(y1 <= y2) {
        return y1 <= y && y <= y2;
    } else {
        return y2 <= y && y <= y1;
    }       
    }       
}

return false;
}
}



public class InOrder {
//Don't change this
public boolean OutOfOrder(int n1, int n2, int n3) {
return (n1 > n2) || (n2 > n3);
}

//The original and messy InOrder, leave this as an example of what not to do
public boolean inOrder(int n1, int n2, int n3) {
if (n2 > n1) {
  if (n3 > n2) {
    return true;
  } else {
    return false;
  }
} else if (n2 == n1) {
  if (n3 == n1) {
    return true;
  } else {
    return false;
  }
} else {
  return false;
}
}
}

SQL - Add If else condition in CHECK Constraint

I'm trying to set a condition in CHECK constraint. The scenario is

  1. When column1 is null then no action required
  2. If column1 is not null then column3 must have defined code

By example, if a student has enquired (1) then the he should have performed a action (visited as code 1 or called as code 2)

table-IMG

CREATE TABLE [dbo].[enquiry_details](
    [Id] uniqueidentifier NOT NULL,
    [Name] [varchar] (100) NOT NULL,
    [Enquired] [int] NULL,
    [location] [int] NOT NULL,
    [Action_Type] [int] NULL,
     -- CONSTRAINT menu_key CHECK ((Enquired IS NOT NULL)and Action_Type IN ('11','22'))
     --CONSTRAINT menu_key CHECK (IF(Enquired!= null)  Action_Type IN ('11','22'))
     CONSTRAINT menu_key CHECK (IF(Enquired is not null)  Action_Type IN ('11','22'))
    -- CONSTRAINT menu_keyi CHECK (CASE WHEN Enquired IS NOT NULL THEN Action_Type IN ('11','22') END)
     -- CONSTRAINT menu_keyi CHECK (CASE WHEN LEN(Enquired)>0 THEN (Action_Type '11' OR Action_Type='22') ELSE NULL END)
) 

Basic python: if condition

I am learning python now a days. I have a doubt: If a user inputs a value thats is not:0,1 or 2. I want to send a certain message, can someone help me?

How to use lapply and ifelse together but keep original values in the df in R

I have a df with intervals of numbers, and I would like to split the numbers with a 'BETWEEN' and 'AND' between them (to use in a sqldf later)

t <- data.frame('id'=c(1:5), 'values'=c("1-1000", ">12", "2-2000", "<100", "5-10"), 'more values' =c(">50", "<10", "500-2000", "1-10", ">100") )

I am using a lapply function together with ifelse, it works, however, in the rest of the table all cells with a value that does not contain '-' are now replaced with a single number eg '1' or '2'. I would like the original values to be preserved (eg. >12. <100 etc..).

#with grepl
t[] <- lapply(t, function(x) ifelse(grepl('-', x), paste('BETWEEN', sub("\\-.*", "", x), 'AND', sub('.*-', '', x)  ), x))

#with %like%
t[] <- lapply(t, function(x) if(x %like% '-') {paste('BETWEEN', sub("\\-.*", "", x), 'AND', sub('.*-', '', x))})

I have also tried with a if no else function, but it did not solve the problem

t[] <- lapply(t, function(x) if(grepl('-', x)) {paste('BETWEEN', sub("\\-.*", "", x), 'AND', sub('.*-', '', x))})

Desired ouput:

t1 <- data.frame('id'=c(1:5), 'values'=c("BETWEEN 1 AND 1000", ">12", "BETWEEN 2 AND 2000", "<100", "BETWEEN 5 AND 10"), 'more values' =c(">50", "<10", "BETWEEN 500 AND 2000", "BETWEEN 1 AND 10", ">100") )

Thanks in advance!

If statement on values of a vlookup

I have2 columns that have VLookups in and I want to do an if statement against the values but for some reason this isn't working, I have tried all sorts of different ways of formatting the if statement.

=IF(H2<=J2,"","Less than 1 pallet left")

Is anybody able to help please?

using ifstatement in powerquery without adding an additional column

hi everyone im trying to use PQ for the first time..

let if column'security name'="future" then column'long/short'="Short' else "error" in Please could you help?

I keep getting token eod expected errors.thank you

Multip Write a function to print the result of a number multiplied with its previous number until the previous number is 1

For example: If the number is 5, then result = 5 * 4 * 3 * 2 * 1 = 120 If the number is 8, then result = 8 * 7 * 6 * 5 * 4 * 3 * 2 *1=403020

mercredi 26 août 2020

Loop through sheets and copy Charts to Word, VBA

I'm trying to write a macro that loops through all sheets in a excel workbook and if there is a chart It copy the chart to a new word document. The workbook consist of around 35 sheets and only half of them are populated with a chart. I want the code to jump to next sheet if there is no chart in it and if there is a chart copy it to Word and then move on to the next one. I am very new to VBA and coding in general and been experimenting a bit. I managed to get one chart from one sheet into word... I've tried a few different things and left that in as comments.

My code as today:


        'Declare word object variables
    Dim WordApp     As Word.Application
    Dim WordDoc     As Word.Document
    
        'Declare excel Object variable
    Dim WrkSht      As Worksheet
    Dim Chrt        As ChartObject
    Dim Cht_Sht     As Chart
    Dim wkBk        As Workbook
    
    
    'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False
    
        'Set the link to the location where the excel evaluation sheet is located, include file name in the link
   Const Utvärdering As String = "C:\Users\A561004\OneDrive - AF\Desktop\Test\Utvärdering.xlsx"
    
        'Open Excel Utvärdering...
    Application.StatusBar = "Utvärdering"
    Set wkBk = Workbooks.Open(Utvärdering)
    
        ' Select sheet based on name
    Sheets(1).Select
         
            
        'Create a new instance of Word
    Set WordApp = New Word.Application
        WordApp.Visible = True
        WordApp.Activate
        
        
        'Create a new word document
    Set WordDoc = WordApp.Documents.Add
            
            
        'Start a loop
        For Each WrkSht In Sheets
        'WrkSht.ChartObjects.Select
        
       If ActiveSheet.ChartObjects.Count > 0 Then
        
        For Each Cht_Sht In wkBk.Sheets(1).ChartObjects
            Cht_Sht.ChartArea.ChartArea.Copy
        
        'ActiveChart.ChartArea.Select
        'ActiveChart.ChartArea.Copy
        
            With Word.Application.Selection
       .PasteSpecial Link:=False, DataType:=15
       
           WordApp.ActiveDocument.Selections.Add
        'Go to new page
    WordApp.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext
        'Clear Clipboard
    Application.CutCopyMode = False
       
     End With
     
     Next Cht_Sht
    
        
    Else
        WrkSht.Next.Activate
    End If
        
        'Test loop
        'For each Cht_Sht in 2 To Sheets(ActiveWorkbook.Sheets.Count - 1)
        
     
    
        'Create a Reference to the chart you want to Export
    'ActiveChart.ChartArea.Select
    'On Error Resume Next
    'ActiveChart.ChartArea.Copy
    
    
    
        
        'Paus application 2 sek
    Application.Wait Now + #12:00:02 AM#
        
        
        'Paste into WOrd Document
    'With Word.Application.Selection
     '  .PasteSpecial Link:=False, DataType:=15
       
    ' End With
    
        'New word page Problems here, need to set a new marker in the document for next paste
   ' WordApp.ActiveDocument.Selections.Add
        'Go to new page
  '  WordApp.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext
        'Clear Clipboard
  ' Application.CutCopyMode = False
    
        'End loop, or start next rotation of loop
        Next WrkSht
        
        'Optimise Code
    Application.EnableEvents = True
    
    On Error GoTo 0
    
End Sub

I'm sorry if it is a bit messy.

Is there a way to simplify this code which aims to return an absolute value given an integer?

Is there a way to simplify this piece of code further? The codes aim is to return an absolute value given an integer.

public class Abs {
public static int abs(int x) {
if(x < 0) { return -x; }
if(x >= 0) { return x; }
assert false;
return 0;
}
}

Solving the Colebrook Equation Iteratively inside and If statement with excel

I am trying to solve the Colebrook equation iteratively in excel in an if statement.

Here is my if statement so far, but I'm not sure how to implement the iterative calculation with the coding in excel.

A1 = 2500
A2 = IF(A1<2300,64/A1,"")

The value of A1 is the Reynolds number, which would make the if statement go to the false side of the calculation.

Here is the colebrook equation.

Colebrook

B2 = 7.00E-05
C2 = 7.94E-04

B2 is the roughness epsilon, and C2 is the diameter D.

Normally I could just do the following iteration technique in the cell A2

A2 = 64/A1 % initial guess, this is for the laminar case but I need the turbulent value for Re > 2300
A3 = 1/(-2*LOG10((B2/C2)/3.7 + 2.51/(A1*SQRT(A2))))^2

and then just set A2 = A3 with the iteration feature turned on with max iterations 100, and max change 0.001. But I'm not sure how to implement this in an if statement since I have other Re values less than 2300 where f = 64/Re. Is there a way to use the iteration technique similar to this but in an if statement.

How to make a condition if is a number in r?

I wanna make a condition in R like, if in a dataframe a value isn't a number change that value for NA, but if is a number let it like the original value. Someone knows how can I do this?

Thanks.

Dealing with NAs in a loop

I have a loop that is checking to see if the each Zipcode[ i ] equals Zipcode[ j ] where there are some NAs for entries of Zipcode[ j ]. I just need the dummy variable for Urban to take a 1 if Zipcode[ j ] is a match for any of the Zipcodes in list urbanZips.

I've tried

for(i in 1:end){
  for(j in 1:end_1){
    if(urbanZips[i]==data_individual$Zipcode[j]) data_individual$Urban=1
}

}

And I've also tried

for(i in 1:end){
  for(j in 1:end_1){
    if(urbanZips[i]==data_individual$Zipcode[j]){
        data_individual$Urban[j]=1
    } else {
        data_individual$Urban[j]=0
    }
}

}

And for both I'm getting Error in if (urbanZips[i] == data_individual$Zipcode[j]) data_individual$Urban = 1: missing value where TRUE/FALSE needed

I know there are NAs but there are also probably some missing values as well. There are close to a million observations.

Checking if any word in a string appears in a list using python

I have a pandas dataframe that contains a column of several thousands of comments. I would like to iterate through every row in the column, check to see if the comment contains any word found in a list of words I've created, and if the comment contains a word from my list I want to label it as such in a separate column. This is what I have so far in my code:

retirement_words_list = ['match','matching','401k','retirement','retire','rsu','rrsp']

def word_checker(row):
    for sentence in df['comments']: 
        if any(word in re.findall(r'\w+', sentence.lower()) for word in retirement_words_list):
            return '401k/Retirement'
        else:
            return 'Other'

df['topic'] = df.apply(word_checker,axis=1)    

The code is labeling every single comment in my dataframe as 'Other' even though I have double-checked that many comments contain one or several of the words from my list. Any ideas for how I may correct my code? I'd greatly appreciate your help.

Count How Many Times to Run ARIMA(1, 0, 0) Until ARIMA(1, 0, 0) is Truly Obtained

I oftentimes run arima.sim() only to check through auto.arima() that the order I simulated for was not obtained.

I want to write a function to count how many times an arima.sim() is run before the simulated order is confirmed through auto.arima() function.

The algorithm of the function will be as follows:

  1. Set counter to cnt <- 0

  2. Run x <- arima.sim(n=60, model = list(ar=0.6, order = c(1, 0, 0)), sd = 1)

  3. Test if the order of x is (1, 0, 0)

  4. If x order is (1, 0, 0) stop and make cnt + 1; if otherwise make cnt + 1 and return to step 2.

  5. Print cnt

Here is my attempt

library(forecast)
y <- c()
x <- arimaorder(auto.arima(arima.sim(n=60, model = list(ar=0.6, order = c(1, 0, 0)), sd = 1)))
cnt <- 0
while (x == c(1, 0, 0)) 
{
  y<-if(all(x[!x %in% y])) # My mistake could be here
    cnt<-cnt + 1
}
cnt

Flagging Lines Below HHMM Threshold SAS IF/THEN Data Statement

I have a dataset where I calculated the number of total hours it took to process a request in hours. A request should be completed in 72 hours, or else if an extension is requested a request should be completed in 408 hours (14 days plus 72 hours).

I need to flag values with a Y or N depending if they meet these criteria.

My problem is that it is only recognizing negative HHMM values as below threshold, not a value like 29:15 which would represent 29 hours 15 minutes. This is less than 72 hours and should be marked "Y" indicating it is timely, but it is marking it "N".

This is what I tried so far:


data work.tbl_6;
set work.tbl_6;

if was_a_timeframe_extension_taken_ = "N" and time_to_notification <= 72 then notification_timely="Y";
else if was_a_timeframe_extension_taken_ = "Y" and time_to_notification <= 408 then notification_timely="Y";
else notification_timely="N";

run;

Can someone advise what could be going wrong here?

Same code, 2 different outputs? (Pycharm vs Hackerrank)

https://www.hackerrank.com/challenges/py-if-else/problem

Given an integer, n, perform the following conditional actions:

  • If n is odd, print Weird
  • If n is even and in the inclusive range of 2 to 5, print Not Weird
  • If n is even and in the inclusive range of 6 to 20, print Weird
  • If n is even and greater than 20, print Not Weird

When I try to solve the problem above, if I define "n" as 24 for example, Hacker rank says it's wrong because it should output "Not Weird" instead of "Weird".

But when I run it in PYCHARM, the output is "Not Weird".

I have changed the PYTHON version to PYTHON3 in Hacker rank, so, that shouldn't be a problem.

Here's my code:

n = 24

if n % 2 == 1:
    print("Weird")
elif n % 2 == 0 and n in range(2, 5):
    print("Not Weird")
elif n % 2 == 0 and n in range(6, 20):
    print("Weird")
else:
    print("Not Weird")

Which Python Code is better for the same solution? If.. Else statements

I am learning pythong at the moment and I have written a quite simple code. But the solution provided is different. Both codes are giving me the same result. I just want to understand which code is better or more efficient and why?

Thank you

## Write a Python program to add two objects if both objects are an integer type

def itg (x,y):
    sum = x + y
    if type(x) is int and type(y) is int:
        return sum
    else:
        return "The values must be intergers"

print (itg(4.22,4))


## Other way:

def add_numbers(a, b):
    if not (isinstance(a, int) and isinstance(b, int)):
         raise TypeError("Inputs must be integers")
    return a + b

print(add_numbers(10, 20))

I am new to R language , i want to know how to convert or equivalent formula of COUNTIFS in R?

I have around 6035 rows in excel applying the formula in excel i.e =IF(F3="",0,COUNTIFS(A:A,A3,E:E,F3)) make it the results time consuming. So, started learning R and but now unable to write the excel formulae equivalent in R. Please Help! Attaching image of excel

React native calling a function from a conditional statement inside onPress

I have the following code but it does not work

The first part is working fine and zi get the alert but the second one ia not

<Button onPress={ 

     if (this.state.value===""){ alert("try again"); } else { this.functionToBeCalled }

}

Conditional jumps in assembler always give same result

I'm trying to get into assembler and I'm reading through a document that gives a short introduction. There is a task to convert the following code to pure assembler code:

mov bx, 30
if (bx <= 4) {
    mov al , ’A’
} else if (bx < 40) {
    mov al, ’B’
} else {
    mov al, ’C’
}
mov ah, 0x0e
int 0x10 ; print the character in al
jmp $
; Padding and magic number.
times 510-($-$$) db 0
dw 0xaa55

I created this assembler code:

mov bx, 30

cmp bx, 4
jle if_branch
cmp bx, 40
jl elif_branch
mov al, 'C'

if_branch:
    mov al, 'A'
elif_branch:
    mov al, 'B'

mov ah, 0x0e
int 0x10

jmp $

times 510-($-$$) db 0
dw 0xaa55

However no matter what I put into bx in line 1 the output will always be 'B'. What am I missing there?

My setup: I'm writing the assembler code in codeblocks and use nasm to create a bin file. Then I execute that bin file using qemu.

Allowing program to covert repeating string to number in a guess game program

Question is, when the answer is a repeating number, eg 9 + 3 = 11 when transformed to text lets say a = 9, b = 3 , c = 1 hence it is a + b = cc. In my if statement, how to let the program acknowledge and convert both c to 1 when one correct guess for c was made?

you can see in the photo of the output where 1 correct guess was made for e but only one e was converted to the number. enter image description here

Another question if my def display(), what is the difference if I were to change all the other if statements after my first if statement to elif and deleting the indent to align to my first if statement. I initially did that but I couldn't get the desired output where the program revels the answer eventho I keyed in the wrong answer. I am really learning here, so it was all trial and error tbh i don't really understand what I was doing with the elif statements.

def getLetterMap():
    stringList = list("abcdefghij")
    shuffle(stringList)
    return "".join(stringList)


def display(letter, num1, num2, rsltTens, rsltOnes, drsltTens, drsltOnes, dnum1, dnum2):
    if dnum1 == -1 and dnum2 == -1 and drsltTens == -1 and drsltOnes == -1:
        print(" ", num1)
        print("+", num2)
        print("----")
        print(rsltTens, rsltOnes)
        print("----")

    if dnum1 == -1:
        print(" ", letter[num1])
    else:
        print(" ", num1)
    if dnum2 == -1:
        print("+", letter[num2])
    else:
        print("+", num2)
    print("----")

    if drsltTens == -1 and drsltOnes == -1:
        print(letter[rsltTens], letter[rsltOnes])

    elif drsltTens == rsltTens and drsltOnes == -1:
        print(rsltTens, letter[rsltOnes])

    elif drsltTens == -1 and drsltOnes == drsltOnes:
        print(letter[rsltTens], rsltOnes)
    else:
        print(rsltTens, rsltOnes)
    print("----")


def main():
    letter = getLetterMap()
    num1 = letter.find("h")
    num2 = letter.find("j")
    total = num1 + num2
    rsltTens = total // 10
    rsltOnes = total % 10
    drsltTens = -1
    drsltOnes = -1
    dnum1 = -1
    dnum2 = -1
    tries = 0
    while True:
        tries += 1
        display(letter, num1, num2, rsltTens, rsltOnes, drsltTens, drsltOnes, dnum1, dnum2)
        ltr = str(input("Enter a letter: "))
        digit = int(input("Enter a digits: "))
        if letter[digit] == ltr:
            print("You guessed {} for {} correctly. Well done!".format(digit, ltr))
            if ltr == letter[num1]:
                    dnum1 = num1
            elif ltr == letter[num2]:
                    dnum2 = num2
            elif ltr == letter[rsltTens]:
                    drsltTens = rsltTens
            elif ltr == letter[rsltOnes]:
                    drsltOnes = rsltOnes
            elif False:
                print("You got it in {} tries".format(tries))
        else:
            print("({},{}) is not correct. Try again.".format(ltr, digit))


main()