samedi 29 février 2020

making a variable dynamic in if statement

I am trying to do the bellow:

setlocal enabledelayedexpansion
set choice=
set /p choice="Select File Number, or no to exit: "

if "%choice%"=="no" (
goto cleanup
) else (
set "!choice!=%choice%"
start %file!choice!%
pause
)

what i want is to open a file where the variable is %filex% and be able to choose what file to open

If- statement in python

Attached if statement doesn't provide valid info. My code is looking for something and if it is found, then the value 1 is assigned. otherwise value 0 is assigned.

Note: It is looking in array in JSON format.

for y in behavior_calls:
    if y["api"] == "NtUnmapViewOfSection":
           f1 = 1
    else:
           f1 = 0

For all cases the value is zero assigned. Can anyone find the problem?

Python elif works in IDLE but not Visual Studio Code

I'm a Python newbie, currently working on my first project.

My elif statements seem to work in IDLE but not VSC

To demonstrate, I have a very simple if statement:

dud = 'You'
if dud == 'You':
    print('You got the dud!')
elif dud == 'Me':
    print('ohhhh, I made myself sad')
else:
    pass

When I submit this code to IDLE, it works no problem. However, when I copy paste the exact same code into VSC and run in Python Terminal I get the following errors:

PS C:\Users\William> & C:/Users/William/AppData/Local/Programs/Python/Python38-32/python.exe
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dud = 'You'
>>> 
>>> if dud == 'you':
...     print('You got the dud!')
...
>>> elif dud == 'Me':
  File "<stdin>", line 1
    elif dud == 'Me':
    ^
SyntaxError: invalid syntax
>>>     print('ohhhh, I made myself sad')
  File "<stdin>", line 1
    print('ohhhh, I made myself sad')
    ^
IndentationError: unexpected indent
>>> else:
  File "<stdin>", line 1
    else:
    ^
SyntaxError: invalid syntax
>>>     pass
  File "<stdin>", line 1
    pass
    ^
IndentationError: unexpected indent
>>>

Naturally, I've tried various different types of formatting but I can't get it to work. If I remove the elif section it works fine, so I feel like I must be missing something basic.

Any help would be greatly apprecaited!

Sum in range that meet criteria [closed]

Trying to learn a new approach.
It's the classical problem of finding the sum of all multiples of 3 and 5 below 'n'.

What I want is:

print ("The sum is: ", sum(range(1, 100)))

But with an if-statement for multiples of 3 / 5.

My question:
How can I include that if-statement for a one-line solution?

Thanks for your help. =)
// Chris S.

How do I store each of these sysouts in an if else statment into one solution string

this project is for a game called Mastermind. I need to create a randomly generated string and store it to a solution so I can later test the solution string to see if the user has entered the correct order. Ive successfully created the generator to output but I don't know how I am going to get it to the String solution variable. We are not allowed to use arrays for this assignment.

    public void makeSolution() {
    int randNum;
    Random randGen = new Random();

    for(int i = 0; i < NUM_OF_PEGS; i++) {
        randNum = randGen.nextInt(6);
        if(randNum == 0){
            System.out.print("Y");

        }
        else if(randNum == 1) {
            System.out.print("O");

        }
        else if(randNum == 2) {
            System.out.print("R");

        }
        else if(randNum == 3) {
            System.out.print("B");

        }
        else if(randNum == 4) {
            System.out.print("G");

        }
        else if(randNum == 5) {
            System.out.print("P");
        }
    }

}

use if loop in awk command unix

#!/bin/bash

read -p "enter 2nd longtitude: " lon2;read -p "enter 2nd latitude: " lat2;read -p "enter 4th longtitude: " lon4;\
read -p "enter 4th latitude: " lat4;read -p "enter date of major earthquake (yy-mm-dd): " date;read -p "insert time of birth (hr:min:sec): " time;\
read -p "insert days after earthquake: " n

year=`echo $date|cut -d "-" -f 1`;month=`echo $date|cut -d "-" -f 2`;day=`echo $date|cut -d "-" -f 3`\
hr=`echo $time|cut -d ":" -f 1`;min=`echo $time|cut -d ":" -f 2`;sec=`echo $time|cut -d ":" -f 3`

head -n 8 finalcat.cat>titlos;sed '1,8d' finalcat.cat>arxeio

awk -v lon4=$lon4 -v lon2=$lon2 -v lat2=$lat2 -v lat4=$lat4 '{lon=$4;lat=$3}{if(lon<lon2 && lon>lon4 && lat>lat4 && lat<lat2) print $0}' arxeio>teliko1

while read line ;do
hrr=`echo $line|awk -F " " '{print $2}'|awk -F ":" '{print $1}'`; minn=`echo $line|awk -F " " '{print $2}'|awk -F ":" '{print $2}'`
secc=`echo $line|awk -F " " '{print $2}'|awk -F ":" '{print $3}'`; yearr=`echo $line|awk -F " " '{print $1}'|awk -F "-" '{print $1}'`
monthh=`echo $line|awk -F " " '{print $1}'|awk -F "-" '{print $2}'`; dayy=`echo $line|awk -F " " '{print $1}'|awk -F "-" '{print $3}'`
done<arxeio

awk -v hrr=$hrr -v minn=$minn -v secc=$secc -v yearr=$yearr -v monthh=$month -v dayy=$dayy -v year=$year -v month=$month -v day=$day -v hr=$hr -v min=$min -v sec=$sec -v n=$n '{if( (yearr==year && monthh==month && dayy==day && hrr>=hr && minn>=min && secc>=sec) || (yearr==year && monthh==month && dayy>day && dayy<day+n) || (yearr==year && monthh==month && dayy==day+n && hrr<=hr && minn<=min && secc<=sec) ) print $0}' teliko1 |sort -k 6n> teliko2

it doesnt work. It just stopps without executing the code. Is it something wrong with my code? thanks!

Counting inputs in a for loop

The variable "countT" keeps adding after every input, even with the if statement that says to add 0 to "countT" it continues to do so. I tried doing, if temp <= 0: then it would also add nothing to "countT".

countT = 0
temp = 0
listT = []

breath = input("Do you have shortness of breath (y/n)? ")
cough = input("Do you have a cough(y/n)? ")
sorethroat_runnynose = input("Do you have a sore throat/runny nose (y/n)? ")
nausea = input("Do you have diarrhea, nausea and vomiting (y/n)? ")

if str.lower(breath)== 'y' and str.lower(cough)== 'y'and str.lower(sorethroat_runnynose)== 'n' and str.lower(nausea)== 'n':
    print("Enter 5 most recent temperature readings:")
    for x in range (1,6):
        temp2= int(input("Temp: "))
        temp += temp2
        listT.append(temp2)
        if temp == 0:
            countT +=0
        else:
            countT +=1

    avgT = (temp/countT) 

    print("Your max Temp was: ",(max(listT)))
    print("Average Temp is: ",avgT)
    print("You likely have the influenza virus")

    if avgT > 100 and temp > max(listT):
       print("Please seek medical attention now!") 

    elif avgT > 99:
        print("Monitor your condition closely!")

elif str.lower(breath)== 'n' and str.lower(cough)== 'n' and str.lower(sorethroat_runnynose)== 'n' and str.lower(nausea)== 'n':
    print("There are no symptoms but you should wait to see if you develop any.")

else:
    print("you likely have the influenza virus.")

How do can I get rid of the blank lines that are created c++?

I have come to ask for help as my professor is not giving me the help I need. I am new to c++ and I am trying to program a program that displays all the integers from 1 to 100 that are divisible by 6 or 7, but not both. and I have to display 5 numbers per row. I got it working except I have blank lines forming in certain areas. I don't know if it's because of how I set up the counter or what.

Here is what I got.


#include <iostream>

using namespace std;

int main()
{
    int counter = 0; // Counter for creating new lines after 5 numbers
    for (int numRange = 1; numRange <= 100; ++numRange) // Starts the loop of number 1 to 100
    {
        if (numRange % 6 == 0 || numRange % 7 == 0) // Makes the numbers divisible by 6 and 7
        {
            cout << numRange << " "; // Displays the output of the divisible numbers
            counter++; // Starts the counter

        }
        if (counter % 5 == 0) // using the counter to create new lines after 5 numbers displayed
        {
            cout << endl; // Creates a new line
        }
    }

    return 0;
}

This is what is outputted:






6 7 12 14 18


21 24 28 30 35
36 42 48 49 54

56 60 63 66 70

72 77 78 84 90
91 96 98

and this is what it's supposed to look like

  6   7 12 14 18 
21 24 28 30 35 
36 48 49 54 56 
60 63 66 70 72 
77 78 90 91 96 
98

When to use else if instead of if?

Suppose we have this code:

if (condition_1)
   do this
if (condition_2)
   do that
else
   do blablabla

And now this one:

if (condition_1)
   do this
else if (condition_2)
   do that
else
   do blablabla

And now let's check what happens line by line. If i'm not mistaken, the first program starts checking if condition_1 is true or false, then the same thing happens for condition_2. And if none of these conditions are true, the program runs "do blablabla".

The second program starts from checking condition_1, and if it's false then if checks condition_2. If condition_2 if false, if does nothing (by nothing i mean it ignores the else statement). If so, the second if statment from the second program can be replaced by:

if (!(condition_1) and condition_2)
   do that

But else then can be run, i thought that every else if statement can be replaced by only if with a bit longer condition. So is this possible to replace every else if by using only if? And when "do blablabla" will run?

My if else statement is not working as intended - innerHTML remaining the same for all statements

I am trying to find out why my conditional statement is not working as intended. The else part of the statement is not working at all, as it remains the same as for the else if statement. I tried to simplify the statement just having an if/else, but it didn't work. I will really appreciate some help to get to the bottom of this issue.

P.S. In my case if I want to use the null statement I must use it as a string. Another mystery.

Here's my code:

var name = prompt("Could you please tell me your name?");
    var newP = document.createElement('p');
    newP.setAttribute('id', 'mainP');
    document.body.appendChild(newP);


    if(name == 'null' || '') {
        newP.innerHTML = "I'm just looking for Aname! " + String.fromCodePoint(0x1F612);
    }else if(name == 'Aname' || 'aname') {
        newP.innerHTML = 'Yes, I finally found Aname! ' + String.fromCodePoint(0x1F60D);
    }else {
        newP.innerHTML = "I'm just looking for Aname! " + String.fromCodePoint(0x1F612);
    }

Power BI: columns concatenation with incremented number between the columns, based on specific conditions

I am using Power BI.

I amconcatenating two columns from the same file. This is ok.

But between this concatenation, I need to add a number.

The number is determine in function of data in another file.

In another file, I have a list of values, string followed by number. The string indicate a category and the number an amount within this category.

When the string matches to a specific string in the first file, the highest number sould be selected, and then incremented, and places in the middle of my two concatenated columns.

I am struggling to do that.

I kmow that I shoulf be using part of "Text.Contains", but my issue if that the text needs to be provided. It is always the same text which needs to be searched. I also wonder how to have a Text.Contains embeded within a Text.Combine.

Text.Contains(text as nullable text, substring as text, optional comparer as nullable function) as nullable logical 

Another issue is that I need to increment, and thus I need to have a number, but in Power BI things need to be either text or numbers.

I also found this formula on another auestion, which seems to somewhat approach what I am looking for because an incrementation is done.

Column = var currentIndex = [Index] 
         var lastFalseIndex = CALCULATE(max(Table1[Index]), 
                                        Table1[Event] = FALSE(), 
                                        Table1[Index] <= currentIndex) 
         var minIndexEachKey = CALCULATE(min(Table1[Index]),
                                         all('Table1'[Event], Table1[Index])) 
         return 
             if(ISBLANK(lastFalseIndex),
                 currentIndex - minIndexEachKey + 1 , 
                 currentIndex - lastFalseIndex)

Below are the two input files, followed by the result:

Input file with the columns that I concatenate

Second inuput file, in which I need to search for a specific category, look for the highet number and increment it

End result

JS switch onlick between two colors w/ if else

I'm working on my portfolio and need to switch between to stylings states of an element. Currently, I'm trying to make it work on the following example. In this particular case, my goal is to click the button and switch between green and red background with every click. But something won't work. I can switch from green to red, but not from red to green. What am I missing?

<button id="button">Toggle</button>
<div class="test" id="test"></div>


.test {
  width: 100px;
  height: 100px;
  background: green;
  margin-top: 20px;
}


var btn = document.getElementById("button");
var test = document.getElementById("test");

btn.onclick = function() {
  if (test.style.background = "green") {test.style.background = "red";} else {test.style.background = "green";}};

Codepen Demo https://codepen.io/yanniksturm/pen/rNVmqJe

Thanks a lot!

Replace Logical OR operator using for and IF loop

I need to automate a chunk of codes for a larger model. Currently, I am using this set of codes

if(mat[1,3]>mat[2,3] ||mat[2,3] > pmat[3,3] ){
    break
  }

this is working fine. I want to dod something like this

for(y in 1:2){
    if(mat[y,3]>mat[y+1,3]){
      break
    }
  }

This is not giving me the result. Can anyone explain me? mat is a 3*3 matrix

Nested If Else Statement in Crystal Reports

I want to nest if-else statements in Crystal Reports, but I don't know the necessary syntax. How can I arrange something like this:

Local StringVar x;
If (IsNull({datatable.id}) or {datatable.id} ="") then
    x := ""
Else
   (If ToText({datatable.id})  <= {?parameter} Then
       x := "new"
Else
       x:= "")

How can I display the data in the right table by using javascript for-loop and if-satement?

I have some data fetching by ajax, I need to use for-loop and if-statement to check which good belongs to whose shopping cart. And then display in their table. The for-loop and if-statement I write worked correctly in HTML, now I just use the same logic to write in js file. But it fails. My code always puts all the data in one table. Which part do I miss it? I scratch my head for a long time and can not fix it.

test.js

function createTable() {
        $.ajax({
                url: "http://127.0.0.1:8000/test2",
                type: "GET",
                success: function (result) {
                    var mybody = document.getElementById("myDynamicTable");
                    var customer_status = (result);
                    var customers = JSON.parse(customer_status.Customer);
                    var carts = JSON.parse(customer_status.Cart);
                    var goods = JSON.parse(customer_status.Good);
                    for (var p in customers){
                        for (var c in carts){
                            if(customers[p].pk == carts[c].fields.customer){
                                for (var g in goods){
                                    if (carts[c].pk == goods[g].fields.cart){
                                        var tr2 = document.createElement('TR');
                                        tr2.className="trClass";
                                        var td1 = document.createElement('TD');
                                        var td2 = document.createElement('TD');
                                        var td3 = document.createElement('TD');
                                        var td4 = document.createElement('TD');
                                        td1.appendChild(document.createTextNode(goods[g].fields.name));
                                        td2.appendChild(document.createTextNode(goods[g].fields.count));
                                        td3.appendChild(document.createTextNode(goods[g].fields.price));
                                        td4.appendChild(document.createTextNode(goods[g].fields.count*goods[g].fields.price));
                                        tr2.appendChild(td1);
                                        tr2.appendChild(td2);
                                        tr2.appendChild(td3);
                                        tr2.appendChild(td4);
                                        mybody.appendChild(tr2);
                                    }
                                }
                            }
                        }
                    }
                }
            })
            $(".trClass").remove();
}

for example, I use the admin site to add two cokes to the second customer, but it still displays under the fisrt customer.

pic1

please help! thank you.

Reasons to or not to declare functions in an if-statement

I need some confirmations on what’s happening behind the screen.

There’s an article in MDN that said that we shouldn’t declare functions in a block-level, such as, inside an if-statement. Because it’s inconsistent throughout browsers and anything to do with pre-ES2015 (or pre-ES6).

The function inside the if-statement will not be created unless the condition is true.

I was wondering, IF the condition is true, let’s say 5 minutes later after JavaScript is loaded and set synchronously, will it create the function? Does it still have memory of the code in order to create the function, or is it dumped in unused code and all?

I would like to know whether the function still exists even after the if-statement is completed. Is it accessible? How long is it accessible? Is it accessible until the if-condition is false? Does the result differ from ES6 and pre-ES6? I’ve heard there’s no scope pre-ES6 in if-statements.

e.g.

if (condition) { function foo() {console.log(“hello world”); } }

I was confused after reading an article in MDN on ‘Functions’ under ‘block-level functions in non-strict code’: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions

vendredi 28 février 2020

Trying to put an if-statement in a for loop

I am trying to input an if-statement inside of this for-loop so that whenever the user still has to eat the loop can be redone without having to lose the data already provided.

boolean yes = true;
                       boolean no = false;
                       double calorieCount = DCN;
                       int snackCalories = 300;
                       int mealCalories = 1100;
                       double meal = mealCalories;
                       double snack = snackCalories;
    for (int i = 1; calorieCount <= calorieCount; calorieCount--) {
                           System.out.println("Did you eat? yes or no");
                           String answer = sc.next();

                        if(yes == true) { //You did eat 
                               System.out.println("Did you eat a meal(1) or a snack(2)?");
                               int foodChoice = sc.nextInt();
                               if(foodChoice == 1) //Meal 
                               System.out.println("Your calories left for the day : " + (calorieCount - meal));
                                }
                               int foodChoice = sc.nextInt();
                                if(foodChoice == 2) {//Snack                  
                               calorieCount = calorieCount - snack;
                               System.out.println("Your calories left for the day : " + (calorieCount - snack));
                               }
                               else {
                               System.out.println("Your calories left for the day : " + calorieCount);
                               };
                               else(no == false){
                                   System.out.println(calorieCount);
                               }

Sorting columns and paste to new sheet if certain cells meet the criteria

I'm new to StackOverflow and kinda fresh in Excel VBA too, and I hope to find answers and eventually provide answers as well.

Here's my problem: Sheet 1 (Called "Disorderly") has a numerous numbers of values gathered from different sensors, stored in every other column. In the column to the left for each sensor value is the associated time stamp for every sensor value. See picture. Not every time stamp is the same, which causes trouble. I need to paste the values which have the same time stamp to a new sheet. My thoughts are two for loops searching through each column in search for the value in the first columns in each row. After trying and failing a bit, I went for the Range.Find function. I get a strange result and it took forever to search through. Is using the find-function even recommended inside a (two) for loop(s)? Anyone with a efficient and correct take on this problem? I would really appreciate any guidance and tips :) Little peak of data set

    Private Sub CommandButton1_Click()
Dim rH As Long
Dim Row As Long
Dim Col As Long
Dim RowSize As Integer
Dim ColSize As Integer
Dim foundRng As Range
Set DataArk = Worksheets("Disorderly")
Set ResArk = Worksheets("Organized")
'Copy the first two rows
rH = 1
    For Row = 1 To 2
        ResArk.Rows(Row).EntireRow.Value = DataArk.Rows(rH).EntireRow.Value
        rH = rH + 1
    Next Row
'Copy column 1 and 2 in DataArk
    DataArk.Columns(1).Copy Destination:=ResArk.Columns(1)
    DataArk.Columns(2).Copy Destination:=ResArk.Columns(2)
'Search through every second column for the associated timestamp in column 1
RowSize = DataArk.Cells(Rows.Count, 1).End(xlUp).Row
ColSize = DataArk.Cells(3, Columns.Count).End(xlToLeft).Column
    For Col = 3 To ColSize Step 2
        For Row = 3 To RowSize
            Set foundRng = Range(DataArk.Cells(Row, Col), DataArk.Cells(RowSize, Col)).Find(DataArk.Cells(Row, 1)) ' After:=DataArk.Cells(Row - 1, Col), SearchOrder:=xlByRows, SearchDirection:=xlNext)
            If foundRng Is Nothing Then
            ResArk.Activate
            ResArk.Cells(Row, Col + 1) = ""
            DataArk.Activate
            Else
            ResArk.Activate
            ResArk.Cells(Row, Col + 1) = foundRng.Address
            DataArk.Activate
            End If
        Next Row
   Next Col
End Sub

Swift return values of different types in function based on conditions

I am new in Swift and have a small question.

I want to build a function which can return values of different types based on the conditions. What return type should I use?? Below is the function. I use "??" as the placeholder. Can anybody help to change the "??" with correct return type?? Thanks!!

fun Req_amt() -> ?? {
    if let input_amt = readLine() {
        if let amount = Float(input_amt) {
            return amount
        } else {
            return "Bad number."
        }
    } else {
        return "Bad input."
    }
}

Nested if-statements get very long and hard to overview what is actually wrong

This is the continuation of the project from my last question. Its basically a program that return console messages by recieving user-input with a scanner. It's a school programm that has a class creating grades with ArrayLists that store the students in their respective grade. Some students can also be class speaker or student speaker which are also stored in their own ArrayLists. The program asks the user to enter a category which leads to the coresponding path through nested if-statements. If the if-statements dont get fulfilled an error message shows up on the console and loops back to the beginning.

The way I set up the program the nested if statements should work, but its still causing problems and I dont know what to do.

I'm from Germany, so I'm sorry for some German words in the programm.

This is the code:

    package package_Fachklassen;

    import java.util.Scanner;

    public class Startklasse {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Schulklasse sk1, sk2;
    sk1 = new Schulklasse("WG 13-1");
    sk2 = new Schulklasse("WG 13-2");

    Sprecher ks1, sss1;
    ks1 = new Sprecher("Klassensprecher");
    sss1 = new Sprecher("Schülersprecher");

    Spezial kS1, kS2, kS3, kS4, sS1, sS2;
    kS1 = new Spezial("Cem", "Yildiz", 19, sk2, ks1);
    kS2 = new Spezial("Fatima", "Baba", 19, sk2, ks1);
    kS3 = new Spezial("Rüveyda", "Yildiz", 20, sk1, ks1);
    kS4 = new Spezial("Zvoni", "Jogovic", 19, sk1, ks1);
    sS1 = new Spezial("Cem", "Yildiz", 19, sk2, sss1);
    sS2 = new Spezial("Fatima", "Baba", 19, sk2, sss1);

    ks1.addKlassensprecher(kS1);
    ks1.addKlassensprecher(kS2);
    ks1.addKlassensprecher(kS3);
    ks1.addKlassensprecher(kS4);
    sss1.addSchuelersprecher(sS1);
    sss1.addSchuelersprecher(sS2);


    //Klasse 13-1

    Schueler s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20;
    s1 = new Schueler("Gonzalo", "Cofre Real", 18, sk1);
    s2 = new Schueler("Swaastika", "Yogeswaran", 19, sk1);
    s3 = new Schueler("Derin", "Sipahi", 19, sk1);
    s4 = new Schueler("Henry", "Reinhold", 19, sk1);
    s5 = new Schueler("Sara", "Perkovic", 19, sk1);
    s6 = new Schueler("Honia", "Aref", 19, sk1);
    s7 = new Schueler("Finn", "Bolheimer", 17, sk1);
    s8 = new Schueler("Karoline", "Garkos", 18, sk1);
    s9 = new Schueler("Hannah", "Hirth", 18, sk1);
    s10 = new Schueler("Sarah", "Schwarz", 18, sk1);
    s11 = new Schueler("Rüveyda", "Yildiz", 20, sk1);
    s12 = new Schueler("Jibi", "Saji", 18, sk1);
    s13 = new Schueler("Rida", "Jafari", 18, sk1);
    s14 = new Schueler("Patrick", "Bruhn", 18, sk1);
    s15 = new Schueler("Andre", "Rosenau", 19, sk1);
    s16 = new Schueler("Irini", "Chrisivolanto", 19, sk1);
    s17 = new Schueler("Xenia", "Aschenbrenner", 19, sk1);
    s18 = new Schueler("Kristina", "Jokic", 19, sk1);
    s19 = new Schueler("Yavuz", "Salik", 21, sk1);
    s20 = new Schueler("Zvonimir", "Jogovic", 19, sk1);


    sk1.addSchueler(s1);
    sk1.addSchueler(s2);
    sk1.addSchueler(s3);
    sk1.addSchueler(s4);
    sk1.addSchueler(s5);
    sk1.addSchueler(s6);
    sk1.addSchueler(s7);
    sk1.addSchueler(s8);
    sk1.addSchueler(s9);
    sk1.addSchueler(s10);

    //Klasse 13-2

    Schueler ss1, ss2, ss3, ss4, ss5, ss6, ss7, ss8;
    ss1 = new Schueler("Cem", "Yildiz", 19, sk2);
    ss2 = new Schueler("Fathima", "Baba", 19, sk2);
    ss3 = new Schueler("Sanjie", "Bislimi", 19, sk2);
    ss4 = new Schueler("Jasmine", "Jaffari", 19, sk2);
    ss5 = new Schueler("Hannah", "Arent", 19, sk2);
    ss6 = new Schueler("Niklas", "Genf", 18, sk2);
    ss7 = new Schueler("Celina", "Musollaj", 18, sk2);
    ss8 = new Schueler("Naomi", "Schmidt", 19, sk2);

    sk2.addSchueler(ss1);
    sk2.addSchueler(ss2);
    sk2.addSchueler(ss3);
    sk2.addSchueler(ss4);
    sk2.addSchueler(ss5);
    sk2.addSchueler(ss6);

    String schueler = "Schüler";
    String sprecher = "Sprecher";


    String ksSuche = "KS-Suche";
    String ssSuche = "SS-Suche";
    String ksAlle = "KS-Alle";
    String ssAlle = "SS-Alle";

    while(true) 
    {   
        Scanner firstscan = new Scanner(System.in);
        System.out.println("Nach welcher Kategorie suchen Sie?");
        String f_input = firstscan.nextLine();
        boolean studentmissing = true;
            if(f_input.equals(schueler)) 
            {
                Scanner scan = new Scanner(System.in);
                System.out.println("Welche Klasse besucht der gesuchte Schüler?");
                String k_input= scan.nextLine();

                    if(k_input.equals(sk1.getBezeichnung())) 
                    {
                        System.out.println("Welchen SChüler aus Klasse 13-1 suchen Sie?");
                        String n_input = scan.nextLine();
                        for(int i = 0; i < sk1.getListenLaenge(); i++) 
                        {
                            if(n_input.equals(sk1.getSchueler(i).getName()) || n_input.equals(sk1.getSchueler(i).getNachname())) 
                            {
                                studentmissing = false;
                                System.out.println("Ihr Schüler:");
                                System.out.println(" " + sk1.getSchueler(i).getName());
                                System.out.println(" " + sk1.getSchueler(i).getNachname());
                                System.out.println(" " + sk1.getSchueler(i).getAlter());
                                break;
                            }
                        }
                        if(studentmissing) 
                        {
                        System.out.println("Schüler existiert nicht oder ist nicht in dieser Klasse!");
                        System.out.println("--------------------------------------------------------");
                        }

                    }
                    else if(k_input.equals(sk2.getBezeichnung())) 
                    {
                        System.out.println("Welchen Schüler aus Klasse 13-2 suchen Sie?");
                        String n2_input = scan.nextLine();
                        for(int i = 0; i < sk1.getListenLaenge(); i++)
                        {
                            if(n2_input.equals(sk2.getSchueler(i).getName()) || n2_input.equals(sk2.getSchueler(i).getNachname()))
                            {
                                studentmissing = false;
                                System.out.println("Ihr Schüler:");
                                System.out.println(" " + sk2.getSchueler(i).getName());
                                System.out.println(" " + sk2.getSchueler(i).getNachname());
                                System.out.println(" " + sk2.getSchueler(i).getAlter());
                                break;
                            }
                        }
                        if(studentmissing) 
                        {
                            System.out.println("Schüler existiert nicht oder ist nicht in dieser Klasse!");
                            System.out.println("--------------------------------------------------------");
                        }
                    }
                }

                else if(f_input.equals(sprecher))
                {
                    Scanner ksScanner = new Scanner(System.in);
                    System.out.println("Suchen Sie nach Klassensprechern oder Schülersprechern?");
                    String ks_input = ksScanner.nextLine();

                    if(ks_input.equals(ksSuche))
                    {
                        System.out.println("Geben sie den Namen der gesuchten Person ein!");
                        String sn_input = firstscan.nextLine();
                        boolean ksMissing = true;
                        for(int i = 0; i < ks1.getListLengthKS(); i++)
                        {
                            if(sn_input.equals(ks1.getKlassensprecher(i).getName()) || sn_input.equals(ks1.getKlassensprecher(i).getNachname()))
                            {
                                ksMissing = false;
                                System.out.println("Ihr Schüler:");
                                System.out.println(" " + ks1.getKlassensprecher(i).getName());
                                System.out.println(" " + ks1.getKlassensprecher(i).getNachname());
                                System.out.println(" " + ks1.getKlassensprecher(i).getAlter());
                                break;
                            }
                        }
                        if(ksMissing) 
                        {
                                System.out.println("Schüler ist nicht gespeichert!");
                                System.out.println("-------------------------------------------------");
                        }
                    }
                }
                else if(f_input.equals(ssSuche))
                {
                    System.out.println("Geben sie den Namen des Schülersprechers ein!");
                    String ss_Input = firstscan.nextLine();
                    boolean ssMissing = true;
                    for(int i = 0; i < sss1.getListLengthSS(); i++) 
                    {       
                        if(ss_Input.equals(sss1.getSchuelersprecher(i).getName()) || ss_Input.equals(sss1.getSchuelersprecher(i).getNachname()))
                        {
                            ssMissing = false;
                            System.out.println("Ihr Schüler:");
                            System.out.println(" " + sss1.getSchuelersprecher(i).getName());
                            System.out.println(" " + sss1.getSchuelersprecher(i).getNachname());
                            System.out.println(" " + sss1.getSchuelersprecher(i).getAlter());
                            break;
                        }

                    }
                    if(ssMissing) 
                    {
                        System.out.println("Schüler ist nicht gespeichert!");
                        System.out.println("-------------------------------------------------");
                    }
                }
                else if(f_input.equals(ksAlle)) 
                {
                    ks1.showKlassensprecher();
                }
                else if(f_input.equals(ssAlle))
                {
                    sss1.showSchuelersprecher();
                }
            }

    }           
}

Most of the function get executed. Problems appear with the case of a value that doesnt fulfill the condition. And every function from "else if(f_input.equals(ssSuche))" just jumps back to the beginning.

These are some examples from the console in the case of student search:

    Nach welcher Kategorie suchen Sie?
    Schüler
    Welche Klasse besucht der gesuchte Schüler?
    WG 13-1
    Welchen SChüler aus Klasse 13-1 suchen Sie?
    Derin
    Ihr Schüler:
    Derin
    Sipahi
    19
    Nach welcher Kategorie suchen Sie?
    Schüler
    Welche Klasse besucht der gesuchte Schüler?
    WG 13-1
    Welchen SChüler aus Klasse 13-1 suchen Sie?
    Cem
    Schüler existiert nicht oder ist nicht in dieser Klasse!
    --------------------------------------------------------
    Nach welcher Kategorie suchen Sie?
    Schüler
    Welche Klasse besucht der gesuchte Schüler?
    WG 13-2
    Welchen Schüler aus Klasse 13-2 suchen Sie?
    Cem
    Ihr Schüler:
    Cem
    Yildiz
    19
    Nach welcher Kategorie suchen Sie?
    Schüler
    Welche Klasse besucht der gesuchte Schüler? 
    WG 13-2
    Welchen Schüler aus Klasse 13-2 suchen Sie? 
    Derin
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 6
         at java.util.ArrayList.rangeCheck(Unknown Source)
         at java.util.ArrayList.get(Unknown Source)
         at package_Fachklassen.Schulklasse.getSchueler(Schulklasse.java:27)
         at package_Fachklassen.Startklasse.main(Startklasse.java:144)

This is a example of the other console output:

    Nach welcher Kategorie suchen Sie?
    Sprecher
    Suchen Sie nach Klassensprechern oder Schülersprechern?
    KS-Suche
    Geben sie den Namen der gesuchten Person ein!
    Cem
    Ihr Schüler:
     Cem
     Yildiz
     19
    Nach welcher Kategorie suchen Sie?
    Sprecher
    Suchen Sie nach Klassensprechern oder Schülersprechern?
    KS-Suche
    Geben sie den Namen der gesuchten Person ein!
    Derin
    Schüler ist nicht gespeichert!
    -------------------------------------------------
    Nach welcher Kategorie suchen Sie?
    Sprecher
    Suchen Sie nach Klassensprechern oder Schülersprechern?
    SS-Suche
    Nach welcher Kategorie suchen Sie?
    Sprecher
    Suchen Sie nach Klassensprechern oder Schülersprechern?
    KS-Alle
    Nach welcher Kategorie suchen Sie?
    Sprecher
    Suchen Sie nach Klassensprechern oder Schülersprechern?
    SS-Alle
    Nach welcher Kategorie suchen Sie?

Concatenation with Formating in bold and italics

I am trying to write a VBA code for concatenation and also format one column values to Bold and other to bold and italics. Unable to get through it . Please help

=CONCATENATE([@[Job Title]],CHAR(10),[@[Business Segment]],CHAR(10),[@[US Pay Band]],CHAR(10)," ",CHAR(10),"Incumbent - ",[@Name],CHAR(10)," ",CHAR(10),"Hay Points - ",[@[Final Hay Points]],CHAR(10))

here Job title should be bold and name should be bold and Italics

Condition on 2 arrays

Hi crew another advice needed on how to make the code more simple ... I have a pickerview with 3 different arrays : 1st is numbers from 1-25 , 2nd and 3rd - string data

Looks something like in the picture below

The first array is used only to multiply in the formula by its value For example When user picks from the pickerviewer something a math formula is executed for example “ 1 mng white “ formula is executed and everything multiplied by *1 , if user picks “2” than everything is multiplied by 2 . But a completely different formula is executed when user picks in the 2nd or 3rd array . What I’ve made is :

‘’’ if self.MyShiftType == "LMNG" , self.MyLevel == "White" { let stavkaNalog = stavka * 11 - stavka * 11 * socialka - ( stavka * 11 - stavka * 11 * socialka ) * incomeTa let matrixTax = performanceBonu * 11 - performanceBonu * 11 * socialka - ( performanceBonu * 11 - performanceBonu * 11 * socialka) * incomeTa let net = stavkaNalog + matrixTax self.result.text = "Your salary: " + (String(format:"%.2f",net * self.shiftnumber)) } “ ‘’’ As you can see I’m checking a condition if myshiftType ==“ LMNG “ , my level= “white “ it’s executes the needed formula , if user picks again LMNG and a different level I need to make again same condition an execute a formula . And here is the problem A LOT OF CODE LINES . tried a switch method but I can’t make it work when I need to select both selections and than execute a code . Is there any solution to simplify the code ?

When I for loop through an ArrayList with If condicions the items before the searched ones get displayed

I wanted to create a program which is Object Oriented, that consists of students stored in an ArrayList in the Grade class. Every Student has a name, a surname and an age. So what I wanted to accomplish is getting back all the information of one student in the ArrayList in the console by using a Scanner. So I basically store the user given value and compare it in an if-Statement with the names or surnames in the ArrayList using a for-loop. If the passed name doesn't equal one of the names in the ArrayList, a message says the person does not exist in this grade.

It works but if I loop through the ArrayList to get person on index 2 for instance, the message that the person doesn't exist in this grade pops up for index 0 and 1 and I dont want that.

I'm from Germany, thats why most of the stuff is written in German. This is the code: ` package package_Fachklassen;

import java.util.Scanner;

public class Startklasse {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Schulklasse sk1, sk2;
    sk1 = new Schulklasse("WG 13-1");
    sk2 = new Schulklasse("WG 13-2");

    //Klasse 13-1

    Schueler s1, s2, s3, s4, s5, s6, s7, s8, s9, s10;
    s1 = new Schueler("Gonzalo", "Cofre Real", 18, sk1);
    s2 = new Schueler("Swaastika", "Yogeswaran", 20, sk1);
    s3 = new Schueler("Derin", "Sipahi", 19, sk1);
    s4 = new Schueler("Henry", "Reinhold", 19, sk1);
    s5 = new Schueler("Sara", "Perkovic", 19, sk1);
    s6 = new Schueler("Honia", "Aref", 19, sk1);
    s7 = new Schueler("Finn", "Bolheimer", 17, sk1);
    s8 = new Schueler("Karoline", "Garkos", 18, sk1);
    s9 = new Schueler("Hannah", "Hirth", 18, sk1);
    s10 = new Schueler("Sarah", "Schwarz", 18, sk1);

    sk1.addSchueler(s1);
    sk1.addSchueler(s2);
    sk1.addSchueler(s3);
    sk1.addSchueler(s4);
    sk1.addSchueler(s5);
    sk1.addSchueler(s6);
    sk1.addSchueler(s7);
    sk1.addSchueler(s8);
    sk1.addSchueler(s9);
    sk1.addSchueler(s10);

    //Klasse 13-2

    Schueler ss1, ss2, ss3, ss4, ss5, ss6;
    ss1 = new Schueler("Cem", "Yildiz", 19, sk2);
    ss2 = new Schueler("Fathima", "Baba", 19, sk2);
    ss3 = new Schueler("Sanjie", "Bislimi", 19, sk2);
    ss4 = new Schueler("Jasmine", "Jaffari", 19, sk2);
    ss5 = new Schueler("Hannah", "Arent", 19, sk2);
    ss6 = new Schueler("Niklas", "Genf", 18, sk2);

    sk2.addSchueler(ss1);
    sk2.addSchueler(ss2);
    sk2.addSchueler(ss3);
    sk2.addSchueler(ss4);
    sk2.addSchueler(ss5);
    sk2.addSchueler(ss6);



    while(true) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Welche Klasse besucht der gesuchte Schüler?");
        String k_input= scan.nextLine();
        if(k_input.equals(sk1.getBezeichnung())) {
            System.out.println("Welchen SChüler aus Klasse 13-1 suchen Sie?");
            String n_input = scan.nextLine();
            for(int i = 0; i < sk1.getListenLaenge(); i++) {
                if(n_input.equals(sk1.getSchueler(i).getName()) || n_input.equals(sk1.getSchueler(i).getNachname())) {
                    System.out.println("Ihr Schüler:");
                    System.out.println(" " + sk1.getSchueler(i).getName());
                    System.out.println(" " + sk1.getSchueler(i).getNachname());
                    System.out.println(" " + sk1.getSchueler(i).getAlter());
                    break;
                }
                else if(){
                    System.out.println("Schüler existiert nicht oder ist nicht in dieser Klasse!");
                }
            }
        }
    }

} }

  • Welche Klasse besucht der gesuchte Schüler?
  • WG 13-1
  • Welchen Schüler suchen Sie?
  • Derin
  • Schüler existiert nicht oder ist nicht in dieser Klasse!
  • Schüler existiert nicht oder ist nicht in dieser Klasse!
  • Ihr Schüler:
  • Derin
  • Sipahi
  • 19
  • Welche Klasse besucht der Schüler?

List with condition to pick values less than 12

I want to give a condition to a list ("listy") that I created, and append its value to a new list ("listy2"). I have 20 points of x and y. Here is how I create listy

import numpy as np
import pandas as pd
x_y_data = pd.read_csv("x_y_points400_labeled_20pnts_csv.csv")
x = x_y_data.loc[:,'x']
y = x_y_data.loc[:,'y']
length_x = len(x)
listy=[]
for i in range(length_x):
    DistX = (x[i]-x)
    DistY = (y[i]-y)
    DistXY= np.sqrt(DistX**2+DistY**2)
    listy.append(DistXY)

Works fine until here, but.. I then tried to use a following code with the condition to get the values in listy that are less than 12:

listy2=[]
for j in listy:
    if j<12:
        listy2.append=(j)

np.savetxt("20pntslisty.csv", listy, delimiter=",", fmt='%s')
np.savetxt("20pntslisty_lessthan12.csv", listy2, delimiter=",", fmt='%s')

I get the following error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Can you help me fix this ?

here are values of x,y

    x   y
783.75  678.25
799.875 677.75
816.75  676.625
775 673.125
791.75  673.375
806.875 672.5
784 668
800.25  668.125
814.75  665.375
775.25  663.5
792.375 662.875
804.875 661
784.75  657.375

and here are values of listy:

 0 16.13275008 33.03998525 10.14042036 9.368330961 23.82914445 10.25304833 19.35886425 33.56732973 17.02388029 17.62898891 27.27321259 20.89893837
16.13275008 0   16.91245843 25.30130925 9.228014413 8.75    18.63003288 9.632302425 19.3495801  28.4508897  16.65880023 17.48034611 25.37530788
33.03998525 16.91245843 0   41.89644973 25.21036493 10.7019274  33.8666964  18.56071119 11.42639488 43.52603388 27.98576647 19.62539809 37.34384153
10.14042036 25.30130925 41.89644973 0   16.75186557 31.88112686 10.35691194 25.74028943 40.49845676 9.628246206 20.17307921 32.24176251 18.52363355
9.368330961 9.228014413 25.21036493 16.75186557 0   15.15028878 9.431496435 9.990620601 24.35159132 19.22929081 10.51858474 18.03902021 17.4642492
23.82914445 8.75    10.7019274  31.88112686 15.15028878 0   23.31342156 7.939222254 10.61985169 32.88070293 17.40375319 11.67261753 26.80076958
10.25304833 18.63003288 33.8666964  10.35691194 9.431496435 23.31342156 0   16.25048076 30.8618393  9.839334327 9.818668443 22.01739369 10.6514377
19.35886425 9.632302425 18.56071119 25.74028943 9.990620601 7.939222254 16.25048076 0   14.75847214 25.42421336 9.464572098 8.494483504 18.86299287
33.56732973 19.3495801  11.42639488 40.49845676 24.35159132 10.61985169 30.8618393  14.75847214 0   39.54447654 22.51423161 10.80075229 31.04834939
17.02388029 28.4508897  43.52603388 9.628246206 19.22929081 32.88070293 9.839334327 25.42421336 39.54447654 0   17.13640131 29.7302981  11.30334574
17.62898891 16.65880023 27.98576647 20.17307921 10.51858474 17.40375319 9.818668443 9.464572098 22.51423161 17.13640131 0   12.63984276 9.401628848
27.27321259 17.48034611 19.62539809 32.24176251 18.03902021 11.67261753 22.01739369 8.494483504 10.80075229 29.7302981  12.63984276 0   20.44886916
20.89893837 25.37530788 37.34384153 18.52363355 17.4642492  26.80076958 10.6514377  18.86299287 31.04834939 11.30334574 9.401628848 20.44886916 0

Excel Return Array if condition is true

I am trying to get something of the effect that when I have an if statement: if({TRUE;FALSE;TRUE},{1,2,3}) it will return with {1,3} is there any way to get this effect with an array of conditions and return an array of results?

Java: Why wont this if-then statement read my string correctly?

I am a very new java programmer and I can't seem to figure out why my if-then statement isn't working. I want the program to display different text depending on whether the user is a boy or girl. The problem is that whenever I test for either of these inputs, they get skipped and I get the else statment's output that prints "INVALID INPUT". Even if the user's input is correct, why wont it test for either boy or girl?

Thanks a bunch!

         Scanner userInput = new Scanner(System.in);
         System.out.println("Are you a boy or a girl?");

         gender = userInput.nextLine();
         gender = gender.toLowerCase();
         System.out.println(gender);
         if (gender == "boy") {
             System.out.println("You decide that you should try to make some short of primitive shelter for the night. Thanks to you being a boy scout, you have some knowledge of how to build");
             System.out.println("a lean-to.");
         } else if (gender == "girl") {
             System.out.println("You decide that you should try to make some short of primitive shelter for the night. Thanks to that survival book you read last summer, you have some knowledge");
             System.out.println("of how to build a lean-to.");

         } else {
             System.out.println("INVALID INPUT");
         }

         System.out.println("next");
     }```


Google Sheets Match / Query from Multiple Dynamic Dropdowns

I have a Sheet that I need to query data from another tab to match 4 if/or dynamic drop downs and 1 if/and dynamic dropdown. It's a stumper on my part. I've attached the sheet as well as a 4 min explanation video. Thanks in advance!

Sheet:

https://docs.google.com/spreadsheets/d/1rUtTJkvFKFI8Q6lnRtxNpky5bYe9u8BZBok0M8hwZ7o/edit?usp=sharing

Video:

https://www.loom.com/share/392fd41c5c0844d6ad7df308d1af9f6c

Trying to get Value from Firebase database and creating if else statement to set value in firebase but app executes the fourth line only

This is my code.

finalteamcount.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    String one = "one";
                    String two = "two";
                    String three = "three";
                    String four = "four";
                    String qwq = dataSnapshot.getValue(String.class);
                    if (qwq == null){finalteamcount.setValue(one);}
                    if (qwq == one){finalteamcount.setValue(two);}
                    if (qwq == two){finalteamcount.setValue(three);}
                    if (qwq == three){finalteamcount.setValue(four);}

                }

It Directely set four, the value i am retriving is null

Creating a list of CheckBoxed items across multiple google sheets

I'm struggling to find the right formula to do a relatively simple task. I have a google sheet document with multiple sheets that have items listed each with a checkbox. I'd like to have each item that is checked be returned in a separate sheet in order to create a list. I've tried a few VLOOKUP formulas as well as combinations of IF/MATCH logic to get there but nothing seems to be working. Here's what I'm looking at:

enter image description here

Id like the list to return the "Item Location" for each column with a checked checkbox.

Iterating inside an IF statement conditioned by a list in Python

Suppose I have a df:

     Name    Surname  Age
0    Alex    Jackson   10
1     Bob      Black   12
2  Clarke  Flingston   13
3  Claude      White   11
4   Julia     Waters   10
5  Robert    Ferrari   12
6    Anna        Red    9
7   David       Blue   10
8    Luke        Man   12

and with:

list_n = []
for age, surname in zip(df.Age, df.Surname):
    if (age != 13 and 
        age != 11 and 
        age != 10):
        list_n.append(surname)

list_n
['Black', 'Ferrari', 'Red', 'Man']

I get a list of surnames excluding the ones with a certain age. Is it possible to iterate the if condition with a list of ages?

I tried with list comprehension but it does not work as it should be:

list_age = [13,11,10]
list_n = []

for age, surname in zip(df.Age, df.Surname):
    [list_n.append(surname) for x in list_Age if age != x]

list_n
['Jackson', 'Jackson',  'Black',  'Black',  'Black', 'Flingston',
 'Flingston',  'White',  'White',  'Waters',  'Waters',  'Ferrari',
 'Ferrari',  'Ferrari',  'Red',  'Red',  'Red',  'Blue',  'Blue',
 'Man',  'Man',   'Man']

Google sheets forumla question(check many cells for data and report data if found )

I'm trying to get a formula that can search through many cells for data and report the data of that cell back

eks: J2() M2(Cake) R2() X2()

Is there an easy way to "loop" or search through these and to check if there is data?

Kinda like =If(J2,M2,R2,X2, print value) would be 'Cake'

Why am I getting syntax error in nested if..else statement in Django views

I believe in Python we can do the following:

if expression1:
   statement(s)
   if expression2:
      statement(s)
   elif expression3:
      statement(s)
   elif expression4:
      statement(s)
   else:
      statement(s)
else:
   statement(s)

I am trying to do something like this in Django views:

if qs1.count() > 100:
    # do something
elif qs1.count() - qs2(count) < 12:
    # do something else
elif qs3.count() > qs2.count():
    if qs1.count() == qs3.count():        # Error here <<
         # do whatever
else:
    # forget it

I am getting SyntaxError: invalid syntax at the code line shown.

What am I doing wrong? How do I improve the statement flow so as not to encounter an error.

Make a new column picking values from a data frame depending on the values in the same data frame in R

I got the data frame

   Z1  Z2  Z3  Z4
   AB  XX  1   100  
   BA  YY  2   200
   AB  YY  1   200
   BA  XX  2   100

And I want to make a new column picking Z1 or Z2 depending on the values in Z3 and Z4.

The conditions are if Z3= h1 or Z4=h10 then Z5 is Z1 else Z5=Z1; the table should look like this:

   Z1  Z2  Z3  Z4  Z5
   AB  XX  h1  h10 AB  
   BA  YY  h2  h20 YY
   AB  YY  h1  h20 AB
   BA  XX  h2  h10 BA

To achieve this I do:

df = within(df,{
 Z5 == ifelse(df$Z3 == "h1" | df$Z4 == "h10", df$Z1,df$Z2)
})

When I do this I get no values in df$Z5

Accessing array from JSON in if statement Node.JS

My JSON file looks something like this

module.exports={
    roles: {
        valid:["Area Director"||"Managing Director"|| "Default"]}}

And I'm trying to do this in my Node.js

if(display_title.includes(roles.roles.valid))

I want to check if my display_title includes any of the valid roles from the JSON. My Node.js syntax seems to be wrong.

jeudi 27 février 2020

how to disable and enable button with condition

i have a button and i want it to be active only if 'status' table in the database is accepted otherwise to be disabled this is the code i tried please help

        <input type="submit" class="btn btn-primary" name="nw_check" value="time in" <?php
$uname= $_SESSION['uName'];

 <div class="col-md-5">

        <input type="submit" class="btn btn-primary" name="nw_check" value="time in" <?php
$uname= $_SESSION['uName'];

$query="select * from optime where user_no='$uname'";

$Result=mysqli_query($connection,$query); $row = mysqli_fetch_array($Result);

if(isset($row['status'] )=='pending') && ($row['status']) == 'rejected'{ ?> disable >

        </div>

Select statement inside IF statement for comparing a given string with records in table

Write a procedure (oracle plsql) to do any one of the following: (a) update the table course and set the fee of the input course name equal to fee of java course. (b) insert a new row for given input course and set the fee lowest of all courses available in the table. Condition is: do (a) if the input course name is already present in the table otherwise do (b) if the input course name is not in the table.

I am providing here the basic details of table:

create table course(cid number primary key, cname varchar2(100), duration number, fee number);
insert into course (CID, CNAME, DURATION, FEE)
values (101, 'java', 30, 13000);

insert into course (CID, CNAME, DURATION, FEE)
values (102, 'c', 20, 5000);

insert into course (CID, CNAME, DURATION, FEE)
values (104, 'oracle', 20, 20000);

insert into course (CID, CNAME, DURATION, FEE)
values (105, 'python', 20, 30000);

insert into course (CID, CNAME, DURATION, FEE)
values (106, 'sql', 20, 1000);

I tried the below code but i don't know how to compare the given name for each rows in the table inside IF statement. Please take a look in the code and help me.

create or replace procedure proc_CourseFeeUpdateTry(coursename in course.cname%type,
                                                    java_fee   out number) is
  n_fee number;
  j_fee number;
begin
    if course.cname = coursename then --i'm getting error here

      select t.fee into j_fee from course t where t.cname = 'java';
      java_fee := j_fee;
      update course t set t.fee = java_fee where t.cname = coursename;
      dbms_output.put_line('new course added');
    else
      dbms_output.put_line(sqlerrm || '-' || sqlcode);
      select min(t.fee) into n_fee from course t;
      java_fee := n_fee;
      insert into course values (103, coursename, 40, java_fee);
    end if;
  commit;
end;

Converted if statement to ternary operator - compiler complains that it is not a statement

package com.myname.zed;

import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;


public class MyTest
{

    AtomicInteger counter = new AtomicInteger(100);

    @Test
    public void testAtomic()
    {
        for (int i = 1; i < 610; i++) {
            if (counter.compareAndExchange(100, 0) == 100) {
                System.out.println("trace");
            }
            else {
                counter.getAndIncrement();
            }
        }
    }

/* converted if to ternary, it is not compiling now */

    @Test
    public void testAtomic1()
    {
        for (int i = 1; i < 610; i++) {
            counter.compareAndExchange(100, 0) == 100 ? System.out.println("trace") : counter.getAndIncrement();
        }

    }

}

I need to print a log line only once out of 100 times. It works as expected when I write using if statement. I converted "if" to ternary, compiler complains it is not a statement.

Am I missing something really simple thing here? And is there any other efficient way of writing this logic.

IFELSE in R returning incorrect values

I have a data frame with categorical values that were entered manually and there are several mistakes. Someone cleaned up the bad data and I loaded that into R and merged that with the rest of my data. Everything so far is good.

As an example, let's say this is the data I have with the original (mix of good and bad data) in the "Value" column and the corrections of the bad data in the "Value_Clean" column. Obviously this is a small example but my actual data frame has dozens of corrections of different values and several thousand rows.

test <- data.frame(ID = c(1, 2, 3)
               , Value = c("Discuss plan", "Discuss plan", "Discuss paln")
               , Value_Clean = c(NA, NA, "Discuss plan"))

I would like to create a new column called "Value_Final" that has "Discuss plan" for IDs 1, 2, and 3.

It seems pretty straightforward that I should be able to accomplish this with an ifelse:

test$Value_Final <- ifelse(is.na(test$Value_Clean), test$Value, test$Value_Clean)

However, when I do that I get the following:

> test
  ID        Value  Value_Clean Value_Final
1  1 Discuss plan         <NA>           2
2  2 Discuss plan         <NA>           2
3  3 Discuss paln Discuss plan           1

What the hell? I feel like I've done similar things with ifelse in R without running into this issue, so what is going?

Thanks!

Using IF function, getting "too many

HELP! I'm getting a "too many arguments for this function" error.

=IF(B13>149,000,"T1",IF(B13>180,000,"T2",IF(B13>210,000,"T3",IF(B13>240,000,"T4",IF(B13>270,000,"T5",IF(B13>300,000,"T6"))))))

If-else statement not evaluating to true when the condition should be true

I am attempting to create a program that draws 5 random cards from a deck of cards and stores the suit and value in 2 parallel arrays, then I have to check if there are duplicate cards and re-draw them if they are duplicate. To do this I have written the following code:

        for (int i = 0; i < suit.length; i++) {
            for (int j = 0; j < 5; j++) {
                randSuit = rand.nextInt(notSuit.length);
                randValue = rand.nextInt(notValue.length);

                suit[i] = notSuit[randSuit];
                value[i] = notValue[randValue];

                firstCards[i] = copyValue[randValue] + " of " + copySuit[randSuit];
            }        
    }

    for (int i = 0; i < suit.length; i++) {
        for (int j = 1; j < 5; j++) {
            if ((suit[i] == suit[j]) && (value[i] == value[j])) { // this if statement will not evaluate to true even when the conditions are true
                randSuit = rand.nextInt(notSuit.length);
                randValue = rand.nextInt(notValue.length);

                suit[i] = notSuit[randSuit];
                value[i] = notValue[randValue];

                verifiedCards[i] = copyValue[randValue] + " of " + copySuit[randSuit];
            }
        }        
    }

The bottom 2 for loops is meant to see if the card is duplicate and if so, redraw it and store that card in the verifiedCards array. Instead, it is not running and no values are put into verifiedCards[].

So my problem is, even when there are duplicates they are not re-drawn.

Example output:

Not Verified 7 of Clubs Queen of Spades 7 of Clubs 7 of Spades Ace of Spades

Verified null null null null null

As shown, 7 of Clubs is a duplicate and the card should have been re-drawn, but it was not, and I can't figure out why.
Thanks.

How to check two string inside if condition

I know this is a bit of a silly question and sorry for that. But I bit confused about this.

I need to check when backToLobbyStatus.ErrorMessage not equal Success or Success2 need to set validationResult = backToLobbyStatus; So I wrote code as,

if ((assistCustomer != null && backToLobbyStatus.ErrorMessage != "Success") || (assistCustomer != null && backToLobbyStatus.ErrorMessage != "Success2")) {
 validationResult = backToLobbyStatus;
}

but when backToLobbyStatus.ErrorMessage == "Success", this conditon assistCustomer != null && backToLobbyStatus.ErrorMessage != "Success2" getting true, What did I do wrong here. How to handle this properly without nested if condtion. or is nested if is the most proper way to handle this error?

js - multiple if statements, if condition isnt met the following if statements are not checked

I have the following if statements, but if the first condition is not met the following if statements are not checked. I need them all to be checked.

document.addEventListener('DOMContentLoaded', function() {
   if(document.getElementById('firstname').value = "unsolicited"){document.getElementById('firstname').value = "";}
   if(document.getElementById('mobile').value = "unsolicited"){document.getElementById('mobile').value = "";}
   if(document.getElementById('email').value = "unsolicited@gmail.com"){document.getElementById('email').value = "";}
}, false);

Thanks so much in advance!

Change Install Directory If Running Catalina But Not on Mojave

Needing to run the appblocker software in our macs in our corporate environment. Currently, the code / appblocker works on Mojave but not Catalina due to the dual hard drive issue it creates (link below).

Hopefully it's an easy one but I cant get it to work. I need a piece of python code, where if the user is on MacOS Catalina, it changes the directory and runs the appblocker, if it is on Mojave, just run the appblocker normally. I've linked all the resources I've used below in including Catalina's dual hard drive, and where I got the appblocker from (recommendation from our vendor.)

The code I use can be found under the github link below under AppBlocker.py

https://github.com/erikberglund/AppBlocker

https://www.launchd.info/

https://www.macworld.com/article/3451363/why-you-might-see-a-new-data-disk-in-catalina.html

Javascript Ternary Operator I need to make a code Help me plss [closed]

Hey i need to make a code That ask the user for his postal code. And if the Postal code is even to: 1010ST There should appear a alert pop-up With the next input: 'Kans op de Nationale Postcode Loterij is 90%' And if its not even to 1010ST there should appear this input: 'Kans op de Nationale Postcode Loterij is 0,969%'

Will there be a performance difference in this case? [closed]

Consider a function like this:

const someFunction = () => {
 if(someCondition) {
  return 'something';
 } else {
  return 'nothing';
 }
}

and if I wrote it this way:

const someFunction = () => {
 if(someCondition) {
  return 'something';
 }
 return 'nothing';
}

Now both of them do the same thing and in the latter function because of the return keyword the part below the if statement doesn't get executed.

Aside from how they look will there be a performance difference between the above two functions?

Make this code shorter without using loops

import random
a = random.randrange(1,100)
b = random.randrange(1,100)
c = random.randrange(1,100)
d = random.randrange(1,100)
e = random.randrange(1,100)
print('Random numbers: ',a,b,c,d,e)
sumEven = 0
sumOdd = 0
print("Even numbers: ")
if (a%2)==0:
    sumEven = sumEven+a
    print(a,end=" ")
if (b%2)==0:
    sumEven = sumEven+b
    print(b,end=" ")
if (c%2)==0:
    sumEven = sumEven+c
    print(c,end=" ")
if (d%2)==0:
    sumEven = sumEven+d
    print(d,end=" ")
if (e%2)==0:
    sumEven = sumEven+e
    print(e,end=" ")
print("\nOdd numbers: ")
if (a%2)!=0:
    sumOdd = sumOdd+a
    print(a,end=" ")
if (b%2)!=0:
    sumOdd = sumOdd+b
    print(b,end=" ")
if (c%2)!=0:
    sumOdd = sumOdd+c
    print(c,end=" ")
if (d%2)!=0:
    sumOdd = sumOdd+d
    print(d,end=" ")
if (e%2)!=0:
    sumOdd = sumOdd+e
    print(e,end=" ")

    print("\nSum of all even numbers: ",sumEven)
    print("Sum of all odd numbers:", sumOdd) 

Please make it shorter suggest shorter code, but without using loops the purpose of the program is to separate odd numbers from even numbers and get the sum of all odd numbers also get the sum of all even numbers

Evaluate value for multiple ranges

what I am looking to achieve, is to take a Value for temperature, and check where it exists within certain ranges and to return a colour based on predefined thresholds.

I am using a customized Javascript color gradient to generate the colour gradients.

var temperatureThreasholds      = [15, 20, 24, 35];

var colourRangeTemperatureCold  =   generateColor("#00FFa0", "#0000FF", temperatureThreasholds[1] - temperatureThreasholds[0] + 1);
var colourRangeTemperatureWarm  =   generateColor("#FF0000", "#A0FF00", (temperatureThreasholds[3] - temperatureThreasholds[2]) + 1);

var _value = Math.round(Value); // Drop the decimal point for evaluation, round to nearest whole number

if      ( _value <= temperatureThreasholds[0] )       return [0, 0, 255, 200];
else if ( _value < temperatureThreasholds[1] )        return colourRangeTemperatureCold[_value - temperatureThreasholds[0]];
else if ( _value >= temperatureThreasholds[3] )       return [255, 0, 0, 200];
else if ( _value > temperatureThreasholds[2] )        return colourRangeTemperatureWarm[_value - (temperatureThreasholds[2] + 1)];
else if ( _value >= temperatureThreasholds[1] &&
          _value <= temperatureThreasholds[2] )       return [0, 255, 0, 128];
else                                                  return [237, 237, 237, 128];  // If the room highlights in gray then the value wasn't caught in logic

Any support to reduce the code and make it easier to read would be greatly appreaciate.

IF statement doesn't allow Select statement to compare the given string

I have a query here: Please download and see the screenshot where i have mentioned many things: 1) In picture 2, i tried to compare if the given course name is present in the table or not using cursor (BECAUSE I TRIED TO COMPARE IT USING IF STATEMENT BUT IT WAS GIVING ME ERROR THAT I CAN'T USE SELECT QUERY IN IF STATEMENT, I DON"T KNOW WHY). Procedure is compiled but after execution, no row is getting affected.

2) In picture 3, I tried the count to be compared in IF statement which is easy but im not sure to use it. I want to use the SELECT statement to compare.

3) In picture 4, FETCHNAME_CUR.CNAME is okay but when running it is giving me error of UNIQUE CONSTRAINT VIOLATION which i don't understand why.

Finally, How can i check if the given name is present in any column of a table using select statement and then use IF statement to do some work without using any COUNT or counter (which is easily comparable in IF statement). Please help me. Many thanks.download the image by clicking here

Why does my python code think that this character is bigger than another?

I'm trying to create a robot that plays "Big 2" card game.

My goal was to start off with making it only play 1 card plays. I am trying to test it out, returning True if number 1 is bigger than number 2 and False if it is not.

RANK_ORDER = '34567890JQKA2'
SUIT_ORDER = 'DCHS'

def is_higher(card1, card2):
  a = list(card1)
  b = list(card2)
  if a[0] == b[0]:
    if a[1] > b[1] in SUIT_ORDER:
      return True
    elif a[1] < b[1] in SUIT_ORDER:
      return False
  elif a[1] > b[1] in SUIT_ORDER:
    return True
  elif a[1] < b[1] in SUIT_ORDER:
    return False
  elif a[1] == b[1]: #problem may be from here downwards
    if a[0] > b[0] in RANK_ORDER:
      return True
    elif a[0] < b[0] in RANK_ORDER:
      return False

if __name__ == '__main__':
  print(is_higher('8D', '9S'))
  print(is_higher('2S', '2D'))
  print(is_higher('3H', '2H')) #this has a problem
  print(is_higher('QS', 'JS'))
  print(is_higher('AD', '2S'))

I have somewhat succeeded in my goal, however, why does it return True for third example even though 3 is higher than 2 in RANK_ORDER?

If Condition Simplification

I'm refactoring a code snippet in which I see the following condition that I wonder whether it's simplified.

data.RecordId != 0 || (data.RecordId == 0 && data.SerialNum == "0000")

Isn't data.RecordId == 0 || data.SerialNum == "0000" same of that?

If it is possible, how come? Could you detailed?

Can't verify result from SSH

I'm verifying matches of a file via SSH to a host ubunty system, and the if statement is not correctly processing the result.

export FILENAME=test.txt
export NUM=$(ssh -t ubuntu@192.168.XXX.XXX "ls ~/Documents/ | grep '$FILENAME' | wc -l")
echo "Received value: $NUM"
if [ $NUM == 0 ]; then
    echo "If processed as: 0"
else
    echo "If processed as: 1"
fi

So if $FILENAME exists, I get the following output

Connection to 192.168.XXX.XXX closed.
Received value: 1
If processed as: 1

And if not, I get the following one

Connection to 192.168.XXX.XXX closed.
Received value: 0
If processed as: 1

Why may this be happening? Am I getting a wrong formatted value? If I force before the if statement NUM=0 or NUM=1 it gets correctly processed.

karate: assist in finding solution for nested if condition in json response. i tried my best to put my question out there

I have lengthy json response (350 lines - tend to increase based on inputs) that has 24 source codes + overall status code.

business logic implemented as:: 
Overall status code = GREEN if all (24 codes) are GREEN;
RED if any of them is RED;
YELLOW is any of them is YELLOW and none is RED;

I have tried this logic step be step as below, also pls suggest me with the minimum lines code to achieve that.

    * def result = callonce read('file.feature')

    Then match result.response.StatusCode == 200
    Then match result.response.Message == 'Request Successful'

    * def final = result.response
    * st1 = final.Result[0].ssmCore.missing.status
    * st2 = final.Result[0].ssmCore.zero.status
    * st3 = final.Result[0].ssmCore.sw.status
    * st4 = final.Result[0].ssmCore.bum.status
    * st5 = final.Result[0].ssmComm.missing.status
    * st6 = final.Result[0].ssmComm.zero.status
    * st7 = final.Result[0].ssmComm.sw.status
    * st8 = final.Result[0].ssmComm.bum.status
    * st9 = final.Result[0].ssmmas.missing.status
    * st10 = final.Result[0].ssmmas.zero.status
    * st11 = final.Result[0].ssmmas.sw.status
    * st12 = final.Result[0].ssmmas.bum.status
    * st13 = final.Result[0].ssmris.missing.status
    * st14 = final.Result[0].ssmris.zero.status
    * st15 = final.Result[0].ssmris.sw.status
    * st16 = final.Result[0].ssmris.bum.status
    * st17 = final.Result[0].ssmhist.missing.status
    * st18 = final.Result[0].ssmhist.zero.status
    * st19 = final.Result[0].ssmhist.sw.status
    * st20 = final.Result[0].ssmhist.bum.status
    * st21 = final.Result[0].ssmpr.missing.status
    * st22 = final.Result[0].ssmpr.zero.status
    * st23 = final.Result[0].ssmpr.sw.status
    * st24 = final.Result[0].ssmpr.bum.status

    * def overallStatus = final.Result[0].Sourcestatus

    * def ssmcorestatus = '{st1 == "RED" || st2 == "RED" || st3 == "RED"  || st4 == "RED" }' ? 'RED' : 'GREEN'
    * def ssmCommstatus = '{st5 == "RED" || st6 == "RED" || st7 == "RED"  || st8 == "RED" }' ? 'RED' : 'GREEN'
    * def ssmmasstatus = '{st9 == "RED" || st10 == "RED" || st11 == "RED"  || st12 == "RED" }' ? 'RED' : 'GREEN'
    * def ssmrisstatus = '{st13 == "RED" || st14 == "RED" || st15 == "RED"  || st16 == "RED" }' ? 'RED' : 'GREEN'
    * def ssmhiststatus = '{st17 == "RED" || st18 == "RED" || st19 == "RED"  || st20 == "RED" }' ? 'RED' : 'GREEN'
    * def ssmprstatus = '{st21 == "RED" || st22 == "RED" || st23 == "RED"  || st24 == "RED" }' ? 'RED' : 'GREEN'


    * def status = '{ssmcorestatus == "RED" || ssmCommstatus == "RED" || ssmmasstatus == "RED"  || ssmrisstatus == "RED" || ssmhiststatus == "RED" || ssmprstatus == "RED" }' ? 'RED' : 'GREEN'

    * print overallStatus
    * print status

    * match overallStatus == status

How can I convert this to an Arrow Function? [duplicate]

Is it possible to rewrite this code to an Arrow Function?


    const inputEl = document.querySelector("input");
inputEl.addEventListener("keyup", fixLength);

function fixLength() {
  let inputString = inputEl.value;
  if (inputString.length > 12) {
    inputString = inputString.slice(0, 12);
    inputEl.value = inputString;
  }
}

Python For loops with while and if statements: Why doesnt it return in the first case?

Hey guys I know this question might seem dumb, but I just started. This is Python 3.7.
Any way I have written 2 versions of the code, the second one works, but I've added another while loop where I thought it wasn't needed. Why doesn't the first version work? Its iterating a list of numbers (nums).

This is from a problem statement: Write a function that takes in a list of integers and returns True if it contains 007 in order.

  • spy_game([1,2,4,0,0,7,5]) --> True
  • spy_game([1,0,2,4,0,5,7]) --> True
  • spy_game([1,7,2,0,4,5,0]) --> False

My first code was this, and it always returned False:

z = 0

for i in nums:
    while z < 2:
        if i != 0:
            break
        else:
            z += 1
            break
    if i != 7:
        break
    else:
        return True

return False

Why does this change, make it work?

z = 0

for i in nums:
    while z < 2:
        if i != 0:
            break
        else:
            z += 1
            break
    while not z < 2:
        if i != 7:
            break
        else:
            return True

return False

Thanks very much!

what expression should i wrtie in python for this R code

x=["245.2","256.3"]
y=["205.7","205.1"]
z=["202.4","250.5"]
'''output <-- function(x=NULL, y=NULL , z= NULL)
{
if(is.vector(x) & is.vector(y) & is.vector(z)){
    data %>%
      select(x,y,z) %>% #selecting the desired columns
      filter_at(.vars= x, any_var(.==1)) %>%
      filter_at(.vars= y, any_var(.==1)) %>%
      filter_at(.vars= z, any_var(.==1)) %>%
      summarise(Total= n())      
  } else if(is.vector(x) &is.vector(y)){
      data%>%
      select(x,y)
      filter_at(.vars = x, any_vars(.==1))%>%
      filter_at(.vars = y, any_vars(.==1)) %>%
      summarise(Total= n())      
    } else if(is.vector(x)){
      data%>%
      select(x)
      filter_at(.vars = x, any_vars(.==1))%>%
      summarise(Total= n())
    } else
        print("enter a valid vector of code")
}
'''

here i have to put a function of filter and is to check that data is vector than function is pass. thanks in advance

mercredi 26 février 2020

In too deep. Mixing If with And statements. Do I need an array?

I find myself deep in the Excel rabbit hole and I can't get out.

Column A has values; Column B has a drop-down list (3 items). Cells K1:M10 also have values.

I am trying to write a formula that says:

If A1 is 1 AND B2 has dropdown value "Name1" then insert K1. If A1 is >1 AND B2 has dropdown value of "Name1" then Sum K1:K10.

If A1 1 AND B2 has dropdown value "Name2" then insert L1. If A1 is >1 AND B2 has dropdown value of "Name2" then Sum L1:L10.

If A1 1 AND B2 has dropdown value "Name3" then insert M1. If A1 is >1 AND B2 has dropdown value of "Name3" then Sum M1:M10.

I have figured out pieces of this (I have a formula working for each pair of lines above) but I can't seem to put it all together successfully.

I'm afraid I'm in over my head. Can anyone offer help? Do I need to learn about arrays?

Creating extra columns based on condition (Case When Sum)

I have survey table where someone is asked roughly 5 questions. 4 of those questions are the same questions, but the options to their answers are different since they were to understand their purchase.

Here are the questions:

 ID                Question                            qid                         Answer
 101005 what brands did you purchase the past 5 months  1          Coca-Cola or Pepsi or Dr.Pepper
 101005 what brands did you purchase the past 5 months  1                       Dr.Pepper
 101005 what brands did you purchase the past 5 months  1                      store brand
 101005 what brands did you purchase the past 5 months  1                      Coca-Cola
 101005  how many people live in your house             4                           4
 101005  what is your prefer retailers                  8                          walmart 

The goal is to create four extra columns based on their answer and they will be assigned a 1 or 0. Since this person's answer is coca cola, I want to assign them in the column of current_buyer and give them 1 and 0 will be new_buyer column. I also want to make sure that even though he answer Dr.Pepper in the second row, it still recognizes him as a current_buyer. In the same breath I want to assign this person a 1 in the 3rd column as a drinker and 0 4th column in prospect.

Here is how the table should look like

  ID             Question                             qid               answer                    Current_buyer    New_buyer   drinker    prospect      
 101005 what brands did you purchase the past 5 months  1        Coca-Cola or Pepsi or Dr.Pepper      1               0             1        0
 101005 what brands did you purchase the past 5 months  1                       Dr.Pepper             1               0             1        0
 101005 how many people live in your house              4                            4                1               0             1        0

The goal is to see if ID bought coca-cola the past 5 months, they are a current buyer (1) and drinker (1) and will have (0) for new_buyer and prospect in their entire profile.

Here is the code that I try:

 select ID,qid,question,answer,s_date,   
 Case when Sum(Case when [answer] like'%coca-cola%' then 1 else 0 end)>=1 then 1 
 else 0 end  current_buyer
 ,Case when Sum(Case when [answer] like'%coca-cola%' then 1 else 0 end)=0 then 1 
  else 0 end  New_buyer 
 ,Case when Sum(Case when [answer] like'%coca-cola,Dr.pepper,pepsi%' then 1 else 0 end)>=1 then 1 
  else 0 end  drinker
 ,Case when Sum(Case when [answer] like'%coca-cola,Dr.pepper,pepsi%' then 1 else 0 end)=0 then 1 
  else 0 end  Prospect

Unfortunately, using this code I'm getting 0 in the drinker column even though people selected coca-cola. Any help would be appreciated.

Echo in one line

It's my first post, so I hope that I am doing everything correct.

I want to add the following PHP code to my site. The code is supposed to display 1-3 images depending on the product ID. The first image displays on every product page, the next two will be displayed depending on the id.

Everything is working great, but I am not able to display images in one row. Right now, the images are displayed under each other.

Would you be able to advise me?

/**
 * Add a selling points to single product page
 */
add_action( 'woocommerce_before_add_to_cart_form', 'bbloomer_single_product_ID', 10 );

function bbloomer_single_product_ID() {
 if(is_single()){
    echo '<div class="product_delivery_icon">
        <div class="pdf">
          <div class="pdf_icon">
            <img src="demo1.png">
          </div>
          <div class="pdf_name">Description 1</div>
        </div>
  </div>';
}if (is_single(array(1, 2, 3))){
    echo '<div class="product_delivery_icon">
        <div class="pdf">
          <div class="pdf_icon">
            <img src="demo2.png">
          </div>
          <div class="pdf_name">Description 2</div>
        </div>
  </div>';
}if (is_single(array(2, 4))){
    echo '<div class="product_delivery_icon">
        <div class="pdf">
          <div class="pdf_icon">
            <img src="demo3.png">
          </div>
          <div class="pdf_name">Description 3</div>
        </div>
  </div>';
}
}

Why does the else statement still play if the if statement in python for a while loop

I decided to make a mini-game as my 1st program since I am very new to python. The user must enter yes to start the game if you type no the program is supposed to say "bye-bye" and end. if anything else is entered it print "I do not understand bye-bye" However when I enter no it plays the else statement along with what was supposed to play when it enters no. How do I fix this? This is my program (sorry if it's a little long). You can run it and type no to see what I mean.

light_on = False
door_open = False
print('hello')
start = input('Would you like to play a game yes or no ? ').lower() 
if start == 'no':
 print('bye bye')
while start == 'yes':
 print('Type help if you do not know how to play')
 command = input('Command?: ').lower()
 if command == 'help':
   print('''
on = turn light on
off = turn light off
open = open door
close = close door''')
 elif command == 'on':
   if light_on:
     print('The light is already on')
   else:
     light_on = True
     print('The light is bright and warming')
 elif command == 'off':
   if not light_on:
     print('the light is already off')
   else:
     light_on = False
     print('the room is dark and scary')
 elif command == 'open':
   if door_open:
     print('the door is already open!')
   else:
     door_open = True
     print('the hallway is so dark you cannot see')
 elif command == 'close':
   if not door_open:
     print('the door is already closed!')
   else:
     door_open = False
     print('you slammed the door shut')
 elif command == 'quit':
   print('bye bye')
   break
 else:
   print('I do not understand')
else:
  print('I do not understand bye bye')

How do I use a for loop to select certain values and put this into a new table of data?

My data frame consists of variable gene expression values recorded at two time points for one of three groups ( either control which is 0, ulcerative colitis which is 1 and Crohns which is 2). Where the ID is the same number, the top value is the first time point and the second value is the second time point.

Please find below my data frame to help explain; Dput(data)

   structure(list(X = c(0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 0, 0, 2, 2, 
   1, 1, 0, 0, 0, 0, 2, 2, 1, 1, 2, 2), ID = c(44, 44, 68, 68, 77, 
   77, 119, 119, 453, 453, 654, 654, 776, 776, 888, 888, 876, 876, 
   899, 899, 901, 901, 987, 987, 990, 990), Gene1 = c(5.54e-05, 
   5.58e-06, 9.74e-05, 1.33e-06, 1.29e-05, 7.22e-06, 0.000215899, 
   3.6e-06, 0.000146724, 1.53e-05, 0.000913187, 1.9e-06, 0.007421464, 
   0.000648006, 5.1e-06, 6.15e-06, 4.73e-06, 0.000119899, 0.000884487, 
   0.000850632, 0.000236607, 7.36e-06, 8.48e-06, 2.63e-05, 0.001368493, 
   1.12e-05), Gene2 = c(0.006338532, 0.006162866, 0.040695132, 0.013255055, 
   0.033086619, 0.074158811, 0.004967497, 0.01247423, 0.043201417, 
   0.011470285, 0.038447751, 0.018825124, 0.027701807, 0.063373762, 
   0.005374513, 0.048876252, 0.009959848, 0.004434078, 0.004176856, 
   0.015288913, 0.060226053, 0.05128922, 0.006557554, 0.017460326, 
   0.007684784, 0.002107577), Gene3 = c(0.076186393, 0.037631043, 
   0.052159393, 0.012179365, 0.047199766, 0.022458838, 0.030261613,  
   0.00626629, 0.028664896, 0.02285845, 0.02801855, 0.017681676, 
   0.040563592, 0.029791175, 0.034778056, 0.019318473, 0.011847912, 
   0.009614177, 0.064027542, 0.035334149, 0.041638955, 0.056015014, 
   0.03304865, 0.017660205, 0.030187166, 0.057919531), Gene4 = c(0.000112884, 
   0.000920886, 0.001081748, 0.000195159, 0.001678445, 0.000171612, 
   0.000191702, 0.000560035, 0.000384056, 0.000454783, 0.000723385, 
   0.000203897, 0.000973337, 0.000822171, 0.000620526, 0.000260769, 
   0.000214607, 0.002077443, 0.00065843, 0.000403672, 0.000378651, 
   0.000409306, 0.001722587, 0.000213785, 0.000176643, 0.002022878
   ), Gene5 = c(0.053029236, 0.022594965, 0.011967636, 0.026851113, 
   0.03773798, 0.031356268, 0.10410326, 0.063265216, 0.018028454, 
   0.116038001, 0.00572817, 0.053635968, 0.059126941, 0.011835241, 
   0.004639624, 0.014302911, 0.082948853, 0.015202238, 0.021295431, 
   0.043342, 0.008153675, 0.015613747, 0.043289609, 0.048834321,  
   0.019144763, 0.059809871), Gene6 = c(0.04082966, 0.02986135, 
   0.061405171, 0.006142619, 0.009767602, 0.035427993, 0.03729329, 
   0.01309739, 0.00221718, 0.040211393, 0.006303841, 0.030146612, 
   0.032033879, 0.024590398, 0.077991721, 0.017215666, 0.014731147,    
   0.04802582, 0.03168714, 0.03244771, 0.032278613, 0.017301885, 
   0.013450667, 0.040207755, 0.042669615, 0.03456749), Gene7 = c(1.93e-05, 
   4.72e-06, 5.41e-05, 0, 1.91e-05, 9.33e-07, 5.98e-06, 0, 1.05e-06, 
   4.1e-07, 7.72e-05, 4.07e-07, 0.000585154, 0.000246992, 7.86e-06, 
   3.13e-06, 2.14e-06, 7.56e-06, 9.29e-05, 0.000116024, 5.51e-05, 
   7.79e-06, 6.65e-06, 2.06e-06, 0.000104342, 4.16e-06), Gene8 = c(0.000197502, 
   0.00015135, 0.000107306, 6.54e-05, 0.000225564, 0.000142631, 
   0.000168873, 3.5e-05, 0.000365242, 0.000174254, 0.000339327, 
  8.7e-05, 0.000136679, 0.000156634, 0.000224181, 0.000205305, 
  8.87e-05, 0.000305774, 0.000133615, 0.00015118, 0.000107229, 
  0.000162579, 0.000152249, 6.88e-05, 0.000113864, 0.000249258), 
  Gene9 = c(0.00079296, 0.007640951, 0.004937327, 0.000422361, 
  0.000953513, 0.000951187, 0.000671306, 0.001106406, 0.002606568, 
  0.003006867, 0.001911646, 0.00135411, 0.012461738, 0.000434917, 
  0.00237646, 0.007857561, 0.000436889, 0.00048816, 0.000348146, 
  0.000931449, 0.000323974, 0.004945321, 0.000693845, 0.000479572, 
  0.000843415, 0.001419675), Gene10 = c(8.16e-05, 6.63e-05, 
  0.000101583, 3.08e-05, 0.000147039, 5.13e-05, 0.000109479, 
  2.39e-05, 0.000225475, 4.28e-05, 0.000230785, 2.1e-05, 0.0001356, 
  0.000124173, 0.000245128, 0.000275446, 3.18e-05, 0.00017516, 
  0.000180192, 0.000246669, 0.000378708, 4.35e-05, 0.000267824, 
  7.2e-05, 7.65e-05, 8.79e-05), Gene11 = c(0.000111462, 3.17e-05, 
  0.000200096, 3.12e-06, 8.75e-05, 3.11e-06, 6.89e-06, 0.000165936, 
  5.98e-05, 0.000201355, 5.92e-06, 2.57e-05, 2.53e-05, 3.27e-05, 
  0.000137446, 0.000134402, 5.86e-07, 3.9e-05, 0.018886909, 
  0.050343466, 4.15e-05, 1.67e-05, 0.000172614, 4.95e-05, 1.27e-05, 
  9.85e-05), Gene12 = c(0.002708402, 0.003215586, 0.00457116, 
  0.001713549, 0.024353184, 0.006660748, 0.003198887, 0.003094386, 
  0.004789163, 0.002816955, 0.021587313, 0.002084725, 0.00378062, 
  0.021751495, 0.009097143, 0.012216225, 0.001125765, 0.013043534, 
  0.005514773, 0.008323962, 0.026898764, 0.002149135, 0.008021623, 
  0.006673567, 0.005391139, 0.018578559), Gene13 = c(0.00080595, 
  0.001289505, 0.002451416, 0.000234107, 0.001694733, 0.000288175, 
  0.002357478, 0.000856129, 0.00159752, 0.000117538, 0.000166581, 
  0.000367288, 0.001039841, 0.001779528, 0.000438092, 0.001012515, 
  0.000529936, 0.003193086, 0.002562702, 0.00277401, 0.003013136, 
  0.001349197, 0.001646296, 0.001114222, 0.001207882, 0.002804949
  )), class = "data.frame", row.names = c(NA, 26L))

I have calculated the distance between the samples using this code;

  distances <- as.matrix(vegdist(data[,3:15], method="euclidean", diag=F))

I now need to formulate a table, where each of the three columns (corresponding to either control, ulcerative colitis or Crohn’s) contains the distances between the first and second-time points. So control will have 5, UC will have 4 and Crohn’s will have 4.

I understand that I will need a for loop and will need to also use if. I am struggling as to where to start with this. Please could anybody advise?

Can python condition when I can only use 1 variable? [closed]

I'm new in Python,and I want to make a program like button debouncing using state and a to control and I need to used in a looping system

I can only control a,this make i=+1 looped when a = True ,so my question is is there any possible way to use if correctly and make i=+1 only 1 times when I let a = True,and when a = False,set and reset need to be False,so on

code for example:

state =True //a and b controlling,since b is True,so does state
a = //True or false 
b = True
set = False //default
reset = False //default

do{
  if a == True:
    set = True
  if state == True: #problem here,I can only use a,b and state to do condition 
    if set == True:
      reset = True
  if set == True & reset = True :
    i+=1
    set = False
    reset = False


while(1) //infinite loop 

ok I'm so bad at creating a title

Shell : How to put multiple statements in one line if

I'm facing a little issue with my "IF" tests.

What I want to do :

if [[ "$foo" == "TEST" ]]
then
  echo "OK"
else
  echo "KO"
  return 1
fi

My first try in one line if :

[[ "$foo" == "TEST" ]] && echo "OK" || echo "KO"; return 1

But the return is applied either if the test is right or wrong.

Second try :

[[ "$foo" == "TEST" ]] && echo "OK" || (echo "KO"; return 1)

The return 1 is executed, but does not exit my function. I've found that the brackets are interpreted as a sub-shell.

I have no idea how to do what I want to do. Is that even possible ?

Thanks in advance, Steve

How can I ask a user for 4 numbers and print them out sorted (ascending / descending)? [duplicate]

When I use this code it asks the user for 4 numbers.

When you write in the 4 numbers it prints them as wanted.

Then I want to ask the user for ascending or descending order, but the code just ends.

import java.util.Collections;
import java.util.Scanner;  //import scanner class
import java.util.ArrayList;

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

    Scanner scanner = new Scanner (System.in);  //create a scanner object
    System.out.println("Enter 4 numbers");

    //numerical input
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    int c = scanner.nextInt();
    int d = scanner.nextInt();

    System.out.println(a + "." + b + "." + c + "." + d);

    System.out.println("you want the numbers by order? (descending / ascending)");
    String order = scanner.nextLine();

    ArrayList<Integer>
            list = new ArrayList<Integer>();

    list.add (a);
    list.add (b);
    list.add (c);
    list.add (d);

    if (order == "ascending"){
        Collections.sort(list);
        System.out.println(list);
    } if (order == "descending"){
        Collections.sort(list, Collections.reverseOrder());
        System.out.println(list);
    }
}

}

How to test if $host in nginx.conf starts with a substring and defining variables?

Is here a way to test if the $host variable for example starts with "www." for example?

if () {
...
}

How about if we wanted to test if it contains a certain substring?

And is here a way to define our own variables (global and local)?

Thanks.

how to start another command with if statement when textview value match float value

i'm new to coding... I have a textview which value changes on user input...how to add another command that will trigger if textview value matches with value I've chosen. for example textview changes to 2.0 from 0.0 and i've set if textview =2.0 then it will show a toast message

multiple IF statements within try except

So my script below is pulling live date from a websocket and parsing it. It can either come as [params][channel], or it can come as a [params][type].

As you can see from my code below depending on which it is I parse it and assign values in the date to my variables.

However the script never goes into the second elif statement. Even when there is a data1["params"]["type"] == "test_request". For some reason it is not moving onto the elif statement, but straight onto pass. I know this because I switched the if statement around and the first if statement is the only one that runs.

I am thinking it is caused by the try except. Any help would be appreciated.

      response1 = await websocket.recv()
      data1 = json.loads(response1)

      try:
        if data1["params"]["channel"]:
          if data1["params"]["channel"] == perp_ticker:
            perp_bid_price = data1["params"]["data"]["best_bid_price"]   
            perp_ask_price = data1["params"]["data"]["best_ask_price"]   
          elif data1["params"]["channel"] == far2_ticker:    
            far2_bid_price = data1["params"]["data"]["best_bid_price"]   
            far2_ask_price = data1["params"]["data"]["best_ask_price"]   
          elif data1["params"]["channel"] == far3_ticker:
            far3_bid_price = data1["params"]["data"]["best_bid_price"]   
            far3_ask_price = data1["params"]["data"]["best_ask_price"]   
        elif data1["params"]["type"] == "test_request" :
          await websocket.send(msg_publictest)
          print('response sent to heartbeat')
      except:
        pass

Why are my python nested if statements not working? [duplicate]

I am making a logic gate program and have this code:

gate = input("Enter gate:\t")
in1 = input("\nEnter first input:\t")
in2 = input("\nEnter second input:\t")

if gate  == "OR":
  if in1 == 1:
    print("\nResult:\t1")

if gate  == "OR":
  if in1 == 1:
    print("\nResult:\t1")
  elif in2 == 1:
    print("\nResult:\t1")
  else:
    print("\nResult:\t0")

elif gate == "AND":
  if in1 == 1 and in2 == 1:
    print("\nResult:\t1")
  else:
    print("\nResult:\t0")

elif gate == "NAND":
  if in1 == 1 and in2 == 1:
    print("\nResult:\t0")
  else:
    print("\nResult:\t1")

elif gate == "XOR":
  if in1 != in2:
    print("\nResult:\t1")
  else:
    print("\nResult:\t0")

elif gate == "NOT":
  if in1 == 0:
    print("\nResult:\t1")
  else:
    print("\nResult:\t0")

elif gate == "NOR":
  if in1 == 0 and in2 == 0:
    print("\nResult:\t1")
  elif in1 == 0 and in2 == 1:
    print("\nResult:\t0")
  elif in1 == in2:
    print("\nResult:\t1")
  else:
    print("\nResult:\t0")

else:
  print("\nEnter a valid logic gate")

But it never returns anything.

I have also translated this into java and it also does not seem to be working

As an aside, on line 10, I get this error: [mccabe] Cyclomatic complexity too high: 16 (threshold 15)

What am I doing wrong?

Thanks in advance.

Javascript nested if statements

I made a simple slideshow using jQuery that checks how many images are in the folder using AJAX and than compares it with index of image to be shown. If the index is to be larger than the amount of images in the folder the index changes to 1 and whole slideshow starts over (and the other way round). The if statement for previous img looks like this (for the next img very alike):

if (SlideNo > SlideMin) {
  SlideNo--;
} else {
  SlideNo = SlideMax;  
};

It works quite well. Now I am trying to implement change of image using keyup function, unfortunately I am not able to implement this if statement into the one that checks which key is pressed. I tried sth like this:

$(document).keyup(function(e){
  if (e.keyCode === 27) {
    $('#overlay').css('display','none');
    SlideMax = -2;
    $(document.body).removeClass('noscroll');
  };
  else if (e.keyCode === 37) {
    if (SlideNo > SlideMin) {
      SlideNo--;
    } else {
      SlideNo = SlideMax;
    };
  };
});

Guess it's just a syntax error but I'm not really able to find what's wrong. Thanks for your help!

my if statment not working i cant find out why? " if (y == "0") " [duplicate]

this is my code and my method suppose to return true, i try to use jtextarea to get 2 lines . " if (y == "0") " looks fine to me i event try charat and its not working.

any one knows how to fix it ? and thank you.


    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JTextPane txt = new JTextPane();
        txt.setEditable(false);
        txt.setText("\r\n0");
        txt.setBounds(10, 11, 414, 57);
        frame.getContentPane().add(txt);

        JButton btn = new JButton("New button");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                txt.setText(str(txt.getText()));
            }
        });
        btn.setBounds(161, 114, 89, 23);
        frame.getContentPane().add(btn);
    }
    public String str(String o){

        String[] nt=o.split("\n");
        String x=nt[0],y=nt[1];


            if (y == "0")
            {   
            o="true";

            }
            else 
            {
                System.out.println(y);
                o="false"+y+"*";
        }
        return o;
        }

How to make a number looped when it's entered on a text box

This is Javascript and also html (i think so)

So, I want to make a textbox, and when you type a certain number and when you submit it, it loops. Example, enter 1 and it loops from 1 to 10, enter 2 and it loops from 2 to 20. basically, a number entered will loop * 10 of it.

jQuery .on(click) function containing IF statement checking for .hasClass() always returning true when it does not contain the class?

I have been battling a dodgy IF that keeps returning a true value although the class it is checking for is not present on page load.

I am trying to add the class if it is not there, then remove the class when it is there.

The console.logs show it is correctly grabbing the attributes for popular-value & full, successfully logging these in their respective console.logs. However, the IF always console.logs 'has class'.

Here is the function:

$(document).on("click", ".popular-tag", function(){
    var popularTag = $(this);
    var popularTagSlug = popularTag.attr('popular-value');
    console.log(popularTagSlug);
    var popularTagName = popularTag.attr('popular-full');
    console.log(popularTagName);

    if (popularTag.hasClass('selected')) {
        console.log('has class');
        popularTag.removeClass('selected');
        popularTag.removeClass('selected-tag');
        popularTag.removeAttr('data-slug');
        popularTag.removeAttr('data-name');
    } else {
        console.log('doesnt have class');
        popularTag.addClass('selected');
        popularTag.addClass('selected-tag');
        popularTag.attr('data-slug', popularTagSlug);
        popularTag.attr('data-name', popularTagName);
    }
});

Here Is the HTML is it playing with (BEFORE CLICK):

<div class="popular-tags-selection">

    <div class="popular-tags-selection-title">
        Popular properties
    </div>

    <div id="popular-tags" class="popular-tags">

        <div class="search-tag popular-tag" popular-value="aesthetic" popular-full="Aesthetic"><div class="popular-tag-title">Aesthetic</div></div>
        <div class="search-tag popular-tag" popular-value="corrosion-resistant" popular-full="Corrosion resistant"><div class="popular-tag-title">Corrosion resistant</div></div>
        <div class="search-tag popular-tag" popular-value="hard" popular-full="Hard"><div class="popular-tag-title">Hard</div></div>

    </div>

</div>

This is the same code (AFTER CLICK):

<div class="popular-tags-selection">

    <div class="popular-tags-selection-title">
        Popular properties
    </div>

    <div id="popular-tags" class="popular-tags">

        <div class="search-tag popular-tag" popular-value="aesthetic" popular-full="Aesthetic"><div class="popular-tag-title">Aesthetic</div></div>
        <div class="search-tag popular-tag" popular-value="corrosion-resistant" popular-full="Corrosion resistant"><div class="popular-tag-title">Corrosion resistant</div></div>
        <div class="search-tag popular-tag" popular-value="hard" popular-full="Hard"><div class="popular-tag-title">Hard</div></div>

    </div>

</div>

This is the console after the two clicks:

11:55:17.801 ready-functions.js?200226115513:448 aesthetic
11:55:17.989 ready-functions.js?200226115513:450 Aesthetic
11:55:17.989 ready-functions.js?200226115513:453 has class
11:55:18.801 ready-functions.js?200226115513:448 aesthetic
11:55:18.801 ready-functions.js?200226115513:450 Aesthetic
11:55:18.801 ready-functions.js?200226115513:453 has class

Why is this always saying the class 'selected' is there?

I appreciate I am probably being daft, appreciate any contributors, Jason.

$(document).on("click", ".popular-tag", function(){
                var popularTag = $(this);
                var popularTagSlug = popularTag.attr('popular-value');
                console.log(popularTagSlug);
                var popularTagName = popularTag.attr('popular-full');
                console.log(popularTagName);

                if (popularTag.hasClass('selected')) {
                        console.log('has class');
                        popularTag.removeClass('selected');
                        popularTag.removeClass('selected-tag');
                        popularTag.removeAttr('data-slug');
                        popularTag.removeAttr('data-name');
                } else {
                        console.log('doesnt have class');
                        popularTag.addClass('selected');
                        popularTag.addClass('selected-tag');
                        popularTag.attr('data-slug', popularTagSlug);
                        popularTag.attr('data-name', popularTagName);
                }
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="popular-tags-selection">

                <div class="popular-tags-selection-title">
                        Popular properties
                </div>

                <div id="popular-tags" class="popular-tags">

                        <div class="search-tag popular-tag" popular-value="aesthetic" popular-full="Aesthetic"><div class="popular-tag-title">Aesthetic</div></div>
                        <div class="search-tag popular-tag" popular-value="corrosion-resistant" popular-full="Corrosion resistant"><div class="popular-tag-title">Corrosion resistant</div></div>
                        <div class="search-tag popular-tag" popular-value="hard" popular-full="Hard"><div class="popular-tag-title">Hard</div></div>

                </div>

        </div>

Upon adding this snippet into the fiddle, it appears to work. Does anyone know how I can go about troubleshooting this so I can find out why this doesn't operate as planned?

EDIT (Adding full jQuery to help further troubleshooting) :

// TAG DROPDOWN TAGS
$(document).on("click", ".search-tag", function(e){
    e.stopPropagation();
    var searchTag = $(this);
    var searchTagSlug = searchTag.attr('value');
    var searchTagName = searchTag.attr('name');

    if (searchTag.hasClass('selected')) {
        searchTag.removeClass('selected');
        searchTag.removeClass('selected-tag');
        searchTag.removeAttr('data-slug');
        searchTag.removeAttr('data-name');
    } else {
        searchTag.addClass('selected');
        searchTag.addClass('selected-tag');
        searchTag.attr('data-slug', searchTagSlug);
        searchTag.attr('data-name', searchTagName);
    }

    var popularTags = $('#popular-tags');
    var alsoPopularTag = popularTags.children('[popular-value=' + searchTagSlug + ']');
    if (alsoPopularTag.length) {
        if (alsoPopularTag.hasClass('selected')) {
            alsoPopularTag.removeClass('selected');
            alsoPopularTag.removeClass('selected-tag');
            alsoPopularTag.removeAttr('data-slug');
            alsoPopularTag.removeAttr('data-name');
        } else {
            alsoPopularTag.addClass('selected');
            alsoPopularTag.addClass('selected-tag');
            alsoPopularTag.attr('data-slug', searchTagSlug);
            alsoPopularTag.attr('data-name', searchTagName);
        }
    }

    var selectedTags = $('#selected-tags');
    var alsoSelectedTag = selectedTags.children('[data-selected-tag-slug=' + searchTagSlug + ']');
    if (alsoSelectedTag.length) {
        alsoSelectedTag.remove();
    } else {
        selectedTags.prepend('<div class="selected-tag-quick" data-slug="' + searchTagSlug + '" data-name="' + searchTagName + '" data-selected-tag-slug="' + searchTagSlug + '" data-selected-tag-name="' + searchTagName + '"><div class="selected-tag-quick-name">' + searchTagName +'</div></div>');
    }
});
// END TAG DROPDOWN TAGS

// POPULAR TAGS
$(document).on("click", ".popular-tag", function(){
    var popularTag = $(this);
    var popularTagSlug = popularTag.attr('popular-value');
    console.log(popularTagSlug);
    var popularTagName = popularTag.attr('popular-full');
    console.log(popularTagName);

    if (popularTag.hasClass('selected')) {
        console.log('has class');
        popularTag.removeClass('selected');
        popularTag.removeClass('selected-tag');
        popularTag.removeAttr('data-slug');
        popularTag.removeAttr('data-name');
    } else {
        console.log('doesnt have class');
        popularTag.addClass('selected');
        popularTag.addClass('selected-tag');
        popularTag.attr('data-slug', popularTagSlug);
        popularTag.attr('data-name', popularTagName);
    }

    var searchTags = $('#search-tags-list');
    var alsoSearchTag = searchTags.children('[value=' + popularTagSlug + ']');
    if (alsoSearchTag.length) {
        if (alsoSearchTag.hasClass('selected')) {
            alsoSearchTag.removeClass('selected');
            alsoSearchTag.removeClass('selected-tag');
            alsoSearchTag.removeAttr('data-slug');
            alsoSearchTag.removeAttr('data-name');
        } else {
            alsoSearchTag.addClass('selected');
            alsoSearchTag.addClass('selected-tag');
            alsoSearchTag.attr('data-slug', popularTagSlug);
            alsoSearchTag.attr('data-name', popularTagName);
        }
    }

    var selectedTags = $('#selected-tags');
    var alsoSelectedTag = selectedTags.children('[data-selected-tag-slug=' + popularTagSlug + ']');
    if (alsoSelectedTag.length) {
        alsoSelectedTag.remove();
    } else {
        selectedTags.prepend('<div class="selected-tag-quick" data-slug="' + popularTagSlug + '" data-name="' + popularTagName + '" data-selected-tag-slug="' + popularTagSlug + '" data-selected-tag-name="' + popularTagName + '"><div class="selected-tag-quick-name">' + popularTagName +'</div></div>');
    }
});
// END POPULAR TAGS

// SELECTED TAGS
$(document).on("click", ".selected-tag-quick", function(e){
    var selectedTag = $(this);
    var selectedTagSlug = selectedTag.attr('data-selected-tag-slug');
    var selectedTagName = selectedTag.attr('data-selected-tag-name');

    selectedTag.remove();

    var searchTags = $('#search-tags-list');
    var alsoSearchTag = searchTags.children('[value=' + selectedTagSlug + ']');
    if (alsoSearchTag.length) {
        if (alsoSearchTag.hasClass('selected')) {
            alsoSearchTag.removeClass('selected');
            alsoSearchTag.removeClass('selected-tag');
            alsoSearchTag.removeAttr('data-slug');
            alsoSearchTag.removeAttr('data-name');
        } else {
            alsoSearchTag.addClass('selected');
            alsoSearchTag.addClass('selected-tag');
            alsoSearchTag.attr('data-slug', selectedTagSlug);
            alsoSearchTag.attr('data-name', selectedTagName);
        }
    }

    var popularTags = $('#popular-tags');
    var alsoPopularTag = popularTags.children('[data-value=' + selectedTagSlug + ']');
    if (alsoPopularTag.length) {
        if (alsoPopularTag.hasClass('selected')) {
            alsoPopularTag.removeClass('selected');
            alsoPopularTag.removeClass('selected-tag');
            alsoPopularTag.removeAttr('data-slug');
            alsoPopularTag.removeAttr('data-name');
        } else {
            alsoPopularTag.addClass('selected');
            alsoPopularTag.addClass('selected-tag');
            alsoPopularTag.attr('data-slug', selectedTagSlug);
            alsoPopularTag.attr('data-name', selectedTagName);
        }
    }
});
// END SELECTED TAGS