mercredi 31 décembre 2014

Python - Novice: Why this simple if-elif (replication of the C case block) always produces the same result?

beginner here. Could anyone explain and/or help me revise this Python code to produce the correct output, whenever I enter the string specified? For example, if March is inputted, output "02". Currently, the program always outputs 00, for January, no matter the input. Here is the code:



x = raw_input("Starting Month: ")

if x == "January" or "january":
stMonth = '00'
elif x == "February" or "february":
stMonth = '01'
elif x == "March" or "march":
stMonth = '02'
elif x == "April" or "april":
stMonth = '03'
elif x == "May" or "may":
stMonth = '04'
elif x == "June" or "june":
stMonth = '05'
elif x == "July" or "june":
stMonth = '06'
elif x == "August" or "august":
stMonth = '07'
elif x == "September" or "september":
stMonth = '08'
elif x == "October" or "october":
stMonth = '09'
elif x == "November" or "november":
stMonth = '10'
elif x == "December" or "december":
stMonth = '11'
else:
print "error"
print stMonth




Output:



$ python month.py
Starting Month: march
00


Thanks in advance - any and all help is much, much appreciated!


Why isn't this printing? (output of radio button)

So I have a radio button and after that I have an if/else statement that is based upon the outcome. But the if/else statements are supposed print things to the console, but they don't. Is something wrong with the Radio Buttons?


If you could, please provide thorough answers, as I'm not very good with Java. Thanks a ton :D



import java.awt.*;

import java.awt.event.*;

import javax.swing.*;


public class RadioButton extends JPanel {

int xDisplacement = 8;
int xVAvg = 8;
int xTime = 8;

static JFrame frame;

JLabel pic;
RadioListener myListener = null;
protected JRadioButton displacement;
protected JRadioButton vAvg;
protected JRadioButton time;
public RadioButton() {



// Create the radio buttons
displacement = new JRadioButton("Displacement");
displacement.setMnemonic(KeyEvent.VK_N);
displacement.setActionCommand("displacement")
//Displacement Button, set to automatically be clicked

vAvg = new JRadioButton("Average Velocity");
vAvg.setMnemonic(KeyEvent.VK_A);
vAvg.setActionCommand("averagevelocity");
//Acceleration Button

time = new JRadioButton("Change in time");
time.setMnemonic(KeyEvent.VK_S);
time.setActionCommand("deltaT");
//The change in time button


// Creates the group of buttons
ButtonGroup group = new ButtonGroup();
group.add(displacement);
group.add(vAvg);
group.add(time);

myListener = new RadioListener();
displacement.addActionListener(myListener);
vAvg.addActionListener(myListener);
time.addActionListener(myListener);


// Set up the picture label
pic = new JLabel(new ImageIcon(""+"numbers" + ".jpg")); //Set the Default Image

pic.setPreferredSize(new Dimension(177, 122));


// Puts the radio buttons down
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
panel.add(displacement);
panel.add(vAvg);
panel.add(time);


setLayout(new BorderLayout());
add(panel, BorderLayout.WEST);
add(pic, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
}



//Listening to the buttons
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
pic.setIcon(new ImageIcon(""+e.getActionCommand() + ".jpg"));

}
}

public static void main(String s[]) {
frame = new JFrame("∆x = Vavg * time");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});

frame.getContentPane().add(new RadioButton(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}



public void running() {
if ( displacement.isSelected()) {
//Option 1
System.out.println("The distance traveled on the x axis in meters is " + xDisplacement);
System.out.println("You can find the Average Velocity by dividing this number by time or find the time by dividing this number by the Average Velocity");
}
if ( vAvg.isSelected()) {
//Option 2
System.out.println("The average velocity in Meters per Second is " + xVAvg);
System.out.println("You can find the displacement by multiplying the time and this number together or to find the time, just divide the displacement by this number");
}

else {
//Option 3
System.out.println("The time in seconds is " + xTime);
System.out.println("You can find the displacement by multiplying the velocity times this number or you can find the average velocity by dividing the displacement by this number");
}
}


}

Exception in thread java.lang.ArrayIndexOutOfBoundsException: 5

I'm a newbie who is trying to complete the below tutorial



// Create a method called countEvens
// Return the number of even ints in the given array.
// Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
/*
* SAMPLE OUTPUT:
*
* 3
* 0
* 2
*
*/


Below is my code



public static void main(String[] args) {

int a[] = {2, 1, 2, 3, 4};
countEvens(a); // -> 3
int b[] = {2, 2, 0};
countEvens(b); // -> 3
int c[] = { 1, 3, 5};
countEvens(c); // -> 0

}


public static void countEvens(int[] x){
int i = 1;
int count = 0;
while ( i <= x.length){
if (x[i] % 2 == 0){
count ++;
}
i ++;
}
System.out.println(count);
}


The code can be run, but I get the below error message



Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at apollo.exercises.ch05_conditionals.Ex5_CountEvens.countEvens(Ex5_CountEvens.java:23)
at apollo.exercises.ch05_conditionals.Ex5_CountEvens.main(Ex5_CountEvens.java:10)


May I know what I'm doing wrong here?


simple jquery calculation

i have a site that has a "container" div that is 200% of the browser window width, and the overflow is hidden. some information is on the left half of the container (the first 100%), and some information is on the right half (the second 100%). i use a simple icon toggle to slide back and forth between both halves of the container, like so:


$('.container').animate({'marginLeft':'-=100%'}, 'slow');


-- or --


$('.container').animate({'marginLeft':'+=100%'}, 'slow');


the issue is, i need to perform certain events based on the marginLeft of the container.


when the first half is visible, i have no problems with getting the events i want. but when jquery slides the container to the left by 100%, making the second half visible, i cannot get anything to work.


after many many hours of research i have learned that i CANNOT use


if ($('.container').css('marginLeft') == '-100%') { //do something here


because the alert never tells me the marginLeft as a percentage, it always returns the number in exact pixels.


my conclusion is that i need a simple calculation in my "if" statement, but i have no idea how to write one.


in written english it would be:


"if the marginLeft in pixels divided by the window width in pixels is equal to -1 then please do stuff..."


can someone please walk me through how to create this very rudimentary jquery calculation and apply it to an if-statement?


any assistance would be greatly greatly appreciated.


many thanks and happy new year, David.


Dictionary key compare with textbox

hi people so what i want to do is check if text in multiple text boxes have the same text/name as keys in a dictionary and if it does i want it to get the value of they keys and add them together (if that makes sense) the if statements should go on till friday then after the program goes through the if statements it should add all the values of the keys together to generate the total and display it on a label (the values are decimals)


pictures http://ift.tt/13UdHqj http://ift.tt/1rBH1gd


code:



private void button2_Click(object sender, EventArgs e)
{
Dictionary<String, Decimal> dictionary1 = new Dictionary<String, Decimal>();
dictionary1.Add("Monday Express", Convert.ToDecimal(mondayExpressTextBox.Text));
dictionary1.Add("Monday FinancialTimes", Convert.ToDecimal(mondayFTTextBox.Text));
dictionary1.Add("Monday Guardian", Convert.ToDecimal(mondayGuardianTextBox.Text));
dictionary1.Add("Monday I", Convert.ToDecimal(mondayITextBox.Text));
dictionary1.Add("Monday Independant", Convert.ToDecimal(mondayIndependantTextBox.Text));
dictionary1.Add("Monday Jang", Convert.ToDecimal(mondayJangTextBox.Text));
dictionary1.Add("Monday Mail", Convert.ToDecimal(mondayMailTextBox.Text));
dictionary1.Add("Monday M.E.N", Convert.ToDecimal(mondayMENTextBox.Text));
dictionary1.Add("Monday ManchesterNew", Convert.ToDecimal(mondayManchesterNewTextBox.Text));
dictionary1.Add("Monday Mirror", Convert.ToDecimal(mondayMirrorTextBox.Text));
dictionary1.Add("Monday Oldham Chronical", Convert.ToDecimal(mondayTextBox.Text));
dictionary1.Add("Monday Racing Post", Convert.ToDecimal(mondayRacingPostTextBox.Text));
dictionary1.Add("Monday Racing Post Betting", Convert.ToDecimal(mondayRacingPostBettingTextBox.Text));
dictionary1.Add("Monday RLE", Convert.ToDecimal(mondayRLETextBox.Text));
dictionary1.Add("Monday Star", Convert.ToDecimal(mondayStarTextBox.Text));
dictionary1.Add("Monday SUN", Convert.ToDecimal(mondaySUNTextBox.Text));
dictionary1.Add("Monday Telegraph", Convert.ToDecimal(mondayTelegraphTextBox.Text));
dictionary1.Add("Monday Times", Convert.ToDecimal(mondayTimesTextBox.Text));
dictionary1.Add("Monday Yorkshire Post", Convert.ToDecimal(mondayYPTextBox.Text));

if (dictionary1.ContainsKey(mondayTextBox.Text))
{
if (dictionary1.ContainsKey(mondayTextBox.Text)){}
}
}

Not understanding how to make my for loop and if statement work

I have this, but I'm very lost in how I can get the final GPA to print out, I've tried various ways but have not been able to do it successfully. This is what I have:



Scanner input = new Scanner(System.in);

System.out.println("How many grades are you putting? ");
int length = input.nextInt();
input.nextLine();

String[] gradesArray = new String[length];

for(int i = 0; i < gradesArray.length; i++)
{
System.out.println("Enter grade (include + or -) ");
gradesArray[i] = input.nextLine();

double points = 0.0;
if(gradesArray[i].equalsIgnoreCase("A+") || gradesArray[i].equalsIgnoreCase("A"))
{
points += 4;

}
else if(gradesArray[i].equalsIgnoreCase("A-"))
{
points+= 3.7;

}
else if(gradesArray[i].equalsIgnoreCase("B+"))
{
points += 3.3;

}
else if(gradesArray[i].equalsIgnoreCase("B"))
{
points += 3.0;

}
else if(gradesArray[i].equalsIgnoreCase("B-"))
{
points += 2.7;

}
else if(gradesArray[i].equalsIgnoreCase("C+"))
{
points += 2.3;

}
else if(gradesArray[i].equalsIgnoreCase("C"))
{
points += 2.0;

}
else if(gradesArray[i].equalsIgnoreCase("D"))
{
points += 1.0;

}
else if(gradesArray[i].equalsIgnoreCase("F"))
{
points += 0.0;

}
else
{
System.out.println("Invalid grade");
}
System.out.println("GPA: " + points / gradesArray.length);
}


I'm guessing the GPA does not print out properly because after the condition matches the grade, it then goes right down to print, right? And also, how can I do it so if they enter an invalid grade, it makes the user start over.


IF Returns True in Chrome, but False in Safari

My javascript function evaluates differently in Chrome/Firefox vs Safari/Opera. There are a number of answers (i.e. here) about my overall goal of show/hide. I'd rather not use jQuery for this case. Anyway, the main problem I want to address is that the conditionals are not returning the same across all browsers.


If I run my code in Chrome or Firefox, I get the alert: "Foo - New Function Ran." If I run the same code in Safari or Opera, I get the alert: "Foo - Else Function Ran."


I don't know why this is browser specific. I'm happy to go read some additional threads or docs if this is addressed elsewhere, but I can't seem to figure it out.





function bar(){
var addGiftVal = document.forms["subscribe"]["addGift"].value;

if (addGiftVal == "yes"){
document.getElementById("showHideGiftShipping").style.display='block';
alert("Bar - Yes Function Ran.");
}

else {
document.getElementById("showHideGiftShipping").style.display='none';
alert("Bar - Else Function Ran.");
}

}

function foo(){
var subTypeVal = document.forms["subscribe"]["sub_type"].value;
var subShipVal = document.forms["subscribe"]["ship_address_check"].value;

if (subTypeVal == "renewal"){
document.getElementById("showHideSubID").style.display='block';
document.getElementById("showHideGiftShipping").style.display='none';
document.getElementById("showHideShippingChoices").style.display='block';
document.getElementById("presentBox").style.display='block';
if (subShipVal == "different"){
document.getElementById("showHideStandardShipping").style.display='block';
}
else {
document.getElementById("showHideStandardShipping").style.display='none';
}
alert("Foo - Renewal Function Ran.");
}

else if (subTypeVal == "new"){
document.getElementById("showHideSubID").style.display='none';
document.getElementById("showHideGiftShipping").style.display='none';
document.getElementById("showHideShippingChoices").style.display='block';
document.getElementById("presentBox").style.display='block';
if (subShipVal == "different"){
document.getElementById("showHideStandardShipping").style.display='block';
}
else {
document.getElementById("showHideStandardShipping").style.display='none';
}
alert("Foo - New Function Ran.");
}

else {
document.getElementById("showHideSubID").style.display='none';
document.getElementById("showHideGiftShipping").style.display='block';
document.getElementById("showHideShippingChoices").style.display='none';
document.getElementById("showHideStandardShipping").style.display='none';
document.getElementById("presentBox").style.display='none';
alert("Foo - Else Function Ran.");
}

}

</script>



<input type="radio" name="sub_type" value="new" id="subf_new" checked="checked" onclick="foo();"><label for="subf_new">New</label>
<input type="radio" name="sub_type" value="renewal" id="subf_renewal" onclick="foo();"><label for="subf_renewal">Renewal</label>
<input type="radio" name="sub_type" value="gift" id="subf_gift" onclick="foo();"> <label for="subf_gift">Gift</label>



How to execute if condition based on a value from query string in javascript/jquery?

I've a variable called url as follows :



url = "http://56.177.59.250/static/ajax.php?core[ajax]=true&core[call]=prj_name.contactform&width=400&core[security_token]=c7854c13380a26ff009a5cd9e6699840"


Now I want to use if condition only if core[call] is equal to the value it currently has i.e. prj_name.contactform otherwise not.


How should I do this since the parameter from query-string is in array format?


Please help me.


Thanks.


How to query an Excel Worksheet using VBA

I have an excel sheet where I need to enter code to query a separate excel document. It will search column A in the second sheet for each of 7 names. When searching for name 1, each time it finds name 1 in col A, if col B equals E, increment in A1 of the first sheet. So basically, every time my name shows up (which is listed randomly in col 1 of the second excel doc), if E is listed in col 2 next to my name, mark that in the first sheet. I need to find the total number of times my name and E match up. Hope that makes sense. Below is a sample.


.....Col A.....Col B............Col C.......Col D.......Col E.....Col F..........Col G.......Col H

1...Name..Calls Offered..Calls...Abandoned..Abn %..Out Calls..Out Time..Staff Time

2 Person A.......6...............6..............0..............0...........19.........0:04:17.....9:16:43

3 Person B.......4...............3..............1.............25..........19.........0:03:07.....8:14:13

4 Person C.......2...............2..............0..............0...........4...........0:05:26.....4:30:05


Sorry it won't let me post a picture... I need the code to be able to query for every instance that Person A shows up in a list. Every time A shows, I need it to take the value in col B and add it to a running total, col C and add it to a different running total, and so on and so forth. Hope this makes more sense.


Treat argument as string in Tcl 'expr' statement

I'm using the short syntax of 'if' statement like this:



set Value 4E20 ;# Merely hexadecimal number
set Selector Second ;# Just for the example
set Data [expr {$Selector eq "First" ? 1234 : $Value}]
puts $Data


The problem is that since the 'expr' statement always treats its arguments as integers, 'Data' gets the value of 4e+20, which is merely the scientific notation of 'Value'.


However, I need 'Data' to be 'Value' (for example, to write to an external register).


Any ideas?


mardi 30 décembre 2014

if condition not working in node js

I am working on mobile application with nodejs and mongo db for server side functionality.


I have implemented a custom header to be sent in every request and I have following function to check header values.


Here is my CODE :



/**
*
* Check Request headers
* @param : headers
* @returns : boolean
*
* */
function checkHeaders(data) {
var customHeader = JSON.stringify(data.appsecret).valueOf().trim();
var contentTypeHeader = JSON.stringify(data["content-type"]).valueOf().trim();
if (contentTypeHeader === "application/x-www-form-urlencoded" && customHeader === "xxxxx") {
return 1;
} else {
return 0;
}
}


Here I always get 0 as the response and I have checked the values of all 3 variables i.e.

1. data,

2. customHeader ,

3. contentTypeHeader

are received correct. but the values in if condition are not matched and I always get " 0 " as the result.


Any suggestion would be a great help!


Thanks in Advance!


When to use 'i' vs. 'str[i]'?

why does using 'i' in the if statement return different results than using 'str[i]'?



function ExOh(str) {
xCount = 0;
oCount = 0;
for (var i=0;i<str.length;i++){
if (str[i]=='x') {
xCount++;
} else if (str[i]=='o') {
oCount++;
}
}
if (xCount==oCount) {
return true;
} else {
return false;
}
}

console.log(ExOh("xox"));

PHP short tags echo method (without the equal to)

Very simple:


So... That is working perfectly



<?=($A>9)?":)":":(";?>


Now... How can I say the same exact thing without = AND without echo ?


iow... I want to use that shortcut technique inside php code in between other php lines.


so this is NOT the correct syntax but just to get the idea more clearly...



<?

$A=50;

($A>9)?":)":":(";

?>

Batch: The syntax of the command is incorrect?

I can't find the error I have spent a long time trying to fix this error but I can't find the error.


The Batch file keeps giving me The syntax of the command is incorrect when I run the following codes.


What's wrong with it?


Code:



@echo off

whoami /groups | find "S-1-16-12288" > nul

if %errorlevel% == 0 (
goto :Runing in Admin Mode
) ELSE (
goto :Not Runing in Admin Mode
)

if %errorlevel% == 2 (
goto :Not Runing in Admin Mode
) ELSE (
goto :Runing in Admin Mode
)

SET AND=IF
SET THEN=(
SET ELSE=) ELSE (
SET NOELSE=
SET ENDIF=)
SET BEGIN=(
SET END=)
SET RETURN=EXIT /B

:Runing in Admin Mode
if %errorlevel% == 0 (
echo Runing in Admin Mode
echo.
attrib -h FileCompressionTool.bat

IF EXIST "upx.exe" %THEN%
attrib -h upx.exe
set missingfilesFalse=False
%ELSE%
echo upx.exe. missing.
set missingfilesTrue=True
ping >nul 3 %THEN%

IF EXIST "mpress.exe" %THEN%
attrib -h mpress.exe
set missingfilesFalse=False
%ELSE%
echo mpress.exe. missing.
set missingfilesTrue=True
ping >nul 3
%THEN%

IF EXIST strip.exe %THEN%
attrib -h strip.exe
%ELSE%
echo strip.exe. missing.
set missingfilesTrue=True
ping >nul 3 %THEN%

IF EXIST reshacker.exe %THEN%
attrib -h reshacker.exe
%ELSE%
echo reshacker.exe. missing.
set missingfilesTrue=True
ping >nul 3 %THEN%

IF EXIST reshacker.ini %THEN%
attrib -h reshacker.ini
%ELSE%
echo reshacker.ini. missing.
set missingfilesTrue=True
ping >nul 3 %THEN%

IF EXIST reshacker.Log %THEN%
attrib -h reshacker.Log
%ELSE%
echo reshacker.Log. missing.
set missingfilesTrue=True
ping >nul 3 %THEN%

%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%

cls

:Not Runing in Admin Mode
if %errorlevel% == 2 (
echo Not Runing in Admin Mode
echo.

attrib -h FileCompressionTool.bat

IF EXIST "upx.exe" %THEN%
attrib -h upx.exe
set missingfilesFalse=False
%ELSE%
echo upx.exe. missing.
set missingfilesTrue=True
ping >nul 3 %THEN%

IF EXIST "mpress.exe" %THEN%
attrib -h mpress.exe
set missingfilesFalse=False
%ELSE%
echo mpress.exe. missing.
set missingfilesTrue=True
ping >nul 3
%THEN%

IF EXIST strip.exe %THEN%
attrib -h strip.exe
%ELSE%
echo strip.exe. missing.
set missingfilesTrue=True
ping >nul 3 %THEN%

IF EXIST reshacker.exe %THEN%
attrib -h reshacker.exe
%ELSE%
echo reshacker.exe. missing.
set missingfilesTrue=True
ping >nul 3 %THEN%

IF EXIST reshacker.ini %THEN%
attrib -h reshacker.ini
%ELSE%
echo reshacker.ini. missing.
set missingfilesTrue=True
ping >nul 3 %THEN%

IF EXIST reshacker.Log %THEN%
attrib -h reshacker.Log
%ELSE%
echo reshacker.Log. missing.
set missingfilesTrue=True
ping >nul 3 %THEN%

%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%

cls

IF EXIST "%~1" %THEN%
SET "result=%~1"
%ELSE%
SET "result="
%ENDIF%

set False= Pause

set True=echo Some file are missing this program may not work correctly please Re-download **File Compression Tool**


echo 1 UPX Compression
echo 2 Mpress Compression
echo 3 Decompress a file
echo 4 Remove VB6 default icon
echo Type exit to exit
echo.
if "%missingfilesTrue%"=="True" %true%

Set /p choice=
If %choice%==1 goto :1
If %choice%==2 goto :2
If %choice%==3 goto :3
If %choice%==4 goto :4
If %choice%==exit goto :exit

if %missingfilesTrue%==True(
%true%
) else (
if %missingfilesFalse%==False
%False%
)

goto :exit

:1
cls
echo ***Drag your exe file into this window and press enter***
set /p File=:
echo.
copy %file% %file%.bak
upx --best %file%
echo.
echo Done!
echo Press any key to exit. . .
pause >nul
goto exit

:2
cls
echo ***Drag your exe file into this window and press enter***
set /p file=:
echo.
copy %file% %file%.bak
Mpress -s %file%
echo.
echo Done!
echo Press any key to exit. . .
pause >nul
goto exit

:3
cls
echo ***Drag your exe file into this window and press enter***
set /p file=:
echo.
copy %file% %file%.bak
upx -d %file%
echo.
echo Done!
echo Press any key to exit. . .
pause >nul
goto exit

:4
cls
echo ***Drag your exe file into this window and press enter***
set /p thefile=:

(
reshacker -delete %thefile%, %thefile%, ICONGROUP, 1, 0
)

strip -s --strip-all -g -S -d --strip-debug -x --discard-all -X --discard-locals %thefile%
upx -9 %thefile%
echo.
echo Done!
echo Press any key to exit. . .
pause >nul
goto exit

:exit
Exit

Arraylist and if statement not working

I am making a bukkit plugin and it has an option to toggle. This is the code I used to make the toggle. In game, the only response is OFF, when it should toggle between ON and OFF. Please help!



public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

ArrayList<String> players = new ArrayList<String>();

if (cmd.getName().equalsIgnoreCase("togglegift") && sender instanceof Player){

Player Tplayer = (Player) sender;

if(players.contains(Tplayer.getName())) {
Tplayer.sendMessage(ChatColor.GOLD + "[BapGift] " + ChatColor.LIGHT_PURPLE + "Gifts Toggled" + ChatColor.GREEN + " ON");
players.remove(Tplayer.getName());

} else {
players.add(Tplayer.getName());
Tplayer.sendMessage(ChatColor.GOLD + "[BapGift] " + ChatColor.LIGHT_PURPLE + "Gifts Toggled" + ChatColor.RED + " OFF");
}
}

Python I/O User Input

I am very new to Python, although I have finished the Codecademy course. I am very sorry if someone has already answered this question, as it all seems way to beyond me. The question I am trying to conquer is if you can use Python's I/O implication to test if a file contains a certain word or phrase and then to run some more code. The goal that I would want to have with this is to have all of the interaction take place in notepad. This would require some form of if statements interaction with the read function in I/O as far as I can see.


I would want to put a code along the lines of:



while True: #Using a while loop to re-ask if not valid answer.
color = input("What is your favorite color? [red/blue/green] ").lower() #Asking and converting to lowercase.
if color == "red" or color == "blue" or color == "green": #Testing if color is valid.
break #Escaping the loop
else: #If it's not valid:
print("Wow, I have never heard of " + color + " being a color before")
continue #Restarting the loop
print("Really? " + color + " is my favorite color too!") #Because they got out of the loop, we can run this.


into some form of it being in notepad. Again, I would like the question to be asked in notepad, the question to be answered by the user in notepad, and then set return some text in NOTEPAD. If you can help me, or direct me to something else that would help me with this, thanks be to you.


ThreeJS Creating three tables with header

.Hello, I'm trying to cycle through a table and create three tables of clickable divs with a header for each (ideally with a separate class to make them look different). I'm trying to use a while loop with 3 if statements but the headers are not displaying properly. All three still show up as normal divs instead of with different classes but the first one is covered with a second copy of the third column header with the correct header and the second header is covered with a second copy of the first header, again with the correct class. If anyone could point out how I'm mistaken it would be greatly appreciated, thanks!


JS Snippet



var table = [


"Column Title", "#", 2,2,
"Column Item", "website.com", 1, 3,
"Column Item 2", "website2.com", 2, 3,
// Etc.
];
var camera, scene, renderer;
var controls;

var objects = [];
var targets = { table: [], sphere: [], helix: [], grid: [] };

init();
animate();

function init() {

for ( var i = 0; i < table.length; i += 4 ) {

if(i === 0){
var courtsTitle = document.createElement('div');
courtsTitle.className = 'listTitle';
courtsTitle.innerHTML = "<p>Column Title</p>";

var object = new THREE.CSS3DObject( courtsTitle );
object.position.x = Math.random() * 4000 - 2000;
object.position.y = Math.random() * 4000 - 2000;
object.position.z = Math.random() * 4000 - 2000;
scene.add( object );

objects.push( object );


var object = new THREE.Object3D();
object.position.x = ( 6 * 480 ) - 2900;
object.position.y = - ( 2 * 340 ) + 1550;

targets.table.push( object );
}
if(i === 14){
var departmentsTitle = document.createElement('div');
departmentsTitle.className = 'listTitle';
departmentsTitle.innerHTML = "<p>Column Title2</p>";

var object = new THREE.CSS3DObject( departmentsTitle );
object.position.x = Math.random() * 4000 - 2000;
object.position.y = Math.random() * 4000 - 2000;
object.position.z = Math.random() * 4000 - 2000;
scene.add( object );

objects.push( object );


var object = new THREE.Object3D();
object.position.x = ( 10 * 480 ) - 2900;
object.position.y = - ( 2 * 340 ) + 1550;

targets.table.push( object );
}

if(i === 28){
var servicesTitle = document.createElement('div');
servicesTitle.className = 'listTitle';
servicesTitle.innerHTML = "<p>Column Title3</p>";

var object = new THREE.CSS3DObject( servicesTitle );
object.position.x = Math.random() * 4000 - 2000;
object.position.y = Math.random() * 4000 - 2000;
object.position.z = Math.random() * 4000 - 2000;
scene.add( object );

objects.push( object );

//

var object = new THREE.Object3D();
object.position.x = ( 2 * 480 ) - 2900;
object.position.y = - ( 2 * 340 ) + 1550;

targets.table.push( object );
} else {
var department = document.createElement('a');
department.className = 'department';
department.style.backgroundColor = 'rgba(0,127,127,' + ( Math.random() * 0.5 + 0.25 ) + ')';
department.setAttribute('href', table[i + 1]);
department.setAttribute('target', "_blank");

var link = document.createElement('div');
link.className = 'link';
link.innerHTML = table[i];
department.appendChild(link);

/*Random Starting point*/
var object = new THREE.CSS3DObject( department );
object.position.x = Math.random() * 4000 - 2000;
object.position.y = Math.random() * 4000 - 2000;
object.position.z = Math.random() * 4000 - 2000;
scene.add( object );

objects.push( object );


/*Final position*/
var object = new THREE.Object3D();
object.position.x = ( table[ i + 2 ] * 480 ) - 2900;
object.position.y = - ( table[ i + 3 ] * 340 ) + 1550;

targets.table.push( object );
}

}

How to calculate the values with using TextWatcher

I want to calculate totals of T,T2,T3,T4 given in calculate method. if i don't put any value in calculate 3 (). there is show 0 value in T3.


I want full total of last row (Total) plz give me idea.. how it possible



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


Edtinch1 = (EditText)findViewById(R.id.inch1);
Edtinch2 = (EditText)findViewById(R.id.inch2);
Edtfeet = (EditText)findViewById(R.id.feet);
Edtquan = (EditText)findViewById(R.id.qunt);
Totaltxt1= (EditText)findViewById(R.id.total1);
Edtquan.addTextChangedListener(this);

Edtinch21 = (EditText)findViewById(R.id.inch21);
Edtinch22 = (EditText)findViewById(R.id.inch22);
Edtfeet2 = (EditText)findViewById(R.id.feet2);
Edtquan2 = (EditText)findViewById(R.id.qunt2);
Totaltxt2= (EditText)findViewById(R.id.total2);
Edtquan2.addTextChangedListener(this);

Edtinch31 = (EditText)findViewById(R.id.inch31);
Edtinch32 = (EditText)findViewById(R.id.inch32);
Edtfeet3 = (EditText)findViewById(R.id.feet3);
Edtquan3 = (EditText)findViewById(R.id.qunt3);
Totaltxt3= (EditText)findViewById(R.id.total3);
Edtquan3.addTextChangedListener(this);


fulltotal1=(EditText)findViewById(R.id.fulltotal);

btnsnap = (Button)findViewById(R.id.btncapture);
btnsnap.setOnClickListener(this);

}

public void calculate(){
//get entered texts from the edittexts,and convert to integers.
inch11 = Double.parseDouble(Edtinch1.getText().toString());
inch12 = Double.parseDouble(Edtinch2.getText().toString());
feet11 = Double.parseDouble(Edtfeet.getText().toString());
quan11 = Double.parseDouble(Edtquan.getText().toString());
//do the calculation
Double calculated1 = (inch11*inch12)*(feet11)/144*(quan11);
//set the value to the textview, to display on screen.
T= calculated1.toString();
Totaltxt1.setText(T);

}


public void calculate2(){
//get entered texts from the edittexts,and convert to integers.
inch21 = Double.parseDouble(Edtinch21.getText().toString());
inch22 = Double.parseDouble(Edtinch22.getText().toString());
feet2 = Double.parseDouble(Edtfeet2.getText().toString());
quan2 = Double.parseDouble(Edtquan2.getText().toString());
//do the calculation
Double calculated2 = (inch21*inch22)*(feet2)/144*(quan2);
//set the value to the textview, to display on screen.
T2= calculated2.toString();
Totaltxt2.setText(T2);

}

public void calculate3(){
//get entered texts from the edittexts,and convert to integers.
inch31 = Double.parseDouble(Edtinch31.getText().toString());
inch32 = Double.parseDouble(Edtinch32.getText().toString());
feet3 = Double.parseDouble(Edtfeet3.getText().toString());
quan3 = Double.parseDouble(Edtquan3.getText().toString());
//do the calculation
Double calculated3 = (inch31*inch32)*(feet3)/144*(quan3);
//set the value to the textview, to display on screen.
T3= calculated3.toString();
Totaltxt3.setText(T3);

}

public void calculate4(){
//get entered texts from the edittexts,and convert to integers.
inch41 = Double.parseDouble(Edtinch41.getText().toString());
inch42 = Double.parseDouble(Edtinch42.getText().toString());
feet4 = Double.parseDouble(Edtfeet4.getText().toString());
quan4 = Double.parseDouble(Edtquan4.getText().toString());
//do the calculation
Double calculated4 = (inch41*inch42)*(feet4)/144*(quan4);
//set the value to the textview, to display on screen.
T4= calculated4.toString();
Totaltxt4.setText(T4);

}

public void fullcalculate()
{


}

@Override
public void afterTextChanged(Editable s) {

}

@Override
public void beforeTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub


if (Edtinch1.getText().toString().length() <= 0)
{
Edtinch1.setError("Input Inch");
}

else if (Edtinch2.getText().toString().length() <= 0)
{
Edtinch2.setError("Input Inch");
}
else if (Edtfeet.getText().toString().length() <= 0)
{
Edtfeet.setError("Input feet");
}
else if (Edtquan.getText().toString().length() <= 0) {
Edtquan.setError("Input Quantity");
}
else
{
if (Edtquan.getText().hashCode() == s.hashCode())
{
calculate();
}
}



if (Edtinch21.getText().toString().length() <= 0)
{
Edtinch21.setError("Input Inch");
}

else if (Edtinch22.getText().toString().length() <= 0)
{
Edtinch22.setError("Input Inch");
}
else if (Edtfeet2.getText().toString().length() <= 0)
{
Edtfeet2.setError("Input feet");
}
else if (Edtquan2.getText().toString().length() <= 0) {
Edtquan2.setError("Input Quantity");
}
else
{
if (Edtquan2.getText().hashCode() == s.hashCode())
{
calculate2();
}
}

if (Edtinch31.getText().toString().length() <= 0)
{
Edtinch31.setError("Input Inch");
}

else if (Edtinch32.getText().toString().length() <= 0)
{
Edtinch32.setError("Input Inch");
}
else if (Edtfeet3.getText().toString().length() <= 0)
{
Edtfeet3.setError("Input feet");
}
else if (Edtquan3.getText().toString().length() <= 0) {
Edtquan3.setError("Input Quantity");
}
else
{
if (Edtquan3.getText().hashCode() == s.hashCode())
{
calculate3();
}
}

if (Edtinch41.getText().toString().length() <= 0)
{
Edtinch41.setError("Input Inch");
}

else if (Edtinch42.getText().toString().length() <= 0)
{
Edtinch42.setError("Input Inch");
}enter code here
else if (Edtfeet4.getText().toString().length() <= 0)
{
Edtfeet4.setError("Input feet");
}
else if (Edtquan4.getText().toString().length() <= 0) {
Edtquan4.setError("Input Quantity");
}
else
{
if (Edtquan4.getText().hashCode() == s.hashCode())
{
calculate4();
}
}

}

How to check for multiple if-conditions in swift

I know this questions sounds silly and it totally is. But somehow I cannot get Xcode (Version 6.1.1 (6A2008a)) to recognize my if-statement is swift. I have tried several different syntaxes and Xcode seems to accept none of them. Here is what I am trying to do:


if (self.status == self.statusRunning && self.nextEpisode == nil) { self.complete = false } else { self.complete = true }


The first part is a simple string comparison between a class property (var ...) and constant (let ...). The second part should just check whether the class property (var nextEpisode:Episode?) is still nil or has already been filled. After that another class property should be set accordingly.


Although I'm still new to swift this seems like a rather minor problem bug Xcode keeps throwing different errors, so I just turn to you guys to tell me whether my syntax or my Xcode is messed up...


Cheers,


Jan


Edit:Error Source https://gist.github.com/Jan0707/a111762fe0c65bb1f84f


How to check the second list element on a line in a file contains 'x'?

What I'm trying to do is to create a login system.

I ask the user for a username, and if that username is in the file, I want to ask for a password.

But I don't know how I could check if the username and password matches.


The file with usernames is formated like this:



Username1 Password
Username2 Password


My code is:



def login():
users = open('passwords.txt', 'r').readlines()
while x == 1:
usernames = [i.split()[0] for i in users]
username = raw_input("> ")
if username.lower() in usernames:
password = raw_input("> ")


else:
print 'That username is not in use.'


So the question is, how may I check if I.E: Password matches with Username1?

I know I can't loop through, every password in the file like this:



passwords = [i.split()[1] for i in users]


Because, then it would accept every single password in the file, and not the matching one only.


Query date from user, use today's date if user press enter

In a C-program I am trying to query user for a date which shall be put into a char-array in a structure (pIndex->startDate). If the date is today's date the user should only need to press enter - and if the date is some other, the user will have to type it in.


The input is done by fgets. What I think is that I'll check if the user input is equal '\n' – in that case I set the array equal to today's date. If not, the array will be whatever the user typed.


To find the date (in general), I use:



time_t now = time(NULL);
struct tm *t = localtime(&now);


..and I have a temp char-array for the if-statement:



char temp_date[11]="2014-01-01"; //initialized with something, guess there is a better solution


I have tried the following:



printf("Enter start date (press Enter for todays date) > ");
fgets(pIndex->startDate, MAXDATE, stdin);
if (pIndex->startDate=='\n'){
sprintf (temp_date, "%d-%02d-%02d", t->tm_year+1900, t->tm_mon+1, t->tm_mday);
(pIndex->startDate)==temp_date;
}
/*Check the result*/
printf("CHECK TEMP_DATE: %s\n> ",temp_date);
system("pause");


However, the only thing that appears in the output is the value char temp_date was initialized with: 2014-01-01


Is this a wrong approach? Anyone knows a better (working) way?


Thanks a lot!


-Espen


toggleClass before if statement

I am wondering why this one is not working. It only works when .removeClass respectively .addClass are added inside the if statement. But this toggle should be executed before the if statement shouldn't it? Is there a way to make this working that way?



$(".submit").click(function() {
$(this).toggleClass("active");
if ($(this).hasClass("active")) {
$(".initialStyle").show();
} else {
$(".initialStyle").hide();
}
});


Many thanks


Clear a value from a textfield and fill that value in an other textfield?

i have the following code:



var s1 = this.getField("One").value;
var s2 = this.getField("Two").value;
var s3 = this.getField("Three").value;
var s1n = this.getField("One");
var s2n = this.getField("Two");
var s3n = this.getField("Three");

if(s1.length > 0) & (s2.length == 0) & (s3.length == 0){
s1n = '' & s2n = s1 & s3n = ''
else if (s1.length > 0) & (s2.length > 0) & (s3.length == 0){
s1n = s1 & s2n = '' & s3n = s3
else if (s1.length > 0) & (s2.length > 0) & (s3.length > 0){
s1n = s1 & s2n = s2 & s3n = s3
}}}


I have three textfields in a row. If i fill out "One" only i want clear the value in "One" and fill that value in "Two". If i fill out "One" and "Two" i want to clear the value in "Two" and fill that value in "Three". If i fill out "One" and "Two" and "Three" i want to do nothing. But with the code above i get an syntax error. What i have to do, to get this working?


Load data local infile with IF statement

I have table with data:



| id | status |
| 1 | 1 |
| 2 | 1 |
| 3 | 0 |
| 4 | 2 |
| 5 | 2 |


I have file, that I need to load into this table and replace:



| id | status |
| 1 | 1 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 1 |


I have one condition: if status in table =2 and status in file =0, leave status in table =2, otherwise replace status in table from file.

After query I need to get new data:



| id | status |
| 1 | 1 |
| 2 | 0 |
| 3 | 0 |
| 4 | 2 |
| 5 | 1 |


I'm trying do it with query:



load data local
infile '".$file."'
replace
into table tec_tca_teacher_prod_copy
fields terminated by ',' enclosed by '\"'
(@tid,
teacher_name,
email,
@pid,
tca_form_type,
prod_company,
prod_name,
@stts)
set status = if((select status from (select status from tec_tca_teacher_prod_copy where teacher_id=@tid and prod_id=@pid) as tmp)=2,status,@var),
teacher_id = @tid, prod_id = @pid


After that I get status fields NULL.


How to resolve this problem?


lundi 29 décembre 2014

Is there a simpler way to write this script? (C programming)

I'm pretty new with C, so I wanted some advice.


This code is looking if the words are anagrams or no. The code threats upper-case input the same as lower-case and it ignores if the input character is not a letter. At the end it should and it does show are the words anagrams or no.


I was wondering is there an easier way to write this code or is this pretty much it?



int alphabet[26] = {0}, sum = 0;
char first[20], second[20];
int i = 0;

printf("Enter the first word: ");
do
{
first[i] = getchar();
if(isalpha(first[i]))
alphabet[toupper(first[i]) - 'A'] += 1 ;
i++;

}while(first[i - 1] != '\n');

printf("Enter the second word: ");
i = 0;
do
{
second[i] = getchar();

if(isalpha(second[i]) && alphabet[toupper(second[i]) - 'A'] > 0)
{
alphabet[toupper(second[i]) - 'A'] -= 1;
}
i++;

}while(second[i - 1] != '\n');

for(i = 0; i <= 26 - 1; i++)
{
sum += alphabet[i];
}
if (sum == 0)
printf("Anagrams\n");
if (sum != 0)
printf("Not anagrams\n");

Is it preferred to use else or else-if for the final branch of a conditional

What's preferred



if n > 0
# do something
elsif n == 0
# do something
elsif n < 0
# do something
end


or



if n > 0
# do something
elsif n == 0
# do something
else
# do something
end


I was using else for awhile. I recently switched to doing elsif. My conslusions are the first option adds readability at the cost of more typing, but could confuse some people if they expect an else. I don't have enough experience to know if the first option would create more readability or more confusion and if there are other pros/cons I've missed. I wrote the code in Ruby but I assume the answer is language agnostic. If it isn't, I would like to know why.


Using Excel Averageif with the HOUR function

I have 2 columns of data. 1 Column time (HH:MM:SS)(C3:C103) and the 2nd meter readings (D3:D103). For each hour there are 5 or 6 meter readings. I would like to average each hours readings to condense the data down to one averaged meter reading per hour. I tried =Averageif(C3:C103,Hour=10,D3:D103) but clearly have something wrong.


Variable cannot be resolved in an If-Statement

I'm trying to do the below tutorial question.



// Create a method called greatestCommonFactor
// It should return the greatest common factor
// between two numbers.
//
// Examples of greatestCommonFactor:
// greatestCommonFactor(6, 4) // returns 2
// greatestCommonFactor(7, 9) // returns 1
// greatestCommonFactor(20, 30) // returns 10
//
// Hint: start a counter from 1 and try to divide both
// numbers by the counter. If the remainder of both divisions
// is 0, then the counter is a common factor. Continue incrementing
// the counter to find the greatest common factor. Use a while loop
// to increment the counter.


And my code is below



import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Ex4_GreatestCommonFactor {

// This is the main method that is executed as
// soon as the program starts.
public static void main(String[] args) {
// Call the greatestCommonFactor method a few times and print the results
}

public static int greatestCommonFactor(int a, int b){
int i = 1 ;
while (i >= 1 ){
i++;
}
if (a%i == 0 && b%i == 0){
ArrayList factor = new ArrayList<Integer>();
factor.add(i);
}
else if (a%i <= 1 || b%i <= 1){
Collections.sort(factor);
List<Integer> topnum = factor.subList(factor.size() - 1, factor.size());

}
return topnum;
}
}


So I have 2 questions.


1) In my elseif statement, I get an error where factor cannot be resolved to a variable. How do I "carry over" the factor ArrayList from the previous If statement into this elseif statement?


2) I also get a similar error where topnum cannot be resolved. Is this also a placement error for this line of code in my method, or am I making a completely different mistake?


Proper Python Syntax and Semantics: if, else, pass [duplicate]


This question already has an answer here:




Is there a preferred/proper style?



This:



def fx(Boolean):
if Boolean:
# Do stuff.
else:
pass


Or this:



def fx(Boolean):
if Boolean:
# Do stuff.


Is it preferred/proper to include else: pass if you don't want anything to happen?

I've read PEP 8 - Style Guide for Python Code and did not find anything concerning my question.


If and else redirections

Im trying to write a code that goes something like this:



if (a certain cookie is detected) stay on the current url
else (screen.width <= 699) {
document.location = "http://www.hotshotsnet.com/portals/0/mobile/mobile.html";

Trouble with If/Then Statements

I am trying to perform a simple if then statement and I am getting confused on the coding. Specifically I want to say that if something is a, then I want it to be b. The example is:


forms$form.type <- if (forms$form.type == 28) {forms$form.type = "Form 28"}


I'm not sure if this is the right code, but I just want to do a simple if/then statement.


Code will execute both if and else statements. Javascript [on hold]

I have an array called used.I have a function which add a code in the array but checks if the code has been added again.If it has been added it has to say "False" else True the problem is that it will say both false and true. Here is my code:



var used=[];//use that to check if the user has added the code to favourites again

var x='',y='',blur='',r="",g="",b="",op="",color="rgb(0,0,0)",shadow=''; //create the variables that will be used
function update(){
x=$("#x").val();
y=$("#y").val();
op=$("#o").val();
r=$("#red").val();
g=$("#green").val();
b=$("#blue").val();
blur=$("#blur").val();
shadow = x+"px "+y+"px ";


}
$(document).ready(function(){
$("#addC").click(function(){
if(used.indexOf(shadow) != -1){
alert("false");
}
else{
used.push(shadow);
alert("True");

}
});
$('.shadow-slider').change(function(){

update();

if (op != 1){
if(op.length > 3){op=op.substring(0, 3);}
color="rgba("+r+","+g+","+b+","+op+")";
}
else{
color="rgb("+r+","+g+","+b+")";
}
if (blur != 0){shadow += blur+"px ";}
shadow += color;
$('#object').css("text-shadow",shadow);
$('#code-output').html("text-shadow:"+shadow+";");

});



});


Shadow is a global variable which changes depending on some sliders of my page.Any ideas?


PHP if $ = $ and $ = $ { header }

I want to do this:



$jmsa = "m";
$hsma = "c";

if($u = $jmsa), if($p = $hsma) {
header('Location: klo.php');
}else{}


But idk how to do two $ if


Please help, im simply noobie :/


I can't understand why this if statement doesn't work in Swift

I am creating a very simple iOS application that involves two labels ("labelDisplay" and "labelStatus"), one button ("buttonAddOne") and a variable ("numbers"). I can't understand why the labelStatus isn't being updated when "numbers" reaches 5. I also tried other ways but had no luck. Here is the Swift code. Thank you! If you want to download the project: https://www.dropbox.com/s/kpv8qqquppe00jc/ProjectStackOverFlow.zip?dl=0



import UIKit

var numbers:Int = 0

class ViewController: UIViewController {

// Declaration of the two labels
@IBOutlet weak var labelDisplay: UILabel!
@IBOutlet weak var labelStatus: UILabel!

// Code for the "Add 1" button
@IBAction func buttonAddOne(sender: AnyObject) {
numbers = numbers + 1
labelDisplay.text = "\(numbers)"
}

override func viewDidLoad() {
super.viewDidLoad()

if numbers == 5 {
labelStatus.text = "Numbers variable is equal to 5! Hurray!"
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

Output the word in a string with the largest amount of vowels

I mostly have the method done but I am confused when it comes to the If statement concerned with storing a variable with the word with the most amount of vowels, NOTE I am not allowed to use arrays. below is my code


//method for vowels and consonants


public static int Vowelcount(String sentence) {



int maxvowelcount =0;
int minvowelcount =0;
String vowel="";
int consonantcount = 0;
int vowelcount = 0;
int index = 0;
String currentword;
int spacePos;
int noOfchars = 0;
int largest = 0 ;
int smallest = 0 ;

//gets rid of leading and trailing spaces so as to get the last word
sentence=sentence.trim() + " ";




//assignments
spacePos=sentence.indexOf(" ");
currentword = sentence.substring(0, spacePos);

while (spacePos >-1)// when no spaces are found
{
noOfchars=0;
currentword = sentence.substring(0, spacePos);

// remove the first word
sentence = sentence.substring(spacePos+1);

spacePos=sentence.indexOf(" ");



// to count the number of vowels in the string
for(index = 0; index<currentword.length(); index++)
{
if(currentword.charAt(index)=='a' || currentword.charAt(index)=='e' || currentword.charAt(index)=='i' || currentword.charAt(index)=='o' ||
currentword.charAt(index)=='A' || currentword.charAt(index) == 'E' || currentword.charAt(index) == 'I' || currentword.charAt(index) == 'O' )
{

vowelcount++;
}

else
{
consonantcount++;
}






//if statement to overwrite currentword with largest/smallest


if (index == 0)
{
minvowelcount = currentword.length();
maxvowelcount = currentword.length();
}

if (vowelcount < minvowelcount)
{
minvowelcount = vowelcount;
}


if (vowelcount > maxvowelcount)
{
maxvowelcount = vowelcount;
vowel=currentword;
}
}
}






//output to show the word with largest amount of vowels
System.out.println( "word with largest amount of vowels is " + maxvowelcount);
return vowelcount;


}


jquery json object if statement

I just recently started becoming familiar with JSON and I'm trying to figure out if I can use an IF statement inside of the JSON object...I hope I am referring that correctly.


So, in my code, I am displaying a SELECT and it's OPTION values with JSON, and the issue I am having is IF a value is NULL, display the text NONE.


This is what I have so far:



function renderIPIEditView ($td)
{
var value = $td.text();
$td.html(''); // clears the current contents of the cell
var $select = $('<select class="form-control"></select>');
$td.append($select);

$.getJSON( 'api/inlands.php', function( data )
{
$.each(data, function(index, item)
{ // here is where I think the IF statement should go
$('<option>').
attr('value', item.POINT_CODE).
text(item.FULL_NAME+', ' +item.US_STATE).
appendTo($select);
});

$select.val(value);
});
}


So with the code above, I can display the necessary options value and text. However, inside the table, there is one record that has a POINT_CODE of NONE, and will list the text FULL_NAME and US_STATE as NULL, NULL on the screen.


I think I need an IF statement right where I listed the comment in the code above, but I am not sure if I can even use an IF statement, let alone how to use it in this case.


Please forgive my incompetence as I am still trying to familiarize myself with JSON.


Please help.


MySQL IF...THEN syntax error

I've been trying to work with the IF statement in MySQL (v5.6.13) without any success. I've eventually pared my code back to the simple example below, which still doesn't work:



IF 10>1 THEN
SELECT 10;
END IF;


When I run this, it gives me the following error:



You have an error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'IF 10>1 THEN
SELECT 10' at line 1


I did wonder whether it was something to do with the MySQL client I'm using (Sequel Pro), but I get exactly the same message running from the command line.


Am I making some kind of ridiculously simple mistake that I just can't see? Or does anyone have any suggestions as to what might be causing the error? Any help would be gratefully received!


Ruby sentence with dates and calibrations

I have Items and Calibrations table. The items can have multiples calibrations. The table calibrations contains (date_calibration, date_expired, item_id). I must show the items with calibrations, and if it is has more than one, show only the max. Then I need write an IF sentence and show a new column with color (red, yellow and green) depending on how many days left to calibrate the item. using date_expired.


Item controller (show the max, works good)



@items = Item.joins(:calibrations)
.order('items.id')
.order('calibrations.date_expired DESC')
.select('DISTINCT ON (items.id) items.id, items.codigo, items.numero, items.den_cont, genre_id, state_id, affectation_id, sector_id, person_id, calibrations.date_expired AS Fecha_Vencimiento')


Index.html



<% @items.each do |item| %>
<tr>
<td><%= item.codigo + '%03d' % item.numero.to_s %></td>
<td><%= item.den_cont %></td>
<td><%= item.genre.genre %></td>
<td><%= item.state.state %></td>
<td><%= item.affectation.affectation %></td>
<td><%= item.sector.sector %></td>
<td><%= item.calibrations.pluck(:date_expired).max %></td>

<td><%= if item.calibrations(:date_expired) <= Date.today + 60 then image_tag '/semaforo/amarillo_small.png'
elsif item.calibrations(:date_expired) <= Date.today + 30 then image_tag '/semaforo/rojo_small.png'
else image_tag '/semaforo/verde_small.png' end %></td>


I have an error in the sentence if "compared with non class/module". Can you help me with the correct sentence.? If date_expired is less than today + 60 days, must show a yellow image...then less than today + 30 days red image and the others green image..


If field = Null then use a different field

I have written some Sql code to display all clients who's offers are about to expire in the next 90 days by using the dateOffered field. However there is another field in the database called OfferExpirydate I would use this field however it it not always filled out.


My question is i want the code to look at OfferExpirydate and if it has a value then use it or else use the Dateoffered field as my code below stats. ( if the OfferExpirydate is not filled out it is set to a NULL ) Any help on this would be great thanks



SELECT
DateOffered,
pr.ClientID,
pr.id AS profileID,
cf.Clntnme,
pm.Lender,
ABS(DATEDIFF(DAY, DateOffered, DATEADD(d,-90, GETDATE()))) AS 'NoOfDays'
FROM tbl_profile AS pr
INNER JOIN tbl_Profile_Mortgage AS pm
ON pr.id = pm.fk_profileID
INNER JOIN dbo.tbl_ClientFile AS cf
ON pr.ClientID = cf.ClientID
WHERE
DateCompleted IS NULL AND
DateOffered > DATEADD(d,-90, GETDATE())
AND DATEDIFF(DAY, DateOffered, DATEADD(d,-90, GETDATE())) > -15
ORDER BY DateOffered ASC

if statement openerp view

What I want is to make an if statement. if it's true an image should be displayed, else the other image should be displayed. However the XML can't do the comparison because it can't find myboolean or it just can't compare the values so it's neither false or true.


Can someone explain it?


I also tried myboolean.raw_value === true but it gives me the error:



Uncaught TypeError: Cannot read property 'raw_value' of undefined



What I wanted to happen:



<if myboolean == true>
<img src="thisimage"/>
</if>
<if myboolean == false>
<img src="otherimage"/>
</if>

BASH: IFfing throuth two (or more) folders to find files matching pattern

I have a bash-related question. To start the explaination. I had a folder structure looking like this:



config--
|-config-chain.conf
|-somefile1.txt
|-somefile2.txt
|-somefile3.txt
|-somefile4.txt
|-somefile5.txt
|-somefile6.txt


config-chain.conf contains text looking like this:



somefile1
somefile2
somefile3
somefile4
somefile5
somefile6


Before today, all those txt files were in one folder, so iterating through this was simple.


But the specification has changed and I have to do this the new way.



config--
|-config-chain.conf
|
|--folder1--
|-somefile1.txt
|-somefile2.txt
|-somefile3.txt
|--folder2--
|-somefile4.txt
|-somefile5.txt
|-somefile6.txt


Before that, I was iterating through this with a simple loop. It looked like this:



while read config-chain
do
if [ -f $config-chain.txt ];
then
echo "Config file found"
else
echo "Config file not found"
fi
done < config-chain.conf


But now the files are in two different folders. My actual approach is looking like this:



while read config-chain
do
if [ -f folder1/$config-chain.txt ] || [ -f folder2/$config-chain.txt ];
then
echo "Config file found"
else
echo "Config file not found"
fi
done < config-chain.conf


It is looking ugly for me, cause I'm looking for the existence of a file in both folders. I don't know how this will look in the future, maybe there will be 15 folders, so imagine this OR with 15 statements... Is there a way to do this cleaner? Maybe with find? Or a more clean way to do this with IF?


Bash -eq doesn't work, maybe because of cal


#!/bin/bash

i=0
d="$(date +%d)"
an="$(cal | awk '/[0-9]/ {print $2}' | tail -2)"
for e in $an
do
if [ "$d" -eq "$e" ]; then
i=1
fi
done

echo i=$i


The problem is with $an/$e but i don't understand why and how to fix it. I've looked and it don't have any spaces, they are numbers however bash don't think this way.


Why else if is not working?

I am using else if in my form but only if part is working.My condition is true but i did not know why it is not working.I am using CakePhp.I tried this one.


Link


Thanks.


dimanche 28 décembre 2014

replacing values in column in R dataframe

I want to replace certain values in R data frame(data1) . I am doing data cleaning.


there are n columns in the data frame data1. In one of the column Article_Description I want to do following operation. how can this be done in R


if data1$Article_Description in ('snova glide 4m','SNOVA Glide 4M','SNova Glide 4 M') then data1$Article_Description='SNOVA Glide 4M'; if data1$Article_Description in ('aSTAR Ride 4M','astar ride 4m') then data1$Article_Description='astar ride 4m'; if data1$Article_Description in ('CC Fresh M','cc fresh m') then data1$Article_Description='CC Fresh M'; if data1$Article_Description in ('cc ride m','CC Ride M') then data1$Article_Description='CC Ride M'; if data1$Article_Description in ('astar solution 2m','aSTAR Solution 2M') then data1$Article_Description='astar solution 2m'; if data1$Article_Description in ('astar salvation 3m','aSTAR Salvation 3M') then data1$Article_Description='astar salvation 3m'; if data1$Article_Description in ('cc chill m','CC Chill M') then data1$Article_Description='CC Chill M';


Android - Concatenated Strings aren't detected by if condition [duplicate]


This question already has an answer here:




Probably this will be so stupid to be asked, but I can't find the way to make it works and even to find the solution on Internet.


I need to concatenate 2 strings (variable STR_Prefix and string "TA+") to create a new one ("ATA+" or "BTA+"), then I have to check the value in an if-statement, but it fails, the if-statement doesn't detect the "ATA+".


But if I set the value of "STR_Action" directly to "ATA+" it works perfectly.



public void Test(boolean ok)
{
String STR_Action = "";
if (ok) { STR_Prefix = "A"; }
else { STR_Prefix = "B"; }

/* I have tried some ways to concatenate */
STR_Action = STR_Prefix + "TA+"; // Not working with the if-statement
// STR_Action = new StringBuilder(STR_Prefix).append("TA+").toString(); // Not working with the if-statement

/* But if-statement only works when I set STR_Action directly with = "ATA+" or "BTA+"; */
// STR_Action = "ATA+"; // This assign is detected by the if-statement

if (STR_Action == "ATA+")
{
Toast.makeText(getApplicationContext(), "ATA+", 0).show();
}
else if (STR_Action == "BTA+")
{
Toast.makeText(getApplicationContext(), "ATA-", 0).show();
}
else
{
Toast.makeText(getApplicationContext(), "Code not found", 0).show();
}
}


Please, help :'(


Thanks in advance


Array.equals(...) is giving incorrect result

Code That is not working


This code is should print the word 'inside if' but doesn't and I don't know what is wrong with it.



doublesArray[0] = 3;
doublesArray[1] = 3;
doublesArray[2] = 3;
doublesArray[3] = 0;

int[] temp6 = {3,3,3,0};
//length is 4 for both arrays

if(doublesArray.equals(temp6))
System.out.println("Inside if");


These are things to show it should print true



int[] temp6 = {3,3,3,0};
doublesArray[0] = 3;
doublesArray[1] = 3;
doublesArray[2] = 3;
doublesArray[3] = 0;
//length is 4 for both arrays

System.out.println("temp6 " + temp6[0] + " " + temp6[1] + " " + temp6[2] + " " + temp6[3]);
System.out.println("doublesArray " + doublesArray[0] + " " + doublesArray[1] + " " +
doublesArray[2] + " " + doublesArray[3]);
System.out.println("This should be true: ");
System.out.println("doublesArray.equals(temp6) = " + doublesArray.equals(temp6) + "\n");

//testing
if(doublesArray[0] == temp6[0])
System.out.println("correct");
if(doublesArray[1] == temp6[1])
System.out.println("correct");
if(doublesArray[2] == temp6[2])
System.out.println("correct");
if(doublesArray[3] == temp6[3])
System.out.println("correct");

//testing with numbers
System.out.println(" ");
if(doublesArray[0] == 3)
System.out.println("CORRECT");
if(doublesArray[1] == 3)
System.out.println("CORRECT");
if(doublesArray[2] == 3)
System.out.println("CORRECT");
if(doublesArray[3] == 0)
System.out.println("CORRECT");


These are the results I got which should show that doublesArray.equals(temp6) = true



temp6 3 3 3 0
doublesArray 3 3 3 0
This should be true:
doublesArray.equals(temp6) = false

correct
correct
correct
correct

CORRECT
CORRECT
CORRECT
CORRECT


Thank you for those that were able to help.


Swift- How can I have a button refresh each time it's hit?

I can't seem to figure out how to have a function block repeated when a UIButton is pressed in swift. Here's what I have:



class CoinFlip: UIViewController {
@IBOutlet var resultLabel: UILabel!
var randomNumber = (Int(arc4random_uniform(2)))
@IBAction func tossButton(sender: UIButton) {
if randomNumber == 0 {
resultLabel.text = "Heads!"
}
else if randomNumber == 1 {
resultLabel.text = "Tails!"
}
}
}


When the button is pressed in the app, it picks a random number. If I hit it again, it displays the same number. What can I do so each time I hit the button it refreshes?


JAVA charAt(i) in a for loop not working

I've got an assignment to write a a method that accepts two strings as an argument and returns a value of 1,0,-1 (respectively) if the first string is lexicographicaly before, equal or after the second string, using only the charAt() and length() methods from the String class.


The problem is that even though I initialized an int variable in my for loop, it won't recognize them later in the loop when using the charAt method. The compiler keeps saying "unexpected type. required: variable; found: value". (using BlueJ).



public class Word {

private String _st;

/**
* range small letters: a = 97, z = 122.
*
* range capital letters: A = 65, Z = 90.
*/
public int myCompare (String s1, String s2) {
char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};


//1st loop i;
//2nd loop j;
//3rd loop k;
for (int i = 0; i < s1.length(); i++) {
_st = new String (s1);
if (_st.charAt(i) < 97) {
_st.charAt(i) += 32;
}

for (int j = 0; alphabet[j] == _st.charAt(i); j++){
int x = alphabet[j];
_st.charAt(i) = x;
}

}

return 1; // temporaray.
/*
if (s1.charAt(0) < s2.charAt(0)){
return 1;
} else if (s1.charAt(0) > s2.charAt(0)){
return -1;
} else {
return 0;
}*/
}


}


So what exactly am I doing wrong? thanx for any help :)


String comparison in if statement

I have the following Bash script, but I get an error in the predicate of my if statement. What am I doing wrong?



#!/bin/bash
$UQ = "noqueue:"
read -p "Aadress: " email
id=$(grep $email mx.log | grep status | awk '{print $6 }')
read b <<<$id read
a <<<$email

if (($id == $UQ ));
then
grep $email mx.log
else
for((i=0;i<${#a[@]};i++)); do
for ((j=0;j<${#b[@]};j++))
do
c+=(${a[i]}:${b[j]});
done
done
for i in ${c[@]} do
echo $i
done
fi

samedi 27 décembre 2014

Python - 'in' keyword and if-statements not working as expected [duplicate]


This question already has an answer here:




I have looked for an answer to my question, but it seems there are none for my problem specifically. Which has lead me to believe this is a simple error.



def intest():

choice = raw_input("> ")

if "hello" or "world" in choice:
print "There is hello or world in 'choice'"
elif "bye" or "cya" in choice:
print "There is bye or cya in 'choice'"
else:
print "Go again"
return intest()

intest()


When run, no matter what is typed in the raw_input, the first if-statement is the one that executes. What is the problem?


Else/If statement help in swift

I'm getting an error when I try to ask an if/else statement in Xcode 6 with swift. This is what I have


}else if countElements(sender.text) == 1, 2


It's telling me "Type 'String!' does not conform to protocol '_CollectionType'


How can I compare two values on one line? Thanks


Elsif test on array

I thought I would try and make a noughts and crosses game to refresh my memory while I was off over Christmas "just for fun" and I've hit a block in the road.


The array holds either a 0 or a x so I am testing for three in a line. I thought maybe it was because I was testing to arrays against each other but I tested $array_cont_val[1][1] == $x as well with no joy.


Any help would be greatly appreciated



function who_won($array_cont_val){
$x = 23;
if($array_cont_val[1][1] == $array_cont_val[1][2] && $array_cont_val[1][3] == $array_cont_val[1][2]){
$x = "wins";
} elseif ($array_cont_val[2][1] == $array_cont_val[2][2] && $array_cont_val[2][3]) == $array_cont_val[2][2] {
$x = "wins";
}elseif($array_cont_val[3][1] == $array_cont_val[3][2] && $array_cont_val[3][3] == $array_cont_val[3][2]){
$x = "wins";
}elseif($array_cont_val[1][1] == $array_cont_val[2][1] && $array_cont_val[3][1] == $array_cont_val[2][1]){
$x = "wins";
}elseif($array_cont_val[1][2] == $array_cont_val[2][2] && $array_cont_val[3][2]) == $array_cont_val[2][2] {
$x = "wins";
}elseif{($array_cont_val[1][3] == $array_cont_val[2][3] && $array_cont_val[3][3] == $array_cont_val[2][3]){
$x = "wins";
}elseif{($array_cont_val[1][1] == $array_cont_val[2][2] && $array_cont_val[3][3] == $array_cont_val[2][2]){
$x = "wins";
}
}
}
}

bash If statement failing

Im working on a bash script to check an ftp site to see if some files exist on it. It works by looping through an array of files using curl to check if the file exists on the ftp server. If it doesnt then curl should output an error which im looking for in my if loop and echoing a result based on it. Code below:



#!/bin/bash

# script variables
ftpaddress=ftpaddress
ftplocation=folderlocation
ftpusername=ftpusername
ftppassword=ftppassword
err="curl: (19) Given file does not exist"

# Initialise array of files
files=( "file1.xml" "file2.xml" "zy.xml" )

for f in "${files[@]}"; do
result=(curl http://ftp$ftpaddress$ftplocation$f --user $ftpusername:$ftppassword --head)
if [[ "$result" == "$err" ]]; then
echo $f " Does not exist!!!!"
else
echo $f "Exists"
fi
done


Something about the if loop is failing, ive tried lots of variations on it but have been unable to find one that works. At the moment the result is never matching the error. When I run the curl just from the command line it outputs the error i have set to $err if the file doesnt exist but when running the script the else branch is being selected everytime saying the file does exist. I've even tried setting the error to be*"19"*and it still doesnt match. I've spent a lot of time looking it up and testing it but have had no luck so would appreciate any help that can be given.


Thanks


Please help, im getting errors

Theres an error that says invalid expression on 'else if' and 'else' Thanks


using System;


namespace test { class MainClass { public static void Main (string[] args) { Random numberGenerator = new Random ();



int num01 = numberGenerator.Next (1,11);
int num02 = numberGenerator.Next (1,11);
int realAnswer = num01 * num02 ;

Console.WriteLine ("What is " + num01 + " multiplied by " + num02 + "?");

int userAnswer = Convert.ToInt32 (Console.ReadLine ());

if (userAnswer == realAnswer) {
Console.WriteLine ("Good");
} else if (userAnswer - realAnswer >= 1 && userAnswer - realAnswer <= 3) {

int greater = numberGenerator.Next (1, 3);

switch (greater) {
case 1:
Console.WriteLine ("little too high");
break;

default:
Console.WriteLine ("little too much");
break;

} else if (realAnswer-userAnswer >= 1 && realAnswer-userAnswer <=3) {

int less = numberGenerator.Next (1, 3);

switch (less) {
case 1:
Console.WriteLine ("little too low");
break;

default:
Console.WriteLine ("go higher!");
break;

} else {

Console.WriteLine ("you just suck");

}

Console.ReadKey ();

}
}
}
}


}


Why don't we add ; at the end of if/else?

In Rust, I have noticed that everything is an expression except 2 kinds of statements. Every expression that adds ; will become a statement. Rust's grammar wants statements to follow other statements.


So why don't we add ; at the end of an if / else "expression"? This is also an expression, so why don't we do this:



if true {
println!("true");
} else {
println!("false");
};

How to move an element in javascript automatically with while loop?

I am making a Snake game so I'm trying to move my snake. It is moving with keys but it should move automatically on the screen. I tried doing that with while loops like in the code below but because of break; I have to press a key every time I want it to move. How can I make it move automatically? I tried removing break; an using an if statement but I didn't succeed.


Any other solutions or something else?


I'm new to programming so any advices would be helpful.



var main = function() {
var i = 0;
var j = 0;
$(document).keyup(function(event) {
var e = event.which;

while(i == 1) {
$('.snake').animate({left: '+=10px'}, 10);
break;
}
while(i == 2) {
$('.snake').animate({left: '-=10px'}, 10);
break;
}
while(i == 3) {
$('.snake').animate({top: '-=10px'}, 10);
break;
}
while(i == 4) {
$('.snake').animate({top: '+=10px'}, 10);
break;
}

//Which key is preesed
//D
if(e == 68) {
i = 1;
}
//A
else if(e == 65) {
i = 2;
}
//W
else if(e == 87) {
i = 3;
}
//S
else if(e == 83) {
i = 4;
}
//Any other key
else {
i = 0;
}


});
};

$(document).ready(main);

the no option in my if-else statement isnt working correctly

i wrote this code to use the if-else statement but the "no" outputs the same as the yes, i first tried declaring the yes and no variables locally and that fixed the first error i got, but now they are not differentiating the output. the condition for yes outputs no matter what i try. here is the code below:



#include<iostream>
#include<string>
using namespace std;
int main()
{
string name;
bool answer;
cout<<"Welcome user 'Divine 9'..."<<"What is your name?"<<endl;
getline(cin, name);
cout<<endl<<"Hello "<<name<<", my name is Xavier."<<endl<<" I am going to ask you some questions about yourself. Fear not, i will not take any of your information back to the boss man, or store it."<<endl;
cout<<"Is this okay with you? (yes/no)"<<endl;
cin>>answer;
{bool yes;
bool no;
if(answer==yes)
cout<<"Great, will proceed with the questions!"<<endl;
else (answer==no)
cout<<"That is okay, still love the Gamma Sig ladies, especially that_girl_teejay :-)";}

return 0;
}


can someone please help me figure this out, i thought i had it but i guess i dont


Trouble in defining a function inside if statement in Python?

i tried to create a python program.i defined a function inside an if statement,but the result will be only till the if statement.the function inside it wont get executed.



if(ch2=="A")|(ch2=="a"):
Name=raw_input("Enter your name:")
Username=raw_input("ENter your username")
Password=raw_input("ENter your password")
Confirm=raw_input("Confirm your password")
DOB=raw_input("DD: MM: YY: ")
Gender=raw_input("I am....")
Mobile=input("Enter your mobile number")
Location=raw_input("Enter your current location")
print"Prove you are not a robot,Type the text shown below"
text="F7HGhfyu"
print"Wa$t3oF#!m3"
text="Wa$t3oF#!m3"
type=input("Type your text")
if(Confirm==Password)&(type==text):
print"You have successfully created an account"
print"You can now proceed!!"
else:
def proceed():
def details():
print"Welcome",Username


its getting executed only up to type variable.should we import any packages??or is there any errors?. Your help is appreciated.thanks in advance!


If clause with multiple conditions

I seem to be lost or just seem to be confused. To simplify the problem: I want to check whether each in an array holds true and if and only if all are true it should return a specific value.



var trueArray=[true,true,true,true];


As in my code, the array can have length up to 100 elements, I can't simply check for every element but need a for loop.



for(var i=0;i<trueArray.length;i++){
if(trueArray[i]===true){
//do something
}
}


However, the above code does something on each step of the loop but I only want it to do something once every condition held true and not inbetween. Can't think of the solution at the moment


Covering all scenarios with if statement

I'm doing the below homework exercise


Given 2 int values greater than 0, return whichever value is nearest to 21 without going over. Return 0 if they both go over.


I've made the below code



public static void main(String[] args) {


System.out.println(blackjack(22,22));

System.out.println(blackjack(25,25));

System.out.println(blackjack(19,25));

System.out.println(blackjack(25,19));

System.out.println(blackjack(10,10));

System.out.println(blackjack(19,10));

System.out.println(blackjack(1,19));

}

// Create a method like:
public static int blackjack(int a, int b){
if ( a > 21 && b > 21){
return 0;
}
else if ( a <= 21 || b > 21){
return a;
}
else if ( a > 21 || b <= 21){
return b;
}
else if ( a >= b){
return a;
}
else {
return b;
}

}


All of it works except the last line of output in my main. I keep getting "a" or, "1" in this case, so I'm not sure what is wrong with my last line in my method declaration. I have a feeling something is wrong but I'm not sure what to change.