dimanche 30 septembre 2018

Java if boolean

got confused randomly. Could someone explain me about this equation?

if((true) && (false)){}
if(true && false){}

What's the difference? I'm thinking that they are equal?

UPDATE:

Old code version:

if ((followServiceRedirects) && (service != null)) {
  return new ModelAndView(new RedirectView(service));
}

New code version:

if (this.followServiceRedirects && service != null) {
    return new ModelAndView(new RedirectView(service));
}

Are these two equal?

if statement not working in Android Studio

I am new to Android Studio. In my project, I am trying to use IF statement in a very simple setting (to activate a change) but it doesn't work. Your help will be greatly appreciated. Below is my code:

public class MainActivity extends AppCompatActivity {


private Button mBtLaunchActivity;
private Button Home;
int a = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Home = (Button) findViewById(R.id.home_button);

    mBtLaunchActivity = (Button) findViewById(R.id.map_button);

    mBtLaunchActivity.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            launchActivity();
            a = 1;

        }

    });

}

private void launchActivity() {

    if (a == 1){
        Home.setVisibility(View.INVISBLE);
    }

    Intent intent = new Intent(this, Activity3.class);
    startActivity(intent);

}

Why does this index give me an error when the same line works if I change the condition?

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array. This is the problem I am trying to solve.

If I use this code, it gives me an index error. However, if I keep everything the same and change the condition del sequence[i] to something else, it doesn't give me the error. However, I want to delete any numbers in the list that are less than the numbers before them and then see whether the length of the new list differs from the old one by more than 1. I don't know where I went wrong.

def almostIncreasingSequence(sequence):
    originalSequence = sequence
    for i in range(1,len(sequence)):
        if sequence[i] <= sequence[i-1]:
            del sequence[i]

    if len(originalSequence) > len(sequence) - 1:
        return False
    else:
        return True

What is wrong with my if-else statements and variable assignments?

Goal: I'm trying to allow the user to input varying spellings for certain auto services, and still have my code work properly. My goal was to use the if-else statements to ensure that if the user misspelled a service, the code could correct the error by changing the variable assignment to the string that matched my dictionary key.

The issue: The code will output: Tire rotation for any input that I enter for auto_serv. Where have I made a mistake? Any better ideas to program this? Keep in mind, I'm a first time programmer that's doing this for class, and I just learned if-else statements.

The code:

# dictionary assigns the cost for each service
services = {'Oil change': 35,
            'Tire rotation': 19,
            'Car wash': 7,
            'Car wax': 12}
# auto_serv is the user's desired car service
auto_serv = input('Desired auto service:')
# The following four 'if' statements are to allow the user multiple variances in spelling of desired auto service
if auto_serv == 'Tirertation' or 'tirerotation':

    auto_serv = 'Tire rotation'
elif auto_serv == 'Oilchange' or 'oilchange':

    auto_serv = 'Oil change'
elif auto_serv == 'Carwash' or 'carwash':

    auto_serv = 'Car wash'
elif auto_serv == 'Carwax' or 'carwax':

    auto_serv = 'Car wax'

# the if-else statements are to give a result for each service the user requests
if auto_serv == 'Tire rotation':

    print('You entered:', auto_serv)

    print('Cost of %s: $%d' % (auto_serv, services[auto_serv]))
elif auto_serv == 'Oil change':

    print('You entered:', auto_serv)

    print('Cost of %s: $%d' % (auto_serv, services[auto_serv]))
# ...there are more elif statements that follow this code with the other auto services

Python: 2 'and' in a statement [on hold]

I am using an if statement which has 2 'and's in it, is this allowed? I keep getting a syntax error so I'm wondering if this is the issue.

Ex: if VARIABLE = 1 and VARIABLE_2 = 2 and VARIABLE_3 = 3:
return RESULT

Unable to get results on many if conditions , i get result only if i run one if statement

Note: i use CodeIgniter framework

I have a big issue when running multiple if statements.

If run the code below the if statement work fine :

    if ($_POST['materialOrder'] != '') {

if ($_POST['materialOrder'] != '') {

            if ($_POST['materialOrder'] != '') {
                $materialOrder = $_POST['materialOrder'];
                $query = $this->db->where("m.material_request_id LIKE '%$materialOrder%'");
            }
        }

The problem come when i run code like below :

        if ($_POST['materialOrder'] != '') {

            if ($_POST['materialOrder'] != '') {
                $materialOrder = $_POST['materialOrder'];
                $query = $this->db->where("m.material_request_id LIKE '%$materialOrder%'");
            }
            if ($materialOrder != "") {
                $materialOrder = $_POST['materialOrder'];
                $query = $this->db->where("l.location_name  LIKE '%$materialOrder%'");
            }
            if ($materialOrder == 'coin' or 'bag') {
                $query = $this->db->where("p.status_name LIKE '%coin%'");
            }
            if ($materialOrder == "round" or 'container') {
                $query = $this->db->where("p.status_name LIKE '%round%'");
            }
        }

i dont get any resuls

Note : if i run each contision like first example i get result for all contision

How to do multiple if conditions

I have searched for that problem and found no answers which solve my problem

    if (true) {
            [0][0] =! 0 [0][1] ==! 0 [0][2] ==! 0;
            }return true;
            if(true) {
            [1][0] =! 0 [1][1] ==! 0 [1][2] ==! 0;
            }return true;
            if(true) {
            [2][0] =! 0 [2][1] ==! 0 [2][2] ==! 0;
            }return true;
            if(true) {
            [0][0] =! 0 [1][1] ==! 0 [2][2] ==! 0;
            }return true;
            if(true) {
            [0][2] =! 0 [1][1] ==! 0 [2][0] ==! 0;
            }return true;
            if(true) {
            [0][0] =! 0 [1][0] ==! 0 [2][0] ==! 0;
            }return true;
            if(true) {
            [0][1] =! 0 [1][1] ==! 0 [2][1] ==! 0;
            }return true;
            if(true) {
            [0][2] =! 0 [1][2] ==! 0 [2][2] ==! 0;

            }return true;

                }else
                    return false;

This method is to find out if someone has a win in TicTactoe I try to check every win possibilities in an 2d-array but eclipse gives me the error "Syntax error on token "{", Expression expected after this token" for the "{" bracket after every if condition and writing another "{" doesnt help

I have no idea how to get this working Hope you could give me some tips im a java beginner Sorry for bad English

if condition with brackets doesn't work in js

I'm so sorry for asking this question but I'm losing my mind over here.

I've this if-statement:

if (($('.alt_menu').text() !== 'Status' && $.trim($('.txt__adminLog_logs').text()).length > 15 && input_adminLog_about!==''&&isCalling_org!=='0') && ((input_adminLog_helped !=='') || (isCalling_org === '0' && $('.input_adminLog_helped').css('display') === 'none'))) {}

This if-statement checks for everything except && ((input_adminLog_helped !=='') || (isCalling_org === '0' && $('.input_adminLog_helped').css('display') === 'none'))

I've also tried without brackets and I still get the same result.

Good to know

$('.alt_menu').text() is a home-made dropdown menu, $('.txt__adminLog_logs').text() is a contenteditable div and should've have more than 15 characters, input_adminLog_about is a variable that contains information and shouldn't be empty, isCalling_org is a global variable and can be 0 or eg. 5705485375

input_adminLog_helped can be empty if $('.input_adminLog_helped').css('display') === 'none' and isCalling_org === 0 otherwise it's has a value.

Try to Use Boolean Logic to Evaluate an If Statement in VBA

I have to say, VBA might just be the most illogical programming language I encountered. So many conventions defied and it's aggravating me. I'm trying to run some code if this logic applies:

If Left(Source.Range("B" & i).Value, 46) <> _
       "There is no Burger of the Day in this episode." Or _
       Left(Source.Range("B" & i).Value) <> "" Then

I was looking at examples online and it seemed people simply used "Or" but I'm getting errors when trying to run this. I even put parentheses around both evaluations and it still didn't help. Help is much appreciated!

Filling columns based on category and intervals

I have the following problem. I need to fill in the points column based on the Category and score interval. I was trying to do it through the IF function but it seems very complicated. Everytime I try it with the HLOOKUP it also does not seems to work, as I simply don't know how to implement the category selection and interval selection in the formula. Any help would be appreciated!

enter image description here

Match controller action in htaccess

I want to add if condition in htaccess file for a controller action. The url is like

www.example.com/user/profile/5?cid=7&pos=1

I want to add condition in htaccess file if url is action "profile". I tried following:

<If "%{REQUEST_URI} == 'profile'">
        // do something
</If>

but it doesn't work. Please advice.

Roblox If Statement not running Script

I was wondering if I could get some help with this small script I tested. For some reason, the If statement isn't responding, meaning the function won't run even if the value doesn't equal Rinzler. charData is a StringValue to be specific.

local charData = script.Parent.Data.CharacterData
local active = game.Workspace.Part

function change()
    if not charData.Value == "Rinzler" then
    charData.Value = "Rinzler"
    print("Character has changed to Rinzler.")
end
end

active.Touched:Connect(change)

"Character has changed to Rinzler" isn't printing in the console no matter what I do.

How to check if only one statement equals 0 (python)?

I got some trouble with finding the matching if-statement to check if only one entry equals 0 of 3. Here's the code:

    def thanx(self):
    if len(self.e.get()) == 0:
        messagebox.showerror("Error", "Please enter affordable infos")
        self.boo = False
    else:
        messagebox.showinfo("Submition done", "Thank you")
        self.boo = True

It is only checking if my variable "e" equals 0, but i actually got 2 more entries. I know i could check every single one individually, however there has to be an easier way of doing this. Im using "tkinter" btw, but this shouldnt be too much important.

I tried it with "or" but this isnt working or I'm doing it wrong. (Also tried to solve this with lambda, but again just errors...)

Maybe someone can help me there...

samedi 29 septembre 2018

If/Else Bootstrap Pagnation Rule only work on root URL (Express JS / Bootstrap)

The issue

This code works perfectly when visiting Page 1 (first page) and Page 574 (last page), it will block the Previous and Next Buttons to show the start/end of the pagination.

However, when I am sorting under a suburb, the url for the route is not being set to localhost:3000/suburb/x (x being page number), and instead, is just being set to suburb/x for the next and previous buttons on the suburbs pagination.

How can I ensure this pagination works under a suburb?

I am aware this may be to do with my routes not being setup properly... Below is pug code for my Bootstrap Pagination and my App.JS code.

JADE (PUG) - index.pug

    nav(aria-label='Page navigation example')#pagination
        ul.pagination
            if currentPage == 1
                li.page-item.disabled
                    a.page-link(href='/' tabindex='-1') Previous

            else
                li.page-item
                    if suburb == null
                        a.page-link(href='/' + (currentPage - 1) tabindex='-1') Previous
                    else
                        a.page-link(href='/' + suburb + '/' + (currentPage - 1) tabindex='-1') Previous
            li.page-item.disabled
                a.page-link(href='#')
                    =currentPage
                    |  of 
                    =totalPages
            if currentPage == totalPages
                li.page-item.disabled
                    a.page-link(href= '/') Next
            else
                li.page-item
                    if suburb == null
                        -var count= currentPage
                        -count++
                        a.page-link(href= '/'  + count) Next
                    else
                        -var count= currentPage
                        -count++
                        a.page-link(href= '/' + suburb + '/' + count ) Next

(JAVASCRIPT)

const express = require('express');
const mysql = require('mysql');
const multer = require('multer');
const path = require('path');
const app = express();

const conn = mysql.createConnection({
    host: "127.0.0.1",
    user: "root",
    password: "",
    database: "realestate"
});

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./public/uploads");
    },
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

const upload = multer({
    storage: storage,
    limits: { filesize: 1000000 },
    fileFilter: function(req, file, cb) {
        checkFiletype(file, cb);
    }
}).single("myImage");

function checkFiletype(file, cb) {
    const filetypes = /jpeg|jpg|png|gif/;
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = filetypes.test(file.mimetype);
    if (mimetype && extname) {
        return cb(null, true);
    } else {
        cb('Error: Image Only!');
    }
}

app.use(express.static("public"));

app.set("view engine", "pug");
app.set("views", "./views");

app.get("/about", function(req, res){
    res.render('about', {
        title: 'About Us'
    })
});

app.get("/:suburb?/:page?", (req, res)=>{

    let suburb = req.params.suburb;
    let page = req.params.page || 1;
    let limit = 12;
    let offset;
    console.log(suburb);
    console.log(page);
    if (page == 1) {
        offset = 1;
    } else {
        offset = (page - 1) * limit + 1;
    }

    let sqlSuburbs = "SELECT DISTINCT suburb FROM properties ORDER BY suburb";
    let sqlProperties = "SELECT * FROM WHERE suburb = ?";
    let sqlCountPlaceholder = [suburb];
    let sqlCount = "SELECT COUNT(*) AS 'count' FROM properties WHERE suburb = ?";
    let placeholders = [suburb, limit, offset];

    if (suburb == parseInt(suburb)) {
        page = suburb;
        suburb = "";
        offset = (page - 1) * limit + 1;
        sqlProperties = "SELECT * FROM properties";
        placeholders = [limit, offset];
        sqlCount = "SELECT COUNT(*) AS 'count' FROM properties ORDER BY ?";
        sqlCountPlaceholder = [suburb];
    }

    else if (suburb === undefined) {
        sqlProperties = "SELECT * FROM properties";
        sqlCount = "SELECT COUNT(*) AS 'count' FROM properties ORDER BY ?";
        placeholders = [limit, offset];
        sqlCountPlaceholder = ['suburb'];
        suburb = "";
    }
    else
    {
        sqlProperties = "SELECT * FROM properties where suburb = '" + suburb + "'";
        sqlCount = "SELECT COUNT(*) AS 'count' FROM properties where suburb = '" + suburb + "' ORDER BY ?";
        placeholders = [limit, offset];
        sqlCountPlaceholder = [suburb];
    }
    console.log(placeholders);
    console.log(sqlProperties);
    // get the distinct suburbs
    conn.query(sqlSuburbs, (err, suburb_result) => {
        if (err) throw err
        // Get the properties
        conn.query(sqlProperties + " LIMIT ? OFFSET ?", placeholders, (err, properties_result)=>{
            if (err) throw err
            // Get the query record count
            conn.query(sqlCount, sqlCountPlaceholder, (err, record_count)=>{
                var totalPages = Math.ceil(record_count[0].count / limit);
                if (err) throw err

                if(suburb)
                {
                    suburb = '/' + suburb;
                }
                //Display the page and provide it with values
                res.render("index", {
                    title: 'Home Page',
                    suburbs: suburb_result,
                    properties: properties_result,
                    currentPage: page,
                    next: Number(page)+1 > totalPages?totalPages:Number(page)+1,
                    prev: Number(page)-1 >= 1?Number(page)-1:1,
                    totalPages: totalPages,
                    suburb: suburb
                });
            });
        });
    });
});


app.get("/admin/user/dashboard", (req, res)=>{
    res.render('admin/dashboard', {
        title: 'Dashboard'
    });
});

app.get("/admin/user/fileupload", (req, res)=>{
    res.render("admin/uploads", {
        title: 'File Upload Area'
    });
});



app.post("/admin/user/uploads", (req, res)=>{
    upload(req, res, (err)=> {
        if (err) {
            res.render("admin/uploads", {
                msg: err
            });
        } else {
            if (req.file == undefined) {
                res.render("admin/uploads", {
                    title: "File Upload Area",
                    msg: "Error: No File Selected!"
                })
            } else {
                res.render("admin/uploads", {
                    title: "File Upload Area",
                    msg: "File Uploaded!",
                    file: 'uploads/${req.file.filename}'
                });
            }
        }
    });
});

app.listen(3000, ()=>{

    console.log("Running on port 3000...")
});

Compare two String using recursion (case insensitive)

I needed to Write a recursive method to compare two Strings using alphabetical order without using compareTo.

string1 comes before string2 returns an integer less than 0 string1 == (or indistinguishable from) string2 returns 0 string1 comes after string2 returns an integer greater than 0

I have written a method that works just fine, the problem is that if I compare two similar string or a string to itself it returns 1 instead of 0.

Any idea how can I optimize my method so it is not too long and does not fail to compare two identical strings?

I think part of my problem is because I declared my variable static, but not sure how I should work it out to declare them inside the method.

Code:

public class test{

        public static String s1 = "alpha";
        public static String s2 = "delta";
        public static String s3 = "omega";
        public static String s4 = "alpha";
        public static int  result;


        public static void main (String[]args){

            System.out.println(recursiveCompare(s1,s2));  // -1  good
            System.out.println(recursiveCompare(s3,s1));  //  1  good
            System.out.println(recursiveCompare(s4,s1));  //  1  FAIL!!! should be 0
            System.out.println(recursiveCompare(s2,s3));  // -1  good
            System.out.println(recursiveCompare(s1,s1));  // -1  FAIL!!! should be 0

            }

            public static int recursiveCompare(String s1, String S2){
                    if  (s1.length() ==0 || s2.length()==0){
                            if ((s1.length() ==0 && s2.length()==0)){result = 0;}
                            else if ((s1.length() !=0 || s2.length()==0)){result =  1;}
                            else if ((s1.length() ==0 || s2.length()!=0)){result = -1;}
                    }

                    else 
                    {
                        recursiveCompareHelper(s1, s2,0);
                    }
            return result;
            }



        public static int recursiveCompareHelper(String s1,String s2, int index){

                try{

                    if (s1.regionMatches(true,index,s2,index,1)){
                            result = recursiveCompareHelper(s1,s2,(index+1));}

                        else {
                                if (s1.charAt(index) > s2.charAt(index)){
                                    result =1;
                                }

                                else if (s1.charAt(index) < s2.charAt(index)){
                                    result =-1;
                                }

                                else if (s1.charAt(index) == s2.charAt(index)){ 
                                    result = recursiveCompareHelper(s1,s2,(index+1));
                                }
                            }

                    } catch (StringIndexOutOfBoundsException e){
                            if      (s1.charAt(index)==0 && s2.charAt(index)== 0){result = 0;}
                            else if (s1.charAt(index)==0 && s2.charAt(index)!= 0){result = 1;}
                            else if (s1.charAt(index)!=0 && s2.charAt(index)== 0){result =-1;}
                    }

                    return result;
        }
    }

Iteration incorrect with if statement

I have a folder path and a dictionary. My goal is to pull a value from my dictionary and use it while iterating through the folders. The value will be called fip:

import arcpy, sys, os, requests, json, xlrd, xlwt
#paths
path = "T:/CCSI/TECH/FEMA/Datasets/NFHL/NFHL_06122018"
prelim_path = "T:/CCSI/TECH/FEMA/Datasets/PreliminaryDFIRMS/Ravi-MSC/Prelim_05092018/Extracted"

#dictionary
masterdict = {'13': ['13245', '13027'], '06': ['06037']}

Everything works fine except when the fip value is found in the filename. However, if the fip is not found in the dir/filename, I still want the word "None" written to that line ('rr' value) of the spreadsheet. I tried using the below code at the same level as the if(fip in dir and '_A_' not in dir and '_B_' not in dir and '_C_' not in dir):' statement by adding an 'elif():' statement, but it essentially writes "None" for EVERY file that does not equal if statement criteria, sets therr` value to plus 1 and does that for every dirname and filename in that folder. I just want it to write "None" once if the 'fip' value does not exist in that directory. That's it. Any ideas on to resolve this iteration issue?

rr = 1 #counter
for k, v in masterdict.items():
    stateFips = k
    print(stateFips)
    fipsList = v
    print(fipsList)

    for fip in fipsList:
        for root, dirs, filename in os.walk(prelim_path):
            for dir in dirs:
                if(fip in dir and '_A_' not in dir and '_B_' not in dir and '_C_' not in dir):
                    print(dir)
                    folder = os.path.join(root, dir)
                    files = os.listdir(folder)
                    for file in files: 
                        # Create temp variable for cases
                        if('S_FIRM_Pan' in file and file[-4:] == '.shp' or 'S_FIRM_PAN' in file and file[-4:] == '.shp'):
                            prelim = os.path.join(folder, file)
                            # get data for Prelim_sx_firmpan dictionary
                            suffix = [row[0] for row in arcpy.da.SearchCursor(prelim, "SUFFIX")]
                            raw_firm_pan = [row[0] for row in arcpy.da.SearchCursor(prelim, "FIRM_PAN")]
                            Prelim_sx_firmpan = dict(zip(raw_firm_pan, suffix))
                            P = str(len(Prelim_sx_firmpan))
                            print("Initial Prelim_sx_firm count for : {} :".format(fip) + P)
                            # get data for dates
                            raw_dates = [row[0] for row in arcpy.da.SearchCursor(prelim, "PRE_DATE")]
                            pre_dates = [d for d in raw_dates if d != datetime.datetime(9999, 9, 9, 0, 0)

                            if pre_dates == [None]:
                                pre_date_1 = "None"
                                sheet1.write(rr, predateCol, pre_date_1)
                                rr = rr + 1
                                print("Predate is: ")
                                print(pre_date_1)

                            elif pre_dates == []:
                                pre_date_2 = "None"
                                sheet1.write(rr, predateCol, pre_date_2)
                                rr = rr + 1
                                print("Predate is: ")
                                print(pre_date_2)

                            else:
                                pre_date_3 = max(pre_dates)
                                pre_date_3 = pre_date_3.strftime('%m/%d/%y')
                                sheet1.write(rr, predateCol, pre_date_3)
                                print(rr)
                                rr = rr + 1
                                print("Predate is: ")
                                print(pre_date_3)
                elif(fip not in dir):
                    pre_date_4 = "None"
                    sheet1.write(rr, predateCol, pre_date_4)
                    print(rr)
                    rr = rr + 1

Vulkan's queue family for transfer capabilities for video card support. Are the condition checks accurate?

I am following this Vulkan Youtube video tutorial by Joshua Shucker. I'm currently on his 14th video where he is working on creating a secondary queue family for the vertex buffer. My code matches that of his in his video except that of a cout statement in which I added for testing. Here is the function:

QueueFamilyIndices FindQueueFamilies( const VkPhysicalDevice* device, const VkSurfaceKHR* surface ) {
    QueueFamilyIndices indices;
    uint32_t queueFamilyCount = 0;
    vkGetPhysicalDeviceQueueFamilyProperties( *device, &queueFamilyCount, nullptr );
    std::vector<VkQueueFamilyProperties> queueFamilies( queueFamilyCount );
    vkGetPhysicalDeviceQueueFamilyProperties( *device, &queueFamilyCount, queueFamilies.data() );

    int i = 0;
    for( const auto &queueFamily : queueFamilies ) {
        VkBool32 presentSupport = false;
        vkGetPhysicalDeviceSurfaceSupportKHR( *device, i, *surface, &presentSupport );

        if( queueFamily.queueCount > 0 && (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) && presentSupport ) {
            indices.graphicsFamily = i;
        }

        if( queueFamily.queueCount > 0 && (queueFamily.queueFlags & VK_QUEUE_TRANSFER_BIT) && !(queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) && presentSupport ) {
            indices.transferFamily = i;
        }

        if( indices.isComplete() ) {
            break;
        }
        i++;
    }

    if( indices.graphicsFamily >= 0 && indices.transferFamily == -1 ) {
        std::cout << "Graphics family found, transfer family missing: using graphics family" << std::endl;
        indices.transferFamily = indices.graphicsFamily;
    }

    return indices;
}

Within this function vkGetPhysicalDeviceSurfaceSupportKHR(...) is being called twice as there have been 2 queue families found after vkGetPhysicalDeviceQueueFamilyProperties(...) has been called to populate the vector of VkQueueFamilyProperties structures. Here is the specs for my NVidia GeForce gtx 750 Ti card based on Vulkan's specifications for its queue families: Vulkan:Report and in case the link changes over time here is the information directly:

Queue family                          0     
queueCount                            16 
flags                                 GRAPHICS_BIT
                                      COMPUTE_BIT
                                      TRANSFER_BIT
                                      SPARSE_BINDING_BIT 
timestampValidBits                    64 
minImageTransferGranularity.width     1 
minImageTransferGranularity.height    1
minImageTransferGranularity.depth     1 
supportsPresent                       1 

Queue family                          1 
queueCount                            1 
flags                                 TRANSFER_BIT
timestampValidBits                    64 
minImageTransferGranularity.width     1 
minImageTransferGranularity.height    1 
minImageTransferGranularity.depth     1 
supportsPresent                       0 

Now according to these specs which coincide with the values in my vector of structs while I'm stepping through the debugger my structures are populated with the values of:

 queueFamilies[0].queueFlags = 15;
 queueFamilies[0].queueCount = 16;
 queueFamilies[0].timestampValidBits = 64;
 queueFamilies[0].minImageTransferGranularity = { width = 1, height = 1, depth = 1 };

 queueFamilies[1].queueFlags = 4;
 queueFamilies[1].queueCount = 1;
 queueFamilies[1].timestampValidBits = 64;
 queueFamilies[1].minImageTransferGranularity = { width = 1, height = 1, depth = 1 };

So this appears to me that my card does support a separate queueFamily specifically the transferFamily.

Based on my assumption of this support and stepping through this function he has two if statements to check for valid conditions within the for loop for each of the indexed queueFamily objects. The if statements are returning exactly as they should be. My code compiles and builds without any errors or warnings, and it still does render then triangle when I'm not running it through the debugger and it does exit with a code of (0). So the code appears to be fine. However I'm not getting the results that I would at least be expecting.

I'm not sure if there is a bug in his code that he happened to missed, if I'm misinterpreting my video card's support of this Vulkan functionality, or if this could be either a Vulkan API bug or NVidia Driver bug.

However as I was stepping through this function to find out why the indices.transferFamily variable was not being set to i on the second iteration of the loop has nothing to do with the presence of the transferFamilyQueue, its parameter values or flags. What is causing this if statement to return false is the presentSupport variable as it is being set to 0 on the second call which does match the data sheet above. So the output is as expected.

My question them becomes: is there an actual implementation problem with the condition checking in the second if statement?

This is where I'm stuck as I am a bit confused because we are checking to see if there is a transferQueueFamily available and if so use that to create and use a stagingBuffer to copy the contents from the CPU to the GPU for the vertex buffer(s). From what I can see it appears my card does have this transferFamily but does not have supportPresent for this family. However, when thinking about it; if you are using a transferFamily - transferQueue you wouldn't want to present it directly as you'll just be copying the data from a temporary vertexBuffer on the CPU to the vertexBuffer that will be used on the GPU. So I'm wondering if the final check in this if statement is correct or not. If my assumptions about how Vulkan is working here is incorrect please don't hesitate to correct me as this is my first attempt and getting a rendering application of Vulkan working.

New to C++, Using if statement if not multiple

I want to create a 5x5 array of '' with a hashtag in the center instead of '', but only when the user inputs either 'a' or 'b.' On the area I marked "RIGHT HERE" it doesn't work unless its ONLY 'a' / ONLY 'b', so what do I do? Thank you in advance!

#include <iostream>

using namespace std;

int main()
{


while (true){

///Variables:

char array[4][4]; //Playing field 5x5
char direc; //Direction player moves




for (int x = 0; x <=4; x++){

    for (int y = 0; y <= 4; y++){

        array[x][y] = '_';
    if (direc != 'a' || 'b'){ ///RIGHT HERE!
        array[2][2] = '#';
    }

        cout << array[x][y]; //Starts printing Board

        if (y == 4){
        cout << endl; //Cuts to next line on print if 4 in a column row
    }

}
}

cin >> direc;
cin.get();




}

}

If else statement trouble

I cannot get my if then statements to work correctly and I cannot figure out why. any help would be greatl appreciated.

import java.text.DecimalFormat;
import java.util.Scanner;

public class Lab02
{
public static void main(String args[])
{
    Scanner input = new Scanner(System.in);

    System.out.print("Number of Exemptions: ");
    double NE = input.nextDouble();

    System.out.print("Gross Salary: ");
    double GS = input.nextDouble();

    System.out.print("Interest Income: ");
    double II = input.nextDouble();

    System.out.print("Capital Gains: ");
    double CG = input.nextDouble();

    System.out.print("Charitable Contributions: ");
    double CC = input.nextDouble();

    double TI = GS + II + CG;
    System.out.printf("%nTotal Income: %12.2f%n", TI);

    double AI = TI - (NE * 1500) - CC;
    System.out.printf("Adjusted Income: %9.2f%n", AI);

    double TT1;
    double TT2;
    double TT3;
    double TT;
    if ((AI > 10000 && AI <= 32000)){
    //TT1 = ((15/100) * (32000 - 10000));}
    //else if ((AI<= 32000)){
    TT1 = ((15/100) * (AI - 10000));}
    else TT1 = 0;
    if ((AI > 32000 && AI <= 50000)){
    //TT2 = ((23/100) * (50000 - 32000));}
    //else if ((AI <= 50000)){
    TT2 = ((23/100) * (AI - 32000));}
    else TT2 = 0;
    if ((AI > 50000)){
    TT3 = ((28/100) * (AI - 50000));}
    else TT3 = 0;

    System.out.println(TT1);
    System.out.println(TT2);
    System.out.println(TT3);
    TT = TT1 + TT2 + TT3;
    System.out.printf("Total Tax: %14.2f%n", TT);
}

I do have some extra stuff in there that i was also working with to try and figure out my problem.

How can I print the volume of one polyhedron based on what users inputs?

Write a program that reads the first capital letter ("T", "C", "O", "D" or "I") of the polyhedron the size of a side and which prints the volume of the corresponding polyhedron. If the letter read is not one of the 5 letters, your program prints "Unknown Polyhedron".

This prints almost every input value as the value of "else statement" but it should print the volume of the polyhedron based on the letter that user inputs and also the measure of the side.

import math
p = str(input())
a = float(input())
T = (math.sqrt(2) / 12) * (a ** 3)
C = a ** 3
O = (math.sqrt(2) / 3) * (a ** 3)
D = (15 + 7 * math.sqrt(5)) / 4 * (a ** 3)
I = 5 * (3 + math.sqrt(5)) / 12 * (a ** 3)
if p == (math.sqrt(2) / 12) * (a ** 3) :
    print (T)
elif p == a ** 3 :
    print(C)
elif p == (math.sqrt(2) / 3) * (a ** 3) :
    print(O)
elif p == (15 + 7 * math.sqrt(5)) / 4 * (a ** 3) :
    print(D)
elif p == 5 * (3 + math.sqrt(5)) / 12 * (a ** 3) :
    print(I)
else :
    print('Polyèdre non connu')

object keys are undefined in if conditional, but inside the if statement I can access it

As the title states, I have a variable which is a javascript object, i'm comparing it with another js object by stringifying them. The problem is that the variable is completely accessible without calling the keys, so if(JSON.stringify(response) == JSON.stringify(lastcmd)) works perfectly fine, but accessing lastcmd's id key will cause it to throw undefined.

full code link here

Python - How can I make if statements get the letters before the actual word?

I know the title is really really badly worded, so let me explain with a quick bit of code.

Code:

choice = raw_input("Do you like pineapple? Y/N: ")
if choice == "y".lower() or choice == "ye".lower() or choice == "yes".lower():
    print("Sammmmeee")
else:
    print("Nani! You criminal!")

How could I make it so instead of doing:

if choice == "y".lower() or choice == "ye".lower() or choice == "yes".lower():

it automatically lets you do, "y" "ye" or "yes" without needing to do "or" so much?

Having trouble with mysql variables, what am I doing wrong here?

See below and test here.
I've been pulling my hair out over this for a couple of hours now. I've searched many posts and as best I can tell everything is correct.
I'm having trouble with the IF comparison and the @malefemale variable. I can pull this off by declaring variables in a stored procedure without any problems, I just want to get the damn thing working in the online editor above to share with a friend, and in this case, just to get the damn thing working at all. What am I missing?

create table test(id int, gender varchar(10), salary int);
insert into test(id, gender, salary) values (1, 'male', 40000), (2, 'male', 50000),  (3,'male', 40000), (4, 'female', 60000), (5, 'female', 60000), (6,'female', 40000);

set @m =0;
set @f =0;
set @malefemale = 'same';

select count(*) into @m from test WHERE gender like 'male' and salary >= 50000;
select count(*) into @f from test WHERE gender like 'female' and salary >= 50000;

if @m > @f then
    @malefemale = 'male';
else if @f > @m then
    set @malefemale ='female';
endif

select @malefemale;

Check if variable is a number below 10 or the text "QUIT"

I would to stay in this loop as long as $CHOICE is not "QUIT" or a number below 10.

I'm using this :

CHOICE=0
while [ "$CHOICE" -gt "10" ] && [ "$CHOICE" != "QUIT" ]; do
  read CHOICE < /dev/tty
done

But if I put let's say "test", the script crashes because it is expecting an integer in the first test.

What can I do to avoid this crash ?

checking value of if conditino isn't printing correct output

I am working on a chat room and the condition i want to implement is: when user send both file and text message it will return an error.

but this isn't working correct.

this is my code

if($_FILES['chat_upload_file']){

                echo "You are in file checking<br/>";
                echo $text_message;
                if($text_messege){
                    echo "It's in IF<br/>";
                    $error = 1;
                    $error_msg = "Either Sender can send file or text";
                    exit(0);
                }
                else{

                    echo "it's in else<br/>";
                    exit(0);

}

the output that i want is from internal IF : It's in IF

but the output is : It's in else

vendredi 28 septembre 2018

I'm having trouble with a nested if returning false in only certain conditions

I am creating column collapsing application and I am having trouble with a certain formula changing its heading to false when it should be showing a value.

=IF($CE2="Line 3",IF((COUNTIF($BY:$BY,">0")>0),"Line 4",IF((COUNTIF($BZ:$BZ,">0")>0),"Line 5",IF((COUNTIF($CA:$CA,">0")>0),"Line 6"))),IF($CE2="Line 4",IF((COUNTIF($BZ:$BZ,">0")>0),"Line 5",IF($CE2="Line 5",IF((COUNTIF($CA:$CA,">0")>0),"Line 6"," ")))

In all of the arrangements of selected "lines", it shows the proper value except when Its column is the last in the series, the rest continue to work properly.

enter image description here

can we write under if condition many if condtions in python and how they work

usr = input(print("Enter your choice \n1\n2\n3"))

if usr is '1': print('You selected one') usr_fst_data = input(print('Make Your Choice..\nPress (A/a) For Register Your Mobile No.')) if usr_fst_data is 'A/a': usr_mobno_ = input(print('Enter Your Mobile No.')) if usr_mobno == 10: print() else: print("Wrong Number\nCheck Your No. Again")

elif usr is '2': print('You selected two') elif usr is '3': print('You selected 3') else: print('Wrong Choice')

How to introduce a new if-condition for a specified case without any business logic given to implement that case?

Essentially, I've been asked to solve a programming quiz where the task is to introduce a new status with id 10 (dtl.getOpStatId() is 10) in the code down below. I've been asked to make any necessary changes to this code to add the required functionality( to add the additional operation stat id). Is there something obvious I'm missing????

I was given the following hint: if the only thing you are doing is adding dtl.getOpStatId() == 10 to the code below, you are not doing it correctly.

public class ChangeMe {

public void doOp(Operation op, Map<Long, String> reliefOperationMap, OperationSummary sum) {
    for (int d = 0; d < op.getOperationDetails().size(); ) {
        OperationDetail dtl = op.getOperationDetails().get(d);
        if (dtl.getOpStatId() == 1 || dtl.getOpStatId() == 3 || dtl.getOpStatId() == 4) {
            sum.setOpCond(true);
            if (dtl.getRelblkId() != null && dtl.getOperationsumRefId() != null && dtl.getOperationsumParentId() != null) {
                sum.setIsReliefOperation("Y");
                reliefOperationMap.put(dtl.getOperationsumId(), "Y");
            }
        } else {
            if (dtl.getRelblkId() != null && dtl.getOperationsumRefId() != null && dtl.getOperationsumParentId() != null) {
                sum.setOpCond(true);
                sum.setIsReliefOperation("Y");
                reliefOperationMap.put(dtl.getOperationsumId(), "Y");
            } else {
                sum.setOpCond(true);
            }
        }
        break;
      }
   }
}

This what I have so far. I can't think of anything else considering there are no implementations given for the objects that are being passed to this method (doOp()).

public static void doOp(Operation op, Map<Long, String> reliefOperationMap, OperationSummary sum) {

/*Missing increment condition from for loop, will be endlessly looping on 
the first element of the ArrayList (op.getOperationDetails())*/

    for (int d = 0; d < op.getOperationDetails().size(); d++ ) {
        OperationDetail dtl = op.getOperationDetails().get(d);
        if (dtl.getOpStatId() == 1 || dtl.getOpStatId() == 3 || dtl.getOpStatId() == 4) {
            sum.setOpCond(true);
            if (dtl.getRelblkId() != null && dtl.getOperationsumRefId() != null && dtl.getOperationsumParentId() != null) {
                sum.setIsReliefOperation("Y");
                reliefOperationMap.put(dtl.getOperationsumId(), "Y");
                System.out.println("Reached 1 or 3 or 4");
            }
        }else if(dtl.getOpStatId() == 10){

            //business logic for OpStatId here

        }else {
            System.out.println("Reached anything but 1,3 or 4");
            if (dtl.getRelblkId() != null && dtl.getOperationsumRefId() != null && dtl.getOperationsumParentId() != null) {
                sum.setOpCond(true);
                sum.setIsReliefOperation("Y");
                reliefOperationMap.put(dtl.getOperationsumId(), "Y");
            } else {
                sum.setOpCond(true);
            }
        }
/*removed break from here, no point of having a for loop if you're only 
 ever checking the first element of the Arraylist*/
    }
}
}

To Recap my changes : *Added a 'd++' in the for loop, otherwise it would be looping forever on the first element of the List.

*Added an else-if(dtl.getOpStatId() == 10) condition with empty business logic...I know they said this is wrong but I can't think of anything else

*removed break condition otherwise would only check the first element of the loop and exit the for loop

Is 'error: variable a might not have been initialized' really necessary in this if construct?

How do I tell Java that I don't need to initialize a to have a working program and to not give me an error?

int a;
boolean b = true;
while (true) {
   if (b == false) {
       System.out.print(a);
       break;
   } else {
       b = false;
       a = 5;
   }
}

And if I can't, is there a reason why this is the way the compiler was designed?

Was it easy to design such a compiler or is this a mechanism to ensure that I restructure my code?

This is not the same question as this one

Trouble with understanding function that uses complex array matters

I'm a little lost with this problem. I have a function called ComplexArray.... The function int ComplexArray(int values[], int numValues) should return ture(1) if the number in the array are a Palindrome( reads the same backwards and forwards), for eg { 1 2 1} is a planidrome hence the function will return 1 but if the array was { 1 2 1 3} then return will be 0. P.S. Im new to coding so please do inform me if what im doing is wrong.

Ive included my code below, I dont understand how to use an if statement that'll allow for the "planidrome effecr". Any help will be much appreciated. Cheers :)

#include <stdio.h>
int ComplexArray(int values[], int numValues)
int i;
int X[1000];
int Y[1000];

for(i=0;i<numValues;i++){ // storing values[i] into new array
values[i] = X[i];
}

for(i=numValues-1;i>=0;i--){
values[i] = Y[i];
}

if(X[i] == Y[i]){ // Planidrome effec? is this the correct way?
return 1;}
else{
return 0;}
}

My code wont pass the test where values[1] = {100}, when values[2] = {100, 100}, values[5] = {99, 2, 2, 2, 99} and when values[4] = {99, 2, 2, 99}.

Need help debugging

The function I'm trying to produce is called:

int Range(int values[], int numValues)

The purpose is to return the difference between the largest value in the array and the smallest value in the array.

Below is my code however it doesn't work. Any help would be appreciated :)

#include <stdio.h>

int Range(int values[], int numValues)
{
    int i;
    int large;
    int small;
    int displayone;
    int displaytwo;
    int calc;

    large = values[0];
    small = values[0];

    for(i=0;i<numValues;i++){

        if(values[i]>large){
            displayone = values[i];
        }
        else if(values[i] < small){
            displaytwo = values[i];
        }
    }

    calc = displayone - displaytwo;

    return calc;
}

Voting If/Else/Elif

New to Python (and to StackOverflow). Trying to figure out how to get this to execute properly. While the program itself executes fine, I'd like it to not have the extra step in there. What I mean by that is that if it fails the first statement, I'd like to to terminate and print the message associated with the else statement.

def main():

# init
messageOne = 'You are too young to vote.'
messageTwo = 'You can vote.'
messageThree = 'You need to register before you can vote.'

# input
age = int(input('Please enter your age: '))
registration = input('Are you registered to vote(Y/N)?: ')

# calculate / display
if age >= 18:
    if registration.upper() == "Y":
        print(messageTwo)
    else:
        print(messageThree)
else:
    print(messageOne)

main()

i want to pass a path to an object

I want to pass a path with the function to the constructor

this.elementImg.src = `${this.changeImage()}`;  

Why this dont Work

changeImage = () => {
    if (this.speed < 6) {
        this.imagePaths[0];
    } else if (this.speed >= 6 && this.speed < 9) {
        this.imagePaths[1];
    } else if (this.speed >= 9) {
        this.imagePaths[2];
    }
}

if/else code keeps giving out an error code

Write an if/else function that goes through and labels a TipPercentage of 16 percent or more as "large" and less than 16 percent as "small". Label this new variable TipPSL Also write an if/else function that labels a party size of 4 or more as "large" and a party size of less than 4 as "small". Label this new variable PartySL.

TipPSL < - if(EX2.TIPS$Tip.Percentage >= 16){
  print("large")
} else{
  print("small")
}
PartySL < - if(EX2.TIPS$Size_of_Party >= 4){
  print("large")
} else{
  print("small")
}

This is the code that I have attempted but I keep getting an error. This data comes form the data set EX2.TIPS

ifelse with list of possible string matches and no else

So normally, if I want to populate a new column data$new.col with 1s if it finds the strings "foo" or "bar" in data$strings and 0s if not, I would use something like this:

data$new.col <- ifelse(grepl("foo|bar",
  data$strings, ignore.case = T, perl = T), "1", "0")

However, I want to do the equivalent of this without an "else". I tried using a simple assignment but I must be doing something wrong because it's not working:

data$new.col[data$strings == "foo|bar"] <- "1"

Thanks in advance.

Why is my if statement False when 'answer' == number1 + number2 should be True?

def checkAnswer(number1, number2, answer, right):
    print (number1)
    print (number2)
    print (answer)
    print (right)
    if answer == number1 + number2:
        print ("Right")
        right = right + 1
    else:
        print ("Wrong")
    return right

I tried debugging my code by printing all the values that came as parameters to the function. number1 and number2 are equal to the answer that the user inputs, but the if/else statement goes to the else statement.

Here is my main function:

def main():
    #Initialize variables
    counter = 0
    studentName = ""
    averageRight = 0.
    right = 0
    number1 = 0
    number2 = 0
    answer = 0

    #Take the student's name as input for personalization
    studentName = inputNames(studentName)

    #Loop the program 10 times
    while counter < 10:

        number1, number2 = getNumbers()
        answer = getAnswer(number1, number2)
        right = checkAnswer(number1, number2, answer, right)
        counter = counter + 1

I am making a "math test" that loops ten times, and each loop consists of a simple addition problem with random ints from 1 to 500. The user then inputs answer and the program stores an int that holds the number of correct answers out of ten in right

Workaround for piping to an if-statement in powershell?

I wanted to pipe an object to a PowerShell if-statement, but it doesn't work:

for($i = 1; $i -le 70; $i++) {
    Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101" | if ($_.ProvisioningState -eq 'Succeeded') {
    Remove-AzureRmRedisCache $_ -Force
}}

"The term 'if' is not recognized as the name of a cmdlet, function, script file, or operable program". So what should I do instead?

The program Enter into the "if" command,When he does not need to

enter image description herePlease help me guys to solve the problem. when i press the button, The app should recognize that there are no values ​​within the edittext and only return toast but enter image description herefor some reason it goes into the second if

Why output is 2 not 3? [duplicate]

This question already has an answer here:

int x, z;
x = 10; z = 1;
if (1<x<5) z=2; else z=3;
printf("%d", z);

What does it mean. What I see - 1<10 true, 10<5 - false. Result must be false. But I get true.

  1<x<5?

Writing if statements as one-liners

I want to write one-liner if statements when i can avoiding two lines of code.

if 10>5:
    print( "10 is greater than 5" )
else:
    print( "nothing here " )

Why the following statement is considered wrong and not being run?

print "10 is greater than 5" if 10>5 else print( "nothing here " )

How does this if-else statement inside a function work?

I've been completing challenges on FreeCodeCamp and stumbled upon this solution for an algorithm. Can't comprehend how the if else statement works here.

function chunkArrayInGroups(arr, size) {

      var temp = [];
      var result = [];

      for (var a = 0; a < arr.length; a++) {
        if (a % size !== size - 1)
          temp.push(arr[a]);
        else {
          temp.push(arr[a]);
          result.push(temp);
          temp = [];
        }
      }

      if (temp.length !== 0)
        result.push(temp);
      return result;
    }

Why is temp = [] at the end of the else block?

Searching for values in array

i'm new to coding and have been introduced to C language. I need help understanding a specific concept.

I want to know how I can search for a specific number(e.g. 4) in a array(e.g. {1 2 4 5 6 4 6}). How ever I want to print out the index of the last occurrence of 4. How can I do this?

I have managed to so far do this...What u don't understand is how to show the ''last occurrence of a given number''

#include <stdio.h>
LastIndexOf(int search, int values[], int numValues){
int i;
int display;
for(i=0;i<numValues;i++){
if(values[i] == search){
display = i
}
}
}

any help would be much appreciated.

OnCheckedChanged event returns Check Box always as unchecked

I am trying to work in a VB project, but since is my first experience in VB i am having some kind of difficulties. I a have a check Box and a text box. I want that if the user checks the check box the text box to enable.

 <tr>
 <td></td>
 <td style="width:100px; ">Staff:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp                                                                          

  <asp:CheckBox ID="CheckBox3" runat="server" AutoPostBack="True" 
      OnCheckedChanged="CheckBox3_CheckedChanged" />
 </td>
 <td style="width:200px; ">

 <edititemtemplate>

 <telerik:RadTextBox ID="RadTextBox2" width="100%" Runat="server" 
     Enabled="false">

 </telerik:RadTextBox>

</edititemtemplate>
</td>  
   <td class="Validator_Cls"></td>                                                                  
   </tr>

and this is the code behind

Dim RadTextBox2 As New TextBox
Dim WithEvents CheckBox3 As New CheckBox

    Public Sub CheckBox3_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox3.CheckedChanged
    If CheckBox3.Checked = True Then
        RadTextBox2.Enabled = True
    End If

End Sub

the thing is that even when i check the check box the if clause says that check box is not checked and does not enter in the if statement.

Any idea where i am doing wrong? Please help because this is taking longer than it should.

Hi im trying to have my if statement equal to more then one number

I know this is incorrect and I cant figure it out. Do I just need to change my whole method? This website also said that this have question has been ask, but none of them help me at all.

public Date(int cMonth, int cDate, int cYear, int cDayToDate, String cStrMonth, int dayYear){
        if (cMonth = 01 && 12){
            month = cMonth;
            if (cMonth = 01,03,05,07,08,10,12){
            if (cDate <= 31 ){
            date = cDate;
            }// end of if
            }// end of if(cMonth) months with 31 days
        else if(cMonth = 04, 06, 09, 11){
            if (cDate <=30){
                date = cDate;
            }
}// end of cMonth month within 30 days

if then else statement will not loop properly

Morning fellow stackers! I figured how to get an if then else statement to work but it now seems to have broken. =( can't work out what's going wrong! There are up to 10 directories in ./ called barcode01 - 09 and one called unclassified. This script is supposed to go into each one, prep the directory for ~/Taxonomy.R (Which requires all the fastq files to be gzipped and put into a subd titled "data". It then runs the ~/Taxonomy.R script to make a metadata file for each.

edit; the tmp.txt file is created using ls > tmp.txt then echo "0" >> tmp.txt to make a sacrificial list of directories for the script to chew through then stop when it gets to 0

#!/bin/bash
source deactivate
source activate R-Env
value=(sed -n 1p tmp.txt)
if [ "$value" = "0" ]; then 
rm tmp.txt
else
cd "$(sed -n 1p tmp.txt)"
gzip *fastq
#
for i in *.gz; do mv "$i" "${i%.*}_R1.fastq.gz"; done
#this adds the direction identifier "R1" to all the fastq.gzips
mkdir Data
mv *gz Data
~/Taxonomy3.R
cd Data
mv * ..
cd ..
rm -r Data
cd ..
sed '1d' tmp.txt > tmp2.txt
mv tmp2.txt tmp.txt
fi

Currently, it's only making the metadata file in the first barcode directory. I'm still very fresh to making scripts so I can take this question down if its too simple, I've looked everywhere but can't find any answers.

How to write lambda function with three conditions

I want to write a function that gives returns 3 if x>y returns 1 if x==0 and returns 0 if x

def make_points():
    return lambda x,y: 3 if x>y else 0 

I tried this but I want to add another condition.

jeudi 27 septembre 2018

react native if else statement won't run function automatically

trying to run a function on a if else statement in react native, however if I just call it straight up like this.removeAlert() I get an infinite loop crash because of calling setState. I read that you should call it within a function, which works fine in onPress functions, but for me its not working outside of that.

  class Settingscontainer extends Component {
  constructor() {
   super();
   this.removeAlert = this.removeAlert.bind(this);
  }
  removeAlert = () => {
    console.log("please work");
    // this.setState({ successAlert: false });
  };

  render() {
    this.props.isFocused
      ? console.log("Focused") // console.log working
      : () => {                // not working
          this.removeAlert();
        };
    return(<View>code...</View>
    )  
    }}
     

logic in if/else method in javascript

i just want to implement if else method in my apps the problem is when in choose the first if it working, but if i choose second if its not working, this is my code

  //filter in session
   filterMarkersx = function (session) {

      var table = $('#edcTable').DataTable().column(1).column(2); 


     var str;


        $("select#type option:selected" ).each(function() {
            str = $(this).val();
        }); 


       for (i = 0; i < gmarkers1.length; i++) {
           marker = gmarkers1[i];
            if(marker.session == session || session.length === 0) {
                   marker.setVisible(true); 
           } else if(marker.session == session || session.length === 0) {
               if (marker.category == str || $("#type").length === 0){
                   marker.setVisible(true); 
               }
           }else{
               marker.setVisible(false);
               infowindow.close(map, marker1);
           }
       }


       table.search(str).draw();

   }  

anyone can help me what must i do, thanks in advance.

-kraken.

how can I make this into a If/else function

Write an if/else function that goes through and labels a TipPercentage of 16 percent or more as "large" and less than 16 percent as "small". Label this new variable TipPSL Also write an if/else function that labels a party size of 4 or more as "large" and a party size of less than 4 as "small". Label this new variable PartySL.

the condition has length > 1 and only the first element will be used >

i have a problem i'm try to make a LM whit one condition if P6020==2 do the Lm, Here my code: tretorno= if(P6220==5)lm (lsalario[lsalario!=NA|lsalario!=-Inf]~educacion+exptrabajo+exptrabajo2+edad+edad2+genero+genxedu+estrato+cursos+subsidios,weights=factor)

But R says : Warning message: In if (P6220 == 5) lm(lsalario[lsalario != NA | lsalario != -Inf] ~ : the condition has length > 1 and only the first element will be used

Can some help me

While loop creates never ending input loop (Java)

So I want my program to read the inputs "A" "B" or "C" and display the number of each. But I am running into an issue where it never reads and displays my input. My code is as follows:

if (command == 'A'){
                        System.out.println("Type the additional input in a single line.");
                        while(in.hasNext()){
                            String input = in.next().toUpperCase();
                            if(input.equals("A")){ numA++;}
                            if(input.equals("B")){ numB++;}
                            if(input.equals("C")){ numC++;}
}
                            System.out.println("---------------------------------------");
                            System.out.printf("\n%4s      |", "A");
                                for (int a = 1; a <= numA; a++) { System.out.print("*");}
                            System.out.println();
                            System.out.printf("\n%4s      |", "B");
                                for (int b = 1; b <= numB; b++) { System.out.print("*");}
                            System.out.println();
                            System.out.printf("\n%4s      |", "C");
                                for (int c = 1; c <= numC; c++) { System.out.print("*");}
                            System.out.println();
                            double gpa = ((numA * 4)+(numB * 3)+(numC * 2)) / ((numA + numB + numC));
                            System.out.println("GPA: " + gpa);
                            System.out.println();
                            System.out.println("---------------------------------------");
} 

Using ifelse within mutate and handling NA's

thanks for your time.

I have a question about using ifelse within the mutate function. ifelse is from base R, while mutate is from the dplyr package.

My question is about how ifelse handles NA values.

I have two character vectors: example_character_vector contains some words and occasional NA values while the other vector, color_indicator, contains only the words Green, Yellow, and Red.

I want to mutate my dataframe example_data_frame to create a new override_color_indicator variable that converts some of the yellows to greens depending on a condition in the example_character_vector.

Example data:

example_character_vector <- c("Basic", NA, "Full", "None", NA, "None", 
NA)
color_indicator <- c("Green", "Green", "Yellow", "Yellow", "Yellow", 
"Red", "Red")

example_data_frame <- data.frame(example_character_vector,
                                color_indicator)

This example_data_frame looks like so:

  example_character_vector color_indicator
1                    Basic           Green
2                     <NA>           Green
3                     Full          Yellow
4                     None          Yellow
5                     <NA>          Yellow
6                     None             Red
7                     <NA>             Red

I am using nested ifelse statements within mutate to create a new column called override_color_indicator.

If color_indicator is yellow and the example_character_vector contains the word "Full", I want the override_color_indicator to be Green (this is a special case within my data). Otherwise, I would like the override_color_indicator to be exactly the same as the color_indicator.

Here is my mutate:

example_data_frame <- example_data_frame %>% 
  mutate(override_color_indicator = 
          ifelse(color_indicator == "Green",
                 "Green",
            ifelse(color_indicator == "Yellow" & 
                          str_detect(example_character_vector, "Full"),
                   "Green",
                      ifelse(color_indicator == "Yellow" & 
                        !str_detect(example_character_vector, "Full") |
                             color_indicator == "Yellow" & 
                        is.na(character_vector),
                             "Yellow",
                             "Red"))))

(Apologies for the formatting - I tried to format this the best I could for Stack Overflow.)

This above code produces this dataframe:

  example_character_vector color_indicator override_color_indicator
1                    Basic           Green                    Green
2                     <NA>           Green                    Green
3                     Full          Yellow                    Green
4                     None          Yellow                   Yellow
5                     <NA>          Yellow                     <NA>
6                     None             Red                      Red
7                     <NA>             Red                      Red

My problem here is that in line 5, an NA is introduced in the override_color_indicator color. Instead of an NA, I would like it be "Yellow".

For clarity, this is my desired dataframe:

  example_character_vector color_indicator override_color_indicator
1                    Basic           Green                    Green
2                     <NA>           Green                    Green
3                     Full          Yellow                    Green
4                     None          Yellow                   Yellow
5                     <NA>          Yellow                   Yellow
6                     None             Red                      Red
7                     <NA>             Red                      Red

I've looked quite a bit for an answer, and couldn't find one anywhere. I could just create a workaround and go back and manually assign the entries to Yellow, but I don't love that option from a programmatic standpoint.

Also, I'm just kind of curious as to why this behavior happens. I've ran into this problem a few times now.


Thanks for your time!

Displaying 2 results when only one should display. Java intro

if(first == second || first == third || second == third)
{
    System.out.println("Isosceles Triangle");
}
if(first == second && first == third && second == third)
{
    System.out.println("Equilateral Triangle");
}
if(first != second && first != third && second != third)
    System.out.println("Scalene Triangle");

I want it to where if only 2 sides are equal then Isosceles will be displayed but as of right now it displays both Isosceles and Equilateral when all sides are equal.

Refactor if statement with many or

How to refactor this conditions to make simpler and cleaner?

if(in_array($sides, [self::ALL_SIDES, self::HORIZONTAL_SIDES, self::LEFT_SIDE ])) {

}

if(in_array($sides, [self::ALL_SIDES, self::HORIZONTAL_SIDES, self::RIGHT_SIDE ])) {

}

if(in_array($sides, [self::ALL_SIDES, self::VERTICAL_SIDES, self::TOP_SIDE ])) {

}

if(in_array($sides, [self::ALL_SIDES, self::VERTICAL_SIDES, self::BOTTOM_SIDE ])) {

}

Nested if else statements c++

Hey guys so Ive got this assignment Im working on that im having trouble with. I had to call everything that is an integer as part of the requirement so thats why only 59 and 60 is still a number.

My question is what am I missing to make this work? The only sample output Ive been able to make work is the first one.

Sample output 1:

Enter start time: 2322
Enter length of call in minutes: 67    
gross cost: $26.80
net cost: $11.85

Sample output 2:

Enter start time: 759
Enter length of call in minutes: 10    
gross cost: $4.00
net cost: $2.08

Sample output 3:

Enter start time: 1300
Enter length of call in minutes: 100    
gross cost: $40.00
net cost: $35.36

Sample output 4:

Enter start time: 1300
Enter length of call in minutes: 10    
gross cost: $4.00
net cost: $4.16    

////////////

//
//  main.cpp
//  Assignment 5
//
//  Created by Jake Anderson on 9/20/18.
//  Copyright © 2018 Jake Anderson. All rights reserved.
//
double grosscost1;
double netcost1;
double netcost2;
double netcost3;
double starttime;
double calllength;
double taxes=.04;
double rate=.40;
double hrdiscount=.15;
double grosscost = (calllength * .40) ;

#include <iostream>
# include <iomanip>
using namespace std;
int eighteenhundred=1800;
int eighthundred=800;
int two=2;
int main()
{

    cout << "Enter start time : ";
    cin >> starttime;

    cout << "Enter length of call in minutes : ";
    cin >> calllength;

    if (starttime >= eighteenhundred) {
        grosscost = (calllength * rate) ;
        netcost1= (grosscost/two) ;


    if (starttime <= eighthundred) {
        grosscost = (calllength * rate) ;
        netcost1= (grosscost/two) ;

    } else {

    if (calllength>=60) {
        netcost2= netcost1-(netcost1 * hrdiscount);
        netcost3= netcost2 + netcost2 * taxes;

    if (calllength<=59) {
        netcost3= netcost2 + netcost2 * taxes;
    }
    cout << fixed << std::setprecision(2) << "gross cost: $" << grosscost << endl;
    cout << fixed << std::setprecision(2) << "net cost: $" << netcost3 << endl;



}





}

}

}

trying to compare object cannot use IF statement JAVA

I am writing a method to find an object in an ArrayList. If I can find the object I will print it out to the screen, otherwise I will print an error message saying "Object not found". The problem I am running into is since my method is the object, "Dodecahedron", and not a boolean, I cannot use an if statement to compare if the object exists in the array. How else could I approach this?

This is the code in my main method.

    System.out.print("\tLabel: ");
    label = userInput.nextLine();

    if(myDList.findDodecahedron(label)) {

        System.out.print(myDList.findDodecahedron(label));
    }
    else {
        System.out.print("\t\"" + label + "\" not found");
    }
        System.out.print("\n\nEnter Code [R, P, S, A, D, F, E, or Q]: ");
    break;

and this is my method.

public Dodecahedron findDodecahedron(String label1In) {
      String label = "";
      String color = "";
      double edge = 0;
      Dodecahedron result = new Dodecahedron(label, color, edge);
      int index = -1;
      for (Dodecahedron d : dList) {
         if (d.getLabel().equalsIgnoreCase(label1In)) { 
            index = dList.indexOf(d);
            break;
         }    
      }
      if (index >= 0) {
         dList.get(index);
         result = dList.get(index);
      }
      return result;
   }

And this is the error I get when I try to compile.

DodecahedronListAppMenu.java:99: error: incompatible types: Dodecahedron cannot be converted to boolean
               if(myDList.findDodecahedron(label)) {

How to make an if statement with multiple variables and multiple conditions into a switch case ? Can && compare cases?

I'm making a rock paper scissors game for school and I have a working game but its 213 lines long. I was trying to shorten it up some by adding switch case in place of my if statements. Are there some instances where a switch case just won't work and it has to be an if statement?

String weaponChoice = keyboard.nextLine();
switch(weaponChoice) {
            case "Rock": 
                System.out.println("You Chose Rock"); break;
            case "Paper":
                System.out.println("You Chose Paper"); break;
            case "Scissors":
                System.out.println("You chose Scissors"); break;
            default:
                System.out.println(weaponChoice + " is not a valid answer the computer gets a point!");
                compScore++;
                break;
            }

I had the above code in an if statement and switched it over no problem but the below code I'm not sure how to change it over.

            String getComputerChoiceVariable = getComputerChoice();
            System.out.println("The computer chose " + getComputerChoiceVariable);

        if(weaponChoice.equals(getComputerChoiceVariable)) {
            System.out.println("It's a draw!");
            ties++;
        } else if((weaponChoice.equals("Rock")) && (getComputerChoiceVariable.equals("Scissors"))) {
            System.out.println("You won!");
            userScore++;
        } else if((weaponChoice.equals("Paper")) && (getComputerChoiceVariable.equals("Rock"))){
            System.out.println("You won!");
            userScore++;
        } else if((weaponChoice.equals("Scissors")) && (getComputerChoiceVariable.equals("Paper"))){
            System.out.println("You won!");
            userScore++;
        } else if(weaponChoice.equals("Rock") && getComputerChoiceVariable.equals("Paper")) {
            System.out.println("You Lost!");
            compScore++;
        } else if(weaponChoice.equals("Paper") && getComputerChoiceVariable.equals("Scissors")) {
            System.out.println("You Lost!");
            compScore++;
        } else if(weaponChoice.equals("Scissors") && getComputerChoiceVariable.equals("Rock")) {
            System.out.println("You Lost!");
            compScore++;
        }

Maybe something like

switch(weaponChoice, getComputerChoiceVariable){
case "Rock", case "Scissors":
    System.out.println("You won!");
}

But Java doesn't like that I get a ton of errors. Can a switch take two parameters? I'm super new to Java. Could I somehow use the && to compare cases?

Base R ifelse test for a span of temperature values

I am aware that this question has been asked for other cases before, but none of the answers matched my case well. I have been trying hard but didn´t get it working for my code. I believe that there is a simple solution and appreciate your help.

My Data looks like that:

start <- as.POSIXct("2018-05-18 00:00")
tseq <- seq(from = start, length.out = 1440, by = "10 mins")
Measurings <- data.frame(
  Time = tseq,
  Temp = sample(10:37,1440, replace = TRUE, set.seed(seed = 10)),
  Variable1 = sample(1:200,1440, replace = TRUE, set.seed(seed = 187)),
  Variable2 = sample(300:800,1440, replace = TRUE, set.seed(seed = 333))
)

Measurings$heat25 <- ifelse(Measurings$Temp >= 25 ,"summer", "normal")
Measurings$heat30 <- ifelse(Measurings$Temp > 30 ,"heat", "normal")

This works, and I need the Columns for choosing my data based on temperature values. Now I need a new column indicating wether the temperature is between 25 °C and 30° C. I expected to be able to combine test arguments like that:

Measurings$summer <- ifelse(Measurings$Temp >= 25 && < 30, "summer", "rest"))

But I get an error.

How can I simply add a new column indicating if Temp is between 25°C and 30°C?

Thanks for helping!

If/else statement syntax using R

I have a semantic question regarding the proper syntax for a simple if statement I'm trying to write with R (having a background in coding with Python). What would be the R equivalent to the Python statement:

def zsco(data, mean, sd):
    if sd==0:
        z=0
    else:
        z=abs((data-mean)/sd)
    return z

Thank you! :)

Is it better to use a boolean variable to replace an if condition for readability or not?

I am in the second year of my bachelor study in information technology. Last year in one of my courses they taught me to write clean code so other programmers have an easier time working with your code. I learned a lot about writing clean code from a video ("clean code") on pluralsight (paid website for learning which my school uses). There was an example in there about assigning if conditions to boolean variables and using them to enhance readability. In my course today my teacher told me it's very bad code because it decreases performance (in bigger programs) due to increased tests being executed. I was wondering now whether I should continue using boolean variables for readability or not use them for performance. I will illustrate in an example (I am using python code for this example):

  • example boolean variable

Let's say we need to check whether somebody is legal to drink alcohol we get the persons age and we know the legal drinking age is 21.

    is_old_enough = persons_age >= legal_drinking_age
    if is_old_enough:
        do something

My teacher told me today that this would be very bad for performance since 2 tests are performed first persons_age >= legal_drinking_age is tested and secondly in the if another test occurs whether the person is_old_enough. My teacher told me that I should just put the condition in the if, but in the video they said that code should be read like natural language to make it clear for other programmers. I was wondering now which would be the better coding practice.

  • example condition in if:

    if persons_age >= legal_drinking_age:
        do something
    
    

In this example only 1 test is tested whether persons_age >= legal_drinking_age. According to my teacher this is better code.

Thank you in advance!

yours faithfully

Jonas

Nested list comprehension with if statement

I'm trying to get my head around nested list comprehension and have read the excellent explanation here.

The problem I'm having translating is that I've an if clause in my inner loop and I can't see how to apply this to the func() step as I'm loosing the counter I get from enumerate() when I go from nested loops to list comprehension.

nested_list = [[{'a': 1, 'b': 2}, {'c': 3, 'd': 4}], [{'a': 5, 'b': 6}, {'c': 7, 'd': 8}]]
new_list = []
for c, x in enumerate(nested_list):
    for d, y in enumerate(x):
        if d == 1:
            new_list.append(y)
print(new_list)
[{'c': 3, 'd': 4}, {'c': 7, 'd': 8}]

Nested list comprehension might look something like

new_list = [if ??? y
               for x in nested_list
                   for y in x]

...but I can't see/think how to get the clause as I have no counter under the nested list comprehension.

Is there a way of achieving this or should I stick to the nested loops approach?

Using case statement/If-then to create a field

Hello Fellow Developers/Analysts/Consultants etc.,

I'm currently working on a project that would be super enhanced if I can get this SQL right! I want to SELECT various variables surrounding vehicles to represent as a table in Tableau, but when creating a calculated field (in tableau) and using If-then conditional format, the THEN options aren't all being displayed within the graphic and some results are even being incorrectly represented by certain options!

For example:

The below skeleton statement creates a field called MissingNumber wherein if "-----1" is true then MissingNumber will take the value 'Number 1'.

          If ------1 Then 'Number 1'
             ELSEIF
          If ------2 Then 'Number 2'
             ELSEIF
          If ------3 Then 'Number 3'
             ELSEIF
          If ------4 Then 'Number 4'
             ELSE 'Number 5'
          END

Continuing with the above format as guide, 'Number 1', 'Number 2', and 'Number 5' are represented categorically but NOT 'Number 3' or 'Number 4' even though I know that the data satisfies 'Number 3' and 'Number 4' too in quite a few records!

I believe that there is an issue with order here (or some other unforeseen problem) so I tried using a case statement:

    CASE 
         WHEN (Rtrim((v.plt_no)) is null) or (Rtrim(v.plt_no = '')) THEN "Plate Only" 

         WHEN (v.rnw_dt is null) THEN "Expiration Only"

         WHEN ((DocumentTemplate is null) or (DocumentTemplate = '')) THEN "Registration Only"

         WHEN (Rtrim((v.plt_no)) is null or Rtrim(v.plt_no = '')) AND (v.rnw_dt is null) THEN "Plate & Expiration"

         WHEN (Rtrim((v.plt_no)) is null or Rtrim(v.plt_no = '')) AND ((DocumentTemplate is null) or (DocumentTemplate = '')) THEN "Plate & Registration"

         WHEN (v.rnw_dt is null) AND ((DocumentTemplate is null) or (DocumentTemplate = '')) THEN "Expiration & Registration"

    ELSE "All Good"

END AS MissingInfo

My QUESTION IS: What advice does the community have about whether I should continue trying the IF-Then format within tableau, or building the variable Missing Info within SQL?

ALSO with the suggested choice, how can I affect the code such that ALL options are correctly represented by a crosstab ("MissingInfo" on row side, "License Plate State" on column side). I have linked a snip of the code and a cross-tab example for reference! Please let me know if there will be anything else I'll need to include to make this more clear! **NOTE in the Tableau image "Plate Only" does NOT show up on the graphic!

Code-SNIP

Tableau-CrossTab

PHP: merge two multimensioanl arrays into one

I try to create a multi-dimensional array ($list) which should look like:

[
  {"uri": "http://www.example.com/1", "traverseCount": "1"},
  {"uri": "http://www.example.com/2", "traverseCount": "1"},
  {"uri": "http://www.example.com/3", "traverseCount": "1"}
]

But, I don't know how best I can achieve this from the following data. The two data sources come from two If-Else and try to create an multi-dimensional array for each case. But, at the end, I would like to generate a multidimensional array which combines the two multi-dimensional array with continuous ordered keys. (So, from the above example, http://www.example.com/1 and http://www.example.com/2 comes from the outcome of the 1st Else-If, and http://www.example.com/3 comes from the 2nd Else-If). Tricky bit is that there is foreach inside Else-If.

// Create an empty multidimentional array to accommodate 2 datasets (2 If-Else cases) below:
$traverseCount = 1;
$list = array(
  array(),
  array()
);
//This is the first data source. Say, it returns 2 URIs when doing the foreach loop:
$match = $graph->resourcesMatching('skos:exactMatch');
if (isset($match) == true && count($match) > 0){
  $graphuris = $match[0]->all('skos:exactMatch');
  echo '<b>skos:exactMatch Links: </b><br>';
  foreach ($graphuris as $uris) {
    $counter = 0;
    $list[$counter][0] = $uris->__toString();
    $list[$counter][1] = $traverseCount;
    $counter++;
    echo '<a href="'.$uris.'" target="_blank">'.$uris.'</a><br>';
  }
}
else {
  echo '<p>No skos:exactMatch found</p>';
}
//This is the second data source, whose multidimensional array should be added to the end of the previous multidimensional array 
$match2 = $graph->resourcesMatching('rdfs:seeAlso');
if (isset($match2) == true && count($match2) > 0){
  $graphuris2 = $match2[0]->all('rdfs:seeAlso');
  echo '<b>rdfs:seeAlso Links: </b><br>';
  foreach ($graphuris2 as $uris2) {
    $counter = 0;
    $list[$counter][0] = $uris2->__toString();
    $list[$counter][1] = $traverseCount;
    $counter++;
    echo '<a href="'.$uris2.'" target="_blank">'.$uris2.'</a><br>';
  }
}
else{
  echo '<p>No rdfs:seeAlso found</p><br>';
}
// $traverseCount is always 1 until here, but it needs to add 1 for the next script to run.
$traverseCount++;

search for files and create conditions using gnuplot

Tell me please how to make a script using gnuplot:

have folder:

d:/data/

in which there are files in the format

[text1][delta=text2][text3][mac=text4].csv

need to create the script for all the files in the folder:

for [file] of [files]
{
    if [file] content text1 == 'packets' and text4 == 'all'
    {
        set xlabel "amount" font "Calibri, 10"
    }
    else
    {
        set xlabel "size" font "Calibri, 10"
    }

    set output "d:/images/out_[file].png"
    plot [file] using ...
}

more simple code without conditions I could create

files = system("ls -1 d:/data/*.csv")
plot for [data in files] data using 1:3 with line ls 2 notitle

but how can I make a more complex code with the terms I can not understand :(

mercredi 26 septembre 2018

Trying to simplify javascript with var instead of numbers. Am I going about this all wrong?

I'm trying to make my FizzBuzz do calculations using modulus by variable in order to simplify the code. They are supposed to count up to 140 displaying True or False.

My previous 'if' statement looks like this (and it worked) :

if (i % 3 === 0 && i % 5 === 0)

The example that I've seen looks like this:

if (checkDivision(iCounter, secondDivisor))

I've created variables for the counter, the two divisors, and the modulus checker, but I can't seem to get it to work.

Any help is appreciated because I am still very new to javascript and coding in general.

Here is my code so far:

    function clickAlert2() {
  var firstDivisor = 3;
  var secondDivisor = 5;
  for (var iCounter = 1; iCounter <= 140; iCounter++) {
    var checkDivision =
      iCounter % firstDivisor === 0 || iCounter % secondDivisor === 0;
    if (checkDivision(iCounter, firstDivisor)) {
      document.getElementById("ngList").innerHTML +=
        checkDivision + ". True [3] <br>";
    } else if (checkDivision(iCounter, secondDivisor)) {
      document.getElementById("ngList").innerHTML +=
        checkDivision + ". True [5] <br>";
    } else {
      document.getElementById("ngList").innerHTML +=
        checkDivision + ". False <br>";
    }
  }
}

java script if condition with multiple values [duplicate]

This question already has an answer here:

I got a role from the back-end If it is equals to "admin" , "staff", "manager" it should go to the if part of the block. otherwise it should go to the else part of the block.

let role = "restaurant";

if(role === "admin" || "manager" || "staff"){
  console.log("IF PART")
  console.log(role)
}
else{
  console.log("ELSE PART")
}

In this scenario it comes to if part. What's wrong with my code?

Any help

Thanks in advanced!

JavaScript - Generate a random number between 1 and 5, but never the same number twice consecutively

Okay hello everyone. I'm going to try to explain this the best I can....I have some simple code to generate a random number between 1 and 5. Depending on what number is pulled, a certain sound file will play..... HOWEVER.....how could I prevent this simple program from generating the same number twice in a row consequently making the same audio to play twice? For example: a roll of the dice is never the same twice consecutively....meaning you cannot roll a 2 if you just rolled a 2 etc.

I was experimenting with if else statements and kind of backed myself into a corner. I know this may seem like a simple problem but I'm at my wits end on this one. Any advice will be much appreciated! Thanks!

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display a random number between 1 and 5.</p>

<button onclick="myFunction()">ROLL DICE</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = Math.floor((Math.random() * 5) + 1);
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

How to get the the "Error" message printed in this situation because the "else" statement doesn't work?

Write the program that reads in input three integers a, b and c. If the integer c is equal to 1, then the program displays on output (prints) the value of a + b; if c is 2 then the program displays the value of a-b; if c is equal to 3 then the output will be the value of ab. Finally, if the value 4 is assigned to c, then the program displays the value of a^2 + ba. If c contains another value, the program displays the message "Error"

a = int(input())

b = int(input())

c = int(input())

if c == 1 :

print(a + b)

if c == 2 :

print(a - b)

if c == 3 :

print(a * b)

if c == 4 :

print(a**2 + b*a)

else :

print('Error')

IF statement condensing multiple OR statements

I have the following line

if 'smoke' in row['product'].lower() or 'grill' in row['product'].lower() or 'choco' in row['product'].lower(): 

I want to add multiple items in the OR clause. ['smoke', 'grill, 'choco', ...], how can I condense the if statement while not losing the logic?

Comparing dates in Excel and adding a set of cells

I am trying to compare a series of cells in a column to match a particular month and if it matches, I want to add the value from a particular cell.

For example, If the month value in A1 to A50 is December, I want to add C1 to C50. If anything in between A1 to A50 is not December, then it would add 0 for that particular cell.

I was able to implement it by using sum, if and month commands. But, I was not able to use arrays to check the month, which is making the formula complicated and huge for a large number of cells.

Is it possible to use an array to implement this.

=sum(if(month(A1)=9, C1, 0),if(month(A2)=9, C2, 0))

Transform an if.. elseif chain of distinct conditions into case switch

Simple curiosity, is there any way to convert what this following into a switch loop?

PHP :

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                  $error = array('type' => 'error', 'value' => 'email');
             }
        elseif (!preg_match($regex_name, $username)) {
                  $error = array('type' => 'error', 'value' => 'username');
             }
        elseif (!preg_match($regex_name, $firstname) && preg_match($regex_name, $lastname)) {
                  $error = array('type' => 'error', 'value' => 'name');
             }
        elseif ($password !== $password_conf) {
                  $error = array('type' => 'error', 'value' => 'password');
             }
        elseif (checkdate($birthday_d, $birthday_m, $birthday_y) == false) {
            $error = array('type' => 'error', 'value' => 'date');
        }
        else {
            $error = array('type' => 'success');
        }

Thanks.

Correct Operator to echo $result statement with multiple operators PHP

The homework goes as follows:

Create 2 variables, with values 10, 12.

Write 5 individual PHP statements that compares the 2 variables using the following comparison operators

Less Than, <

Less than or Equal to, <=

Greater than, >

Greater than or Equal to, >=

Not Equal to, !=

If the comparison value is TRUE, echo a string statement that describes the results of the comparison. Examples:

$a = 10; $b=12; if ($a < $b) { echo "$a is less than $b
";}

Display the $result value using an echo statement.

   <?php

       $varOne = 10;

       $varTwo = 12;

       $lessThan = $varOne < $varTwo;

       $lessThanEqualTo = $varOne <= $varTwo;

       $greaterThan = $varOne > $varTwo;

       $greaterThanEqualTo = $varOne >= $varTwo;

       $notEqualTo = $varOne != $varTwo;

       $result = "$varOne"." "."is"." "."less"." "."than"." 
        "."$varTwo"." <br>";

       if ($varOne < $varTwo)
       { echo $result ;}

       else 
       { echo "$varOne is NOT less than $varTwo <br>";}

       if ($varOne <= $varTwo)
       { echo "$varOne is less than or equal to $varTwo <br>";}

       else 
       { echo "$varOne is NOT less than or equal to $varTwo <br>";}

       if ($varOne > $varTwo)
       { echo "$varOne is greater than $varTwo <br>";}

       else
       { echo "$varOne is NOT greater than $varTwo <br>";}

       if ($varOne >= $varTwo)
       { echo "$varOne is greater than or equal to $varTwo <br>";}

       else
       { echo "$varOne is NOT greater than nor equal to $varTwo <br>";}

       if ($varOne != $varTwo)
       { echo "$varOne is not equal to $varTwo <br>";}

       else 
       {  echo "$varOne IS equal to $varTwo <br>";}

   ?>

What I want to know is how to make the if statement only have echo $result but have the exact statement needed for the correct operation

Python Functions, if, conditional, storing & assigning values

Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd

If else statement not calling isServiceCharge() method?

I am almost finished with this bank account program. I have a call to calculateSavings() method or calculateCheckings() method. If the currentBalance is less than the required minSavings or minChecking I have an else statement to call the isServiceCharge() method to deduct a fee. The program is not giving me errors but if the user inputs a currentBalance that is less than the required amount for minChecking or minSavings the JOptionPane is not showing the output. The inputs still work but there is no output popping up. Everything else works fine such as adding interest, but deducting a fee in the service charge isn't. How can I fix this.

Main class

package com.company;

import javax.swing.*;

public class Main
{


public static void main(String[] args)
{
    {
        BankAccount myBank = new BankAccount();

        myBank.calculateNewBalance();
    }

}
}

BankAccount class

package com.company;

import javax.swing.*;

public class BankAccount

{
private int accountNumber;
private String accountType;
private double minSavings = 2500.00;
private double minChecking = 1000.00;
private double currentBalance;


public BankAccount()
{

    accountNumber = Integer.parseInt(JOptionPane.showInputDialog("Please enter your account number"));
    accountType = JOptionPane.showInputDialog("Please enter your account type");
    currentBalance = Double.parseDouble(JOptionPane.showInputDialog("Please enter your current balance."));

}

public int getAccountNumber()
{
    return accountNumber;
}

public void setAccountNumber(int accountNumber)
{
    this.accountNumber = accountNumber;
}

public String getAccountType()
{
    return accountType;
}

public void setAccountType(String accountType)
{
    this.accountType = accountType;
}

public double getMinSavings()
{
    return minSavings;
}

public void setMinSavings(double minSavings)
{
    this.minSavings = minSavings;
}

public double getMinChecking()
{
    return minChecking;
}

public void setMinChecking(double minChecking)
{
    this.minChecking = minChecking;
}

public double getCurrentBalance()
{
    return currentBalance;
}

public void setCurrentBalance(double currentBalance)
{
    this.currentBalance = currentBalance;
}


public void calculateNewBalance()
{
    if (accountType.equals("S") || accountType.equals("s"))
    {
        accountType = "Savings";
        calculateSavingsBalance();

    } else if (accountType.equals("C") || accountType.equals("c"))
    {
        accountType = "Checking";
        calculateCheckingBalance();
    }


}

private void calculateSavingsBalance()
{

    if (currentBalance >= minSavings)
    {
        double newBalance = currentBalance + (currentBalance * .04 / 12);

        JOptionPane.showMessageDialog(null, "Account Number: " + getAccountNumber() + "\nAccount Type: " + getAccountType() + "\nMinimum Balance: $" + getMinSavings()
                + "\nBalance Before Interest and Fees: $" + getCurrentBalance() + "\n\nNew Balance: $" + newBalance);
    }
    else if(currentBalance < minSavings)
    {
        isServiceCharge();
    }

}


private void calculateCheckingBalance()
{
    if (currentBalance > 6000)
    {
        double newBalance = currentBalance + (currentBalance * .03 / 12);
        JOptionPane.showMessageDialog(null, "Account Number: " + getAccountNumber() + "\nAccount Type: " + getAccountType() + "\nMinimum Balance: $" + getMinSavings()
                + "\nBalance Before Interest and Fees: $" + getCurrentBalance() + "\n\nNew Balance: $" + newBalance);
    }
    else if (currentBalance >= minChecking)
    {
        double newBalance = currentBalance + (currentBalance * .05 / 12);
        JOptionPane.showMessageDialog(null, "Account Number: " + getAccountNumber() + "\nAccount Type: " + getAccountType() + "\nMinimum Balance: $" + getMinSavings()
                + "\nBalance Before Interest and Fees: $" + getCurrentBalance() + "\n\nNew Balance: $" + newBalance);

    }
    else if(currentBalance < minChecking)
    {
        isServiceCharge();
    }


}

public void isServiceCharge()
{
    if(accountType.equals("s") || accountType.equals("S"))
    {
        double newBalance = currentBalance - 10.0;
        JOptionPane.showMessageDialog(null, "Account Number: " + getAccountNumber() + "\nAccount Type: " + getAccountType() + "\nMinimum Balance: $" + getMinSavings()
                + "\nBalance Before Interest and Fees: $" + getCurrentBalance() + "\n\nNew Balance: $" + newBalance);
    }
    else if(accountType.equals("c") || accountType.equals("C"))
    {
        double newBalance = currentBalance - 25.0;
        JOptionPane.showMessageDialog(null, "Account Number: " + getAccountNumber() + "\nAccount Type: " + getAccountType() + "\nMinimum Balance: $" + getMinSavings()
                + "\nBalance Before Interest and Fees: $" + getCurrentBalance() + "\n\nNew Balance: $" + newBalance);
    }

}
}