samedi 30 novembre 2019

Manipulate a clocked signal in order to get 10 pulses

I quiete need some help in attempting to create a very specific signal in my code. Basically i need a signal to be generated after load_0 ends, in the falling edge, where such signal would be 10 pulses of the 1KHz signal and the rest 0. Which is just preserving 10 pulses that are aligned with the variable Serial_out.

Thus far i have tried and if to attempt this, with a counter to attempt to count to 10 for the 10 pulses i want and discarding the rest. This always ends either not being able to be synthesized due to error or the test bench clk_trig never being initialized.

My coding is quite cruse due to the fact that i have been using xilinx for about 2 weeks now. Any quick help with examples and such would be greatly appreciated as the deadline ks basically in 4 days.

FPGA2 code running

MIPS code for while loop and if condition

How would I convert this code into MIPS instructions?

while(i>0){ 
 if(i>2) {
  A[i] = A[i]+B[k]
 }
 else{
  A[i] = A[i]-B[k]
 }
i--;
}

where i,k are stored in $11,$12 registers and the base address of A and B are stored in $15,$16 registers .

Issue displaying text if between two integers

Still trying to learn PHP, and I'm making a digital display for a homebrew bar setup I have and have a bit of code that should reading a CSV containing 5 beers, and spitting out the data for each beer. I have no issues parsing the CSV, displaying the strings and integers using echo, but when I tried to use an if statement, it starts spitting out the code as text

Here's my snippet of code:

        <? if ($ibu['Beer1'] >= 1 && $ibu['Beer1'] <= 25):?>        
    Slightly bitter
    <? elseif ($ibu['Beer1'] >= 26 && $ibu['Beer1'] <= 50) :?>
    Kind of bitter
    <? elseif ($ibu['Beer1'] >= 51) :?>
    Very bitter
    <? endif;?>

What I get when I load the page is this:

= 1 && $ibu['Beer1'] <=25):?> slightly bitter= 26 && $ibu['Beer1']<=50:?>Kind ofbitter=51):?>Very bitter

So it seems to be reading the "if" and "elseif" but spitting out everything else as text. As I said, I'm still teaching myself so I'm not entirely sure what could be causing it.

How do I program the following contingency? C#

I have an array with names of Pets and another parallel array with the names of the sounds they make. I'm writing a method ShowSounds which asks user for an animal name, and then displays the respective sound. How do I code in an error message that says "Sorry that animal isn't in our list" if the user enters something random? The problem I have right now is that with the if statement it displays the error message 4 times even if I enter the correct animal.

public static void ShowSound(string userInput2, string[] localPets4, string[] localSounds2)
        {
            for (int l = 0; l < localPets4.Length; l++)
            {
                if (userInput2 == localPets4[l])
                {
                    Console.WriteLine("{0} makes the sound {1}", localPets4[l], localSounds2[l]);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine("Sorry that item isn't in our list of animals");
                }

            }
        }

Python (2.7) - Simple IF THEN logic considering multiple fields

Attempting to perform something I can do in 5 second in Excel in Python and I'm finding myself very frustrated.

I have data that looks like this:

        HomeTeam AwayTeam  HomeScore  AwayScore  TotalScore
0        OAK      LAC         26         24          50
1        CHI      DET         20         13          33
2        CIN      BAL         13         49          62
3        CLE      BUF         19         16          35
4         NO      ATL          9         26          35

I want to create a NEW COLUMN in the data frame called "WINNER". If HomeScore > AwayScore, I want the new column WINNER to equal the HomeTeam value, ELSE, equal the AwayTeam value. For example,WINNER should = OAK on row 0 and CHI on row 1.

this is what I have attempted so far, but this did not give me the results needed above.

I know this is simple! Please help

#new df
df1 = df[['HomeTeam','AwayTeam','HomeScore','AwayScore','TotalScore']]

df1['winner'] = lambda x : df['HomeTeam'] if (df['HomeScore'] > df['AwayScore']) else df['AwayTeam']

print(df1.head())

statement that executing code over and over

I do not know how to do code that is executing over and over again. I would like to achieve something like this: (< stands for input, > stands for output)

message=input()
print('Write down the text.')
>Write down the text.
<qwerty
>qwerty
>Write down the text.
<asd
>asd

Print only negative numbers and its sum aplaying loops and arrays

I need help with a program, I have to use a loop to output all negative integers and their sum. I should use just basic method.

Negative integers: -2, -1, -7 <----//No comma at the end.

Sum negative nums: -10

When I run my program the last integers has an additional comma at the end, I can’t take it out with “if (i != array.length-1)” because the last element in my array is positive but the loop analyze that there is a empty element. How I can remove that comma in a logical way. The result have to be print inside a loop separate by comma space: (", ").

function negativeArray(array)
    {
        document.write("Negative integers: ")
        for (var i = 0, count = 0; i < array.length; i++) 
        {
            if (array[i] != undefined && array[i] < 0){
                    document.write(array[i]);
                    count += array[i];
                    if (i != array.length-1) document.write(", ")}
        }
            document.write( "<br>Sum negative nums: " + count)
    }
        var items = [1, -2, 3, 4 -5, 6, -7, 8];
        negativeArray(items);

Array Formula to Check for Blanks

I have a google sheet with customer orders on.

Column A contains the order number

The next four columns contain various data, filled at various stages of the order. (Columns B through E)

In Column F I'd like to have an array formula that checks when the orders are complete, i.e. each column in a row is filled in, for all rows that contain an order number.

Therefore, if A2:E2 are all filled with data, then in F2 it should state "Complete".

I've tried:

COUNTA
ISBLANK
AND
OR
COUNTBLANK

All formula work on a row by row basis, but not when entered in an arrayformula.

=ArrayFormula(if(and(LEN(A2:A),COUNTA($B2:E)=0)="True","Complete","There be blanks afoot")

Or

=ArrayFormula(If(LEN(A3:A),IF(COUNTBLANK($B2:$E)>0,"Blanks","No Blanks"),""))

Test sheet can be found here: https://docs.google.com/spreadsheets/d/1mNIGRh910k_q9J2P6mzv9q-h-me3zxbCWeJ2mcaFsXQ/edit?usp=sharing

Any help appreciated.

How to stop code from continuing onto particular section once IF statement has been fullfilled?

I have multiple IF statements, that I want execute but once the logic for any of the IF statements has been fulfilled I want the code to skip over a particular section that is not included in any of the IF` statements.

How do I do this?

How code is setup currently:

 if 1 in df.index:
        if df.col1.isnull()[1] or (df.col1[1]==''):
           [rest of the code]

    if 2 in df.index:
        if df.col1.isnull()[2] or (df.col1[2]==''):
           [rest of the code]

    if 3 in df.index:
        if df.col1.isnull()[3] or (df.col1[3]==''):
           [rest of the code]


[code I want to skip once any of the IF statements have been fulfilled]

[code I need to run regardless]

For loop stops at first iteration [Arduino]

My code stops at the first iteration for the phot_val "for" statement.

void loop() {
  double sound = MIC();                            //Declare variable for obtaining microphone data
  double phot_val;
  int nreadings = 100;
  int song1[N]={CN4, DN4, EN4, FN4, GN4, AN4, BN4, CN5};
  int song2[M]= {RT0, RT0, CN4, DN4, CN4, FN4, EN4, RT0,CN4, DN4, CN4, GN4, FN4, RT0, CN4, CN5, AN4, FN4, EN4,DN4, RT0, AS4, AN4, FN4, GN4, FN4, RT0, RT0};
  phot_val = read_analogn(2,nreadings);
Serial.print("Sound: ");Serial.println(sound);    //Testing purposes, Print out sound/mic value
Serial.print("Light: ");Serial.println(phot_val,5);//Testing purposes, Print out light sensor data

  if(phot_val >= .5){play_song(song1,N);} //Stops after first 100???

/// Else If statements to change RBG colors depending on sound 
 if(MIC() >= 30){ setColor(255, 0, 0); }                        //Red Color
 else if(MIC() >= 35){setColor(0, 255, 0);}                     //Green Color
  else if(MIC() >= 40){setColor(0, 0 , 255);}                   //Blue Color
    else if(MIC() >=25){setColor(255, 255, 255);}               //White Color
      else if(MIC() >=25){setColor(170, 0, 255);}               //White Color
 else {setColor(0, 0, 0);}

}

I can post more code if needed, but I have no Idea why it stops

if statement returns false, while it is true

I have (>)as input

color = ['grey', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
nickcolor = input()
>red
nickcolor in color
>True

Then I write

if nickcolor in color == True:
    print('You are now logged in ' + nickname + ' !\n Write something in chat!')
else:
    print('Error occured. Please restart.')
>Error occured. Please restart.

Why does in if statement it is a false?

Problem updating arrays inside a for loop and if-else statments

Table8.5 trying to implement this table in python.

To obtain the following results: enter image description here

I am currently printing up to the 7th step, then the program ceases to update correctly. Almost there.

I am suspecting the bug to be either with the placement of the global arrays or if-else indentation.

Please help if you could point out the problem and explain how I can avoid it in the future. Thanks

here is the link for more details if needed:https://rodolfoferro.wordpress.com/2017/02/24/nelder-mead-method/.

B=[1.2, 0] #Initial starting points. 
G=[0, 0.8]
W=[0 ,0]

# M(B,G)
def Mid(X,Y):
    z=[(X[0]+Y[0])/2.,(X[1]+Y[1])/2.]
    return z
# R(M,W)
def Ref(X,Y):
    z=[2*X[0]-Y[0],2*X[1]-Y[1]]
    return z
#E(R,M)
def Exp(X,Y):
    z=[2*X[0]-Y[0],2*X[1]-Y[1]]
    return z

def fun(z):
    x=z[0]
    y=z[1]
    f= x**2-4*x+y**2-y-x*y
    return f
#C= Cont(W,M)
def Cont(X,Y):
    z=[(X[0]+Y[0])/2.,(X[1]+Y[1])/2.]
    return z
#S= Stre(W,B)
def Stre(X,Y):
    z=[(X[0]+Y[0])/2.,(X[1]+Y[1])/2.]
    return z




#E= Exp(R,M)
#C= Cont(W,M)
#S= Stre(W,B)
#M= Mid(B,G)
#R=Ref(M,W)



for i in range(0,8):
    Points=sorted([[B,fun(B)],[G,fun(G)],[W,fun(W)]],key=lambda x:x[1])
    B=Points[0][0]
    G=Points[1][0]
    W=Points[2][0]
    M= Mid(B,G)
    R=Ref(M,W)
    C= Cont(W,M)
    S= Stre(W,B)
    E= Exp(R,M)


    if fun(R) < fun(G):
        #Case I
        #print(" {:^20}   \t {:^20}   \t {:^20}".format(fun(B), fun(G), fun(W)))
        if fun(B) < fun(R):
            W=R


        else:
            if fun(E) < fun(B):
                W=E


            else:

                W=R


    if fun(R) < fun(W):
        W=R
        if fun(C) < fun(W):
            W=C
        else:
            W=S
            G=M



    print(Points)

Is there a way to match two different data frames for multiple columns

I want to make a link between columns by the condition. I have two data frames as follows:

df1<-read.table(text=" gol
4
7
6
9
",header=TRUE)

and the second df is :

df2<-read.table(text=" cost1     cost2   cost3   cost4
7       9       5       13
3       12      4       14
9       13      3       11
5       6       2       13
4       3       5       12
8       16      6       9
9       11      2       9
6       14      11      12
5       10      14      6
2       9       4       12

",header=TRUE)

The condition is, for example, in df2, cost1, if the value is greater or equal to 4 in df1, it gets "y" else it gets "n". in Cost 2 if the value greater or equal to 7 in df1, it gets "y" else it gets "n" and so on. Please assume I have more than four columns.

The outcome would be as follows:

output<-read.table(text=" cost1  cost2   cost3   cost4   out1    out2    out3    out4
7       9       5       13      y       y       n       y
                   3    12      4       14      n       y       n       y
                   9    13      3       11      y       y       n       y
                   5    6       2       13      y       n       n       y
                   4    3       5       12      y       n       n       y
                   8    16      6       9       y       y       y       y
                   9    11      2       9       y       y       n       y
                   6    14      11      12      y       y       y       y
                   5    10      14      6       y       y       y       n
                   2    9       4       12      n       y       n       y
                   ",header=TRUE)

I just now I need to do it using ifelse, but I struggled to do it for this example. Your help very miuch appriciated.

If statement with radio buttons jquery

I need some help With my work. I need to have a 2 radio buttons select different pictures that will be added when i click a button. How can i, with Jquery create the if statement?

Showing an equality of a name java

I have got a problem. I want to write down a method, which returns me the name "name" of an object in the class Account, if there is an object with this name. If there is no name which equals the name "name" it should return a null.

Got anyone an idea, beacause I tried the way over "equals" and with "instanceof" but none worked...

   public Account getAccount(String name) {

    }

Understanding and adding to if statement

I parse a text (HTML) file for the first GCcode. I have this if sentence that works:

$wp = if($html | %{$x -match '\b((GC)[A-Z0-9]+)'}){$matches[1]}

The problem is that some time the first value that matches is "gcCode" which is not a valid value. How do I make it search on if the result is "gcCode"

Select in if-Statement

I am writing a simple calculator where the result depends on what selector has been chosen and the issue is that it doesn't work because code stops in seconde if statement. I checked the if statement a few times and it has true on the exit иге I'm new in coding and I don't know can I put the callback function into the If-statement or not and perhaps that is why It doesn't work.

<strike><div class="section"> 
    <div class="container">
      <div class="row justify-content-center">
        <div class="col-md-8 text-center">
          <h2 class="mb-4 section-title">Calculator</h2>
        </div>
        <div class="calculator">
          <div class="stri area">
            <div class="stri_text area_text">Type of material</div>
            <div class="stri_input area_input"><select><option value="matt">Matt</option><option value="glossy">Glossy</option><option value="satin">Satin</option><option value="Тканевый">Тканевый</option></select></div>  
          </div>
          <div class="stri material">
            <div class="stri_text material_text">Area of a ceiling</div>
            <div class="stri_input material_input"><input class="expenses-item"></div>  
          </div>
          <div class="stri angles">
            <div class="stri_text anglesl_text">Number of corners</div>
            <div class="stri_input angles_input"><input class="expenses-item"></div>  
          </div>
          <div class="stri chandelier">
            <div class="stri_text chandelier_text">Number chandeliers</div>
            <div class="stri_input chandelier_input"><input class="expenses-item"></div>  
          </div>
          <div class="stri light">
            <div class="stri_text light_text">Number of spotlights</div>
            <div class="stri_input light_input"><input class="expenses-item"></div>  
          </div>
          <div class="stri pipe">
            <div class="stri_text pipe_text">Bypassing of pipes</div>
            <div class="stri_input pipe_input"><input class="expenses-item"></div>  
          </div>
          <div class="result_btn">
            <button class="btn btn-lg">Рассчитать</button>
          </div> 
          <div class="result">
            <div class="stri_text result_text">TOTAL:</div>
            <div class="result_num preserve-whitespace" id="result-item">&nbsp</div>
          </div>
        </div>
      </div>
    </div>
  </div></strike>
    'use strict';

    let selectSelector = document.getElementsByTagName('select'),
        optionsSelector = document.getElementsByTagName('option'),
        expensesItem = document.getElementsByClassName('expenses-item'),
        resultItem = document.getElementById('result-item'),
        expensesBtn = document.getElementsByTagName('button')[1]; 

    let sum;


    expensesBtn.addEventListener('click', function () {
        if (isNaN(expensesItem[0].value) || isNaN(expensesItem[1].value) || isNaN(expensesItem[2].value) || isNaN(expensesItem[3].value) || isNaN(expensesItem[4].value)) {

            resultItem.textContent = "Введите числовые данные ..."; 

            } else if (selectSelector.addEventListener('select', function () {
                optionsSelector[0].value == "mat";
                })) {

                sum = +expensesItem[0].value + +expensesItem[1].value + +expensesItem[2].value + +expensesItem[3].value + +expensesItem[4].value;
                resultItem.textContent = sum;

        }
    });
```````````````````````````````````````````````````````````````````````````````````````````````````

Conditional replacement while match on a variable

I want to replace the NA values for observations within a particular sub-group, but the sequence of the observations in that group is not ordered properly. So I am wondering if there exists some dplyr or plyr command that would allow me to replace missing values in a column belonging to one dataframe using the values from the same column from another dataframe while matching on the values of that "key" column.

Here's what I got. Hope someone could shed light on this. Thanks.

## data frame that contains missing values in "diff" column

df <- data.frame(type = c(1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3), 
diff = c(0.1, 0.3, NA, NA, NA, NA, NA, 0.2, 0.7, NA, 0.5, NA), 
name = c("A", "B", "C", "D", "E", "A", "B", "C", "F", "A", "B", "C"))

## replace with values from this smaller data frame

df2 <- data.frame(diff_rep = c(0.3, 0.2, 0.4), name = c("A", "B", "C"))

## replace using ifelse
df$diff <- ifelse(is.na(df$diff) & (df$type == 2), df2$diff_rep , df$diff)

df

   type diff name
1     1  0.1    A
2     1  0.3    B
3     1   NA    C
4     2  0.3    D
5     2  0.2    E
6     2  0.4    A
7     2  0.3    B
8     2  0.2    C
9     2  0.7    F
10    3   NA    A
11    3  0.5    B
12    3   NA    C

## desired output

   type diff name
1     1  0.1    A
2     1  0.3    B
3     1   NA    C
4     2   NA    D
5     2   NA    E
6     2  0.3    A
7     2  0.2    B
8     2  0.4    C
9     2   NA    F
10    3   NA    A
11    3  0.5    B
12    3   NA    C

Adding three cells if a cell has a value, and if it doesn't, adding two

So basically here's what I want to do:

I need to add cells B12 and C12 normally, however -

If cell C3 has a certain text value (let's say "Apples"), I need to add B12, C12, and K3.

But if C3 -isn't- Apples, it should just add B12 and C12.

Additionally, I have two versions of Apples: "Apples - Red" and "Apples - Green". Maybe an Apples wildcard?

Python Code that returns true while key is pressed down false if release?

I need a code in python that returns an if statement to be true if a key is pressed and held down and false if it is released. I would like this code to be able to be executed whenever the key is pressed and held down.

Conditional Formula: display text if cell contains

I want to change the display text in a cell if the cell contains a keyword. For example, I have a column with many similar text strings:

Christmas Tree - School A
Christmas Tree - School B
Christmas Tree - School C

In the above example, I would want the cell to simply display "Christmas Tree"

I can't work the customer formula in conditional formatting to achieve this. Possible?

vendredi 29 novembre 2019

Compare UIColor to Text Label/String [SWIFT]

How can I test to see if the textColor of a label (meaningLabel) matches the name of the color in another label (textColorLabel)?

ex: (red color appears on screen) == "RED" (appears on label) --> score += 1 (blue color appears on screen) == "BLUE" (appears on label) --> "boo -- no match"

Here is my attempt:

    func updateScore() {
        if meaningLabel.textColor == textColorLabel.textColor{
            print("yay -- match")
            score += 1
            scoreLabel.text = String(score)
        } else {
            print("boo -- no match")
        }
    }

Position of 'if' in statement

is there a difference between:

  1. if x > 0: print x
  2. print x if x > 0

Is the 2nd option preferred when the if statement is embedded in other code? If not in what are the situations where one is preferred over the other?

condense if, else JS with similar condition rules

trying to find a way to condense this. wasnt sure of the best way to do it. basically if criteria is met i display an alert with a parameter that is the message. i was thinking of maybe trying it in function. this is part of a larger function react component. i was also thinking if i could find a way to condense the else if's i could use a ternary. thanks in advance for the assistance.

if (!isDifferent) {
    Alert.alert(different);
  } else if (!passwordsMatch) {
    Alert.alert(noMatch);
  } else if (!meetsPasswordRequirements) {
    Alert.alert(pasReqs);
  } else if (usesName || usesUserID) {
    Alert.alert(pasName);
  }
} else {
  Alert.alert(fieldNotComplete);
}

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

I have a columns of data that have percentages, such as 5.76%, 4.2%, or 2.34%, and the the word Free. I want to create another column for each of those columns that has a 0 for free and converts the percentages into an integer/fraction, such as 0.0576, 0.042, and 0.0234.

I have created the following function:

def ad_val_rate(data):
if data['2021'] == 'Free':
    return 0
else:
    return data['2021'].str.rstrip('%').astype('float') / 100.0

When I use this function, I get the following error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Other similar stackoverflow questions seem to indicate the issue is because of more than one condition, but I am just using one condition.

Referencing a cell as the Value to use in an IFS statement in Google Sheets

I'm using an IFS statement to decide what a cell should use as a value dependant on what is entered into the cell. Which is fine, except that I have to hard code it into every cell that uses it as an equation. I need to have the Value1, Value2 etc be whatever is in another cell. That way I can update one cell and have it cascade.

=IFS(C34=<100, "$10", C34=500, "$5", C34=1000, "$2") I need the "$10" to be a value of another cell, ie B28

I've tried !B28 , $B28, =(B28) and every other thing I could think of. I can't find anything online in Googles documentation.

How to move along a 2d grid in python?

Stumbled upon an interesting question which i'm not sure how to approach. I have to make a function which takes in a set of moves such as L = left, R = right and F = forward, and moves the point on the 2D grid which is sitting at (0,0) pointing up. For example, given the string 'RFLFR', (1,1) would be returned since it is sitting on that point on the grid now, pointing to the right.

Does input nextLine return String in JAVA? the problem is in following: [duplicate]

This question already has an answer here:

Code sample:

Scanner input = new Scanner(System.in);
System.out.print("Input Language: ");
String language = input.nextLine();

if (language == "en") {  
    System.out.println("en");
}

The problem is if statement never gets checked and I don't understand why Can anybody help the beginner programmer? Thanks

How to store the value in mysql database in inside If else statement ? whether it is possible or not?

I have stuck with this concept for the past 2 days, Please help me with this. Thanks in Advance. Let me explain my concepts.

I have attached 2 JSP files along with this, It was to convert the marks into IELTS score. For EX: I have to enter the score like (Listening: 30, Reading: 25, Writing: 31, Speaking:18 ) It want to convert and store into IELTS score in SQL Database like EX:(Listening: 6.5, Reading: 7, Writing:5.8, Speaking: 8). I can able to convert and display the value but I don't know how to store this score into MySQL Database.

Here is my Code :

User.jsp

<html>
<head>
<meta charset="ISO-8859-1">
<title>Enter the value</title>
</head>
<body>
<form method="post" action="convert.jsp">
Enter Mark for Listen (0 to 40): <input type="text" name="score">
<input type="submit" value="submit">
</form>
</body>
</html>

And this convert.jsp will convert the marks into grade.

Convert.jsp

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <%
    String ints=request.getParameter("score");
     double s=Integer.parseInt(ints);
    double band ;

    if(s>=0 && s<=3) {
        band=0;
        out.print(band);


      } else  if(s>=4 && s<=5) { band=2.5; out.print(band); }

        else  if(s>=6 && s<=7) { band=3; out.print(band); } 

        else  if(s>=8 && s<=10) { band=3.5; out.print(band);}

        else  if(s>=10 && s<=12) { band=4; out.print(band);}

        else  if(s>=13 && s<=15) { band=4.5; out.print(band);} 

        else  if(s>=16 && s<=17) { band=5; out.print(band);}

        else  if(s>=18 && s<=22) { band=5.5; out.print(band);}

        else  if(s>=23 && s<=25) { band=6; out.print(band);}

        else  if(s>=26 && s<=29) { band=6.5; out.print(band);}

        else  if(s>=30 && s<=31) { band=7; out.print(band);}

        else  if(s>=32 && s<=34) { band=7.5; out.print(band);}

        else  if(s>=35 && s<=36) { band=8; out.print(band);}

        else  if(s>=37 && s<=38) { band=8.5; out.print(band);}

        else  if(s>=39 && s<=40) { band=9; out.print(band); }



 %>
</body>
</html>

And here is my database Structure.

Table name : score

---------------------------------------------|
|                                            |
|  Listening | Reading | Writing | Speaking  |
|--------------------------------------------|
|            |         |         |           |
|____________________________________________|     

Here I want to store the score according to marks(Listening,Reading,Writing,Speaking). 1. How to convert for all 4 fields . 2. how can i store the converted score into database. Can anyone help me with this, please? Thanks in Advance.

how to render input fields required based on the selection of a select

my intent is to make input and second select fields all required if the value of first select was selected

select:

<select name="AMC_metavalue_tipologia_evento" id="AMC_metavalue_tipologia_evento">
    <option value="" disabled selected>Ingresso Singolo?</option>
    <option value="8" '.selected( $AMC_metakey_tipologia_evento, '8', false ) . '>Orario Custom</option>
    <option value="0" '.selected( $AMC_metakey_tipologia_evento, '0', false ) . '>Annulla orario Custom</option>
</select>

input:

<input type="text" name="AMC_metavalue_primo_orario_prezzo_pista_uomo" value="'.esc_attr( $AMC_metakey_primo_orario_prezzo_pista_uomo ).'"/>        

<input type="text" name="AMC_metavalue_primo_orario_prezzo_pista_donna" value="'.esc_attr( $AMC_metakey_primo_orario_prezzo_pista_donna ).'"/>   

second select:

<select name="AMC_metavalue_cosa_ha_uomo_primo_orario_custom" id="AMC_metavalue_cosa_ha_uomo_primo_orario_custom">
    <option value="" disabled selected>Imposta Cosa ha Uomo</option>
    <option value="Solo Ingresso" '.selected( $AMC_metakey_cosa_ha_uomo_primo_orario_custom, 'Solo Ingresso', false ) . '>Solo Ingresso</option>
    <option value="Ingresso + 1 Cocktail in omaggio" '.selected( $AMC_metakey_cosa_ha_uomo_primo_orario_custom, 'Ingresso + 1 Cocktail in omaggio', false ) . '>Ingresso + 1 Cocktail in omaggio</option>
    <option value="0" '.selected( $AMC_metakey_cosa_ha_uomo_primo_orario_custom, '0', false ) . '>Non Previsto</option>
</select>

when is the appropriate time to use [? and :] instead of if statement?

ok so i've seen [? and :] used in as replacement for some if statements in a lot of code

for example

driftDirec = Input.GetAxis("Horizontal")>0 ? 1: -1;

why not something like

if (driftDirec > 0)
{ do stuff}
else
{do stuff}

or something, can you tell me when is the appropriate time to use those and i don't know what that's called?

Why does lapply(file_list, function(i){} not work?

Why does this not work? Thanks for help. I got this message. Why Error in [.data.frame(true, rep(NA_integer_, length(condition)))

a = 350
b = 250
Track <- lapply(file_list, function(T1) {
  if_else (T1[2] > 0, 
           round(((acos((T1[1]-a)/sqrt(((T1[1]-a)^2)+((T1[2]-b)^2))))
                  *(180/pi)),
                 digits = 0), 
           round(((-acos((T1[1]-a)/sqrt(((T1[1]-a)^2)+((T1[2]-b)^2))))
                  *(180/pi))+360,
                 digits = 0)
  )
})

jeudi 28 novembre 2019

Checking multiple validations using if statement

I'm trying to work on ForgotPassword section, not in advance but normally by checking conditions. Here trying to check if the user input values Username, Mail Id, Usertype are correct otherwise, show error messages such as username or mailid or type doesn't match. But here am failing to show error messages such that the else part isn't working.

controller

public ActionResult Forgotpassword1( FormCollection collection)
        {
                string username = collection["username"];
                string mail = collection["mail"];
                string type = collection["type"].ToString();
                Random rand = new Random();
                var password = rand.Next().ToString();
                var getrandomkey = password.Substring(0, 5);
                var lgn = db.tb_log.Where(ob => (ob.username == username) && (ob.usertype == type)).FirstOrDefault();
                string userid = lgn.username;
                if (lgn != null)
                {
                    if (lgn.usertype == ("User"))
                {
                    Session["username"] = lgn.username;
                    Session["type"] = lgn.usertype;
                    userid = lgn.username;
                    var useraccount = db.tb_reg.Where(i => i.gmail == mail && i.usertype == type && i.username == username).FirstOrDefault();
                    if (useraccount != null)
                    {
                        tb_log login = db.tb_log.Where(i => i.username == username && i.usertype == type).FirstOrDefault();
                        if (login != null)
                        {
                         login.code = getrandomkey;
                            db.tb_log.Add(login);
                            int i = db.SaveChanges();
                            if (i > 0)
                            {
                                ViewBag.s = "Verification Code has been send to your registered mail id";
                            }
                            else
                            {
                                ViewBag.f = "Something went wrong";
                            }
                        }
                        else
                        {
                            ViewBag.f = "Username or type not match";
                        }
                    }
                    else
                    {
                        ViewBag.f = "Username or Mail not match";
                    }}

else value not reurning [duplicate]

This question already has an answer here:

function add(n){
    var arrtemp = n.toString().split('').map((e)=> parseInt(e))
    var temp = arrtemp.reduce((a,b)=> a+b);
    var arrtemp2 = temp.toString().split('').map((e)=> parseInt(e))
    if(arrtemp2.length>1 ){
        add(temp);
    }
    else {
        return (temp);
    }
}

I am trying to add the digits of a number and if the sum is 2 digit then it will again add the digits till the result is single digit. But the else statement is not returning the value.

How can I create functions to reduce redundancy in my code? [JS]

My code is running well but I have repeated myself too much and the code will be too large considering that I have only handled a query for one collection.
I have tried using a function to handle some of the code but it doesn't work as some variables are not accessible globally.
Here is the code

 var markers = [];

        function addMarker(coords, content, animation){

            var marker = new google.maps.Marker({
                position:  coords,

                map: map,
                icon: icon = {
                    url : isBouncing ? red_icon : green_icon,
                    scaledSize: new google.maps.Size(40, 40), // scaled size

                },
                // IF THERE'S AN ERROR, BOUNCE IT
                animation: animation
            });

            var infoWindow = new google.maps.InfoWindow({
                content: content

            });


            marker.addListener('spider_click', function() {
                map.panTo(this.getPosition());
                infoWindow.open(map,marker);
            });
            oms.addMarker(marker); 

            markers.push(marker);
        }



      function clearMarkers() {
        setMapOnAll(null);
      }


      function deleteMarkers() {
        clearMarkers();
        markers = [];

      }



 db.collection('Nairobi').onSnapshot(function(snapshot) {

        snapshot.forEach(function(child){
                var name_loc = child.id;
                var loc = child.data().marker;
                var forward = child.data().ForwardPower;
                var reflected = child.data().ReflectedPower;

                var ups = child.data().UPSError;
                var upsDesc = child.data().UPSDesc;
                var trans = child.data().TransmitterError;
                var transDesc = child.data().TransDesc;
                 var kplc = child.data().KPLC;
                var kplcDesc = child.data().KPLCDesc;
                var sat = child.data().SatelliteReceiver;
                var satDesc = child.data().SatDesc;


                       if(ups === true && trans ===true && sat ===true && kplc ===true){
                        isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<p> UPSError: ${upsDesc} </p>`
                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`
                         +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }   


                  else if(ups === false && trans ===true && sat ===true && kplc ===true){
                        isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`
                         +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                } 



               else if(ups === true && trans ===false && sat ===true && kplc ===true){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<p> UPSError: ${upsDesc} </p>`
                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`


                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }


               else if(ups === false && trans ===false && sat ===false && kplc ===false){
                    isBouncing = false;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },


                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<h2> Running well </h2>` 

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'

                    );
                }


                console.log(child.id, child.data());
            });


                 snapshot.docChanges().forEach((change) => {

                 if (change.type === "modified") {

                    deleteMarkers();
                    snapshot.forEach(function(child){

      /***************************REDUNDANT CODE****************************************/
                var name_loc = child.id;
                var loc = child.data().marker;
                var forward = child.data().ForwardPower;
                var reflected = child.data().ReflectedPower;

                var ups = child.data().UPSError;
                var upsDesc = child.data().UPSDesc;
                var trans = child.data().TransmitterError;
                var transDesc = child.data().TransDesc;
                 var kplc = child.data().KPLC;
                var kplcDesc = child.data().KPLCDesc;
                var sat = child.data().SatelliteReceiver;
                var satDesc = child.data().SatDesc;


                       if(ups === true && trans ===true && sat ===true && kplc ===true){
                        isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"
                        +  `<p> UPSError: ${upsDesc} </p>`
                        +  `<p> SatelliteReceiver: ${satDesc} </p>` 
                        +  `<p> KPLC: ${kplcDesc} </p>`
                         +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }   




                else if(ups === false && trans ===true && sat ===false && kplc ===true){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> KPLC: ${kplcDesc} </p>` 
                        +  `<p> TransmitterError: ${transDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                else if(ups === true && trans ===false && sat ===true && kplc ===false){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                         '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> UPSError: ${upsDesc} </p>` 
                        +  `<p> SatelliteReceiver: ${satDesc} </p>`

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                else  if(ups === true && trans ===false&& sat ===false && kplc ===false){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> UPSError: ${upsDesc} </p>` 

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                else if(ups === false && trans ===true && sat ===false && kplc ===false){
                    isBouncing = true;
                    addMarker(
                        {lat: loc.latitude, lng: loc.longitude },
                        '' +
                        '<div id="iw-container">' +
                        `<div class="iw-title"> ${name_loc}</div>` +
                        '<div class="iw-content">' +
                        "<br/>"

                        +  `<p> TransmitterError: ${transDesc} </p>` 

                        +  '</div>' +
                        '<div class="iw-bottom-gradient"></div>' +
                        '</div>'


                        ,google.maps.Animation.BOUNCE
                    );
                }

                console.log(child.id, child.data());
            });

          }
       });

     })

And also is there a better way to handle those IF Statements to make my code more cleaner.

My if statement prints on every if statement in my while loop regardless if it is false

So i'm making a text adventure game i'm just programming directions. I have a script with north south etc. And then an if statement that says if the user enters something other than a direction it will say that is not a direction and loop to the top but its not working. It will always print That is not a direction even if I enter the right input. Can anyone help?

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



int main()
{
    string input;
    while (input != "north", "n", "south", "s", "east", "e") {
        cout << "Enter a direction" << endl;
        getline(cin, input);
        if (input == "north" || input == "n") {
            cout << "north" << endl;
        }
        if (input == "west" || input == "w") {
            cout << "west" << endl;
        }
        if (input == "east" || input == "e") {
            cout << "east" << endl;
        }
        if (input == "south" || input == "s") {
            cout << "south" << endl;
        }
        if (input != "n", "s", "e", "w")
        {
            cout << "That is not a direction" << endl;
        }
    }
    return 0;
}

If statement depending of Informations

Here is my problem: I have a if statement regrouping multiple conditions eg: if(stat1 & stat2 & stat3 & stat4).

in this condition, I want to compare 4 times 2 numbers.

If the number 1 is negative and the number 2 positive, I want the if statement to be if(num1 >= num2 & ....). If the number 1 is positive and the number 2 is negative, I want the if statement to be if(num1 <= num2 & ...). If the numbers are both positive but number 1 is smaller, I want it to be if(num1 >= num2 & ...)

And I think you get it.

the problem is that i can't just make multiple if statements for every possibilities, since there are something like 8 cases per conditions and 4 conditions. Is there anyway I can adapt my if statement to fit my needs in the script ? (the values number 1 and number 2 are generated randomly)

How do I import data from n number of csv files within a folder?

[PYTHON HELP]

Hello, I would like some help figuring out how to import data from n number of files within a folder. Just as an example, I am currently trying to import the data within the first 3 files from a folder containing 30 files, but so far I have only been able to isolate the first 3 files without actually reading the data. When I try to extract the actual data I get an error stating that the file/directory does not exist.

This is the chunk of code that simply prints the first 3 files which works fine, but once I try to add more code that will actually read the data within the files, that's when I run into errors.

import os, csv
fcm_path = ("my directory")
fcm_files = sorted(os.listdir(fcm_path)) 

def fcm():
    count = 0
    for file in (fcm_files):
        if count < 4:
            if file.endswith('.csv'):
                print ('file: ' + file)
        else:
            break
        count = count + 1 

OUTPUT:

file: 001.csv
file: 002.csv
file: 003.csv

Here I tried being more specific but then I get an error stating that the file doesn't exist

import os, csv
fcm_path = ("my directory")
fcm_files = sorted(os.listdir(fcm_path)) 


def fcm():
    count = 0
    for file in (fcm_files):
        if count < 4:
            if file.endswith('.csv'):
                print ('file: ' + file)
                with open(file, 'r') as csvfile:
                    data = csvfile.read
                    print(data)
        else:
            break
        count = count + 1 

OUTPUT:


 File "<ipython-input-158-1f4c11da5a68>", line 1, in <module>
    fcm()
 File "<ipython-input-157-b977510dbfcd>", line 8, in fcm
    with open(file, 'r') as csvfile:

FileNotFoundError: [Errno 2] No such file or directory: '001.csv'

How to style one array element, different from the rest, in leafelt?

I'm trying to only style one element in an array but I'm uncertain how to write the if statement. I'd like to achieve dates[0] returns a weight of 3 while the remaining elements in the array return a weight of 1. Is this possible?

Function:

var dates=[]
function mostRecent(time) {
    dates.push(time)
    if (dates[0]){
        weight = 3
    } else {
        weight = 1
    }
return weight
}

Style:

 pointToLayer: function(feature, latlng){  // changes default icons to circles and styles accordingly
            return new L.CircleMarker(latlng, {
                radius: circleSize(feature.properties.mag),
                fillColor: getColor(feature.properties.mag),
                color: "#000",
                weight: mostRecent(feature.properties.time),
                opacity: 1,
                fillOpacity: 0.5,
            });

One line condition assignment

The author of the following code stack = root and [root] wrote that it means:

if root:
  stack = root
else:
  stack = None

I have seen the post One line if-condition-assignment and I can understand how it works. But I do not understand how [root] means None. Can anybody explain?

How to detect vowels in a string and if a specific letter is beside a vowel, it is also considered a string?

Working on a function that would detect if there are any vowels in a given string, also checks if the letter "g" is beside the vowels or not. If the letter "g" is beside a vowel, then it will also be considered a vowel. I did post a question similar to this and got an answer that almost works but I got no explanation as to how it was done and no-one replied to my comment asking for clarification.

Here is the function:

    import re


def disemvowel(text):
    result = re.sub(r"G[AEIOU]+|[AEIOU]+G|[AEIOU]+", "", text, flags=re.IGNORECASE)
    print(result)


disemvowel("fragrance")
# frrnc

disemvowel('gargden')
# rgdn

disemvowel('gargdenag')
# rgdn

This function works for most cases except for when the letter 'g' both precedes and exceeds a vowel. For example, it does not work when I input 'gag' it returns 'g' when it isn't supposed to return anything. I just need clarification as to how this function works and what edits I could make to it to have it run properly for all scenarios.

This is my original function that I worked on but it only works for vowels since I could not figure out how to add a condition where it would detect the letter 'g' beside a vowel:

def disemvowel(text):
text = list(text)
new_letters = []
for i in text:
    if i.lower() == "a" or i.lower() == "e" or i.lower() == "i" or i.lower() == "o" or i.lower() == "u":
        pass
    else:
        new_letters.append(i)
print (''.join(new_letters))

disemvowel('fragrance')
# frgrnc

Javascript How to have ("string"+variable) as condition [duplicate]

This question already has an answer here:

i have Multiples arrays like: Cards1, Cards2, Cards3. and i want this if to adapt to the array choosed the var Seed can be 1,2,3

else if (("Cards"+Seed[Nr]) == ("Cards"+Seed[Last])) {
            console.log("kaart " + Nr + " en " + Last + "zijn dezelde")
            Gevonden[Last] = "Found"
            Gevonden[Nr] = "Found"
            Toon(Nr)
            i = 0
        }

my program works if i use (Cards2[Nr]) == (Cards2[Last]) for example but what i want is to use the same if that will adapt to the var Seed to work with the 3 arrays

thx in advance sorry for my bad English i hope it was comprehensible

Handles in programmatically GUI and flags for buttons MATLAB

Hey i've got really annoying problem.

I want to operate some buttons in my programmatically GUI. I want to open port, close port and exit the while loop. I really want to do it outside the buttons callbacks. I mean, that script is in infinite while loop and when i press(in this case) Exit button it changes it own value(flag) for true and this will proceed to the while loop to break it. I can't get how to parse this data with handles or any other way. I want to avoid initializing so much global variables. Is there any way to do it as I said?

Here is the code:

clc;
close all;
clear all;
global s;
s = serial("COM3",'BaudRate',1000000,'Terminator','CR/LF'); %Zmienna dotycząca portu 
fclose(s);
figureHandle = figure('Position',[160,500,260,200]);
h.Open  = uicontrol('Style','pushbutton','String','Open port','Position',[75,120,90,25],...
             'Callback',@Openbutton_Callback);
h.Close = uicontrol('Style','pushbutton','String','Close port','Position',[75,80,90,25],...
             'Callback',@Closebutton_Callback);
h.Exit = uicontrol('Style','pushbutton','String','Exit','Position',[75,40,90,25],...
             'Callback',@Exitbutton_Callback);


while(1)
    if strcmp(s.Status, 'closed')
        disp('port zamkniety');
        pause(0.5)
    else
        disp('port otwartty');
        pause(0.5)
    end
    if handles.exitbtnValue
        handles.exitbtnValue = false;
        exit
    end
end
function Openbutton_Callback(hObject,event) %Funkcja dotycząca otwierania portu
        global s;
    fopen(s);
        s
    end
    function Closebutton_Callback(hObject,event)%Funkcja dotycząca zamykania portu
    global s;
        fclose(s);

    end
    function Exitbutton_Callback(hObject,event)
    handles.exitbtnValue=true;
    guidata(hObject, handles);

    end

using Asterisk in if statment in a bash script

I am trying to find special kinds of files in a directory using "if", however, it seems it does not work. I am pretty sure that the problem has to do with using asterisk. Thanks for any help.

Here is the code.

if [ -f "$IMAGES_DIRECOTRY"/R*.FIT ] ; then echo " exist" fi

Using multiple else if statements in a HTML function

I am a beginning programmer and I am creating my first website. I haver a problem with an else if statement in an function in HTML. The problem is that my website always seems to go for the first else if answer, even if its not true. this is the function:

if ( 600<=regenid<614 ){ var tempcijfer= 1 }
                 else if (gevoelstempc<0.1)  {var tempcijfer = 1}
                 else if (0.1<gevoelstempc<6.5) {var tempcijfer = 2}
                 else if (6.5<gevoelstempc<10.9) {var tempcijfer = 3}
                 else if (10.9<gevoelstempc<12.9) {var tempcijfer = 4}
                 else if (12.9<gevoelstempc<15.9) {var tempcijfer = 5}
                 else if (15.9<gevoelstempc<17.5) {var tempcijfer = 6}
                 else if (17.5<gevoelstempc<19.5) {var tempcijfer = 7}
                 else if (19.5<gevoelstempc<21.1) {var tempcijfer = 8}
                 else if (21.1<gevoelstempc<22.9) {var tempcijfer = 9}
                 else if (22.9<gevoelstempc<25.2) {var tempcijfer = 10}
                 else if (25.2<gevoelstempc<27.9) {var tempcijfer = 9}
                 else if (27.9<gevoelstempc<30.1) {var tempcijfer = 8}
                 else if (30.1<gevoelstempc<32.9) {var tempcijfer = 7}
                 else if (32.9<gevoelstempc<34.9) {var tempcijfer = 6}
                 else if (34.9<gevoelstempc<37.1) {var tempcijfer = 5}
                 else if (37.1<gevoelstempc<39.1) {var tempcijfer = 4}
                 else if (39.1<gevoelstempc<40.5) {var tempcijfer = 3}
                 else if (40.5<gevoelstempc<41.5) {var tempcijfer = 2}
                 else if (gevoelstempc>41,5) {var tempcijfer = 1}

('tempcijfer' always seems to become 1 even if 'gevoelstempc' is bigger than 6.5) How do I solve this?

Excel formula: how do i put a sum of the true concatenation outputs at the end of the string

I'm trying to put a number(the sum of the true concatenations) at the end of my string in excel.

I'm using if statements with concatenate:

=CONCATENATE("";IF(AG$1=31;"LETTERXX, ";"");IF(AG$2=CALENDER!$K$31;"SMS xxxx xxxxxx, ";""))

the output now is:

LETTERXX, SMS xxxx xxxxx,

and the output I want is:

LETTERXX, SMS xxxx xxxxx, 2

can someone please help me with this?

I would be really happy.

How to write php If statement for multiple conditions true (Condition#1=true, Condition#2=true, Condition#3=true)

I have a form with FromDate , ToDate, VendorName and GoodsName, i need to show the result once everything is true(i.e. FromDate="11/20/2019", ToDate="11/28/2019", VendorName="Abdullah" and GoodsName="Wheat"), here is my code

if ( ($vendor_name == $vendor_name) && ($snack_name == $snack_name) &&  ($start_Date == $start_Date)) {
  $sql = "SELECT * FROM t_purchase WHERE from_vendor ='$vendor_name' AND goods_name ='$snack_name' AND date BETWEEN '$start_Date' AND '$end_Date'";
  $result = $con->query($sql);

  if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

     $data = '<tr><td>' .$row["id"]. '</td><td>' .$row["date"]. '</td><td>' .$row["goods_name"]. '</td><td>' .$row["from_vendor"]. '</td><td>' .$row["no_kgs"]. '</td><td>' .$row["rate_of"]. '</td><td>' .$row["bill_rate"]. '</td><td>' .$row["now_paid"]. '</td><td>' .$row["v_balance"]. '</td></tr>';
     echo $data;
    }
  } 
 else {
    echo "0 results";
 }
}

Optimize the 'if' statement(PHP)

I want to optimize the 'if' statement when a variable can meet 2 different values, for example:

if($x==5 || $x == 7)
{
//Do something
}

I feel that maybe it is not necessary to have to write the same variable twice, so I wonder if there is a way to optimize that condition. For something similar to this:

if($x== (5 || 7))
{
 //Do something
}

how to fined the given number is digit or not?

n=5 def digit(n): for i in nu=[0,1,2,3,4,5,6,7,8,9]: if return True else: return False output True

Php syntax for if statement with multiple conditions true

I have a form with FromDate , ToDate, VendorName and GoodsName, i need to show the result once everything is true(i.e. FromDate="11/20/2019", ToDate="11/28/2019", VendorName="Abdullah" and GoodsName="Wheat"), here is my code

if ( ($vendor_name = $vendor_name) && ($snack_name = $snack_name) &&  ($start_Date = $start_Date)) {
  $sql = "SELECT * FROM t_purchase WHERE from_vendor ='$vendor_name' AND goods_name ='$snack_name' AND date BETWEEN '$start_Date' AND '$end_Date'";
  $result = $con->query($sql);

  if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

     $data = '<tr><td>' .$row["id"]. '</td><td>' .$row["date"]. '</td><td>' .$row["goods_name"]. '</td><td>' .$row["from_vendor"]. '</td><td>' .$row["no_kgs"]. '</td><td>' .$row["rate_of"]. '</td><td>' .$row["bill_rate"]. '</td><td>' .$row["now_paid"]. '</td><td>' .$row["v_balance"]. '</td></tr>';
     echo $data;
    }
  } 
 else {
    echo "0 results";
 }
}

How can I make my main program appear first and how can I call my functions in my main program?

Right now I've tried making my main program the main "function" in my code. But when I run it, the analysis bit comes up first which is not what i want. I want to make my code to do the following: output the main program so the user can input the marks total and input the marks scored in a test.

"Write a program that inputs a mark from the keyboard for sections of a project: ‘analysis’, ‘design’, ‘implementation’ and ‘evaluation’. The program should output the total mark, the grade, and how many more marks were needed to get into the next mark band."

That was my task.


    def analysis():
        print("Welcome to the analysis section")
        marktotal=int(input("Input mark total which is out of /100"))
        marks=int(input("Input marks"))
        totalanalysis=print("You got",marks,"/",marktotal)
        if marks > 80 or marks == 80:
            print("A*")
        elif marks > 67 or marks == 67:
            print("A")
        elif marks > 54 or marks == 54:
            print("B")
        elif marks > 41 or marks == 41:
            print("C")
        elif marks > 31 or marks == 31:
            print("D")
        elif marks > 22 or marks == 22:
            print("E")
        elif marks > 13 or marks == 13:
            print("F")
        elif marks > 4 or marks == 4:
            print("G")
        elif marks ==0:
            print("U")
        return
    analysis()

    def design():
        print("Welcome to the design section")
        marktotal=int(input("Input mark total which is out of /100"))
        marks=int(input("Input marks"))
        totalanalysis=print("You got",marks,"/",marktotal)
        return

    design()


    def main():
        selectedsection=str(input("What section would you like to grade?"))#main program starts here
        if selectedsection =="analysis":
                analysis()
        elif selectedsection =="design":
                print("design")
        elif selectedsection =="implementation":
                 print("implementation")
        elif selectedsection =="evaluation":
                print("evaluation")

    if __name__ == "__main__":main()
    ```

I wish to merge categories from a factor variable to reduce the number of levels

I have this dataset bank-full with a variable job summary(bank.full$job) admin. blue-collar entrepreneur housemaid management 5171 9732 1487 1240 9458 retired self-employed services student technician 2264 1579 4154 938 7597 unemployed unknown 1303 288 This is the percent cross tab of the variable with the target variable y no yes admin. 0.88 0.12 blue-collar 0.93 0.07 entrepreneur 0.92 0.08 housemaid 0.92 0.08 management 0.87 0.13 retired 0.83 0.17 self-employed 0.89 0.11 services 0.91 0.09 student 0.72 0.28 technician 0.90 0.10 unemployed 0.84 0.16 unknown 0.89 0.11 Now I wish to merge job categories whose cross tab values are similar I used this two approaches

 bank.full$newjob<-ifelse(c(bank.full$job=='admin.',
+                            bank.full$job=='self-employed',
+                            bank.full$job=='unknown'),'CAT1',
+                   ifelse(c(bank.full$job=='blue-collar',
+                            bank.full$job=='entrepreneur'),'CAT2',
+                   ifelse(c(bank.full$job=='housemaid',
+                            bank.full$job=='services'),'CAT3',
+                   ifelse(c(bank.full$job=='management',
+                            bank.full$job=='unemployed',
+                            bank.full$job=='technician'),'CAT4',
+                   ifelse(bank.full$job=='student','student','retired')))))
Error in `$<-.data.frame`(`*tmp*`, newjob, value = c("CAT4", "retired",  : 
  replacement has 135633 rows, data has 45211

Second Approach

bank.full$newjob<-ifelse(bank.full$job=='admin.','CAT1',
+                   ifelse(bank.full$job=='self-employed','CAT1',
+                   ifelse(bank.full$job=='unknown'),'CAT1',
+                   ifelse(bank.full$job=='blue-collar','CAT2',
+                   ifelse(bank.full$job=='entrepreneur','CAT2',
+                   ifelse(bank.full$job=='housemaid','CAT3',
+                   ifelse(bank.full$job=='services','CAT3',
+                   ifelse(bank.full$job=='management','CAT4',
+                   ifelse(bank.full$job=='unemployed','CAT4',
+                   ifelse(bank.full$job=='technician','CAT4',"")))))))))
Error in ifelse(bank.full$job == "self-employed", "CAT1", ifelse(bank.full$job ==  : 
  unused arguments ("CAT1", ifelse(bank.full$job == "blue-collar", "CAT2", ifelse(bank.full$job == 
"entrepreneur", "CAT2", ifelse(bank.full$job == "housemaid", "CAT3", ifelse(bank.full$job == "services", "CAT3", ifelse(bank.full$job == "management", "CAT4", ifelse(bank.full$job == "unemployed", "CAT4",
 ifelse(bank.full$job == "technician", "CAT4", ""))))))))

I was able to get an output till this level but when i inserted all the if conditions it's giving me a an error

bank.full$newjob<-ifelse(bank.full$job=='admin.','CAT1',
+                          ifelse(bank.full$job=='self-employed','CAT1',
+                                 ifelse(bank.full$job=='unknown','CAT1',
+ ifelse(c(bank.full$job=='blue-collar',bank.full$job=='entrepreneur'),'CAT2',""))))
> bank.full$newjob<-as.factor(bank.full$newjob)
> summary(bank.full$newjob)
> summary(bank.full$newjob)
       CAT1  CAT2 
28441  7038  9732 

mercredi 27 novembre 2019

Simpler way of adjusting X/Y values in a 8x25 matrix

I have an image with some patterns. The patterns are arranged in an 8 column x 25 rows format. Im inspecting these patterns and sending the coordinate of defective pattern to a 4 axis robot for marking in a mirror pattern. I have the COG of each pattern, but the marking position is not at center, its a little to the left on left mirror pattern and little to the right on the right mirror pattern.

Ref image below:

enter image description here

In the above image, the red spot is the COG that I have, green spots are the marking area that I need to send to robot.

The height and width of each pattern is the same. So what im doing now is specifying that if the rejection is (> 0pxX and < 30pxX)&& (>0pxY < 15pxY) then subtract the COG by 9, so the marking position shifts 9 px to the left. Code Eg :

 //less than 30 column and 15 row
 if (df1.cog_X >10 && df1.cog_X < 30 && df1.cog_Y >10 && df1.cog_Y <15)
  {
   df1.cog_X = df1.cog_X - Convert.ToInt32(txtrow1.Text);                                   
  }
 // less than 30 column and 15-30 row
 if (df1.cog_X >10 && df1.cog_X < 30 && df1.cog_Y >15 && df1.cog_Y <30)
  {
   df1.cog_X = df1.cog_X - Convert.ToInt32(txtrow2.Text);                                   
  }
 // less than 30 column and 30-45 row
 if (df1.cog_X >10 && df1.cog_X < 30 && df1.cog_Y >30 && df1.cog_Y <45)
  {
   df1.cog_X = df1.cog_X - Convert.ToInt32(txtrow3.Text);                                   
  }
  ......and so on.

But this is a long process and I have to do it for an 8x25 matrix which means I have to write if statements 200 times, which in turn increases the processing time.'

Is there a simpler way to do it?

In the if else statement, else block is not working in python

   if (filenames.rfind(fileName) != -1):
            sftp.chmod(sftpPath + filenames, 0644)
            print (" Permission changed successfully ")
   else:
            print (" No file available to process ")

In the above code if statement works but the else block doesnt work(its not printing if file is not available)

JS while loop doesnt stop at true

When you run this script it shows the HP for both of the pokemon when you press 1 and click enter it subtracts your attack hit points to the enemies hit points. When you or the ememy hits 0 or less than 0 hit points it is supposed to stop and just show who won in the console log. Instead it takes an extra hit to for it to show the message.

So if you are at -10 hp it takes one more hit.

let firstFight = false;

while (!firstFight) {
  let fightOptions = prompt("1. Fight, 2.Items, 3.Potions " + wildPokemon[0].name + ":" + wildPokemon[0].hp + " " + pokeBox[0].name + ":" + pokeBox[0].hp);
  if (fightOptions == 1) {

    if (!firstFight) {

      if (wildPokemon[0].hp <= 0) {
        console.log("You have won!");
        firstFight = true;
      } else {
        let attack1 = wildPokemon[0].hp -= pokeBox[0].attack.hp;
        console.log(wildPokemon[0].hp);
      }

      if (pokeBox[0].hp <= 0) {
        console.log(wildPokemon[0] + " has killed you");
        firstFight = true;
      } else {
        let attack2 = pokeBox[0].hp -= wildPokemon[0].attack.hp;
        console.log(pokeBox[0].hp);
      }
    }

  } else if (fightOptions == 2) {

  } else if (fightOptions == 3) {

  } else {

  }

}

Are there any ways I can make this code more efficient?

Efficient use of conditional statements over dictionary in python

I want to check in what combination do these values exist and one condition is that hashtag can not exit alone so the combination is 4C1 + 5C2 + 5C3 + 5C4 + 5C5 that makes up these conditional statements.

I want to know whether there is a more efficient way of doing this by using dictionary methods in python.

My Dictionary

data = { 'all_words': '', 'exact_phrase': '', 'any_words': '', 'not_words': '', 'hashtag': ''}

My conditional statements

        if self.all_words is not None and (self.any_words, self.exact_phrase, self.not_words, self.hashtag is None):
            c.Search = self.all_words
        elif self.any_words is not None and (self.all_words, self.exact_phrase, self.not_words, self.hashtag is None):
            c.Search = self.any_words
        elif self.exact_phrase is not None and (self.all_words, self.any_words, self.not_words, self.hashtag is None):
            c.Search = self.exact_phrase
        elif self.hashtag is not None and (self.all_words, self.any_words, self.not_words, self.exact_phrase is None):
            c.Search = self.hashtag

        elif (self.all_words, self.any_words is not None) and (self.exact_phrase, self.not_words, self.hashtag is None):
            c.Search = self.all_words + " " + self.any_words
        elif (self.all_words, self.exact_phrase is not None) and (self.any_words, self.not_words, self.hashtag is None):
            c.Search = self.all_words + " " + self.exact_phrase
        elif (self.all_words, self.not_words is not None) and (self.any_words, self.exact_phrase, self.hashtag is None):
            c.Search = self.all_words + " " + self.not_words
        elif (self.all_words, self.hashtag is not None) and (self.any_words, self.exact_phrase, self.not_words is None):
            c.Search = self.all_words + " " + self.hashtag
        elif (self.any_words, self.exact_phrase is not None) and (self.all_words, self.hashtag, self.not_words is None):
            c.Search = self.exact_phrase + " " + self.any_words
        elif (self.any_words, self.hashtag is not None) and (self.all_words, self.exact_phrase, self.not_words is None):
            c.Search = self.any_words + " " + self.hashtag
        elif (self.any_words, self.not_words is not None) and (self.all_words, self.exact_phrase, self.hashtag is None):
            c.Search = self.any_words + " " + self.not_words
        elif (self.exact_phrase, self.hashtag is not None) and (self.all_words, self.any_words, self.not_words is None):
            c.Search = self.exact_phrase + " " + self.hashtag
        elif (self.exact_phrase, self.not_words is not None) and (self.all_words, self.any_words, self.hashtag is None):
            c.Search = self.exact_phrase + " " + self.not_words
        elif (self.not_words, self.hashtag is not None) and (self.all_words, self.any_words, self.exact_phrase is None):
            c.Search = self.not_words + " " + self.hashtag

        elif (self.all_words, self.any_words, self.exact_phrase is not None) and (self.hashtag, self.not_words is None):
            c.Search = self.all_words + " " + self.exact_phrase + " " + self.any_words
        elif (self.all_words, self.any_words, self.not_words is not None) and (self.hashtag, self.exact_phrase is None):
            c.Search = self.all_words + " " + self.any_words + " " + self.not_words
        elif (self.all_words, self.any_words, self.hashtag is not None) and (self.not_words, self.exact_phrase is None):
            c.Search = self.all_words + " " + self.any_words + " " + self.hashtag
        elif (self.all_words, self.exact_phrase, self.not_words is not None) and (self.any_words, self.hashtag is None):
            c.Search = self.all_words + " " + self.exact_phrase + " " + self.not_words
        elif (self.all_words, self.exact_phrase, self.hashtag is not None) and (self.any_words, self.not_words is None):
            c.Search = self.all_words + " " + self.exact_phrase + " " + self.hashtag
        elif (self.all_words, self.not_words, self.hashtag is not None) and (self.any_words, self.not_words is None):
            c.Search = self.all_words + " " + self.not_words + " " + self.hashtag
        elif (self.exact_phrase, self.any_words, self.not_words is not None) and (self.hashtag, self.all_words is None):
            c.Search = self.exact_phrase + " " + self.any_words + " " + self.not_words
        elif (self.exact_phrase, self.any_words, self.hashtag is not None) and (self.not_words, self.all_words is None):
            c.Search = self.exact_phrase + " " + self.any_words + " " + self.hashtag
        elif (self.any_words, self.not_words, self.hashtag is not None) and (self.all_words, self.exact_phrase is None):
            c.Search = self.any_words + " " + self.not_words + " " + self.hashtag
        elif (self.exact_phrase, self.not_words, self.hashtag is not None) and (self.all_words, self.any_words is None):
            c.Search = self.exact_phrase + " " + self.not_words + " " + self.hashtag

        elif (self.all_words, self.exact_phrase, self.any_words, self.not_words is not None) and (self.hashtag is None):
            c.Search = self.all_words + " " + self.exact_phrase + " " + self.any_words + " " + self.not_words
        elif (self.all_words, self.exact_phrase, self.any_words, self.hashtag is not None) and (self.not_words is None):
            c.Search = self.all_words + " " + self.exact_phrase + " " + self.any_words + " " + self.hashtag
        elif (self.all_words, self.any_words, self.not_words, self.hashtag is not None) and (self.exact_phrase is None):
            c.Search = self.all_words + " " + self.any_words + " " + self.not_words + " " + self.hashtag
        elif (self.all_words, self.exact_phrase, self.not_words, self.hashtag is not None) and (self.any_words is None):
            c.Search = self.all_words + " " + self.exact_phrase + " " + self.not_words + " " + self.hashtag
        elif (self.exact_phrase, self.any_words, self.not_words, self.hashtag is not None) and (self.all_words is None):
            c.Search = self.exact_phrase + " " + self.any_words + " " + self.not_words + " " + self.hashtag

        elif (self.all_words, self.exact_phrase, self.any_words, self.not_words, self.hashtag) is not None:
            c.Search = self.all_words + " " + self.exact_phrase + " " + self.any_words + " " + self.not_words + " " + self.hashtag

Writing an If statement to = a number but not allow for than another [duplicate]

This question already has an answer here:

Im writing an if statement that allows to display a choice based on users input,

Im basically trying to say if something like if they pick 2-4 nights then allow the option.

This is what i've written:

if (userObj.guests = 2 || userObj.guests <=4 && userObj.dayDifference <=10 ) {
    $('.motel_container').removeClass('disable')
}

How can i only allow the if statement to work if they pick 2 - 4 nights only.

Setting Enable or Disable instead of True or False using IF and ELSE statement

So basically what I'm trying to do is that I'm sending a request using retrofit to get a data from my server and I was able to do it. My problem is that I want my program to display "Enable" or "Disable" instead of True or False and change its color based on their status ex: green for enable and red for disable. But its only displaying "Disabled" and it isn't incremented.

Here is my model class from the json data

    public class ObjectList {

    @SerializedName("hardware")
    @Expose
    public Objects[] hardware;
    @SerializedName("software")
    @Expose
    public Objects[] software;

    /**
     * No args constructor for use in serialization
     */
    public ObjectList() {
    }

    /**
     * @param software
     * @param hardware
     */
    public ObjectList(Objects[] hardware, Objects[] software) {
        super();
        this.hardware = hardware;
        this.software = software;
    }

    public Objects[] getHardware() {
        return hardware;
    }

    public void setHardware(Objects[] hardware) {
        this.hardware = hardware;

    }

    public Objects[] getSoftware() {
        return software;
    }

    public void setSoftware(Objects[] software) {
        this.software = software;
    }


    public String getHardwareName() {
        String HWname = "";
        for (int i = 0; i < hardware.length; i++) {
            Objects item = hardware[i];
            HWname += ((Objects) item).name + "\n\n";

        }

        return HWname;

    }

    public String getHardwareStatus() {
        String HWstatus = "";
        for (int i = 0; i < hardware.length; i++) {
            Objects item = hardware[i];
            HWstatus += ((Objects) item).status + "\n\n";

        }
        return HWstatus;
    }

    public String getSoftwareName() {
        String SWname = "";
        for (int i = 0; i < software.length; i++) {
            Objects item = software[i];
            SWname += ((Objects) item).name + "\n\n";
        }
        return SWname;
    }

    public String getSoftwareStatus() {
        String SWstatus = "";
        for (int i = 0; i < software.length; i++) {
            Objects item = software[i];
            SWstatus += ((Objects) item).status + "\n\n";
        }

        return SWstatus;
    }

}

Here is my SystemStatus class

 package com.nerarobotics.robotutility.fragments

public class SystemStatusFragment extends Fragment { private static final String ARG_SECTION_NUMBER = "section_number";

private String baseURL = "http://10.24.204.231:11211/ros/";
private View currentView;
private PageViewModel pageViewModel;
private TextView HardwareName, HardwareStatus, SoftwareName, SoftwareStatus, FlagName;
private Runnable mRepeatRunnable;
private final static int UPDATE_INTERVAL = 2000;


public static SystemStatusFragment newInstance(int index) {
    SystemStatusFragment fragment = new SystemStatusFragment();
    Bundle bundle = new Bundle();
    bundle.putInt(ARG_SECTION_NUMBER, index);
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pageViewModel = ViewModelProviders.of(this).get(PageViewModel.class);
    int index = 1;
    if (getArguments() != null) {
        index = getArguments().getInt(ARG_SECTION_NUMBER);
    }
    pageViewModel.setIndex(index);
}

@Override
public View onCreateView(
        @NonNull LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    currentView = inflater.inflate(R.layout.fragment_system_status, null);

    HardwareName = currentView.findViewById(R.id.hardware_name);
    HardwareStatus = currentView.findViewById(R.id.hardware_status);
    SoftwareName = currentView.findViewById(R.id.software_name);
    SoftwareStatus = currentView.findViewById(R.id.software_status);
    FlagName = currentView.findViewById(R.id.flagreport_name);
    getSystemObject();

    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this,2000);
        }
    }; handler.postDelayed(runnable,2000 );


    return currentView;

}

public void getSystemObject() {
    Retrofit Systemretrofit = new Retrofit.Builder()
            .baseUrl(baseURL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    WebApi jsonAPI = Systemretrofit.create(WebApi.class);
    Call<ObjectList> callSystem = jsonAPI.getNameStatus();
    callSystem.enqueue(new Callback<ObjectList>() {
        @Override
        public void onResponse(Call<ObjectList> callSystem, Response<ObjectList> response) {

            if (!response.isSuccessful()) {
                HardwareName.setText("Code: " + response.code());
                return;
            }


            HardwareName.setText(response.body().getHardwareName ());


            if (response.body().getHardwareStatus().equals("true")) {
                HardwareStatus.setText("Enable");
            } else {

                HardwareStatus.setText("Disable");
            }

        }

        @Override
        public void onFailure(Call<ObjectList> callSystem, Throwable t) {
            HardwareName.setText(t.getMessage());
            SoftwareName.setText(t.getMessage());
        }
    });

    final Call<FlagReportStamped> callFlagReport = jsonAPI.getReportID();
    callFlagReport.enqueue(new Callback<FlagReportStamped>() {
        @Override
        public void onResponse(Call<FlagReportStamped> call, Response<FlagReportStamped> response) {

            if (!response.isSuccessful()) {
                FlagName.setText("Code: " + response.code());
                return;
            }

            FlagName.setText(response.body().getFlagReport().toString());

        }

        @Override
        public void onFailure(Call<FlagReportStamped> call, Throwable t) {
            FlagName.setText(t.getMessage());

        }
    });

}

}

fast Algorithm to compare elements in array column-wise in JAVA

I have a multidimensional array of type int.

Example: c1 c2 c3 c4 r1 1 1 1 3 r2 2 2 3 3 r3 1 2 1 3

In here, I want to compare the corresponding elements of different columns. So elements on r1, for c1 are first compared with elements on r1 of c2, c3 and c4. Then elements of c2 for r1 will be compared against all other columns for r1.

After this, the same procedure is repeated for other rows.

Please suggest me a fast algorithm to do this. Mine one is using three loops to do this. And I want to reduce this complexity. Is it possible?

Let me know if the question is not clear.

Replace string with PHP if statement

I have a API which outputs property (real estate) data from a central database into my website. I want to replace the names of some property types, with my own names. I have this code:

<?php echo isset($property['ROLType']) ? $property['ROLType'] : (isset($property['PropertyType']['NameType']) ? $property['PropertyType']['NameType'] : '-'); ?>

This category has many names/types of properties in it. One of them is "Detached Villa" which i would like to change to just "Villa".

I have tried with this, but no luck:

<?php echo isset($property['ROLType']) ? $property['ROLType'] : (isset($property['PropertyType']['NameType']) ? $property['PropertyType']['NameType'] : '-'); ?>

<?php
if(isset($wprow_details['Property']['ROLType'])){
if($wprow_details['Property']['ROLType'] == 'Detached Villa'){
echo 'Villa';
}?>

What am i doing wrong?

VBA IF Statements converted to Case

Hi this one of the first times I am using the case statement and it would be really helpful for someone to convert.

I had a more simplistic If statement that was working but unable to have this work likely due to my end if/else placements. Always appreciate the help!

Public SLA As Range
Public Data1, Data5 As Range
Public TotalT As Range

Set Data1 = Worksheets("Log").Range("N" & ActiveCell.Row)
Set Data5 = Worksheets("Log").Range("R" & ActiveCell.Row)
Set TotalT = Worksheets("Log").Range("L" & ActiveCell.Row)
Set SLA = Worksheets("Log").Range("M" & ActiveCell.Row)



If Data1 <> "" Then
    If Data5 = "A" Or "B" Then
        If TotalT.Value <= 5 And TotalT.Value <> "" Then
            SLA.Value = "Yes"
        Else
            If TotalT.Value = 0 Then
            Else
                SLA.Value = TotalT - 5

            End If
        End If
    End If
End If

If Data1 <> "" Then
    If Data5 = "C" Or "D" Then
        If TotalT.Value <= 1 And TotalT.Value <> "" Then
            SLA.Value = "Yes"
        Else
            If TotalT.Value = 0 Then
            Else
                SLA.Value = TotalT - 1
            End If
        End If
    End If
End If

If Data1 <> "" Then
    If Data5 = "E" Or "F" Or "G" Or "H" Or "I" Or "J" Then
        If TotalT.Value <= 10 And TotalT.Value <> "" Then
            SLA.Value = "Yes"
        Else
            If TotalT.Value = 0 Then
            Else
                SLA.Value = TotalT - 10
            End If
        End If
    Else
    End If
End If

SFDC "if" or CASE condition in soql

Here is my soql query

select ordernumber,productcode,UOM,itemseq,qty from order where createddate= today

output:

ordernumber  productcode itemseq UOM  qty

ord1           100        01      CS  20
Ord1           100        02      EA   7

ordernumber productcode itemseq qty1 qty2

ord1 100 01 20 Ord1 100 02 7

I tried the regular SQL case function but did not work so that i could get the output as:

basically splitting the qty into 2 columns based on the UOM CS/EA respectively Any help from the experts is much appreciated.

If condition with verification in selenium webdriver java

I am trying to validate a scenario where I want to click an element only if the element is loaded, but the problem is that both these elements are on a different panel. Below is the piece of code:

@FindBy(xpath = "//div[contains(@class,'PriceButton')]")
List<WebElement> priceButton;

The method to load the above element:

public List<WebElement> loadList() {
return priceButtonList;
}

Element to locate PhotoButton

@FindBy(xpath = "//div[contains(@class,'PhotoButton')]")
List<WebElement> photoButton;

Method to verify photo button present

public void verifyPhotoButton() {
photoButton.verifyPresent();
}

Then in the Page class I have implemented the above method

public void clickOptionThatHasAPhoto() {
for(WebElement list : loadList()) {
    if(verifyPhotoButton()) {
        priceButton.click();
        break;
    }
}

I need to know how I can use if condition with verify method.

Oracle CASE WHEN multi rows

I am just wondering if I can rewrite my query using CASE WHEN THEN ELSE. When all codes are NULL then return 'no values' but if not then use subquery with UNPIVOT function. Is this possible? All the time I got an error, that my query return multi rows instead of single one. I can add I am working with Oracle on daily basis.

Please see the SQL Filddle below:

http://sqlfiddle.com/#!4/a88e6/13

Thanks for help!

The for loop works for the first iteration but for the next item in the list

So I am trying to create a simple game using pygame which is kind of like 'brick breaker' except there is no bricks. You get a plank and try to hit the ball so that it doesn't drop below the plank. When the ball hits the plank it should bounce off in the opposite direction. It works perfectly for the first ball, but when I try to introduce the second ball (when your score is 10), the second ball follows all the conditions except it ignores the plank (just goes through it). Here is the bit of the code where I suspect the problem lies:

    for j in range(0, len(ball_x)):

    ball_y[j] += ball_vely[j]
    ball_x[j] += ball_velx[j]

    if ball_y[j] <= 0:
        ball_vely[j] *= -1

    if ball_y[j] + 55 > y and ball_y[j] + 40 < y and ball_x[j] > x and ball_x[j] < x + 160:
        ball_vely[j] *= -1
        score += 1

        if ball_x[j] > x + 75:
            ball_velx[j] = 10
            ball_velx[j] *= 1 + (ball_x[j] - x + 75)/60
        elif ball_x[j] < x + 75:
            ball_velx[j] = 10
            ball_velx[j] *= -1 * (1 + (x + 75 - ball_x[j])/60)

    if ball_x[j] - 25 <= 0 or ball_x[j] + 45  >= 680:
        ball_velx[j] *= -1
    if ball_y[j] > 795:
        lives -= 1

ball_y and ball_x while ball_velx and ball_vely are the velocities (all of them are stored in a list). When the second ball goes below the screen, the lives are taken off which makes no sense to me. I have tried getting rid of the for loop and instead writing the code twice but it didn't work. Any help would be appreciated.

Matching values between dataframes using ifelse in R

I am trying to match data between two dataframes, but am getting the value for the position in the vector, rather than the corresponding value.

I have two data.frames:

df1=data.frame(Gene=c("gene1","gene2","gene3","gene4","gene5"),TWAS.testable=c(1,0,1,1,0),stringsAsFactors=FALSE)

    > df1
       Gene TWAS.testable
    1 gene1             1
    2 gene2             0
    3 gene3             1
    4 gene4             1
    5 gene5             0

df2=data.frame(Gene=c("gene1","gene3","gene4","gene7","gene8"),TWAS.Z=c(0.43,3.63,0.11,-0.82,0.36),stringsAsFactors=FALSE)

    > df2
       Gene TWAS.Z
    1 gene1   0.43
    2 gene3   3.63
    3 gene4   0.11
    4 gene7  -0.82
    5 gene8   0.36

I am trying to replace the values in TWAS.testable, with those in TWAS.Z which correspond to the matching Gene, otherwise fill with NA. So that what I get back is:

      Gene TWAS.testable
    1 gene1          0.43
    2 gene2            NA
    3 gene3          3.63
    4 gene4          0.11
    5 gene5            NA

So I tried:

df1$TWAS.testable=ifelse(df1$Gene %in% df2$Gene,df2$TWAS.Z,NA)

which returns

    > df1
      Gene TWAS.testable
    1 gene1          0.43
    2 gene2            NA
    3 gene3          0.11
    4 gene4         -0.82
    5 gene5            NA

so it is returning the position in the vector, rather than matching TWAS.Z to its corresponding Gene. i.e. gene3 is the third object in df1$Gene, so it is filling TWAS.testable with 0.11, the 3rd object from df2$TWAS.Z. When really, I want the df2$TWAS.Z where df1$Gene==df2$Gene.

I can see why this is happening, but I can't figure out how to get what I want in an ifelse context, so that it returns the corresponding TWAS.Z where possible, or fills with NA.

Thanks in advance.

Powershell specific character not match for function

Am trying to create a filter to only run the IF clause in case of the character in the 4 position be either "W", "X", "Y", "Z".

The code so far looks like this:

$name= "123Y567"

if ($name.notcontains("Y"))
{
 "Action 1"
}
  else
{               
  "Action 2"
 }
}

I have tried this as well

$name= "123Y567"

if ($name -notmatch (/^.{4}["Y"]/))
{
 "Action 1"
}
  else
{               
  "Action 2"
 }
}

What could be the best solution for this? but new working with scripting and Powershell in general.

IF all cells in a range are the same, excluding blank cells

I have a table to calculate the price of a project, where one column is the description of an element of the project followed by a column for its unit (usually hours), the price per unit, number of units, and the final price, sort of like this: enter image description here

My question really only involves the highlighted cells. Im making a template, and I add elements to the table as I go along, so some rows are left blank, but I want the total number of hours to be displayed in D7 (easy enough, =SUM(D2:D6)), but my problem is that some of the elements aren't written per hour (eg. row 4), so I want the total to only show up if all the values are for hours. Essentially:

IF all values in row B are "Hours", then sum of row D, else "")

I guess in short, is there a formula I can use that would return TRUE if all the values in a range are the same, excluding blank cells?

Thanks.

powercli create snapshot if vm's datastore has more than %10 free space

Hi i'm workin over a script for days. I want to take vm snasphot if vm's datastore has requred space.

My script :

$myarray =@{}
$myarray = get-vm test | get-datastore | select-object @{N="DSFreespace"; E={[math]::Round(($_.FreeSpaceGB)/($_.CapacityGB)*100,2)}}
$Treshold = "{0:n2}" -f 10

foreach ($Treshold in $myarray) {
if ($myarray -ge $Treshold){new-snapshot -vm test -name test123} else {
Write-Host "You cannot take a snapshot. Datastore free spce is lower than 10%" }
}

When i run script in shell it Also i composed another one for same thing, but no luck. when i use "-ge" condition, script always take snapshot of vm, regardless free space percent (i tried it many different numbers, other than original treshold)

İf i use "-gt" condition, script never take snaphot, regardless free space percent.

I also tried another script for same thin, same results. Also, same thing for -lt and -le conditions

$vm = get-vm test
$Treshold = "{0:n2}" -f 10
$DSFreespace = get-vm $vm| get-datastore | select-object @{N="DSFreespace"; E={[math]::Round(($_.FreeSpaceGB)/($_.CapacityGB)*100,2)}}
if($DSFreespace -ge $Treshold){new-snapshot -vm $vm -name test123} else {
Write-Host "You cannot take a snapshot. Datastore free space is lower than 10%" }'''

What is wrong, how to solve this problem ?

Adding a if statement

My code looks like this:

$('a').each(function(){
  $(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source  + '&utm_campaign' + utm_campaign + '&utm_medium' + utm_medium);
});

The code adds some UTM Parameters to all Links on a site. But now I want to exclude some specific links:

https://www.mysite.or/cat1
https://www.mysite.or/cat2

So I came up with that:

$('a').each(function() {
  if ("href:contains('https://www.mysite.or/cat1')") {
    $(this).attr('href');
  } else if ("href:contains('https://www.mysite.or/cat1')") {
    $(this).attr('href');
  } else {
    $(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign' + utm_campaign + '&utm_medium' + utm_medium);
  }
});

But it isn't working properly.

Retrieve and display the values of a form

This is not a question but I would like to share my experience regarding value recovery and its poster. I hope this little piece of code can help more than one.

Here's how I did it:

 #Allows you to display the value of the field: anneeDeNaissance

Here is an example of a (functional) condition :


Documentation : https://symfony.com/doc/4.1/reference/forms/twig_reference.html

If you have any suggestions regarding the code, do not hesitate. This is the first time I've done this kind of post

Support with ISBLANK and IF statements

I'm looking to return a value based on the latest of a range of cells having a result.

I log data at fixed points and want to be able to display the latest value listed. I've tried using If and ISBLANK but don't seem to be able to find the best combination that works.

Currently looking at this set up:

Display latest grade in K3. Information should be taken from cells S3, W3 and AA3 in that order. Ie. If there is data in S3 only then display that result in K3. If there is data in W3 then display the data from W3 in K3, and if there is data in AA3 then display that data in K3.

Thanks in advance!