dimanche 31 juillet 2016

Load existing files in blueimp jQuery file upload by id

hi iam trying to use blueimp jQuery file upload with codeigniter but i need to load existing files by id inserted in database

this is function in my controller

 public function get_files()
{

    $last = $this->uri->total_segments();
    $record_num = $this->uri->segment($last);

    if (is_numeric($record_num) == TRUE) {

    $upload_path_url = base_url() . 'uploads/';
    $config['upload_path'] = FCPATH . 'uploads/';
    $config['allowed_types'] = 'jpg|jpeg|png|gif';
    $config['max_size'] = '30000';

        $existingFiles = get_dir_file_info($config['upload_path']);
        $foundFiles = array();
        $f=0;
        foreach ($existingFiles as $fileName => $info) {
          if($fileName!='thumbs'){//Skip over thumbs directory
            //set the data for the json array   
            $foundFiles[$f]['name'] = $fileName;
            $foundFiles[$f]['size'] = $info['size'];
            $foundFiles[$f]['url'] = $upload_path_url . $fileName;
            $foundFiles[$f]['thumbnailUrl'] = $upload_path_url . 'thumbs/' .                 $fileName;
            $foundFiles[$f]['deleteUrl'] = base_url() . 'http://ift.tt/2akxtQW' . $fileName;
            $foundFiles[$f]['deleteType'] = 'DELETE';
            $foundFiles[$f]['error'] = null;

            $f++;
          }
        }
        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(array('files' => $foundFiles)));

and in main.js

// Load existing files:
    $('#fileupload').addClass('fileupload-processing');
    $.ajax({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        // url: $('#fileupload').fileupload('option', 'url'),
        url: 'http://localhost/mysite/index.php/App/controll/get_files',
        dataType: 'json',
        context: $('#fileupload')[0]
    }).always(function () {
        $(this).removeClass('fileupload-processing');
    }).done(function (result) {
        $(this).fileupload('option', 'done')
            .call(this, $.Event('done'), {result: result});
    });

but this if statement if (is_numeric($record_num) == TRUE) didn't work

Executing A Line Of Code When Two Different Conditions In An If Statement Are True

my name is Henry and I am relatively new to jQuery. Currently I have a problem with a calculator that I am trying to build. This is my HTML code, which is probably less relevant than...

    <html>

    <head>
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" type="text/css" href="style.css" />
    </head>

    <body>
        <div id="integers">
            <button type="button" value="">1</button>
            <button type="button" value="">2</button>
            <button type="button" value="">3</button>
            <button type="button" value="">4</button>
            <button type="button" value="">5</button>
            <button type="button" value="">6</button>
            <button type="button" value="">7</button>
            <button type="button" value="">8</button>
            <button type="button" value="">9</button>
            <button type="button" value="">0</button>
        </div>
        <br />
        <div id="operators">
            <button type="button" value="" id="plus">+</button>
            <button type="button" value="" id="minus">-</button>
            <button type="button" value="" id="times">*</button>
            <button type="button" value="" id="by">/</button>
            <button type="button" value="" id="equals">=</button>
        </div>
        <br />
        <div id="misc">
            <button type="button" value="">.</button>
            <button type="button" value="">C</button>
        </div>
        <br />
        <input type="text" placeholder="" value="" id="input" disabled />
        <script src="http://ift.tt/29q98ga"></script>
        <script src="script.js"></script>
    </body>
</html>

... the jQuery code:

$(document).ready(function () {
    $('#input').val('');
    $('#plus , #minus , #times , #by').attr("disabled", false);
    $('#integers > button').click(function () {
        if ($('#input').val() !== 'Error') {
            a = $(this).text();
            $('#input').val($('#input').val() + a);
        }
    });
});


$('#operators > button').click(function () {
    if ($(this).is('#plus')) {
        window.x = $('#input').val();
        console.log(x);
        $('#input').val('');
        $('#plus , #minus , #times , #by').attr("disabled", true);
        $('#plus').val('used');
    } else if ($(this).is('#minus')) {
        // Yet to be implemented
    } else if ($(this).is('#times')) {
        // Yet to be implemented
    } else if ($(this).is('#by')) {
        // Yet to be implemented
    } else if ($(this).is('#equals')) {
        if ($('#input').isNumeric) {            
            if ($('#plus').val() === 'used') {
                window.y = $('#input').val();
                console.log(y);
                $('#input').val('');
                $('#input').val(parseInt(x) + parseInt(y));
            } else {
                $('#input').val('Error');
            }
        }
    }
});

The problem lies at this point:

else if ($(this).is('#equals')) {
            if ($('#input').isNumeric) {            
                if ($('#plus').val() === 'used') {
                    window.y = $('#input').val();
                    console.log(y);
                    $('#input').val('');
                    $('#input').val(parseInt(x) + parseInt(y));
                } else {
                    $('#input').val('Error');
                }
            }
        }

I am trying to say that if #Input is Numeric and if #plus has the value "used" then execute the code. These two conditions should be in one if statement if that is possible.

Note that the calculator is not at all completed and is only (supposed to be) capable of adding numbers, yet. The methods I used (such as global variables created in functions or making the equal button work by checking for a value, etc.) are, I guess, representative for my level of skill so don't be surprised about bad workarounds.

I am very thankful for every kind of help to solve the problem so I can continue my work. Thanks to everyone in advance! :)

Sorry for typos or bad english, it is not my mother language.

C++ while loop cut short by std::cout command in if statement

I made a program in C++ that ask for any integer input other than 5, and keeps asking until you enter 5. It then outputs a statement. If the user has not entered 5 after 10 iterations of the while loop then the user wins. However, after trying to check if the loop had run 10 times in the while loop using an if statment and a std::cout command, The program crashes after only 2 iterations. I am clueless to why this is. Code below:

#include<iostream>

int main()
{   
    int user_choice;
    int right_answer = 5;
    int counter = 0;

    std::cout <<"Please enter any number other than five: ";
    std::cin >> user_choice;

    while(user_choice != right_answer)
    {
        counter += 1;
        std::cout <<"Please enter any number other than five: ";
        std::cin >> user_choice;

        if (user_choice == 5)
            user_choice = right_answer;

        if (counter == 10)
            std::cout << "Wow you still have not entered 5. You win!";
            user_choice = right_answer;
    }
    std::cout << "I told you not to enter 5!";

    return 0;
}

The funny thing is though, is that when i remove the std::coutcommand under the second if statement, the program runs fine.

Problems with cleaning a data frame with ifelse

I am a novice at R, and trying to clean a data frame (MSdatanew) using ifelse. I want to change a variable E2_new so that wherever it was coded as "<0.057" it is now coded as "0.57". However, wherever it isn't coded as "<0.057", I wanted it to stay as originally coded.

    MSdataclean<-MSdatanew
    MSdataclean$E2_new <- ifelse(MSdataclean$E2_new=="<0.057",0.057,MSdataclean$E2_new)

The result from this is that the variable E2_new is altered even where it wasn't "<0.57"

    head(MSdatanew$E2_new)
    [1] 0.102  <0.057 2.797  11.226 5.156  10.032
    46 Levels: <0.057 >30 0.058 0.080 0.094 0.102 0.109 0.124 0.136 0.147 ... 9.711

    head(MSdataclean$E2_new)
    [1]  6.000  0.057 26.000 19.000 32.000 18.000

Any suggestions on what I'm doing wrong?

Java- if and else issue

while i'm working on my first desktop application and finished design the scene for "adding" feature which allows the user to adding new words and its meaning and other stuff like description and more the point here is all of this is a text fields and return Strings so if a user want to add a word without adding description so the description area will return (null), so is i wanted to display the word on the other scene after saving it ill need to make a type for every word like this

if(addobj.audio == null && addobj.image == null && addobj.des != null)
                {addobj.type = "a"; addobj.createFile(); addobj.aadd(); addobj.close(); stage.setScene(msc);}

                if(addobj.audio == null && addobj.des == null && addobj.image == null)
                {addobj.type = "b"; addobj.createFile(); addobj.badd(); addobj.close(); stage.setScene(msc);}

                if(addobj.image == null && addobj.audio != null && addobj.des != null)
                {addobj.type = "c"; addobj.createFile(); addobj.cadd(); addobj.close(); stage.setScene(msc);}

                if(addobj.audio == null && addobj.des != null && addobj.image != null)
                {addobj.type = "d"; addobj.createFile(); addobj.dadd(); addobj.close(); stage.setScene(msc);}

                if(addobj.des == null && addobj.audio != null && addobj.image != null)
                {addobj.type = "e"; addobj.createFile(); addobj.eadd(); addobj.close(); stage.setScene(msc);}

and as you can see the last if is commented and that because every word i have insert was carrying the type "s" that should appear with only the word that have all the features so i commented it to see the result of the others and once i clicked save i get no response so here is the hole code main class

package application;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


public class Main extends Application {

    Add addobj = new Add();

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {

        //Components

        //Layouts
        VBox settly, openly, addly, mly = new VBox();
        settly = new VBox();
        openly = new VBox();
        addly = new VBox();

        //Scenes
        Scene settsc,addsc, vsc, msc = new Scene(mly, 600, 400);
        settsc = new Scene(settly, 600, 400);
        addsc = new Scene(addly, 600, 400);
        vsc = new Scene(openly, 600, 400);

        //labels
        Label well = new Label();

        //Buttons
        Button settingsb, addb, openb = new Button("Open the vocabulary");
        settingsb = new Button("Settings");
        addb = new Button("Add new word");

        //Buttons Settings
        addb.setOnAction(e -> stage.setScene(addsc));
        settingsb.setOnAction(e -> stage.setScene(settsc));
        openb.setOnAction(e -> stage.setScene(vsc));



        //Label Settings
        well.setText("Vocabulary Builder");
        //Layouts Settings
        mly.getChildren().addAll(well, openb, addb, settingsb);
        mly.setPadding(new Insets(20, 20, 20, 20));

        //Adding word interface
        TextField tfa, tfi, tfw, tfm = new TextField();
        tfw = new TextField();
        tfa = new TextField();
        tfi = new TextField();
        tfw.setPromptText("Type The New Word Here");
        tfm.setPromptText("Type The Meaning Here");
        tfa.setPromptText("Paste the link of the audio file");
        tfi.setPromptText("Paste the link of the image");

        TextArea tad= new TextArea();
        tad.setPromptText("Type The Description Here");

        Button sbtn = new Button("Save");
        Button cbtn = new Button("Cancel");

            //Saving And Canceling presses
            sbtn.setOnAction(e -> {
                addobj.word = tfw.getText();
                addobj.mean = tfm.getText();
                addobj.des = tad.getText();
                addobj.audio = tfa.getText();
                addobj.image = tfi.getText();

                if (addobj.word == null) 
                    tfw.setText("Please add a word");

                if (addobj.mean == null) 
                    tfm.setText("Please add the meaning");

                if(addobj.audio == null && addobj.image == null && addobj.des != null)
                {addobj.type = "a"; addobj.createFile(); addobj.aadd(); addobj.close(); stage.setScene(msc);}

                if(addobj.audio == null && addobj.des == null && addobj.image == null)
                {addobj.type = "b"; addobj.createFile(); addobj.badd(); addobj.close(); stage.setScene(msc);}

                if(addobj.image == null && addobj.audio != null && addobj.des != null)
                {addobj.type = "c"; addobj.createFile(); addobj.cadd(); addobj.close(); stage.setScene(msc);}

                if(addobj.audio == null && addobj.des != null && addobj.image != null)
                {addobj.type = "d"; addobj.createFile(); addobj.dadd(); addobj.close(); stage.setScene(msc);}

                if(addobj.des == null && addobj.audio != null && addobj.image != null)
                {addobj.type = "e"; addobj.createFile(); addobj.eadd(); addobj.close(); stage.setScene(msc);}

                //if(!(addobj.audio == null && addobj.des == null && addobj.image == null))
                //{addobj.type = "s"; addobj.createFile(); addobj.sadd(); addobj.close(); stage.setScene(msc);}

            });

            cbtn.setOnAction(e -> stage.setScene(msc));


        addly.getChildren().addAll(tfw, tfm, tad, tfa, tfi, cbtn, sbtn);

        //Adding Components

        //finishing
        stage.setTitle("Vocabulary Builder");
        stage.setScene(msc);
        stage.show();
    }
}

the Add class

package application;

import java.util.*;
import java.io.*;
import java.lang.*;

public class Add {

    private Formatter x;

    //Strings
    String type,word,mean,des,audio,image;


    public void createFile(){
    try
    {
        x = new Formatter("Vocabulary.txt");
    }
    catch(Exception e)
    {
        System.out.println("let this apper in a box later");
    }
    }

    public void aadd()
    {
        x.format("%s %s %s ", type, word, mean, des);
    }

    public void badd()
    {
        x.format("%s %s", type, word, mean);
    }

    public void cadd()
    {
        x.format("%s %s %s %s", type, word, mean, des, audio);
    }

    public void sadd()
    {
        x.format("%s %s %s %s %s", type, word, mean, des, audio, image);
    }

    public void dadd()
    {
        x.format("%s %s %s %s", type, word, mean, des, image);
    }

    public void eadd()
    {
        x.format("%s %s %s %s", type, word, mean, audio, image);
    }

    public void close()
    {
        x.close();
    }


    /*
     * a include word, mean and description
     * b include word and mean 
     * c include word, mean, description and audio 
     * s include word, mean, description, audio and image
     * d include word, mean, description and image
     * e include word, mean, audio and image
     */

PS i'm using JavaFX for the interface

Ruby: Using "if else" inside a function gives unexpected keyword_end error

I am very much new to Ruby. Experts, please bare with me.

I have defined a function which looks like this:

def putValAndmyBool val mybool
    if mybool
        puts val + "true"
    else
        puts val + "false"
    end
end

It gives the following error:

SyntaxError: (irb):101: syntax error, unexpected tIDENTIFIER, expecting ';' or '(irb):107: syntax error, unexpected keyword_end, expecting end-of-input from K:/Ruby22-x64/bin/irb:11:in `'

But when I defined following function, it runs successfully. The reason I tried doing this is I thought something in line puts val + "true" is causing the issue.

def addbool val
    puts val + "true"
end

Any explanation is appreciated. Thanks in advance.

Struggles with input in Python 3.4.2 [duplicate]

This question already has an answer here:

I just made little Python program, but I'm getting the same problem all the time. If I type in the input t or S, then the program asks (and calculates) everything what it should do if the input was V. I can't find the place where it's going wrong! Here's my script:

print ('Wat wil je weten: V (snelheid), S (afstand) of t (tijd)? ')
vst_choise = input()

if vst_choise == 'V' or 'v' or 'Snelheid' or 'snelheid':
    print ('Geef de waarde van S (afstand): ')
    s1 = eval(input())
    print ('Geef de waarde van t (tijd) :')
    t1 = eval(input())
    v_ans = s1 / t1
    print ('V (snelheid) = ' + str(v_ans)) 

elif vst_choise == 'S' or 's' or 'Afstand' or 'afstand':
    print ('Geef de waarde van V (snelheid): ')
    v1 = eval(input())
    print ('Geef de waarde van t (tijd) :')
    t2 = eval(input())
    s_ans = v1 * t2
    print ('S (afstand) = ' + str(s_ans)) 

elif vst_choise == 'T' or 't' or 'Tijd' or 'tijd':
    print ('Geef de waarde van V (snelheid): ')
    v2 = eval(input())
    print ('Geef de waarde van S (afstand) :')
    s2 = eval(input())
    t_ans = s2 / v2 
    print ('t (tijd) = ' + str(t_ans))

I hope one of you can solve the problem. Thanks in advance!

i want my statement to re-execute if the condition if met false

So what i want to happen is that when the input is not "start" the if statement should run again asking for the user to input "start". any ideas would be helpfull. thanks :) example:

import java.util.Scanner;

import java.util.Random;
public class Words {
    public static void main(String[]args){


        Scanner scan = new Scanner(System.in);
        String words[] = {"Iterate","Petrichor"};

        System.out.println("type *start* to begin");
        String input = scan.nextLine();

        if (input.equals("start")){
            String random = (words[new Random().nextInt(words.length)]);
            System.out.println(random);
        }
    }

}

samedi 30 juillet 2016

If / Else statement in a loop, javascript

Hi For some reason the console is returning to me SyntaxError: Unexpected token else, but I don't really know the problem, can someone help me please ?

lineN = ["Times Square", "34th", "28th", "23rd", "Union Square", "8th"];
storeStops = [];

 function input ( start, stop ){

    if (lineN.indexOf(start)<lineN.indexOf(stop)){
        for (var fwd =lineN.indexOf(start) ; fwd < lineN.indexOf(stop) ;foward++);
        fwd.push(storeStops);
    }}
    else {for (var bwd =lineN.indexOf(start) ; bwd < lineN.indexOf(stop) ;bwd--);
        bwd.push(storeStops)
    };

Python Tkinter: If-statement not working

from tkinter import *

def callbackX(button, win, buttonNR):

    print("Pressed button", buttonNR)
    player1.append(buttonNR)
    win.destroy()
    gameScreen()

def gameScreen():

    win = Tk()
    #f = Frame(win)
    if '1' in player1 == 'True':
        b1 = Button(win, text="X", command=lambda: callbackX(b1, win, '1'))
        b1.grid(row=0, column=0)
    if '2' in player1 == 'True':
        b2 = Button(win, text="X", command=lambda: callbackX(b2, win, '2'))
        b2.grid(row=0, column=1)
    if '3' in player1 == 'True':
        b3 = Button(win, text="X", command=lambda: callbackX(b3, win, '3'))
        b3.grid(row=0, column=2)
    if '4' in player1 == 'True':
        b4 = Button(win, text="X", command=lambda: callbackX(b4, win, '4'))
        b4.grid(row=1, column=0)
    if '5' in player1 == 'True':
        b5 = Button(win, text="X", command=lambda: callbackX(b5, win, '5'))
        b5.grid(row=1, column=1)
    if '6' in player1 == 'True':
        b6 = Button(win, text="X", command=lambda: callbackX(b6, win, '6'))
        b6.grid(row=1, column=2)
    if '7' in player1 == 'True':
        b7 = Button(win, text="X", command=lambda: callbackX(b7, win, '7'))
        b7.grid(row=2, column=0)
    if '8' in player1 == 'True':
        b8 = Button(win, text="X", command=lambda: callbackX(b8, win, '8'))
        b8.grid(row=2, column=1)
    if '9' in player1 == 'True':
        b9 = Button(win, text="X", command=lambda: callbackX(b9, win, '9'))
        b9.grid(row=2, column=2)


player1 = []; player2 = []

gameScreen()

The program doesn't seem to recognize the if-statement criterion being met. Is this some sort of Tkinter quirk? How can this be fixed?

The code should open a tic-tac-toe game screen, for player1, which closes and reopens the window, without the button that was previously pressed.

Why does the if-block not run for the final case?

Consider the following code, which counts how many of each element an array has:

public static void getCounts(int[] list) {
    int current = list[0];
    int count = 0;
    for (int i = 0; i < list.length; i++, count++) {
        if (list[i] > current) {
            System.out.println(current + " occurs " + count + timeOrTimes(count));
            current = list[i];
            count = 0;
        }
    }
   System.out.println(current + " occurs " + count + timeOrTimes(count));
}

For this question, please assume list is sorted in ascending order. If list is [1, 1, 2, 3, 4, 4], for example, the output is:

1 occurs 2 times
2 occurs 1 time
3 occurs 1 time
4 occurs 2 times

Now, if I get rid of the println that comes after the for-loop, i.e.

public static void getCounts(int[] list) {
    int current = list[0];
    int count = 0;
    for (int i = 0; i < list.length; i++, count++) {
        if (list[i] > current) {
            System.out.println(current + " occurs " + count + timeOrTimes(count));
            current = list[i];
            count = 0;
        }
    }
   // System.out.println(current + " occurs " + count + timeOrTimes(count));
}

Then using the same example input, the output becomes:

1 occurs 2 times
2 occurs 1 time
3 occurs 1 time

In other words, the if block doesn't execute if list[i] is the maximum value of the array. Why is this the case? For the example above, the index of the first 4 is i = 4, and list[4] > 3, so the conditional statement is met, but it still won't execute.

How can I adjust the code so that the if block will run for all cases?

Thanks

Bash Multiple Conditions in If Statement and Functions

I'm trying to check if the number of arguments is one and if functions that I wrote in my script previously are true , but it does not work:

if [ $# -eq 1 && echo "$1" | lgt && echo "Invalid Length - $1" && echo "$1" | checking_another_function_etc ]; then
echo "some output" && exit 1

"lgt" is a function name.

I was trying to use (( [[ [ quotes, multiple if statements but it didn't work either. Maybe I should separate the number of arguments checking and functions with qoutes, but I'm not shure how to do it.I'm wondering if it is even possible to pass echo command to if condition.

The thing is I need one echo statement after checking of all functions, but after each function I need its own echo statement.

working with NaN in a dataframe with if condition

I have 2 columns in a dataframe and I am trying to enter into a condition based on if the second one is NaN and First one has some values, unsuccessfully using:

if np.isfinite(train_bk['Product_Category_1']) and np.isnan(train_bk['Product_Category_2'])

and

   if not (train_bk['Product_Category_2']).isnull() and (train_bk['Product_Category_3']).isnull()

vendredi 29 juillet 2016

Simple If else unable to get work

I have two textbox named txtA,txtB

var count;//which needs to be compared with BValue
var AValue = $("#txtA").val();
var BValue = $("#txtB").val();

 if ($("AValue  == "") {
            alert("Enter AValue and continue");
        } else if (BValue  == "") {
            alert("Enter To BValue and continue");
        } else if (AValue  > BValue ) {
            alert("AValue should be lesser than To BValue");
        } else if (AValue == "" || BValue == "") {
            alert("Please enter the AValue and BValue to continue");
        } else if (AValue == "0") {
            alert("Invalid AValue");
        } else if (BValue  > pagecount) {
            alert("Invalid To Page Number");
        } else {
             // do some operations here
        }

All the conditions are passing well but this BValue > count is triggering me though it satisfy the conditions

How can I input an if statement inside a while loop?

import java.util.Scanner;
public class ex11 
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
    int fact=1;
    System.out.println("Enter a natural number ");
    int num=type.nextInt();

    int i=1;
    while(i<=num)
    {
        fact*=i;
        i++;    
    }
    System.out.println("Factorial of number " + num + " is " + fact);
}

}

/* I'm trying to place a conditional statement inside of the while loop. The condition to test for would be that of, if num is a negative number, S.O.P.("You entered a negative #"); in other words, if(num<0) S.O.P.("You entered a negative #"); however it doesn't print it properly. */

Autohotkey condition issue

the code still driving me crazy tried like everything in my mind but still not working. i am out of tries and ideas

here is the exact code:

MaxPresses := 2
Presses := 0
Lock := 0
~Up::
if (Presses > 0)
{
Presses -= 1
TrayTip, %A_ThisLabel%, presses is %Presses%
}
[b][u]else[/u][/b]
{
Lock := 1
Hotkey, Up, DoNone
DoNone:
return
TrayTip, %A_ThisLabel%, lock is %Lock%
}


return
/*
~Down::
if (Presses != 2)
{
Presses += 1
}
return
*/


~NumpadEnter::
~Enter::

Presses += 1

;SetTimer, ResetPresses, -25000


If (Presses <= MaxPresses)

    GoSub, Presses%Presses%
;TrayTip, %A_ThisLabel%, presses is %Presses%
return
;ResetPresses:

;Presses := 0

;return



Presses1:
if (Lock = 1)
{
Lock := 0
Hotkey, Up, ~Up
TrayTip, %A_ThisLabel%, lock is %Lock%

}
return



Presses2:

some action

return

If (Presses <= MaxPresses)

also at this part, it doesnt gosub until i change Presses to Pressed although there is no Pressed var in the whole script and when i change it to pressed the rest of the conditions doesnt work. i am really confused and dont have any clue why this happening at all...

plus When I use this code with

else if

marked with bold and underline tags: the condition of lock var works which make the up button not working temporarily but it does stop working on 0 presses but -1 for some reason. Means the up button still works when it is zero i don't know why tbh but when I change else if with if only it stops st zero but the lock condition doesn't work. It just disable the key on 0 press exactly but never re-enable it when enter is pressed and adds more presses to var.

appreciate all the help if possible, thanks ^^

Max

PHP If with or, then do something, reference specific true clause

For example:

<?php
varONE = "I am not empty";
unset($varTWO);
unset($varTHREE);

if(empty($varONE || $varTWO || $varTHREE)) {
  echo "TRUE vars are empty"
 }

//the long way round:
if(empty($varONE)) { echo "varONE is empty" }
if(empty($varTWO)) { echo "varTWO is empty" }
if(empty($varTHREE)) { echo "varTHREE is empty" }

?>

So the result would tell me that specifically varTWO and varTHREE are empty. Ultimately, the goal is to check an entire forms worth of input, make sure that all 12 inputs have some value input.

how to add condition in Nth row of the MySQL database fetching in codeigniter

I am using codeigniter and I am stuck in giving if condition in a database loop:

<?php 
foreach ( $gallery as $raw ) {

    $g_id = $raw->gallery_id;
    $src_z =$raw->zoom_img;
    $src_m = $raw->main_img;
    $src_t =$raw->thumb_img;
    echo "<a href='#' data-zoom-image='".base_url().$src_z."'"; 
    echo "data-image='".base_url().$src_m."' class='active d_block wrapper r_corners tr_all translucent m_bottom_10'>";
    echo "<img src='".base_url().$src_t."' alt='' class='r_corners'></a>"; 

    if ( /*row is 4th then add*/ ) { 
        echo "</li><li>";
    }
}
?>

If the row is the 4th then it should add </li><li> at the end.

Excel IF formulas correction?

I am trying to apply different formulas based on the range a number is in. Can anyone help me correct this formula?

=If(AND(B4>0,B4 < 50000), 0, IF(AND(B4>49999.99,B4 < 100000),((B4-50000)*0.0275*2/3), IF(AND(B4>99999.99,B4<150000),(B4*.02+1850),IF(AND(B4>149999.99,B4<250000),(B4*.07/3+2850),IF(B4>249999.99),(B4*.08/3+5185)))))

In other words, if number is 0-50k, apply one formula, if 50k-100k, apply different formula, etc.

Any ideas how to make it work? Thank you!

How to set a range in an "if" statement?

I am trying to set up a function in a way that it will only proceed if two conditions are met: if the variable is greater than another and smaller than a third one. This is what I have:

########################################################################
def Read_Data(file_location, start_date, end_date):
########################################################################
    #imports file
    fname = (file_location)
    ncfile = netcdf_file(fname,'r');
    #reads file and prepares it for usage
    juld = np.array(ncfile.variables['JULD'][:])
    juld[juld<start_date]=float('nan')
    juld[juld>end_date]=float('nan')
    if start_date<juld<end_date:
        temp = np.array(ncfile.variables['TEMP'][:])
        temp[temp>45]=float('nan') #eliminates inaccurate data
        temp[temp<-10]=float('nan') #eliminates inaccurate data
        lon = np.array(ncfile.variables['LONGITUDE'][:])
        lat = np.array(ncfile.variables['LATITUDE'][:])
        ncfile.close()
        return temp, lon, lat, juld

I have two functions over this one that define start_time and end_time, as well as a loop that processes the files. As you can see by my "if" statement, I am trying to set a range of numbers, and if the file's data fits the range, the reading will proceed. When I set it as I did, however, I get this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I don't understand how to solve this, especially because I am using two variables (start_date, end_date: both are given a numeric value on the previous function). In short, how to I make my desired "if" statement possible.

Edit

In addition, I want the files that don't meet the criteria to be ignored, and I am not sure if they will be if I don't write an "else" statement.

Setting a breakpoint on else-if statement doesn't work

Example code:

public class test {
    public static void main(String[] args) {
        if (false) {
            System.out.print("if");
        } else if (true) {

            System.out.print("else-if");
        }
    }
}

and set breakpoint like the picture: enter image description here

Then debug it, however, Intellij IDEA doesn't stop at the breakpoint. Why?

VBA - IF loop improvements.

I'm currently running a macro which identifies duplicates in a workbook, however it identifies the first set off the index and doesn't tag the first set then which has led to me setting up a if statement to by pass this, which adds duplicate to the first instance too. This is taking a long time to do however and would like to improve this, if possible. Any suggestions would be greatly appreciated, I am new to VBA but have been learning bits as I've encountered new problems!

'Declaring the lastRow variable as Long to store the last row value in the Column1
Dim lastRow As Long
'matchFoundIndex is to store the match index values of the given value
Dim matchFoundIndex As Long
'iCntr is to loop through all the records in the column 1 using For loop
    Dim iCntr As Long
    Dim first_dup As Long
    Dim tagging As Long
    Dim item_code As String

'Finding the last row in the Column 1
    lastRow = Range("B1000000").End(xlUp).Row
'
'looping through the column1
    For iCntr = 2 To lastRow

'checking if the cell is having any item, skipping if it is blank.
    If Cells(iCntr, 1) <> "" Then
'getting match index number for the value of the cell

    matchFoundIndex = WorksheetFunction.Match(Cells(iCntr, 1), Range("A1:A" & lastRow), 0)

'if the match index is not equals to current row number, then it is a duplicate value
    If iCntr <> matchFoundIndex Then

'Printing the label in the column B
    Cells(iCntr, 4) = "Duplicate"

End If
End If
Next


            For first_dup = 2 To lastRow
            If Cells(first_dup, 5) = "Duplicate" Then
            item_code = Cells(first_dup, 1)



                 For tagging = 2 To lastRow
                If Cells(tagging, 1) = item_code Then
                Cells(tagging, 5) = "Duplicate"
                End If

      Next




            End If


                Next

Example data:
item code   
1   
2   
3   
4   
1   duplicate
2   duplicate
3   duplicate
4   duplicate
1   duplicate
2   duplicate
3   duplicate
4   duplicate

If Statement to change field.control source

I have a small If statement that that changes the controlsource of a field if another field is empty. The " just before = is incorrect, and I'm not sure what to use to ensure the entire string starting with the = is included.

Private Sub Report_Load()
If IsNull(FirstName2) Then
OwnersNames.ControlSource = "=FirstName1] & " " & [LastName1]"
Else
OwnersNames.ControlSource = "=[FirstName1] & " " & [LastName1] & " and " & [FirstName2] & " " & [LastName2]"
End If
End Sub

If/Else block with variable number of conditions

if(m.options.hicColors != null ) {
                                if(d.hic <= m.options.cutoffs[0]) {
                                        d.fillColor = m.options.hicColors[0];
                                        return m.options.hicColors[0];
                                } else if (d.hic > m.options.cutoffs[0] && d.hic <= m.options.cutoffs[1]) {
                                        d.fillColor = m.options.hicColors[1];
                                        return m.options.hicColors[1];
                                } else if(d.hic > m.options.cutoffs[1] && d.hic <= m.options.cutoffs[2]){
                                        d.fillColor = m.options.hicColors[2];
                                        return m.options.hicColors[2];
                                } else if(d.hic > m.options.cutoffs[2] && d.hic <= m.options.cutoffs[3]) {
                                        d.fillColor = m.options.hicColors[3];
                                                return m.options.hicColors[3];
                                } else  {
                                        d.fillColor = m.options.hicColors[4];
                                        return m.options.hicColors[4];
                                }
                              }

The program I am working on involves taking a set of shapes and coloring them based on two arrays, one containing the colors to be used, the other containing the cutoff values to decide which color is used. Previously, these were always 5 colors and 4 cutoffs, but now I need to accept arrays of any length. I'm not sure how I can accomplish this. Does anyone have any suggestions how I could complete this task?

Note that the length of the color array is always one more than the cutoff array.

If cell Value Changed Then run different If statements

I'm currently trying to make a spreadsheet that can be used to input and store large volumes of data. One way of speeding up the process of inputting the data is to copy data from the previous row. So far what I have is:

 Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$J$3" Then

Call LD_Copy_Paste_Delete

End If

End Sub

Sub FillBlanks()

If Range("B13").Value = Empty Then
    Range("B14").Selects
    Selection.Copy
    Range("B13").Select
    ActiveSheet.Paste
    Range("B13").Select
    Application.CutCopyMode = False

If Range("C13").Value = Empty Then
    Range("C14").Select
    Selection.Copy
    Range("C13").Select
    ActiveSheet.Paste
    Range("C13").Select
    Application.CutCopyMode = False

If Range("D13").Value = Empty Then
    Range("D14").Select
    Selection.Copy
    Range("D13").Select
    ActiveSheet.Paste
    Range("D13").Select
    Application.CutCopyMode = False


If Range("E13").Value = Empty Then
    Range("E14").Select
    Selection.Copy
    Range("E13").Select
    ActiveSheet.Paste
    Range("E13").Select
    Application.CutCopyMode = False


If Range("F13").Value = Empty Then
    Range("F14").Select
    Selection.Copy
    Range("F13").Select
    ActiveSheet.Paste
    Range("F13").Select
    Application.CutCopyMode = False

    End If
    End If
    End If
    End If
    End If

End Sub

What I would like is for the FillBlanks() to run just after the first sub, without having to do anything more. All help would be appreciated.

Many thanks

Results based on multiple variables (flowchart style)

I'm trying to find a way to convert a bunch of else if's to a simple function to find out a result for two possibilities. It compares answers from two questions to produce an answer.

The defined variable 'usage' is

var usage = {
  '1': { value: false, num: 1, string: 'gaming' },
  '2': { value: false, num: 2, string: 'browsing the web' },
  '3': { value: false, num: 3, string: 'streaming video' },
  '4': { value: false, num: 4, string: 'streaming music' }
};

The code for determining the outcome goes as follows.

'firstSelected' detects whether the first option of the second question is selected.

// Check if more than one option is selected on first question
if (selectedOptions.length > 1) {
  maxPackage();
}

// Check if gaming is selected on first question
else if (usage['gaming'].value == true) {
  maxPackage();
}

// Check if web is selected on the first question and firstSelected is true
else if ((usage['web'].value == true) && (firstSelected == true)) {
  standardPackage();
}

// Check if web is selected on the first question but firstSelected is false
else if ((usage['web'].value == true) && (firstSelected == false)) {
  maxPackage();
}

// Check if video is selected on the first question
else if (usage['video'].value == true) {
  maxPackage();
}

// Check if music is selected on the first question and firstSelected is true
else if ((usage['music'].value == true) && (firstSelected == true)) {
  standardPackage();
}

// If none of these apply show Max Package
else {
  maxPackage();
}

Thanks!

Nested if's and cases in hibernate

First of all I am totally new to Hibernate. I managed to write following query:

"select new ShallowPayment(" +
                    "p.id, " +
                    "l2.id, " +
                    "l1.id, " +
                    "l0.id, " +
                    "p.repository.code, " +
                    "l0.workflow.config.code, " +
                    "p.errorReasonCode," +
                    "p.errorReasonDescription," +
                    "p.lastUpdateTimestamp%s) " +
                    "from com.trax.payment.hibernate.Payment p " +
                    "join p.repository as repo " +
                    "join p.envelope as l2 " +
                    "join l2.parentEnvelope as l1 " +
                    "join l1.parentEnvelope as l0 " +
                    "where p.datamart = :%s and p.workflow.routing.sourceFormat.code in (:%s) and " +
                    "(repo.code in (:%s) or l0.repository.code in (:%s)) " +
                    "order by p.creationDate desc, p.id desc"; 

I want to make a a select statement, where I have 4 objects, where I choose 1 ID from to insert:

  • p
  • l2
  • l1
  • l0

I want to make a value insert that when

p.workflow.routing.internalClassificationType.id > 1 I choose, the id of p, otherwise I go to:

l2.workflow.routing.internalClassificationType.id > 1

In that case, I choose l2, otherwise I go to l1, like

l1.workflow.routing.internalClassificationType.id > 1

And if even l2 isn't bigger than 1, I take the l0.workflow.routing.internalClassificationType.id

But how can I implement these statements in an IF/ELSE or Case in Hibernate?

Bash "if" condition being executed no matter what

I'm new to bash scripting, and, while I know this is undoubtably a duplicate question, I can't figure out how to word it to search for it.

for i in $( ls); do
    FILETYPE=$( file -b $i )
    if [ "$FILETYPE"="Apple binary property list" ]; then
        echo $FILETYPE
    else 
        echo "nope"
    fi
done

I'm expecting this to ONLY print
"Apple binary property list"
when the statement succeeds and to ONLY print "nope" otherwise.

What's happening is that it's printing the filetype regardless of whether the statement succeeds or fails, and never prints "nope".

I know it's something simple, but can someone please tell me why it's printing anything other than "Apple binary property list" and "nope",
and what i can do to fix it?

jeudi 28 juillet 2016

Defiing function using if-statement

def roots4(a,b,c,d):
d = b * b - 4 * a * c
if a != 0 and d == 0:
        roots4(a,b,c,d) 
        x = -b/ (2*a)
if a != 0 and d > 0:
        roots4(a,b,c,d)
        x1 = (-b + math.sqrt(d)) / 2.0 / a
        x2 = (-b - math.sqrt(d)) / 2.0 / a
if a != 0 and d < 0:
        roots4(a,b,c,d)
        xre = (-b) / (2*a)   
        xim = (math.sqrt(d))/ (2*a)
        print x1  = xre + ixim
        strx1 = "x2 = %6.2f + i %6.2f" %(xre, xim)
        print strx1 

This is part of my code for a project. What im trying to do is define "roots4(a,b,c,d)". For example, in the case that "a != 0 and d == 0" then roots4(a,b,c,d) shall then go to to finding x by solving equation "x = -b/ (2*a)". And so on... i dont know what im doing wrong. Any tips?

Java: When should use if-else and when should use try...catch to handle conditional check?

I am confused. Does it depend on the concrete situation? Or it has a universal standard? Could anyone give a summary to tell me when to use if-else, and when to use try...catch?

Delete some UL if empty

right now my output is something like this enter image description here

I want to delete the list that are empty

just tried this code empty or isset inside the listitems

<?php if(isset($page<1): //but i got an error instead    ?>

even something like

<?php if(empty($page): //but i got different output    ?>

heres my running code without if statement

<?php 
$letter='A';
for($i= 1; $i <=26 ;$i++,$letter++):?>
<?php 

    $pages = $db->prepare("
    SELECT * FROM pages WHERE LEFT(`title`, 1) = '".$letter."'

    ");
    //$check =$db->query("SELECT * FROM watch WHERE animelist_id=".$page['id']." and acc_id=".$_SESSION["user_id"]."");
    $pages->bindParam(1,$letter, PDO::PARAM_STR);
    $pages->execute();
?>

<div class = "listitems">

    <?php echo '<h5>'.$letter.'</h5>';?>
            <?php foreach($pages as $page): ?>

                        <ul>
                            <li>
                            <a href="<?php echo BASE_URL;?>/page.php?page=<?php echo e($page['slug']);?>"><?php echo e($page['label']);?></a>

                            </li>
                        </ul>



            <?php endforeach; ?>

</div>
<?php endfor; ?>

R studio (error: the condition has length > 1 and only the first element will be used)

I have this data set which looks something like this.

This is the error I got

This is my code

#set a variable to capture the path to this folder
path <- "C:/Users/PGO User/Desktop/Text Mining by GRC"

#set working directory
setwd(path)

read <- read.csv("sample.csv")

text2 <- read$text2
if(text2 == "No concern" | text2 == "No concern." | text2 == "No concerned" | text2 == "No concerns." | text2 == "No concerns") {
  read$emotion <- "unknown"
  read$polarity <- "neutral"
}else 
{
  read$emotion = emotion
  read$polarity = polarity
}

write.csv(text2, file = "test1.csv", row.names = TRUE)

I actually thought of using if or if else statements to change the emotions and polarity in the csv file (see picture attached). The reason why I want to change the emotion and polarity is because some are not correct. So for example if under text2, it is "no concern", "no concerns", or "no concerned" it's emotion should be unknown and polarity should be neutral.

Can someone please help??

Language change in the app locally

I am developing an app witch support 3 language Telugu,Hindi,English... Now my requirement is if when I click the Telugu button my whole app need to change to Telugu vise versa to remaining language, I have language IDs for each language te=1,hi=2,en=3 Before calling API I need to append the language id to all the APIs in my all classes for respective results according to language ids, I saved the 3 language ids in NSuser default s, failing to append the language IDs to API Parameters

Failing to write if statement for this

Please help me on this, stuck on this since 10 days

Excel Formula If Statement - in between percentages

Here is what I am trying to do:

I have one column (lets say Column A) of percentages (ranging from 100% to 0%). I have a second column (lets say Column B) with a number 1-10. I want to create a third column which adds together whatever number is in Column B, and the following: If the percentage is 99-90, add 1. If 89-80, add 2. 79-70, add 3. 69-60, add 4. 59-50, add 5. 49-40, add 6. 39-30, add 7. 29-20, add 8. 19-10, add 9. under 10, add 10.

However, I can't seem to write it properly. Any help would be greatly appreciated.

Conditional statement for attribute in an array

I have an array that gets imported daily. For the specific field 'special_price' i only want it to import into Main Website > Main Website Store > Default Store View

Default store view = 1

  protected function _getFieldNames()
        {
            return array(
                'company_number',
                'sku',
                'style_number',
                'name',
                'div_code',
                'div_desc',
                'color_code',
                'color',
                'size_type',
                'size',
                'price',
                'weight',
                'description',
                'special_price',
                'tax_code',
            );
        }

I can instantiate the class like so:

$storeId = Mage::app()->getStore()->getStoreId();

My question is how to parse that one specific field for only the default store and let the other updates run as usual. I assume i'm using an IF statement.

Doing math with Timestamps?

To the best of my limited knowledge and abilities with PHP the following code should work:

<?php
////DISPLAY DATE OF NEXT COUNCIL MEETING////

$now = date('U'); //get current time
$firstTues = strtotime("-1 month first Tuesday 4pm"); //get first Tuesday of the month
$secondTues = strtotime("-1 month second Tuesday 5pm"); //get second Tuesday of the month
$fourthTues = strtotime("-1 month fourth Tuesday 5pm"); //get forth Tuesday of the month
$nextTues = strtotime("first Tuesday 4pm"); //get first Tuesday of next month

function nextCouncilMeeting() {

//If todays date less than 1st Tuesday at 11pm, display date for 1st Tuesday 4pm.
if ($now < $firstTues) {
    echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A', $firstTues);
}

//If todays date greater than 1st Tuesday 5pm and less than 2nd Tuesday 11pm, display date for 2nd Tuesday 5pm
elseif ($now > $firstTues and $now < $secondTues) {
    echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A', $secondTues);
}

//If todays date greater than 2nd Tuesday 5pm and less that 4th Tuesday 11pm, display date for 4th Tuesday 5pm
elseif ($now > $secondTues and $now < $fourthTues) {
    echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A', $fourthTues);
} 

//If todays date greater than 4th Tuesday
elseif ($now > $fourthTues){
    echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A', $nextTues);
}
else{
    echo "foobar";
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="test">
Current Time: <?php echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A',$now); echo " " . $now;?></br>
First Tuesday: <?php echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A',$firstTues);echo " " . $firstTues;?></br>
Second Tuesday: <?php echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A',$secondTues);echo " " . $secondTues;?></br>
Fourth Tuesday: <?php echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A',$fourthTues);echo " " . $fourthTues;?></br>
Next Month First Tuesday: <?php echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A',$nextTues);echo " " . $nextTues;?>
</p>
<h2>Next Council Meeting:</h2>
<h1><?php nextCouncilMeeting()?></h1>
</body>
</html>

My best guess is that there's something going wrong with my math in the if/elsif conditions. Is there a trick to doing math with timestamps? What am I missing here?

Syntax error on token(s), misplaced construct(s) on else if

This is my code. I'm super new to Java. Basically trying to make a super-easy calculator. I get the in the title named error on the else if(add){...etc. Would appreciate any help! Thanks!

import java.io.Console;
import java.util.Scanner;
public class letsgo {

    @SuppressWarnings("resource")
    public static void main(String args[]) {

        Scanner input = new Scanner(System.in);

        System.out.println("Hello, and welcome to my first calculator.");
        System.out.println("Please type your first number here:");
        int num1 = input.nextInt();
        System.out.println("Please type your second number here");
        int num2 = input.nextInt();
        boolean add;
        boolean subtract;


        int answerAdd = num1 + num2;
        int answerSubtract = num1 - num2;
        boolean tryAgain;
        do{
        add = input.hasNext("add");
        subtract = input.hasNext("subtract");
            System.out.println("Do you want to subtract or add?"  );
            if(subtract){
                System.out.println(answerSubtract);}
            else if(add){
                System.out.println(answerAdd);}
            else("AssignmentOperator Expression" (tryAgain)){
                System.out.println("Please say add or subtract instead: ");}
        }
        while(tryAgain);

If statement scenario

All,

I have a scenario where I want to exit sub if ("Summary").Range("C17").Text = "Yes" and either CBL or RBL does not equal zero. I thought the below code would work however if CBL = 0 and RBL = 100 the code will not exit sub.

 Dim CBL As Long
 CBL = Worksheets("Summary").Cells(97, Yearcol).Value
 Dim RBL As Long
 RBL = Worksheets("Summary").Cells(101, Yearcol).Value

'Check if prestage two projects
    If Worksheets("Summary").Range("C17").Text = "Yes" And RBL Or CBL <> 0  Then

If statement structure in R - when to use & and && [duplicate]

This question already has an answer here:

I am writing a complex if statement in R involving comparing the numeric value of three different number vectors to a given number.

However I don't fully understand the difference between & and &&.

What is the difference between these four:

a[i] > 30 && b[i] > 30 && c[i] > 30
a[i] > 30 & b[i] > 30 & c[i] > 30
a[i] > 30 & b[i] > 30 && c[i] > 30
a[i] > 30 && b[i] > 30 & c[i] > 30

Also I don't fully understand the same situation with | and ||. For instance, what is the difference between:

a[i] > 30 & b[i] > 30 || c[i] > 30

and the following?

a[i] > 30 & b[i] > 30 | c[i] > 30

Any help would be greatly appreciated! My question is about an if statement with three conditions so previous posts haven't fully addressed this.

Confuse with If Condition in php [duplicate]

This question already has an answer here:

Php Code:

$resData = array('result'=>true);

if($resData["result"] == "success")
    echo "Success";
else
    echo "Failure";

Above code work perfect, but confuse with condition $resData["result"] contain true so, actual condition we use for compare is like if($resData["result"] == true) or if($resData["result"]) but, here condition is if($resData["result"] == "success") and that run fine and give perfect result.

So, my question is how condition work fine with true == "success" ?

HTML elements using internetexplorer object in vba

Hi I'm trying to access the value at 'data-mod-results-inceptiondate=' within this button object

<button class="o-buttons mod-tearsheet-historical-prices__moreButton mod-ui-
hide-small-below" type="button" data-mod-symbol="GB00B52YRG95:GBX" data-mod-
results-inceptiondate="41043" data-mod-results-startdate="42549">Show more</button>

I can find the button using:

    set btns = IE.Document.getElementsByTagName("button") 
    For each btn in btns
    if btn.innerText = "Show more" then btn.Click
    next btn

How can I find the inner element called 'data-mod-results-inceptiondate' in order to access its value (in this example "41043"). Any help on this would be much appreciated.

Matlab help to match statements and then calculations

Table

This is homework for a data analysis class, I have taken a small part of the table. As you can see in the image above, I have a table with several headings. The table is full of data from a trading desk, headers include Amount traded,counter party(who we traded with), amount intially ordered , and the various providers who were showing the amount the offered (size). I need a function of some sort that can: 1. link the counter party to the Provider row by row. 2. do a calculation based on which provider the we traded with(counterpart) went through. the calculation is called fill ratio which is = (Amounttraded)/min(amountordered,size(depending on the provider) for example the 1st row fill ratio would be (1000000.0)/min(amount ordered=100000.0),(size based on provider=CS=100000.0) meaning fill ratio in this case is 1 if CS only showed 500000.0 then the fill ratio would be 0.5.

Thank you, please don't hesitate to comment for more info if needed

Python - Parameter checking with Exception Raising

I am attempting to write exception raising code blocks into my Python code in order to ensure that the parameters passed to the function meet appropriate conditions (i.e. making parameters mandatory, type-checking parameters, establishing boundary values for parameters, etc...). I understand satisfactorily how to manually raise exceptions as well as handling them.

from numbers import Number

def foo(self, param1 = None, param2 = 0.0, param3 = 1.0):
   if (param1 == None):
      raise ValueError('This parameter is mandatory')
   elif (not isinstance(param2, Number)):
      raise ValueError('This parameter must be a valid Numerical value')
   elif (param3 <= 0.0):
      raise ValueError('This parameter must be a Positive Number')
   ...

This is an acceptable (tried and true) way of parameter checking in Python, but I have to wonder: Since Python does not have a way of writing Switch-cases besides if-then-else statements, is there a more efficient or proper way to perform this task? Or is implementing long stretches of if-then-else statements my only option?

Code not executing after if statement inside of a for loop

So. I have a web scraper that will download pdf sources based on the name of the "a" tag given. If there is a match in the link title. I want to download the pdf source and save it to the directory specified... However, not ALL of the links get downloaded... It will print the "File Type", then skip my entire for loop and move on to the next link... HELP!

numb = 0
# Go through each link found in the "Virtual Web Folder"
for item in linkList:

    print(item)
    # Open up the link, locate and extract the block and lot numbers, as
    # well as the type of report found in the webpage
    html = urlopen(item)
    time.sleep(2)
    soup = BeautifulSoup(html.read(), "html5lib")
    mainInfo = soup.find_all("td",{"class":"maininfo"})
    try:
        reportType = mainInfo[0].text
    except:
        pass
    reportType = reportType.strip()
    try:
        location = mainInfo[4].text.split()
    except:
        pass
    binBlock = location[3]+"-"+location[5]


    aName = reportType.upper()


    print("Determining Report Type...")
    time.sleep(1)
    # "Soil Report titles can be upper or lower case.. So to make sure they all
    # match. Force the upper case and look for a match
    if reportType.upper() == "SOIL REPORT" or reportType == "TECHNICAL REPORT: SOIL INSPECTION":

        if aName == "SOIL REPORT":
            name = "SR"
            print("File Type: " + name)
            pass

        else:
            name = "TR"
            print("File Type: " + name)
            pass

        pass

        # If a match is found. Find the source in the html code that contains
        # the pdf
        for link in soup.select("iframe[src]"):

            print("Downloading...")
            time.sleep(1)
            #Extrace the source and make the link useable
            extractLink = startUrl+link["src"]
            #Check if path is valid.. If not, create a new folder
            firstPath = "/Volumes/Westergaard/BRONX/"+binBlock+"/"
            if not os.path.exists(firstPath):
                os.makedirs(firstPath)

            path = firstPath + name + str(numb) + ".pdf"
            #Download the file and save to correct path
            pdfFile = urllib.request.urlretrieve(extractLink, path)
            time.sleep(2)
            print("Finished"+"\n")
            numb = numb + 1
            continue
        else:

        binBlock = str(accum)
        name = "NA"

        for link in soup.select("iframe[src]"):

            print("Downloading Uknown...")
            time.sleep(1)
            extractLink = startUrl+link["src"]
            #Now... download this link
            firstPath = "/Volumes/Westergaard/BRONX/"
            path = firstPath + binBlock + name + "(1).pdf"
            pdfFile = urllib.request.urlretrieve(extractLink, path)
            time.sleep(2)
            print("Finished"+"\n")
            continue

Is there a difference between == true and != false in swift?

I had this code in my Swift App

func parseJSON() {

    let urlString = "http://ift.tt/2aAt1hi"

    if NSURL(string: urlString) == true {
        let url = NSURL(string: urlString)
        let data = try? NSData(contentsOfURL: url!, options: []) as NSData
        let json = NSData(data: data!)

// more code

However, even though the link actually worked and was true, the if statement was never met and it kept skipping it and moving to else. So I changed the code to

if NSURL(string: urlString) != false 

and it worked perfectly. I'm not sure why though?

How to avoid the "blink" when exchanging gifs?

I am creating a website where when you scroll into an area, a gif appears. It only loops once; if you continue scrolling, it changes to another gif (which plays only once, too) If you scroll back, it changes to the first gif, restarting it so it can play again.

However, when the changing occurs, there is a blink that I do not want. Here is the fiddle. And here is the javascript:

$(window).ready(function() {
  var v = 0;

  $(window).on("scroll", function() {
    var scrollTop = $(this).scrollTop();

    if (scrollTop > 100 && scrollTop < 200) {

      if ($('#container').attr('data-img') != 'http://ift.tt/2adrjBf') {
        ++v;
        $('#container').attr('data-img', 'http://ift.tt/2adrjBf');
        $('#container').css('background-image', 'url(http://ift.tt/2apX2Cs' + v + ')');
      }

    } else if (scrollTop >= 200) {

      if ($('#container').attr('data-img') != 'http://ift.tt/2adr6yb') {
        ++v;
        $('#container').attr('data-img', 'http://ift.tt/2adr6yb');
        $('#container').css('background-image', 'url(http://ift.tt/2apXn8o' + v + ')');
      }

    } else {
      $('.imageHolder').css('background', 'blue');
    }

  });

});

I tried removing the ?v='+v+' from the background-image but then it won't load everytime it changes... Is there a way to keep the functioning as it is without the blinking?

Enterprise Architect document template conditions like `if` and `else´

I'm working on my first Enterprise Architect custom document template to export our use cases considering the company design guidelines. Unfortunately, I am not able to print data based on certain conditions. E. g. hide fields with specific values or change their layout.

In my example or screenshot below I would like to hide {ElemScenario.Type} if the value is Basic Path, in example something like (I highlighted the position red):

if ({ElemScenario.Type} != "Basic Path") {
    {ElemScenario.Type}
}

enter image description here

How can I change the document template in Enterprise Architect with certain conditions? Is it even possible?

Programe Not Executing in Correct Order in Android Studio

I want to check whether the email id entered by user is unique or not so for that initially I have my variable Boolean valid = false;. On clicking a button i am taking the email id entered and checking it for valid email id expression using regular expression and then i am using an asyntask to check its uniqueness. Code in my onclicklistner is

if (emailid.matches(regexp) && emailid.length() > 0) { new Validate().execute(); Toast.makeText(getApplicationContext(), valid.toString(), Toast.LENGTH_LONG).show(); if (valid) { Intent i = new Intent(getApplicationContext(), GamesFragment.class); startActivity(i); } else { Toast.makeText(getApplicationContext(), "Email Address Already Exist", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(getApplicationContext(), "Check Your Email Address", Toast.LENGTH_LONG).show(); }

Here what problem i am facing is, for first time when i am entering an email which is unique and clicks the button, the Validate() asynctask checks and sets the valid variable to true, but it doesn't goes to next activity GamesFragment because i have declared valid = false initially. Now when i again click the button, then it goes to next activity as the valid variable is set to true because of previous click.

Please help i am not getting why this is happening.

Different time formats in same variable

I am writing a script that is filtering for computer accounts in AD. I want to disable/delete all accounts that are at least inactive for more than 90 days . If they are inactive for at least 90 days they should be disabled and if inactive for more than 180 days they should be deleted

So, I get the dates for disabling and deleting

$disbale= (Get-Date).AddDays(-90)
$delete = (Get-Date).AddDays(-180)

Now I loop through a given OU and get all accounts that are at least 90 days inactive, therefore I also get those that are inactive for more than 180 days, too.

$acc = Get-ADcomputer -Filter {LastLogonTimeSTamp -lt $disable)} -Properties LastLogonTimeStamp,Description -SearchBase "OU=Computer,DC=dom,DC=de" -Server dom

Then I would put them into a foreach to disbale or delete them

foreach ($pc in $acc) {if($pc.LastLogonTimeSTamp -lt $delete){write-host 'delete'} else {write-host 'disable'}}

But here I ran into the error that $pc.LastLogonTimeSTamp is of type [int64] and is a number of 18 digits and $delete is in format time. But why did the same comparison above LastLogonTimeSTamp -lt $disable work and now it doenst? How can I work arround this easy?

(empty?) return of readline is not caught by control structure

I have a multidimensional hash containing opened file handles on SEEK_END with the intention to always read the latest line without getting to much I/O (what I would get with tail).

I'm now going through all of these handles with a for loop and calling readline on them.

It looks like this:

for $outer ( keys %config ) {

    my $line = readline($config{$outer}{"filehandle"});

    if (not defined $line || $line eq '' ){
        next;
    }
    else{
        print "\nLine: -->".$line."<--\n";
        $line =~ m/(:)(\d?\.?\d\d?\d?\d?\d?)/;
        $wert = $2;
    }
}

If new content is written into these files, my script reads it and behaves just as planned.

The problem is that readline will usually return nothing because there is currently nothing at the end of the file, but my if doesn't seem to identify the empty return of readline as undef as empty -- it just prints nothing, which is would be right because there is nothing in this string, but I don't want it to be processed at all.

PHP Get value then put it to a variable

I have a code to do this:

<?php
$xml=simplexml_load_file("d2ladder.xml") or die("Error: Cannot create object");
$xp1 = 4439;
$xp2 = 8439;
?>

<?php for ($i = 0; $i < 100; $i++) {
<?php $xp = $xml->ladder[12]->char[$i]->experience;
      $xppercent = $xp/$xp2*100; ?>

      <div style="width: <?php echo $xppercent; ?>px">teste</div>
<?php echo $xml->ladder[12]->char[$i]->level; ?>
<?php } ?>

That "$xp2" on the formula need to be set by the $xml->ladder[12]->char[$i]->level

if level = 1 then calculate with $xp1 if level = 2 calculate with $xp2 and goes, I've got 99 fixed xps that varies level 1-99 to calculate in that way

There's a simple way to solve this? thanks

mercredi 27 juillet 2016

Need to this table with 100 rows and asign a valor to the code PHP

I need to solve this simple thing: Got this code:

<?php
$xml=simplexml_load_file("d2ladder.xml") or die("Error: Cannot create object");
?>    
<table width="100%" border="1" cellspacing="0" cellpadding="2" align="center" style="text-align:center">
  <tbody>
    <tr class="<?php if ($xml->ladder[12]->char[0]->status == "alive") { echo "alive"; } else { echo "dead"; } ?>">
      <td width="10%">1.</td>
      <td width="50%" style="text-align:left"><?php echo $xml->ladder[12]->char[0]->prefix; ?> <?php echo $xml->ladder[12]->char[0]->name; ?></td>
      <td width="10%"><?php echo $xml->ladder[12]->char[0]->class; ?></td>
      <td width="10%"><?php echo $xml->ladder[12]->char[0]->level; ?></td>
      <td width="20%"><?php echo $xml->ladder[12]->char[0]->experience; ?></td>
    </tr>
        <tr class="<?php if ($xml->ladder[12]->char[1]->status == "alive") { echo "alive"; } else { echo "dead"; } ?>">
      <td width="10%">2.</td>
      <td width="50%" style="text-align:left"><?php echo $xml->ladder[12]->char[1]->prefix; ?> <?php echo $xml->ladder[12]->char[1]->name; ?></td>
      <td width="10%"><?php echo $xml->ladder[12]->char[1]->class; ?></td>
      <td width="10%"><?php echo $xml->ladder[12]->char[1]->level; ?></td>
      <td width="20%"><?php echo $xml->ladder[12]->char[1]->experience; ?></td>
    </tr>

  </tbody>
</table>

Need to create rows on this table till char[99] Maybe I need to use while? Because sometimes it wont get to 99 on the sitemap

Is it possible to shorten my if/else statement?

The Questions of if/else statements and other alike codes

Hi, currently I am using this code to call an if/else statement, to add and/or remove the class ".hide" whenever the different tables are clicked on. This code is working all fine, no trouble with it at all.

Example 1

$(document).ready(function() {
    $('#Year_Table').click(function() {
        if ($('#Month_Table').hasClass("hide")) {
            $('#Month_Table').removeClass('hide');
        } else {
            $('#Month_Table').addClass('hide');
            $('#Day_Table').addClass('hide');
        }
    });
});

But what I am wondering about, is if there is anyway to make the code shorter? but with the same outcome. That the class is add or removed.

I had another question a few days ago, where a guy shortened my if/else statement to this code below. Thank you

Example 2

$( document ).ready(function(){
    var games_month  = 0;
    var month_games  = "Games";

    $("#Games_Month").html(games_month);

    $('#January').click(function(){ 
        $('#Games_Month').html(function(_, html) {
        return html === month_games ? games_month : month_games;
     });
});

The shortened code works perfectly too, but gives me a couple of question marks. Now, what I would like to know is:

1: What is this type of code that was shortened for me? I mean, what is it called?

I have been told it might be a callback function.

2: What is different from a standard if/else statement and the shortened code?

is it the same, just cleaned up? or is there any important difference?

3: What does the different parts of the shortened code mean? what do they do?

To me it just seem like another kind of an if/else statement?

4: is there any way to make such a code with classes instead of variables?

Simply instead of changing the variable, I would like to add or remove the class ".hide" and is it possible to add and remove several classes within this function?

5: Is there any other ways to code an if/else statement or code which gives the same result?

I am very new at using both javascript and jQuery, but I'm trying to learn as much as possible. I appreciate all the help I can get to understand all this, everything will help me getting further into my knowlegde of coding.

Thank you very much.

IF statement with Right, Len, and Concatenate

I am using Google sheets and not sure why I can not get this to work but I think I have a bracket off or syntax not quite right.

I am trying to parse out a URL and get the last 3 letters to compare to in my IF statement. If the 3 letters match png then do something if not do another.

=IF(RIGHT(E2,LEN(E2)4)=".png",CONCATENATE(F2,G4), CONCATENATE(F2, G3))

The URL comes in through a formula into the cell E2 using this:

=ImportXML(B3, "//meta[@property='og:image']/@content")

I am not sure if that has something to do with it or not but I have found I need to test for .jpg and .png because not everyone uploads .jpg all the time causing things to break on my feed.

Here is my google spreadsheet

Python Ignore if/else Command? [duplicate]

This question already has an answer here:

The python if/else command is completely not working.

import time
import os
import sys

def zelphaMain():
    def zelphaMain_Credits():
        print("Coding:")
        print("John Antonio Anselmo")
        print("")
        print("")
        print(">>Back")
        def zelphaMain_CreditsInput_Options():
            zelphaMain_CreditsInput = input(">> ")
            if zelphaMain_CreditsInput == ("back") or ("Back"):
                os.system('cls')
                zelphaMain()
            else:
                print("What you have entered is not a valid command")
                zelphaMain_CreditsInput_Options()
        zelphaMain_CreditsInput_Options()

    def zelphaMain_Game():
        print("*")
        time.sleep(1)
        print("*")
        time.sleep(1)
        print("*")
        time.sleep(1)
        os.system('cls')
        time.sleep(1)
        print("Zelpha808")
        time.sleep(1)
        print("")
        print("Booting...")
        time.sleep(8)
        os.system('cls')
    def zelphaMain_Menu():
        print("Main Menu")
        print("")
        print("")
        print("Welcome to Zelpha808")
        print("")
        print("")
        print(">>Start")
        print(">>Credits")
        print("")
        zelphaMain_MenuInput = input(">> ")
        if zelphaMain_MenuInput == ("Credits") or ("credits"):
            zelphaMain_Credits()
        else:
            exit()

    zelphaMain_Menu()

zelphaMain()

Down to if zelphaMain_MenuInput == ("Credits") or ("credits"): when I run the program, and get to the main menu of the game, no matter what I input, the program goes on to zelphaMain_Credits(). And in the credits, no matter what I input, it acts as if I inputted "back". I have no idea what is happening, if any of you are confused or need clarification, I'd be happy to add more details.

if statement in ruby, to determine input type

First of all I'm new to ruby, and all of coding. I do this as a hobby and work in a totally different field. I'm trying to make a small hangman game in ruby. I am trying to validate the guess input using the following code

puts "Enter a word: "
answer = gets.chomp
tries = 5
answer_array = answer.chars

until tries == 0
        hits = ""
        puts "enter your guess: "
        guess = gets[0]
        if guess.class != "String"
                puts "enter a letter!!"
        else
                puts "nice!!!"
        end
        tries -= 1
end

for some reason, whatever input I get for "guess", the program throws "enter a letter!". Is there something wrong with the way I defined the if statement. I just want it to differentiate between a String and an Integer. Thanks in advance!!

Creating if (double has certain number of decimal points)

I'm curious if there is a succinct way to create a conditional that checks for a generated double value over a certain number of digits, and throws it away if it's too many decimal places. For instance, if 1.0, 1.5, or 2.2 are generated use those digits. If it generates numbers like 1.61, 1.64, or 2.432, throw these away. Something like this:

if(generated number is over alloted decimal points) continue;

Best/Most Efficient Way to Return All or One Based Off Of Type

I am trying to return a collection of one or multiple Notifications back to the front end for display. I've kicked the wall for a while, and have come up with two different yet similar solutions, posted below.

I'm curious if A: one of these is better than the other, or B: there is better more awesome solution out there and I'm too close to the problem to see it.

The Switch/Case Statement:

    var dl = new Notification() { Type = "dl" };
        var m = new Notification() { Type = "m" };
        var t = new Notification() { Type = "t" };
        var bb = new Notification() { Type = "bb" };

        switch (type)
        {
            case "dl":
                dl.Count = _dlRepository.GetNotificationCount(userId);
                return Enumerable.Repeat(dl, 1);
            case "m":
                m.Count = _mRepository.GetNotificationCount(userId);
                return Enumerable.Repeat(m, 1);
            case "t":
                t.Count = _tRepository.GetNotificationCount(userId);
                return Enumerable.Repeat(t, 1);
            case "bb":
                bb.Count = _bbRepository.GetNotificationCount(userId);
                return Enumerable.Repeat(bb, 1);
            default:
                dl.Count = _dlRepository.GetNotificationCount(userId);
                m.Count = _mRepository.GetNotificationCount(userId);
                t.Count = _tRepository.GetNotificationCount(userId);
                bb.Count = _bbRepository.GetNotificationCount(userId);
                var notifications = new List<Notification>();
                notifications.Add(dl);
                notifications.Add(m);
                notifications.Add(t);
                notifications.Add(bb);
                return notifications;
        }

The Ifs:

    var notifications = new List<Notification>();

        if (type == "dl" || type == null)
        {
            notifications.Add(new Notification()
            {
                Type = "dl",
                Count = _dlRepository.GetNotificationCount(userId)
            });
        }
        if (type == "m" || type == null)
        {
            notifications.Add(new Notification()
            {
                Type = "m",
                Count = _mRepository.GetNotificationCount(userId)
            });
        }
        if (type == "t" || type == null)
        {
            notifications.Add(new Notification()
            {
                Type = "t",
                Count = _tRepository.GetNotificationCount(userId)
            });
        }
        if (type == "bb" || type == null)
        {
            notifications.Add(new Notification()
            {
                Type = "bb",
                Count = _bbRepository.GetNotificationCount(userId)
            });
        }

        return notifications;

Any thoughts/opinions are appreciated.

Adruino newbie trying to figure out how to make conditional moves based on inputs.

I am building a chicken egg rocker “Incubator” This is my first attempt with a Arduino projects but I have programmed PLC’s for years. I have run into problems: The top section of code (find home sequence when switched) I can’t get to run but it compiles, I am lost on this I am not sure if I missed some syntax some ware? I wanted to build some subroutines to jump to that both sections of code could access similar to PLS’c but see this is a no no (the goto command). I would appreciate some direction if anyone is willing. I do have a up/down cycle timer working with limit switches timer based on pot position. The goal : when the home switch is turned on the system will figure out where it is by moving to a limit then find home. This may need to be done mid cycle to remove hatchlings (the trays have to be level / home to be removed). I thought I could accomplish this using the while command to watch the switch then stay in that section of code (at home until the switch is turned off) The verify function failed until I added extra brackets that did not look right but it would compile and load to the board. Thanks in advance.

    // breaking down the chicken code to find the bug


int sensorPin = A0;    // select the input pin for the potentiometer
int ledPin =  13;      // the number of the LED pin
int ledState = LOW;   // ledState used to set the LED
int sensorValue = 0;  // variable to store the value coming from the sensor
int homeswPin = 4;         // toggle sw for home sequence
int homelimitswPin = 5;         //  home limit sensor
int timer = 0;          // variable to store timer
int uplimitswPin = 2;     // up limit switch
int dwnlimitswPin = 3;     // down limit switch
int upoutputPin = 7;      // output to drive up
int upoutput2Pin = 8;      // output to drive up
int dwnoutputPin = 9;      // output to drive down
int dwnoutput2Pin = 10;      // output to drive down
long previousMillis = 0;        // will store last time LED was updated
long interval = timer;        //    interval at which to change 3519 x sensor value (milliseconds)
long timedown = timedown;           // interval at which to change 3519 x sensor value (milliseconds
unsigned long currentMillis = millis();

void setup() { // put your setup code here, to run once:

  pinMode(ledPin, OUTPUT);
  pinMode(homeswPin, INPUT_PULLUP);
  pinMode(homelimitswPin, INPUT);
  pinMode(uplimitswPin, INPUT);
  pinMode(dwnlimitswPin, INPUT);
  pinMode(upoutputPin, OUTPUT);
  pinMode(dwnoutputPin, OUTPUT);
  digitalWrite(7, HIGH);  // +up safety stop motor
  digitalWrite(8, HIGH);  // -up safety stop motor
  digitalWrite(9, HIGH);  // + dwn safety stop motor
  digitalWrite(10, HIGH); // - dwn safety stop motor

}


void loop() {

  { // section 1 find home and stay there
    while (digitalRead(homeswPin) == LOW); {
  if  // dont know where it is but need to find home or up limit
  (digitalRead(homeswPin) == LOW && digitalRead(homelimitswPin) == HIGH &&
      digitalRead(uplimitswPin) == HIGH && digitalRead(dwnlimitswPin) == HIGH) {
    // drives motor up
    digitalWrite(upoutputPin, LOW);
  }
  // move until home or up limit switch found
  else if
  (digitalRead(homelimitswPin == LOW) || digitalRead(uplimitswPin == LOW)) {
    //turn motor off
    (digitalWrite(upoutputPin, HIGH));
  }
  else if
  // at up limit need to go home
  (digitalRead(homeswPin) == LOW && digitalRead(uplimitswPin) == LOW) {

    digitalWrite(dwnoutputPin, LOW); // drives motor down
    //at home ?
    digitalRead(homelimitswPin == HIGH);

    digitalWrite(dwnoutputPin, HIGH);
  } //turns motor off}
  else if
  // at down limit go home
  (digitalRead(homeswPin) == LOW && digitalRead(dwnlimitswPin) == LOW) {
    // drives motor up
    digitalWrite(upoutputPin, LOW);
    //at home
    (digitalRead (homelimitswPin) == 0);
    //turn motor off
    digitalWrite(upoutputPin, HIGH);
  }
  else
    //  at home with home switch on stay here
    (digitalRead(homeswPin) == LOW && digitalRead(homelimitswPin) == LOW);
}

} }

At job asking for time

#!/bin/bash

at now +1 minutes -f ./test.sh

logFile="/home/.../testLog.txt"

time1="114000"
time2="153000"
currentTime=`date +"%H%M%S"`

echo "" >> "$logFile"
date >> "$logFile"
echo "$currentTime" >> "$logFile"
echo "" >> "$logFile"


if [[ "$currentTime" < "$time1" || "$currentTime" > "$time2" ]]
then
    echo "case1" >> "$logFile"
else
    echo "case2" >> "$logFile"
fi

This script is saved in a file called test.sh. When I execute it at for example 5 pm it writes case1 into my log file. But for each subsequent at call (which takes place every minute) the script writes case2 into my log file. Can you explain why?

htaccess redirect if condition Chinese characters

How can redirect if url contains Chinese characters VS English characters in the same .htaccess file as below:

Chinese characters : http://ift.tt/2ah62sS

Redirect : http://ift.tt/2a4IC6B

English characters : http://ift.tt/2a4IxzS

Redirect : http://ift.tt/2ah6Ei9

Now, I am using the below code, how can I use if condition to join the 2 codes in the same .htaccess file ?

Redirect for English:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^abcdefg.com/wiki/$ [NC]
RewriteRule ^(.*)$ http://ift.tt/2a4IwMn [L,R=301]

Redirect for Chinese:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^abcdefg.com/wiki/$ [NC]
    RewriteRule ^(.*)$ http://ift.tt/2ah5K5j [L,R=301]

Thank you for your help in advance.

jQuery: IF conditions for multiple radio button fields?

http://ift.tt/2awOTx5

  <form action="">
<input type="radio" name="colour" value="black"> black
<br>
<input type="radio" name="colour" value="white"> white
<br>

<br>

<input type="radio" name="form" value="round"> round
<br>
<input type="radio" name="form" value="triangle"> triangle
<br>

There are two form-fields "colour" and "forms" with radio buttons that decide which image to show. Choosing the colour works as seen in the fiddle.

If the user now checks triangle in the second field (name="forms") I want a white triangle to show. If he checks black in "colour" and "round" in forms it should change the img src to black_round.jpg and so on.

This is a simplified version. I will have many fields and many more options in the end.

Thanks for your help!

Basic c# if-statement inquiry

I need to input 3 numbers, and then output the highest & lowest of the 3 numbers using IF commands. I have everything working, except I'm getting 1 largest number (correct) and 3 outputs of the lowest number (incorrect). Now I totally understand why they're all being displayed, I just do not know how to fix it. My code, once the integers have been defined by user input, is as follows:

if (num1 > num2 && num1 > num3)
{
    Console.WriteLine("Largest Number: " + num1);
}

if (num2 > num3)
{
    Console.WriteLine("Smallest Number: " + num3);
}
else
{
    Console.WriteLine("Smallest Number: " + num2);
}

and then duplicated 3 times, switching the respective integers. I understand what the issue is, it's that the second if command is correct for all 3 scenarios. I just... don't know how to fix it. I feel like I just need to join these two if statements together somehow but I'm unsure how to do this, or if it's even possible.

IF STATEMENT to return on column Criteria

please forgive what I am about to write its the only way i know how to get across what I am trying to achieve. I believe the picture will help. The IF statement I would love to have would work like this. IF column O contains "TRUE" any where in its range and column P contains "TRUE" anywhere in its range and the customer id in column d is identical for both return me "BINGO" Is this possible to achieve and as always any help is greatly appreciated.

enter image description here

Highlight Button onClick in if clause

I am recently struggling with creating a java based code on Android Studio which I am working on since 2days now. Unfortunately, I cannot find any resolution for my problem on the stackoverflow or any other forum..

I try to highlight a button when clicked in red or green depending on if the buttons text is text1 or text2 of a string-array.

If I run the application it always shows me an error or the button simply doesn't change it's color when I press it. I guess that this has to do with the if-clause, but I don't really know how to solve this problem in any other way.

I would really appreciate any help on this matter!

XML code for green button

<item
    android:state_pressed="true"
    android:drawable="#81c784"/>
<item
    android:state_selected="true"
    android:drawable="@color/#4caf50"/>

XML code for red button

    <item
    android:state_pressed="true"
    android:drawable="#FF4081"/>
    <item
    android:state_selected="true"
    android:drawable="#d50000"/>

Java code:

Button button1;
Button button2;

String[] txtString;            
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.first_layout);

    txtString = getResources().getStringArray(R.array.optiontxt);
    String random = answerString[new random().nextInt(txtString.length)];


    button1 = (Button)findViewById(R.id.btn1);
    button2 = (Button)findViewById(R.id.btn2);


    if (random == txtString[0])
    {
        button1.setText(txtString[0]);
        button1.setBackgroundResource(R.drawable.button_green);
        button2.setText(txtString[1]);
        button2.setBackgroundResource(R.drawable.button_red);

    }
    else
    {
        button1.setText(txtString[1]);
        button1.setBackgroundResource(R.drawable.button_red);
        button2.setText(txtString[0]);
        button2.setBackgroundResource(R.drawable.button_green);
    }       button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {}}; button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {}};

I also tried varies other codes which didn't work aswell, like

button1.setBackground(Drawable.createFromPath("/drawable/button_green"));

or

button1.getBackground().setState(new int[]{R.drawable.button_green});

or

button1.setBackgroundResource(R.drawable.button_green);

If anybody could help me with my problem I would be very thankful. Thank you for any help in advance!!

If condition for XML Parser condition

This condition is true then why its showing toast for

if(objBean.getId().equalsIgnoreCase("4") && objBean.getTitle().equalsIgnoreCase("2")
                                && objBean.getDesc().equalsIgnoreCase("0") && objBean.getPubDate().equalsIgnoreCase("F"))
                        {
                            Toast.makeText(A.this, "true", Toast.LENGTH_LONG).show();

                        }

then why its showing toast for this below

 {
       Toast.makeText(A.this, "out", Toast.LENGTH_LONG).show();
              }

see the image below for more clearity- enter image description here

How to avoid error ocuured due to minus sign of southern latitudes when mixed set of latitudes convert from degrees minutes to decimal degree using R

I have mixed data set of both North (positive) and Negative latitude column and separate minutes column in data frame. I used simple Lat + (minutes/60) to convert this in to decimal degrees.

lat1 <- c(7, -7, 6,  -0, -1, 6,  8, -7, 6,  6)
lat2 <- c(7.4, 55.7, 32.6,  8.9, 47.5, 25.6,  6.8, 45.7, 24.6,  7.6)

ifelse(lat1<0,(lat <- lat1-(lat2/60)),(lat <- lat1+(lat2/60)))

>[1]  7.1233333 -7.9283333  6.5433333  0.1483333 -1.7916667  6.4266667
 [7]  8.1133333 -7.7616667  6.4100000  6.1266667

this result is correct but

> lat
 [1]  7.1233333 -6.0716667  6.5433333  0.1483333 -0.2083333  6.4266667
 [7]  8.1133333 -6.2383333  6.4100000  6.1266667

ifelse statement provide correct result in R console but not to stored it to vector "lat" I need to add minutes/60 to degree if degree value is positive and subtract minutes/60 from degrees if degree value is negative

mardi 26 juillet 2016

Python ; IF word in line and word2 not in line

Apologies for being a noob here , as i am a newbie in this

i have been trying to write a code which could find a certain words in line and then match from 2nd list of words to see if 2nd word exist in the same line. only print line only if first word exist not both in a line; here is the snippet and example

keywords =("a","b","c","d")
keywords2 = ("e","f","g")
a = ("a  is a ", "a is not e","b is b", "b is not f")
for key2 in keywords2:              
    for key in keywords:                

        for line in a:

                if key2 not in line:
                    if key in line:

                        print(key+" Found in --> ")
                        print      (line)

the output required is

a is a
b is b

while we have

a Found in --> 
a  is a 
b Found in --> 
b is b
b Found in --> 
b is not f
a Found in --> 
a  is a 
a Found in --> 
a is not e
b Found in --> 
b is b
a Found in --> 
a  is a 
a Found in --> 
a is not e
b Found in --> 
b is b
b Found in --> 
b is not f

i have tried few ways to implement the loop but to no use

Python: Shorten concatenation by using inline conditionals

If the title is a bit obscure, an example of what I would like to do is:

print("Status: " + if serverIsOnline: "Online" else: "Offline")

I know this is improper, but what I am trying to do is check if serverIsOnline is True then print Status: Online else Status: Offline. I know it's possibe, I have seen it done, but I can't remember how it was done.

This is a shorter equivalent of:

if serverIsOnline:
    print("Status: Online")
else:
    print("Status: Offline")

Could someone please refresh me?

Edit: I always research my questions to the best of my abilities before I ask a question on StackOverflow.

As it is with this question. None of the google search terms I used yielded any results, and I wasn't about to go searching through every Python forum to find an answer to a question which could easily be asked on StackOverflow, especially when this is most likely going to be useful for other users in the future.

VBA loop one cell upward until cell not equal "" and a cell incorporate two IF functions

I'm really sorry but I'm totally new to VBA, learn it by myself without no one to teach and I have project deadline coming up in few days so in desperate and hopeless mode now. Been struggling to find the answer for days but still couldn't come up with any.

Here is the problem: refer the image

Ok so for Column E If B = "S" Then E = "" // null

If B = "F" Then E = (Reverse Rank x PREVIOUS Adjusted Rank + no of failure + 1)/(Reverse Rank + 1)

or in formula excel format

E5 = ((D5*E4)+($K$1+1))/(D5+1)

So the problem lies on the PREVIOUS adjusted rank in the formula. Say, to get value of E5 it needs value of E4 BUT if E4 = "" so it has to go one cell upward. If one cell upward is also ="", it has to go one cell upward again until is not equal <> "". The problem is I'm not sure what function is right to use. I think it would be IF and LOOP but I don't understand how to write the condition. Like I said I'm totally new and time constraints cause me anxiety. Also, if you notice, for Column E there are two IFs function I suppose? One is E is depended on Column B. If Range("B2:B" & lastRow) = "S" or "F" and one is if E="" or <> "" How I incorporated with that?

I am sorry if I break the rules, I'm trying my luck here and it is my last resort >_<

String is equal to an If statement value and yet doesn't work, need help ASAP

I have problem with the following code:

            if finalName == "London, GB" {

        let londonImage = UIImage(named: "united-kingdom-1043062.jpg")

        imageViewPage1.image = londonImage

    }

    if finalName == "Novaya Gollandiya, RU" {

        let StPetersbourgImage = UIImage(named: "architecture-995613_1920.jpg")

        imageViewPage1.image = StPetersbourgImage

    }

    if finalName == "Berlin, DE" {

        let BerlinImage = UIImage(named: "siegessaule-200714_1920.jpg")

        imageViewPage1.image = BerlinImage

    }

    if finalName == "Tel Aviv, IL" {

        let TelAvivImage = UIImage(named: "buildings-89111.jpg")

        imageViewPage1.image = TelAvivImage

    }

    else {

        let elseImage = UIImage(named: "sun-203792.jpg")

        imageViewPage1.image = elseImage

    }

}

I already debugged and the value is "Berlin, DE" and it still does the else instead of the finalName == "Berlin, DE", can anyone help me?

awk - Issues with if else statements

Let file.txt be the following file

1
2
3
5
6
7
15
16
17
19
20
23
24

I was trying to write an awk command that prints the ranges of numbers that are missing. When the range includes only one number, then this number alone should be printed. The expected output is

4
8-14
18
21-22

This post pretty much did the job for me with the one liner

awk '$1!=p+1{print p+1"-"$1-1}{p=$1}' file.txt

4-4
8-14
18-18
21-22

I tried to modify it to

awk 'if ($1!=p+1){if (p+1!=$1-1) {print p+1"-"$1-1} else {print p+1} }{p=$1}' file.txt

but it does not work as expected. I seem to misunderstand the if-else grammar. What am I doing wrong?