dimanche 31 décembre 2017

List sorted-Python card game

I have a card came that contains a list of cards in a players hand from top to bottom. And i need to check up to what point the cards list break from the order of small to large(from top to bottom).I am not able to use any sort of GUI's.

for example, cards in players hand: 23 24 12 5-check for the fifth element in the list that is properly sorted 4 3 2 1

Switch on an if statement?

I am a bit of a beginner with coding, so can someone please tell me if it is possible to do something like this in Java, in a void result type?

switch (if this != null {return this;}
            else {return that;}) {

    case "This": blah
        break;
    case"That": blah
        break;
}

Also, can anyone tell me the most efficient way to do a switch statement with two variables? Thanks! :)

Updating Flutter page after setState()

I have a user follow/unfollow page that searches Firebase for a list of followers and returns a Boolean if their usedID is found. The bool is then set in a separate function that changes a public bool. The trouble is that my Widget/Scaffold doesn't update here...

friends == true ? new RaisedButton "unfollow" : new RaisedButton "follow"

Any ideas? I'll update with exact code once later.

else gets blank and no redirects

I have this code (validarusuario.php) and if username and pass. it´s ok it redirects to the right address. The problem is that if I put my pass wrong or username I would like to redirect to index (if it is easy to show a message intermediatly) but mainly redirect to indes.php (in the folowing code) I will try to make it but when the pass is wrong, no appears any error message only appears a blank (white) page validarusuario.php but no redirects.

I have tried to put else in several places but don´t get it:

<?php
include("conectar_bd.php"); 
conectar_bd();

$usr = $_POST['usuario'];
$pw = $_POST['password'];
//Obtengo la version cifrada del password
$pw_enc = md5($pw);



$sql = "SELECT id_usuario FROM tbl_users
INNER JOIN ctg_tiposusuario
ON tbl_users.id_TipoUsuario = ctg_tiposusuario.id_TipoUsuario
WHERE tx_username = '".$usr."'
AND tx_password = '".$pw_enc."'

"; 
$result =mysql_query($sql,$conexio); 

$uid = "";




$sql1 = "SELECT id_TipoUsuario FROM tbl_users
WHERE tx_username = '".$usr."'
AND tx_password = '".$pw_enc."' "; 



$result1=mysql_query($sql1,$conexio); 

$uid = "";
$rs=mysql_fetch_array($result1);

if( $rs[0]=="2"){ 

if( $fila=mysql_fetch_array($result) )
{ 
//Obtener el Id del usuario en la BD 
$uid = $fila['id_usuario'];
//Iniciar una sesion de PHP
session_start();
//Crear una variable para indicar que se ha autenticado
$_SESSION['autenticado'] = 'SI';
//Crear una variable para guardar el ID del usuario para tenerlo siempre 
disponible
$_SESSION['uid'] = $uid; 
//CODIGO DE SESION

//Crear un formulario para redireccionar al usuario y enviar oculto su Id 
?>
<form name="formulario" method="post" action="principalcero.php">
<input type="hidden" name="idUsr" value='<?php echo $uid ?>' />
</form>
<?php
}
else {
//En caso de que no exista una fila...
//..Crear un formulario para redireccionar al usuario a la pagina de login 
//enviandole un codigo de error
?>
<form name="formulario" method="post" action="index.php">
<input type="hidden" name="msg_error" value="1">
</form>
<?php
}
?>


 <script type="text/javascript"> 
 //Redireccionar con el formulario creado
document.formulario.submit();
</script>

<?php




}


elseif( $rs[0]=="1"){ 



if( $fila=mysql_fetch_array($result) )
{ 
 //Obtener el Id del usuario en la BD 
 $uid = $fila['id_usuario'];
 //Iniciar una sesion de PHP
 session_start();
//Crear una variable para indicar que se ha autenticado
$_SESSION['autenticado'] = 'SI';
//Crear una variable para guardar el ID del usuario para tenerlo siempre 

disponible $_SESSION['uid'] = $uid; //CODIGO DE SESION

//Crear un formulario para redireccionar al usuario y enviar oculto su Id 
?>
<form name="formulario" method="post" action="administrador.php">
<input type="hidden" name="idUsr" value='<?php echo $uid ?>' />
</form>
<?php
}
else {
//En caso de que no exista una fila...
//..Crear un formulario para redireccionar al usuario a la pagina de login 
//enviandole un codigo de error
 ?>
 <form name="formulario" method="post" action="index.php">
 <input type="hidden" name="msg_error" value="1">
 </form>
 <?php
 }



 ?>

    <?php
}

?> 
<script type="text/javascript"> 
//Redireccionar con el formulario creado
document.formulario.submit();
</script>

If Else Statements , AND OR logic operations, and text files (using Python)

I'm having some trouble with AND and OR within if else statements. This is my code:

if subject == 'history' or subject == 'History' and unit == 'WWII' or unit == 'ww2':
        with open("hisEasy.txt", "a") as hisWw2File:
            for hisEasy in quizzes:
                userName = hisWw2[0]
                subject = hisWw2[1]
                unit = hisWw2[2]
                score = hisWw2[3]
                grade = hisWw2[4]
                hisWw2File.write(userName + ';' + subject + ';' + unit + ';' + str(score) + ';' + grade + '\n')

if topic == 'history' or topic == 'History' and unit == 'Hitler' or difficulty == 'hitler':
    with open("hisMedium.txt", "a") as hisMediumFile:
            for hisH in tests:
                userName = hisH[0]
                subject = hisH[1]
                unit = hisH[2]
                score = hisH[3]
                grade = hisH[4]
                hisHFile.write(userName + ';' + subject + ';' + unit + ';' + str(score) + ';' + grade + '\n')

I'm trying to print the scores of tests to text files according to subjects and units but it actually saves it to BOTH text files. For example, if my unit is ww2 it will save to ww2 file AND to the Hitler unit file. Any ideas how to fix this?

Python: Print each match just one time with if statement

Am trying to check the existence of a string in a list, it might exist more that one time, so when I print the result am getting more then 1 occurance in the result and I want it to print each occurance one time:

This is what I have been doing so far:

spec = [result[:i]+s+result[i+1:]for i in range(len(result)) for s in L if s!=result[i]]
    for i in range (0, len(spec)):
        if spec[i] in my_list:
            print ("R7:You mean:",spec[i])

The input is 'mangge'

The output am getting :

R7:You mean: manège
R7:You mean: mangée
R7:You mean: manège
R7:You mean: mangée
R7:You mean: manège
R7:You mean: mangée
R7:You mean: manège
R7:You mean: mangée
R7:You mean: manège
R7:You mean: mangée
R7:You mean: manège
R7:You mean: mangée

The output am expecting:

R7:You mean: manège
R7:You mean: mangée

Am missing something I don't know what it is !

samedi 30 décembre 2017

issue with test code +rating bar code

how can i code : rating bar + test*

*test :-if user click less than 4 star it will show a toast messg say thank you . - and if user click more than 4 star it will send him to my app to review. Thank you.

If-then constraints in integer linear programming

I have a 30*40 matrix. Lets say the components in the matrix are specified with "P" and the related number of the row and column of each "P" is specified by "X" and "Y" accordingly. I have a model that the output should give us the P, X and Y. How can I define constraints (for solving a simplex) which connect P with it's exact X and Y? I want to say for example:

if X=1 and Y=1 then P= 0.1

if X=1 and Y=2 then P= 0.5

if X=1 and Y=3 then P= 0.8 and so on.

I dont want the model to return a P that does not match it's location in the matrix. How can I achieve this?

Python script to find nth prime number

I'm new to Python and I thought I'd try to learn the ropes a bit by writing a function to find the nth prime number, however I can't get my code to work properly. No doubt this is due to me missing something fundamental, but I'd appreciate your help in finding where it went wrong!

`c=2

n=input("Which prime would you like? ")

n=int(n)

a=[]

l=len(a)

while l<=n:
    if c==2:
        a.append(c)

    elif (c % 2 ==0): #c is even
        break

    elif (c % 2 !=0): #c is odd
        if c<7:
            a.append(c)

        elif c >=7:
            for i in range(3,int((c+1)/2)):
                if (c % i ==0):
                    break
            else:
                a.append(c)
    else:            
        c+=1

a[n]`

Thanks! Andrew

Breaking inline for loop on condition

I want to find the first number k such that the sum of squares of all naturals up to that number is divisible by 200.

Normal solution:

sum = 0
for k in range(1, max+1):
    sum += k**2
    if sum % 200 == 0:
        return k

I have a one-liner:

print(sum([i^2 for i in range(1, 1000)]))

But I want to break this loop as soon as this sum is divisible by 200.

Is it possible to do this?

using int instead of boolean in if statements

I'm working on a small program which uses switch statements to identify the day of the week using a scanner input.

package Dummies;
import java.util.Scanner;
public class DaysOfTheWeek {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner keyboard = new Scanner(System.in);
        int day = keyboard.nextInt();
        switch(day) {
        case 1:
            if(day = 1) {
                System.out.println("Sunday");
            }
        }
    }

}

I wanted the programme to tell me what the day of the week it is depending on what number the user inputs, for example in the United States the first day of the week is Sunday so if the user inputs "1" Sunday would be printed. I wanted the switch statement with each case containing an if statement for a detailed response. The issue I'm having here is that i can't convert an int to a boolean in an if statement and I wanted to ask if anyone knows how I can solve it. I know that my code isn't complete.

Thanks for help.

what does if(getClass().getSimpleName().equals("blahblah")) is actually doing

I Made a Class "Hamburger" and it Has 2 Other Sub classes that Extend from it, there's also a method in Hamburger Class Which is "setbaseprice", I want to Make this Method Unchangeable for one of Sub Classes which is Called Delux... so I made an if statement inside of that method like

public void setBaseprice(double price){
        if(getClass().getSimpleName().equals("Delux")){
            this.baseprice = 37000;
            System.out.println("Total Price for Delux Burger is $" + this.baseprice);

I wanted to tell the method, don't take anything other than 37000 from Delux.. or change what ever it gives you to 37000.. but i just noticed, this thing is working even if we don't call the method. baseprice is set and system.out.prinln works right after we create an object in delux class.. no matter we write object.setBaseprice() or not. Can you please tell me what is happening in there ?

-I'm a Beginner

Java making the program run continuously with a while loop [duplicate]

This question already has an answer here:

This is a joke program that i just wrote for this question but i do have some serious programs that i have tried this with. Im unsure of how to get this to work. If i have multiple while loops or if else statements that are nested within each other, then how does java know which closing curly brace { applies to which loop? For instance if i type the following code: package fiahsticks;

import java.util.Scanner; public class fishsticks {

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

String fishSticks = "";
String keepGoing = "yes";
String go = "go";

while (keepGoing == "yes"){

System.out.print ("do you like fish sticks");
fishSticks = scan.nextLine();

if (fishSticks == "yes"){
  System.out.println ("your a gay fish");
  keepGoing = "null";
  }

else if (fishSticks == "no"){
  System.out.println ("wrong answer");
  keepGoing = "yes";
}
}

}

}

Java just continues to prompt me with the do you like fish sticks question and never makes it to the if statements. I also have another program that is bigger which contains multiple if else statements that are all nested within a while loop but this program runs into a different issue. Java goes through the while loop and makes it to the if statement but when it hits the closing } of the if statement, java thinks that this is the closing curly brace for the while loop and the program quits. Why is this? If this were python then I could tell the program which statements are nested in what simply by indenting them, but java doesn't seem to work this way. How does java know what is nested inside of what?

vendredi 29 décembre 2017

Simplify chain of if statements in a foreach

I have this logic and it's working but it's not pretty (as I'm sure you can tell). There are rewards that are given when a person reaches a certain level and I need to show the date when the person reaches the reward. So if a person reaches the over 250 dollar reward show the date. But if a person spends $1000 in one day then I need to show that they have reached Level 1, 2, and 3 all on the same day. All the DateTimes are null to begin with. How could I simplify the if chain that I have going on:

foreach (var receipt in receiptsLastYear.OrderBy(x => x.DateCreated))
        {
            totalLastYear += receipt.Amount;
            if (totalLastYear >= 250 && totalLastYear < 500 && 
                vm.Rewards.DateAwardedLevel1 == null)
            {
                vm.Rewards.DateAwardedLevel1 = receipt.DateCreated;
            }
            if (totalLastYear >= 500 && totalLastYear < 1000 && 
                vm.Rewards.DateAwardedLevel2 == null)
            {
                if (vm.Rewards.DateAwardedLevel1 == null)
                {
                    vm.Rewards.DateAwardedLevel1 = receipt.DateCreated;
                }
                vm.Rewards.DateAwardedLevel2 = receipt.DateCreated;
            }
            if (totalLastYear >= 1000 && totalLastYear < 2500 && 
                vm.Rewards.DateAwardedLevel3 == null)
            {
                if (vm.Rewards.DateAwardedLevel1 == null)
                {
                    vm.Rewards.DateAwardedLevel1 = receipt.DateCreated;
                }
                if (vm.Rewards.DateAwardedLevel2 == null)
                {
                    vm.Rewards.DateAwardedLevel2 = receipt.DateCreated;
                }
                vm.Rewards.DateAwardedLevel3 = receipt.DateCreated;
            }
            if (totalLastYear >= 2500 && vm.Rewards.DateAwardedLevel4 == 
                 null)
            {
                if (vm.Rewards.DateAwardedLevel1 == null)
                {
                    vm.Rewards.DateAwardedLevel1 = receipt.DateCreated;
                }
                if (vm.Rewards.DateAwardedLevel2 == null)
                {
                    vm.Rewards.DateAwardedLevel2 = receipt.DateCreated;
                }
                if (vm.Rewards.DateAwardedLevel3 == null)
                {
                    vm.Rewards.DateAwardedLevel3 = receipt.DateCreated;
                }
                vm.Rewards.DateAwardedLevel4 = receipt.DateCreated;
            }
        }

Multiple handling functions in if statement

I was wondering if multiple handling functions in an if statement is bad practice or hated?
Example:
if(empty($employee) OR empty($project) OR empty($streetName) OR empty($zipCode) OR empty($city)){ $error = true; }

Struggling with compare last 2/3/4 characters Java (repl.it 018 - Conditional Statement Practice 4)

Dear Stackoverflow community I am Struggling with one task on repl.it (018) Conditional Statements 4

So they want me to do that :

Instructions from your teacher: For you to do:

Given a string variable "word", do the following tests

If the word ends in "y", print "-ies" If the word ends in "ey", print "-eys" If the word ends in "ife", print "-ives" If none of the above is true, print "-s" No more than one should be printed.

and my code looks like this :

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner inp = new Scanner(System.in);
    System.out.print("In:");
    String word = inp.nextLine();
    //DO NOT CHANGE ABOVE CODE!  Write your code below

    if(word.endsWith("y"){
      System.out.println("-ies");
    }
    else if(word.endsWith("ey")){
      System.out.println("-eys");
    }
    else if(word.endsWith("ife")){
      System.out.println("-ives");
    }
    else{

      System.out.println("-s");
    }
  }
}

When I run it for example my input is :Hey

and of course my code will go through the code and see if the first statement is correct and yes it is equal because y = y at the end and that is WRONG!

My question is how can i let my code compare the last 2 or 3 characters so it will print out the right value when I input Hey.

If I input Hey it should print out :

-eys and not -ies

Ty

Xamarin Android C# Start Service 'else' not called

I have buttons that give the ability to start or stop the app's background service, but for some reason my 'else' call in the button's click event isnt being activated if the service is already running.

Heres the whole button code, hope someone knows why it doesnt call:

private void StartServiceButton_Click(object sender, EventArgs e)
    {
        if (Application.Context.GetSystemService("com.prg.NotificationService") == null)
        {
            Application.Context.StartService(intent);
        }
        else
        {
            Toast.MakeText(this, "Service already running)", ToastLength.Long).Show();
        }
    }

replace special values for each column of a data frame

If i want to replace all the negative values as well as values of (999,9991,9992,9996) for all the columns of my data frame with -100, how should i do it. I want to save it as a new data frame and not on the same data frame.

thanks

Issues with curly braces in if/else statement

I'm pretty new to R and I am trying to create a function with some geographical output. I am trying to include some if/else statements to set defaults for certain parameters like the map title but have been encountering the same issue repeatedly. Others have had the same issue but the responses their queries haven't helped me.

Below is a simplified version of my code, as well as the errors I am encountering.

   my_function <- function(x, y, map.title, a, ... ){
    neighbours <- spdep::poly2nb(x, queen=T, snap=T)
    print("neighbours defined")
    local <- spdep::localmoran(y, listw=nb2listw(neighbours, style="W")) 
    moran_map <- x
    moran_map@data <- cbind(x@data, local)
  if(map.title = NULL) {
    seg_map <- tmap::tm_shape(moran_map) +
               tm_fill(col = "Ii",
                       style = "quantile",
                       title = "Local Moran's I Statistic") +
               tm_layout(title = "Good Maps Have Titles")
    return(map) 
} else {
    seg_map <- tmap::tm_shape(moran_map) +
                     tm_fill(col = 'Ii',
                             style = 'quantile',
                             title = "Local Moran's I Statistic",
                             palette = a) +
                     tm_layout(title = map.title)
   return(map) 
   }
}

I keep getting the following errors.

>Error: no function to return from, jumping to top level

>   }
Error: unexpected '}' in "  }"

>   }
Error: unexpected '}' in "  }"

Does anyone know what I am doing wrong, and how I could fix this?

Thanks so much!

this program executes both if and else

import math
while True:
 n=(raw_input("Please enter a number to check if it is prime or not " ))
 if n == "gate":
    exit()
 n=int(n)
 x=int( math.sqrt(n))
 if n%2==0:
    print n , "is an even number"
 else:
    for i in range(3,x+1,2):
        if n%i==0 :
           print " Composite",n, "div by" ,i ,"."
        else:
           print "PRIME"

This code runs fine if I enter an even but acts abnormal when I input an odd or prime integer. It identifies composite accurately. Irrespective of prime or composite odd it prints PRIME many times.(sometimes twice or thrice). The output is like:

Please enter a number to check if it is prime or not  53
PRIME
PRIME
PRIME
Please enter a number to check if it is prime or not  36
36 is an even number
Please enter a number to check if it is prime or not  21
Composite 21 div by 3 .
Please enter a number to check if it is prime or not  23
PRIME
Please enter a number to check if it is prime or not  37
PRIME
PRIME
Please enter a number to check if it is prime or not  

I think I have done some indentation error or implemented while loop incorrectly. please help.

Python if statement error

very new Python user here with limited programming experience. I have the following code,

if df['one'] >= df['two'].shift(1) and df['three'] <= df['two'].shift(1) \
        and df['stdnormprob'] > trigger1 and df['stdev'] > trigger2:
    df['execution']=1
else:
    df['execution']=0

and I get the following error when I try to execute it,

line 1121, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(),

a.item(), a.any() or a.all().

I'm not sure why this is occurring. The dataframe looks okay, with the exception that there are some Nan entries in there that I probably need to ignore. Any insight as to why this error is occurring would be much appreciated...Thank you!

How to repeat an operation after If statement ( back to top ) in Python 3

I just recently started writing code and using SO. I'm stuck. I've done a little research on how to repeat a whole operation but nothing seems to work. Any help will be greatly appreciated. I'm trying to loop this code so if there is an error in typing "YES" or "NO" the program will go back to the top and start over for a maximum of 10 times. Then maybe it could print "Overload, please restart".

This is the current code I'm working on:

answer1=input("Are you unhappy-YES OR NO").lower()
if answer1=="yes":
    print("Did you know God loves you?")
    print("God is great and forgiving.")
elif answer1=="no":
    print("Thats because God loves you!")
    print("God is great and forgiving.")
elif answer1=="":
    print("ERROR-Please answer Yes or No")
else:
    print("ERROR-Please answer Yes or No")

How to pop up answers to the questions in android studio?

I want to display on the screen answers to each question in the quiz everytime I will press the true button.

So here is my snippet of code in java:

private Question[] mQuestionBank = new Question[]{
        new Question(R.string.volcano, true),
        new Question(R.string.drinking_milk, true),
        new Question(R.string.woman_oscar, true),
        new Question(R.string.hurricanes, true),
        new Question(R.string.pyramids_of_giza, true),
        new Question(R.string.coca_cola, true),
        new Question(R.string.sputnik, true),
        new Question(R.string.napoleon_bonaparte, false),
        new Question(R.string.brazil_soccer, true),
        new Question(R.string.barack_obama, false),
};
private int mCurrentIndex = 0;
private boolean[] mIsCheater = new boolean[mQuestionBank.length];

private void updateQuestion() {
    int question = mQuestionBank[mCurrentIndex].getTextResId();
    mQuestionTextView.setText(question);
}

private void checkAnswer(boolean userPressedTrue) {
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
    int messageResId = 0;
    if (mIsCheater[mCurrentIndex]) {
        messageResId = R.string.judgment_toast;
    } else {
        if (userPressedTrue == answerIsTrue) {
            messageResId = R.string.correct_toast;
        } else {
            messageResId = R.string.incorrect_toast;
        }
    }
    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}

Thank you very much!

combining 2 if statement in excel (logic operator)

Hi guys is it possible to combine 2 if statement in excel?
i want to combine this if

IF('1 aug dem post'!F7=3,"X") 

with this if

IF('1 aug dem post'!$F$6='1 aug dem post'!F7,1,0)

i tried with or statement but it only return true or false. I need it to return 1,0 or X.
is there any way to do this or any function??
please advice thankss

I have an error in my if statement where only the if is ever run even if its false

var run = function projectileMotion() {
  var dispX = document.getElementById("displacementX").value;
  console.log(dispX)
  var dispY = document.getElementById("displacementY").value;
  var finVY = document.getElementById("finalVelocityY").value;
  var time = document.getElementById("time").value;
  var avrVX = document.getElementById("test").value;
  console.log(avrVX);
  var accelY = 9.8;


  if (dispX && finVY && dispY != "Unknown") {
    avrVX = (accelY * dispX) / finVY;
    time = dispX / avrVX;
    console.log("found it")
  } else if (dispY && avrVX && finVY != "Unknown") {
    dispX = 2 * (dispY * avrVX) / finVY;
    time = dispX / avrVX;
    console.log(2)
  } else if (finVY && dispX && avrVX != "Unknown") {
    dispY = (finVY * dispX) / (2 * avrVX);
    time = dispX / avrVX;
  } else if (avrVX && dispX && dispY != "Unknown") {
    finVY = 2 * (avrVX * dispY) / dispX;
    time = dispX / avrVX;
  } else if (dispY && avrVX != "Unknown") {
    dispX = avrVX * Math.sqrt(dispY / (0.5 * accelY));
    time = dispX / avrVX;
    finVY = 2 * (avrVX * dispY) / dispX;
    console.log("pie");
  } else if (dispX && dispY != "Unknown") {
    avrVX = dispX / (Math.sqrt(dispY / (0.5 * accelY)));
    time = dispX / avrVX;
    finVY = 2 * (avrVX * dispY) / dispX;
    console.log(39)
  } else if (dispX && avrVX != "Unknown") {
    dispY = (0.5 * accelY) * Math.pow((dispX / avrVX), 2);
    time = dispX / avrVX;
    finVY = 2 * (avrVX * dispY) / dispX;
  } else if (avrVX && finVY != "Unknown") {
    dispX = (avrVX * Math.pow(finVY, 2)) / (2 * accelY);
    time = dispX / avrVX;
    dispY = (finVY * time) / 2;
  } else if (dispX && finVY != "Unknown") {
    avrVX = ((2 * accelY) * dispX) / Math.pow(finVY, 2);
    time = dispX / avrVX;
    dispY = (finVY * time) / 2;
  } else if (dispX && avrVX != "Unknown") {
    finVY = Math.sqrt(((2 * accelY) * dispX) / avrVX);
    time = dispX / avrVX;
    dispY = (finVY * time) / 2;
  } else if (avrVX && time != "Unknown") {
    dispX = avrVX * time;
  } else if (avrVX && dispX != "Unknown") {
    time = dispX / avrVX;
  } else if (time && dispX != "Unknown") {
    avrVX = dispX / time;
  } else if (time && finVY != "Unknown") {
    dispY = (finVY * time) / 2;
  } else if (time && dispY != "Unknown") {
    finVY = (2 * dispY) / time;
  } else if (dispY && finVY != "Unknown") {
    time = (2 * dispY) / finVY;
  } else if (time != "Unknown") {
    dispY = (0.5 * accelY) * Math.pow(time, 2);
    finVY = accelY * time;
  } else if (dispY != "Unknown") {
    time = Math.sqrt(dispY / (0.5 * accelY));
    finVY = accelY * time;
  } else if (finVY != "Unknown") {
    time = finVY / accelY;
    dispY = (0.5 * accelY) * Math.pow(time, 2);
  } else {
    console.log("invalid")
  }
  document.getElementById("horizontalDisplacementInsert").innerHTML = dispX;
  document.getElementById("verticalDisplacementInsert").innerHTML = dispY;
  document.getElementById("horizontalVelocityInsert").innerHTML = avrVX;
  console.log(avrVX);
  document.getElementById("finalVerticalVelocityInsert").innerHTML = finVY;
  document.getElementById("timeInsert").innerHTML = time;

};
document.getElementById("inputCheckSubmit").onclick = run;
form {
  width: 400px;
  float: left;
}

#answersDiv {
  float: left;
}
<!DOCTYPE html>
<html>

<head>
  <title>
    Projectile Motion
  </title>
  <link rel="stylesheet" type="text/css" href="Projectile Motion.css"></link>
  <script>
  </script>
  <style>

  </style>
</head>

<body>
  <form method="post">
    <fieldset>
      <legend class="inputCheck" id="inputCheckLegend">Which of these do you know the value of?</legend>
      Reply "Unknown" for variables that you don't know
      <br/>
      <br/>
      <h2>
        Time
      </h2>
      <input class="inputCheck" id="time" type="text" name="time">
      <br/>
      <h2>
        Horizontal (x-axis)
      </h2>
      Displacement
      <br/>
      <input class="inputCheck" id="displacementX" type="text" name="displacementX">
      <br/> Velocity
      <br/>
      <input class="inputCheck" id="test" type="text" name="velocityX">
      <br/>
      <h2>
        Vertical (y-axis)
      </h2>
      Displacement
      <br/>
      <input class="inputCheck" id="displacementY" type="text" name="displacementY">
      <br/> Final Velocity
      <br/>
      <input class="inputCheck" id="finalVelocityY" type="text" name="fianlVelocityY">
      <br/>
      <input class="inputCheck" id="inputCheckSubmit" type="button" value="Submit" />
    </fieldset>
  </form>
  <div class="answersDiv" id="answersDiv">
    <h2 class="answers, answerPrompt" id="horizontalAccelerationAnswer">
      Horizontal Acceleration = 0.00
    </h2>
    <h2 class="answers, answerPrompt" id="verticalAccelerationAnswer">
      Vertical Acceleration = 9.81
    </h2>
    <h2 class="answers, answerPrompt" id="horizontalDisplacementAnswer">
      Horizontal Displacement =
      <span id="horizontalDisplacementInsert"></span>
    </h2>
    <h2 class="answers, answerPrompt" id="verticalDisplacementAnswer">
      Vertical Displacement =
      <span id="verticalDisplacementInsert"></span>
    </h2>
    <h2 class="answers, answerPrompt" id="horizontalVelocityAnswer">
      Horizontal Velocity =
      <span id="horizontalVelocityInsert"></span>
    </h2>
    <h2 class="answers, answerPrompt" id="initialVerticalVelocityAnswer">
      Initial Vertical Velocity = 0.00
    </h2>
    <h2 class="answers, answerPrompt" id="finalVerticalVelocityAnswer">
      Final Vertical velocity =
      <span id="finalVerticalVelocityInsert"></span>
    </h2>
    <h2 class="answers, answerPrompt" id="timeAnswer">
      Time =
      <span id="timeInsert"></span>
    </h2>
  </div>
</body>
<script src='http://ift.tt/29q98ga'></script>
<script src="Projectile Motion.js"></script>

</html>

I have no clue what the error is please console.log()'s were only to help me find the error

jeudi 28 décembre 2017

Low speed of python using while ,for,if-else condition

Hi I have below code in python . I am comparing multiple columns to 1 single data each time based on certain flag value presence. Here two such sets are shown. ST9 and ST1 I am using while loop,for and if-else condition. But it is taking almost 13 minutes to process. How can I increase the computation speed.

i=0
Reslt_9=[]

while i<len(xx):
    for val in xx.ST9:
      if val==4:
         xz = xx[['SV1','SV2','SV3','SV4','SV5','SV6','SV7','SV8','SV9','SV10','SV11','SV12']].eq(xx['G9'], axis=0).assign(no = True)
         i1 = xz.values.argmax(axis=1)
         Reslt_9 =  np.append(Reslt_9,xx['R9'][i] -xx[['PR1','PR2','PR3','PR4','PR5','PR6','PR7','PR8','PR9','PR10','PR11','PR12']].assign(no = np.nan).values[xx.index, i1][i])
      elif val==2:
         Reslt_9=np.append(Reslt_9,0) 
      i=i+1

a2=0
Reslt_1=[]
aa=read_data
while a2<len(aa):
# Debug area
    for val1 in aa.ST1:
      if val1==4:
           a = aa[['SV1','SV2','SV3','SV4','SV5','SV6','SV7','SV8','SV9','SV10','SV11','SV12']].eq(aa['G1'], axis=0).assign(no = True)
           a1 = a.values.argmax(axis=1)
           Reslt_1 = np.append(Reslt_1,aa['R1'][a2] - aa[['PR1','PR2','PR3','PR4','PR5','PR6','PR7','PR8','PR9','PR10','PR11','PR12']].assign(no = np.nan).values[aa.index, a1][a2])
      elif val1==2:
           Reslt_1 = np.append(Reslt_1,0)
      a2=a2+1
   .....................

Apply log and log1p to several columns with an if condition

I have a dataframe and I need to calculate log for all numbers greater than 0 and log1p for numbers equal to 0. My dataframe is called tcPainelLog and is it like this (str from columns 6:8):

$ IDD:  num  0.04 0.06 0.07 0.72 0.52 ...
$ Soil: num  0.25 0.22 0.16 0.00 0.00 ...
$ QAI:  num  0.00 0.50 0.00 0.71 0.26 ...

Therefore, I guess need to concatenate an ifelse statement with log and log1p functions. However, I tried several different ways to do it, but none has succeeded. For instance:

tcPainelLog <- tcPainel
cols <- names(tcPainelLog[,6:17]) # These are the columns I need to calculate

tcPainelLog$IDD   <- ifelse(X = tcPainelLog$IDD>0, log(X), log1p(X))

tcPainelLog[cols] <- lapply(tcPainelLog[cols], function(x) ifelse((x > 0), log(x), log1p(x)))

tcPainelLog[cols] <- if(tcPainelLog[,cols] > 0) log(.) else log1p(.)

I haven't been able to perform it and I would appreciate any help for that. I am really sorry it there is an explanation for that, I searched by many words but I didn't find it.

Best regards.

What is an efficient way to test a string for a specific datetime format like "m%/d%/Y%" in python 3.6?

In my pthon 3.6 application, from my input data I can receive datatimes in two different formats:

"datefield":"12/29/2017" or "datefield":"2017-12-31"

I need to make sure the that I can handle either datetime format and convert them to (or leave it in) the iso 8601 format. I want to do something like this:

#python pseudocode
import datetime
if datefield = "m%/d%/Y%":
  final_date = datetime.datetime.strptime(datefield, "%Y-%m-%d").strftime("%Y-%m-%d")
elif datefield = "%Y-%m-%d":
  final_date = datefield

The problem is I don't know how to check the datefield for a specific datetime format in that first if-statement in my pseudocode. I want a true or false back. I read through the python docs and some tutorials. I did see one or two obscure examples that used try-except blocks, but that doesn't seem like an efficient way to handle this.

Create new column variables based upon condition in R

I don't know why this is not working. I have tried it various ways and it just does not work. It's not that I get an error using the if-statements I made myself, but it doesn't apply right.

Basically, there is a column Data$Age and a column Data$Age2.

If Data$Age is value 50 - 100, I want Data$Age2 to say "50-100 Years" for that particular row.

Likewise, if Data$Age is 25-50, I want Data$Age2 to say 25-50 Years" for the rows to which it applies.

What would the cleanest way to go about doing this in R?

Thank you in advance.

Cumsum excluding some rows

I have a question linked to: Cumsum excluding current value How to apply cumsum excluding a certain customer.id? For instance:

order.id   customer.id      Apples   Peaches  Pears
1001       J Car Ltd            1       0       0
1002        Som Comp            1       2       0
1005       Richardson           0       0       1
1004       J Car Ltd            1       0       0
1003       J Car Ltd            2       0       0
1006       Richardson           1       0       1
1007        Aldridge            0       0       1
1008       J Car Ltd            0       0       1
1010        Som Comp            0       1       0

I want to apply cumsum to keep track of previous apple orders:

Fruits <- Fruits[order(Fruits$order.id), ]  #sort data
Fruits$prev_Apples<-with(Fruits, 
    ave(
        ave(Apples, customer.id, FUN=cumsum),  #get running sum per customer.id
        interaction(customer.id, order.id, drop=T), 
    FUN=max, na.rm=T) #find largest sum per index per seg
)

But I also want to exclude from my cumsum customer.id Som Comp. For him, I want the prev_Apples column to be equal to 0:

order id    customer id     Apples  Peaches Pears   Prev_Apples
1001      J Car Ltd             1           0       0       0
1002      Som Comp            **1**         2       0       0
1003      J Car Ltd             2           0       0       1
1004      J Car Ltd             1           0       0       3
1005      Richards              0           0       1       0
1006      Richards              1           0       1       0
1007      Aldridge              0           0       1       0
1008      J Car Ltd             0           0       1       4
1010      Som Comp              1           0       0     **0**

So I thought to add this line of code:

if(Fruits$customer id =='NULL'){
Prev_Apples = 0
return (Fruits$customer id)
}

But of course I get the error: “the condition has length > 1 and only the first element will be used”

I understood why I get the error, but how can I avoid it? Thanks in advance.

How to create a new column by appending values to a list from other columns in R

I would like to make a new column by appending to a list conditional on the values of other columns. If possible, I would like to do so in dplyr. Sample input and desired output is below.

Suppose a dataframe newdata:

col1 col2 col3 col4
dog  cat  NA   NA
NA   cat  foo  bar
dog  NA   NA   NA
NA   cat  NA   NA

Here is my desired output, with the new column newCol:

col1 col2 col3 col4 newCol
dog  cat  NA   NA   (dog, cat)
NA   cat  foo  bar  (cat, foo, bar)
dog  NA   NA   NA   (dog)
NA   cat  NA   bar  (cat, bar)

I have tried using ifelse within mutate and case_when within mutate, but both will not allow concatenation to a list. Here is my (unsuccessful) attempt with case_when:

newdata = newdata %>% mutate( 
    newCol = case_when(
        col1 == "dog" ~ c("dog"),
        col2 == "cat" ~ c(newCol, "cat"),
        col3 == "foo" ~ c(newCol, "foo"),
        col4 == "bar" ~ c(newcol, "dog")
        )
    )

I tried a similar approach with an ifelse statement for each column but also could not append to the list. Any help would be much appreciated.

I'm getting an error saying I've entered too many arguments in excel

I am trying to do a calculation on the fiscal year expenditure based on whether the contract ends within the fiscal year or if it starts within the fiscal year, then determine the number of months and multiply it by the monthly rate but I keep getting an error saying "too many arguments" I don't think I'm at 64 arguments but I'm a sometimes excel user here is the nested IF statement:

=IF([@[Contract End Date]]>=43190,[@[Annual Rate]],
IF([@[Role Start Date]]<42826,(((YEAR("2018-3-31")-YEAR([@[Role Start Date]]))*12+MONTH("2018-3-31")-MONTH([@[Role Start Date]]))*[@[Monthly Rate]])),
IF([@[Contract End Date]]<43190,(((YEAR([@[Contract End Date]])-YEAR("2017-4-1"))*12+MONTH([@[Contract End Date]])-MONTH("2017-4-1"))*[@[Monthly Rate]])))

My else didn't work

I don't know why my else didn't work, it's my first time that actually happened and i check console log. This is my code:

setTimeout(function() {
  var b = 2;
  var d = 80000;
  if ("div[class='resultInfo resultLose']") {
    setTimeout(function() {
      var a = ($("input[name='_4']").val().replace(/\s+/g, ''));
      var c = a * b;
      $("input[name='_4']").val(c);
      $("input[value='Play!']").click();
    }, 1000);
  } else if ("div[class='resultInfo resultWin']") {
    setTimeout(function() {
      $("input[name='_4']").val(d);
      $("input[value='Play!']").click();
    }, 1000);
  }
}, 4500);

I try to: 1. delete the setTimeout in if 2. delete the " if ("div[class='resultInfo resultWin']") "

This only use first if even the elseif is true, I don't know what to do :/

C++ Statement can be simplified

Apologies for the lame question. I am using Intellij Clion Student licensed version for my C++ curriculum. As a part of implementing an UnsortedList class, we had to write a method isInTheList to see if an element is present in the array. The class implementation goes as

bool UnsortedList::isInTheList(float item) {

    for (int i = 0; i < length; i++) {
        if (data[i] == item) {
            return true;
        }
        return false;
    }
}

However, the ide shows a coloured mark at data[i] == item with a popup saying

Statement can be simplified less... (Ctrl+F1) 
This inspection finds the part of the code that can be simplified, e.g. constant conditions, identical if branches, pointless boolean expressions, etc.

For a previous method to check if the list if empty, I used the following simplified form instead of if-else statement.

bool UnsortedList::isEmpty() {
    return (length == 0);
}

However, with iteration involved now, I cannot come up with a simplified statement in the former. Any help is much appreciated. Thank you.

Generating variables with a loop in Python from Matlab

I am trying to convert a code from Matlab to Python. In python I wrote:

age=np.arange(start_age, start_age+D, deltat)
For num in age:        this doesn't
if age[:]<(65):
    Y=1
    break
else
    Y=0
    break
    break
H = (1/r) * (1 - math.exp(-r * max(0, (65 - age[:])))
A = ((1 - theta) * r - rho) / theta + 0.5 * ((1 - theta) / theta ** 2) *(    _lambda **2)
g = (1/A) * (math.exp(A * (D - (age[:] - start_age))) - 1)# equation (A11)

What I am trying to do is the following: for age I need a series of integers that goes from 20 to 79; for Y i need that for every value in age, for number smaller that 65 i need a 1 and for every number bigger or equal than 65 i need a 0. H, A and g are simply functions.

I find two problems: firstly, it doesn't allow me to works with values inside age, secondly, the loop for Y doesn't work.

I have tried many different variants of this code, but I always get mistakes and I think the problem is on how I have built age.

Can somebody help me please?

Generate column in Rstudio if other columns are equal

I have two dataframes:

df1 <- data.frame('ID'=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 
              'invoice'=c(24000, 25000, 26000, 27000, 28000, 29000, 30000, 31000, 32000, 33000),
              'settle'=c(40000, 41000, 42000, 43000, 44000, 45000, 46000, 47000, 48000, 49000), 
              'amount'=c(10, 20, 30, 10, 20, 30, 10, 20, 30, 10), 
              'reason'=c(4, 5, 9, 4, 5, 9, 4, 5, 15, 8))

And:

df2 <- data.frame('ID'=c(1, 2, 4, 5, 7, 8, 11, 12), 
              'invoice'=c(40000, 41000, 43000, 44000, 46000, 47000, 40000, 41000),
              'settle'=c(24000, 25000, 27000, 28000, 30000, 31000, 24000, 25000),
              'amount'=c(10, 20, 10, 20, 10, 20, 10, 10), 
              'reason'=c(4, 5, 4, 5, 4, 5, 4, 4))

df1:

   ID invoice settle amount reason
   1   24000  40000     10      4
   2   25000  41000     20      5
   3   26000  42000     30      9
   4   27000  43000     10      4
   5   28000  44000     20      5
   6   29000  45000     30      9
   7   30000  46000     10      4
   8   31000  47000     20      5
   9   32000  48000     30     15
  10   33000  49000     10      8

df2:

ID invoice settle amount reason
 1   40000  24000     10      4
 2   41000  25000     20      5
 4   43000  27000     10      4
 5   44000  28000     20      5
 7   46000  30000     10      4
 8   47000  31000     20      5 
11   40000  24000     10      4
12   41000  25000     10      4

So I'd like to generate a dummy variable in df1 from the following conditions:

if df1$ID == df2$ID
if df1$settle == df2$invoice
if df1$amount == df2$amount
if df1$reason == df2$reason

So if the conditions are met, my new column should be equal 1, else 0.

I've tried:

 df1$newvar <- ifelse(df1$ID == df2$ID & 
                      df1$settle == df2$invoice &
                      df1$amount == df2$amount &
                      df1$reason == df2$reason, 1, 0)

I get the warning message:

 "longer object length is not a multiple of shorter object length"

So I gues an ifelse isn't possible since my two dataframes aren't of the same size (more ID's in df1 than in df2).

Can you help me solve this problem?

In SPSS pr Stata I'd just use the IF-command, but R is pretty new to me!

Thanks! :)

if logic in pandas, Python3

I've got a Pandas Dataframe from which I want to compare two columns and create a new column with a calculation based off the result of the comparison. Logic would be the following:

If df['column1']>df['column2'] :
   df['New column']=(df['column1']+df['column2'])
else :
   df['New column']=(df['column1']+df['column2']+1)

I am fairly new to pandas and Python so I'm sure I'm getting the structure wrong. Could you guys pint me in the right direction?

Thanks!

mercredi 27 décembre 2017

Echo variable first and assign variable values later in php

I am echoing the $indicator before $total using if else condition.

But I am getting php error

Notice: Undefined variable: indicator.

How I can achieve this without getting any error and get my result which will be yellow according to the if else condition. Is it possible?

<?php 

$total=6;
echo $indicator;
echo $total;

if($total<5) {
    $indicator="red";
} else if($total>7) {
    $indicator="green";
} else {
    $indicator="yellow";
}

?>

Get the evaluation of if statements in Python pdb

I am new to pdb. I use python3 -m pdb myscript.py in the command line interface. I am currently using s to trace code step by step. There are many if statement in the code that I want to know what they are evaluated to while tracing.

The way I am doing now is p if-statement-that-I-am-interested-in to print them out. This works fine when the if statement is short but gets intimidating when the line is long. Is there a way to print out the evaluated results of if statements without efforts? Or should I look into other tools for the purpose?

I am currently copying these statements if they are too long.

Thanks in advance.

JavaScript if statement data-id

I am trying to validate that the time in my "if" statement. This is a javascript file. It's not able to add a new to-do.

validateFields() {
var self = this;
var good = true;

if(self.$el.find('.todo-name-input').val().trim().length<=0)
{
  good = false;
}

if (self.$el.find(State.getState().sectionID ==0))
{
  time = self.$el.find('.edit-todo[data-id=]' + State.getState().openSectionId + ('.todo-time-input').val().trim()
}

//var time = self.$el.find('.todo-time-input').val().trim();
if(time.length<=0) {
  good = false;
}

How to update line dynamically in VBScript?

I am writing a script, and I wanted to know how I can read a txt file and find the line and then replace it.

For example, if I have a txt file called ImportParms.txt which has some parameter lines in it that look like this:

cmdFile=E:\Jobs\UPCS\Parms\ImportParms.upcs_cmd
Process=StandardImport
LogFile=e:\JOBS\UPCS\Logs\ImportLog.txt
File=E:\jobs\UPCS\TestImportFile.txt
ImportRejects=No
RenameToOld=No
RenameDateStamp=No
ResultsReport="Public Reports\ImportResult"
LinkExisting=Custom1

I want to update the line that says File=something.txt every time it runs. So that instead of having

sCmd = sBotCmd & " file=""" & sUtilOut &""" " 

it will just say

sCmd = sBotCmd

From the part of my code that runs the exe which looks like this:

' Run processbot to update
Set oFile = oFSO.GetFile(sUtilOut)
if oFile.Size <> 0 then
   strFile=sWORK & "\parms\" & BOTPARMFILE
   Set objFile = objFS.OpenTextFile(strFile)
   Do Until objFile.AtEndOfStream
       strLine= objFile.ReadLine
       'if first for characters = "file" 
           'delete this line
           strFile.Write "file=" & sUtilOut
       'end if
   Loop
   objFile.Close 

   sBotCmd = """"& sWORK & "\" & BOTPROG & """ " _
             & " cmdFile=""" & sWORK & "\parms\" & BOTPARMFILE & """ "

   sCmd = sBotCmd
   Call OutMsg(isVerbose, isVerbose, sSysLog, _
              "Command: " & sCmd)
   iRetC = oShell.Run(sCmd,0,TRUE)
   Call OutMsg(isVerbose, isVerbose, sSysLog, _
              "RC: " & iRetC)
   If iRetC <> 0 Then 
            Call OutMsg(isVerbose, isVerbose, sSysLog, "Exiting with code "_ 
            & rcPROCBOT)
            wscript.quit(rcPROCBOT)
   end if
end if

How can i fix my simple calculator with python 3 please help me [on hold]

print("Python Taschenrechner")

while True:
    print("\nBitte wählen sie ihre Rechenart aus:")
    user = input("\nTippen sie \'Multiplikation' oder \'Division' oder 
    \'Addition' oder \'Subtraktion' ein")

    if user == "Addition" or user == "addition":
        num1 = float(input("Bitte geben sie eine Zahl ein:"))
        print("plus")
        num2 = float(input("Bitte geben sie eine weitere Zahl ein:"))
        result = num1 + num2
        print(result)
        continue
    elif user == "Subtraktion" or "subtraktion":
        num1 = float(input("Bitte geben sie eine Zahl ein:"))
        print("minus")
        num2 = float(input("Bitte geben sie eine weitere Zahl ein:"))
        result = num1 - num2
        print(result)
        continue
    elif user == "Multiplikation" or user == "multiplikation":
        num1 = float(input("Bitte geben sie eine Zahl ein:"))
        print("mal")
        num2 = float(input("Bitte geben sie eine weitere Zahl ein:"))
        result == num1 * num2
        print(result)
        continue
    elif user == "Division" or user == "division":
        num1 = float(input("Bitte geben sie eine Zahl ein"))
        print("geteilt durch:")
        num2 = float(input("Bitte gebe sie eine weitere Zahl ein:"))
        result == num1 / num2
        print(result)
        continue

this is my first try of creating a simple calculator with python. there are some parts like some inputs or prints that are written in german thats just because i am german. The program should ask the user for input and type in the desired arithmetic operation ( +-*/) for + and - it works well but when i enter multiplikation (multiplication) it does subtraction can somebody please explain it and tell me what i did wrong ?

Add validation/if else statements to public class functions PHP

Hi im trying to build a simple blog using PHP PDO but ive got a bit stuck on validation/if else because what used to happen in the no class messy version was it would say "This article does not exist" but now it just shows the page with empty boxes so i was wondering how i add if/else staements to classes to make it work and show the message when the id is not one that matches in the database

 public function fetch_data($pid){

    try{
    global $pdo;

    $query = $pdo->prepare('SELECT * FROM post where post_id = ? order by post_date desc');
    $query->BindValue(1,$pid);
    $query->execute();

    return $query->fetch();

    }
     catch(PDOException $e) {
      echo '{"error":{"text":'. $e->getMessage() .'}}'; 
      }
     }

Thats the public function bit of code and the article.php page code is:

<?php

include_once('functions/main.php'); 
$post  = new Main;
$check = new Main;
$check_login = $check->logged_in();

if(isset($_GET['id'])){
    $pid = $_GET['id'];
    $post = $post->fetch_data($pid);

    $query = $pdo->prepare("UPDATE post SET post_views = post_views + 1 WHERE post_id = ?");
$query->execute(array($pid));
    ?>
<html>
    <head>
        <title><?php echo $post['post_title'];?></title>
          <meta name="viewport" content="width=device-width, initial-scale=1">


      <style>
.customimage{
background: url('<?php echo $post['post_image'];?>') !important;
}
</style>


    </head>


<body>

          <div class="pusher">
    <!-- Site content !-->
<div class="ui inverted vertical masthead center aligned segment purple customimage">
 <div class="ui text">
      <h1 class="ui inverted header">
        <?php echo $post['post_title'];?></h1>
              <br>
              <div class="ui black inverted label"> <i class="calendar icon"></i><?php echo $post['post_date'];?></div><div class="ui black inverted label"><i class="user icon"></i> <?php echo $post['post_author'];?></div><div class="ui black inverted label"><i class="unhide icon"></i> <?php echo $post['post_views']?></div>

  </div>
</div>

<div class="ui divider hidden"></div>

<div class="ui container">
<div class="ui segments">
  <div class="ui segment purple">
  <h1 class="ui header">
  <div class="content">
    <?php echo $post['post_title'];?>
     </div>
</h1>
  </div>
    <div class="ui segment">
    <?php echo $post['post_content'];?>
  </div>
  <div class="ui secondary segment">
    <button class="ui labeled icon button">
  <i class="left arrow icon"></i>
  Return to Posts</button>
  </div>
</div>
</div>

</div>
    </body>
</html>

    <?php
}else{
    header('Location:index.php');
}

?>

And i cant figure out how to make it so that when you go to ?id=876799 it then says that article doesn't exist but currently its just blank.

Thanks all help appreciated + this is not a duplicate i cant find any answers anywhere!

else if (a != 65);

#include <iostream>
#include <Windows.h>
using namespace std;

void noret()
{

    for (int i = 1; i < 11; i++)
    {
        cout << "Line number : " << i << endl;
    }

    system("pause");
}

void StartProgram(string filename)
{
    ShellExecute(NULL, "open", filename.c_str(), NULL, NULL, SW_SHOWNORMAL);
}

int main()
{
    for (int a = 1; a < 100; a += 3)
    {
        cout << "The number is: " << a << endl;
        if (a == 65)
        {

            StartProgram("mspaint");
        }
        else if (a != 65);
        {
            StartProgram("devenv");
        }
    }
    system("pause");
    return 0;

}

Here is the code I made(I am still new to programming). Please ignore the void noret() part. The code is Fully working, but in the part with else if (a != 65), I want to make it open the program only if it isn't equal to 65.

The program counts from 1-100. a = a+3 where "a" is equal to 1. While it counts to 100, if "a" is never equal to 65 it will open "devenv". But the way I did it it's made that "devenv" will open to very number that isn't equal to 65. How can I make it so that it will open ONCE if throughout the counting it never was 65... Does it make any sense?

Consecutive if statements: order of execution

Here is my Python code:

my_constant = 5
my_constant_2 = 6
list_of_lists = [[3,2],[4,7]]

my_new_list = []

for i in list_of_lists:
    my_dict = {}
    for j in i:    
        if j > my_constant:
            my_dict["a"] = "Hello"
            my_dict["b"] = "Hello"
            print(my_dict)
            my_new_list.append(my_dict)
        if j > my_constant_2:
            my_dict["a"] = "Hello"
            my_dict["b"] = "Bye"
            print(my_dict)
            my_new_list.append(my_dict)


print(my_new_list)

Here are the results:

{'a': 'Hello', 'b': 'Hello'}
{'a': 'Hello', 'b': 'Bye'}
[{'a': 'Hello', 'b': 'Bye'}, {'a': 'Hello', 'b': 'Bye'}]

The first two lines of the results are according to my expectations, but the third line is not. I would expect this:

[{'a': 'Hello', 'b': 'Hello'}, {'a': 'Hello', 'b': 'Bye'}]

So it looks that when the loop waits for the second "if" before appending to my_new_list, and us such the my_new_list get twice the new my_dict.

I know that the below code solves the issue (ie moving the my_dict inside the "if"):

my_constant = 5
my_constant_2 = 6
list_of_lists = [[3,2],[4,7]]

my_new_list = []

for i in list_of_lists:
    for j in i:        
        if j > my_constant:
            my_dict = {}
            my_dict["a"] = "Hello"
            my_dict["b"] = "Hello"
            print(my_dict)
            my_new_list.append(my_dict)
        if j > my_constant_2:
            my_dict = {}
            my_dict["a"] = "Hello"
            my_dict["b"] = "Bye"
            print(my_dict)
            my_new_list.append(my_dict)


print(my_new_list)

However, in practice my_dict is not empty and a function is used to create it (and it takes some time). Also, there are more "ifs", so i prefer not to use the above code.

Is there a trick to get over it?

Thanks.

Add HTML breaker with PHP if statement

I have a PHP loop listing results from a database:

foreach($_SESSION['all'] as $result) {
echo $result;
}

What I have done is write an if statement in PHP so that every time 4 results have been outputted, execute a line of code. In order to do this I have declared '$i = 0;' outside of this loop and then inside the loop I have '$i++;'. I then say:

if ($i %4 == 0) {
//execute code inside this if statement
}

I then put a breaker inside this loop so that every 4 results, there would be a breaker ('<br />'). It looks like this:

if ($i %4 == 0){
echo "<br />";
echo $i;
}

When I look at the source code of the site the '<br />' is there but it doesn't move the rest of the information to another line. When I add a different line of code it shows, for example, if I print '<p>Hello</p>', it outputs 'Hello'. It just seems to be the '<br />' that doesn't work. This results in all the results after the first 4 being off the end of the screen.

Here is the whole page and a screenshot of the output:

<?php

session_start();

?>

<section class="hero is-dark is-halfheight is-bold">
<div class="hero-head">

</div>

  <div class="hero-body">

    <div class="container has-text-centered">

      <div class="columns">

      <?php

              $i = 0;

              foreach($_SESSION['all'] as $result) {

              echo '<div class="column is-3">';

              echo '<a href="#">';
              echo '<div class="box has-text-centered">';
              echo $result;
              echo '</div>';
              echo '</a>';

              echo '</div>';

              $i++;

              if ($i %4 == 0){

                echo "<br />";
                echo $i;

              }

              }

      ?>

      </div>

    </div>

  </div>

<div class="hero-foot">
  <?php echo $i; ?>
  <div class="container has-text-centered">
      <a class="button is-light is-small" href="add.php">
        Add Client
      </a>
    </div>
    <br>
</div>

</section>

And...

Screenshot of output in browser

Thanks in advance for any answers. Help will be greatly appreciated!

if statement doesn't work in for loop

Ok i have this problem: if doesn't want to work and i dont know why.

The program is supposed to take from a file some numbers, first indicates the number of numbers on the second line and say what is the minimum and maximum on that line.

#include <iostream>
#include <fstream>


using namespace std;

int main()
{
 ifstream f("file.in");
 ofstream g("file.out");
 int minim,x,maxim,i,n;

 f>>n;
 f>>maxim;
 minim=maxim;

 for(i=2;i<=n;i++){
    f>>x;
    if(minim > x)x=minim;
    if(maxim < x)x=maxim;
 }
    g << "min=" << minim;
    g << "\n" << "max=" << maxim;
    f.close();
    g.close();

return 0;
}

The problem is "if" doesn't work at all.

srry for bad english

Java If statement not returning expected result [duplicate]

This question already has an answer here:

I'm trying to get my hands dirty with JAVA, I'm currently using Eclipse as my compiler and when I'm trying to execute this code

    import java.util.*;
    public class HelloWorld {

    public static void main(String[] args) 
    {
        String password = null;
        Scanner in = new Scanner(System.in);
        System.out.println("Please Enter Your Name: ");
        String UserName = (String)(in.nextLine());
        if(UserName == "Michael")
        {
            System.out.println("Hello " + UserName);
        }
        else
        {
            System.out.println("Invalid User");
        }

    }

}

Everytime I run it, even with the correct name it says "Invalid User", the only way I've been able to get it to work is to hard set the if statement to Michael == "Michael", which for obvious reasons is not something I'd prefer to do.

I know Java.util.* is not exactly the most low-cost memory method but found it's minimal compared to simplicity sake.

Sum by date using "if" statement

I am trying to sum between two dates in a data frame using an "if" statement.

date = seq(as.Date("2000-01-01"), as.Date("2000-01-31"), by="days")
nums = seq(1, 1, length.out = 31)
df = data.frame(date, nums)

if(df$date >= as.Date("2000-01-01") && df$date <= as.Date("2000-01-07")){
  sum(df$nums)
}

However, the output is "31" rather than "7" as I would expect. Is there a better way to sum by date? I would like to use an "if" statement because I would like to apply this to a much larger dataset with many different columns and within different lengths of time.

If-statement put in for instruction

Given the 2 cases:

1.

if (n % 2 == 0)
    for(i = 1; i <= 10; i++)
             ...
else 
    for(i = 1; i <= 9; i++)
             ...

2.

for(i = 1; i <= 9 + (n % 2 == 0); i++)
          ... 

Is there a difference in time between the 2 cases? (Case 2) Verifying every step if n is an even number (or just an additional condition) should run the program a bit slower, am I correct?

Drop line in pandas df when string type cell's right characters don't match condition

I am working on a dataframe containing demographic data for every single U.S state and county.

FIPS    State   Area_Name   CENSUS_2010_POP ESTIMATES_BASE_2010 ...
01000   AL  Alabama         4779736         4780131             ...    
01001   AL  Autauga County  54571           54571               ...      
01003   AL  Baldwin County  182265          182265              ...
01005   AL  Barbour County  27457           27457               ...

...     ... ...             ...             ...                 ...

I would like to drop all the lines regarding counties in order to keep only lines regarding U.S states (that's a lot of lines to drop indeed!). My idea was to focus on the FIPS column and to keep only FIPSs ending with '000', which are corresponding to states. After converting the FIPS into strings, I tried the following:

for k in df.index:
    if df.iloc[k,0][-3:] != '000':
        df=df.drop(df.index[k])

I am getting the following error: single positional indexer is out-of-bounds.

Column names don't match table using SELECT variables as INSERT values

I created a stored procedure that would INSERT/UPDATE when necessary. I am using this method to evaluate if i have to insert or not:

INSERT INTO X
SELECT @A, @B, @C -- Exactly as the table, all nullables
WHERE NOT EXISTS (SELECT * from ... WHERE condition)

But i am receiving the

Msg 213, Level 16, State 1, Procedure ArtigoEAN_Remover, Line 48 [Batch Start Line 7] Column name or number of supplied values does not match table definition.

This is my complete code (i signaled line 48):

@ArtigoID AS varchar(14),
@TipoArtigo AS varchar(3),
@CodBarras AS varchar(24)

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
SET NOCOUNT ON;

    IF (@ArtigoID IS NOT NULL AND @TipoArtigo IS NULL) OR (@ArtigoID IS NULL AND @TipoArtigo IS NOT NULL)
    BEGIN
        PRINT 'Tem que escolher ArtigoID & TipoArtigo para remover código EAN da referência.'
        RETURN
    END
    --
    IF (@CodBarras IS NOT NULL) AND (@ArtigoID IS NOT NULL OR @TipoArtigo IS NOT NULL)
    BEGIN
        PRINT 'Escolher Código EAN apenas (Para remover esse código de barras de todas as referências) OU ArtigoID + TipoArtigo (remover todos os códigos EAN associados a essa referência)'
        RETURN
    END
    --
    IF @ArtigoID IS NOT NULL AND @TipoArtigo IS NOT NULL 
    BEGIN 

    UPDATE [s].[dbo].[FArtigo]
    SET CodBarras = ''
    WHERE ArtigoID = @ArtigoID AND TipoArtigo = @TipoArtigo AND CodBarras = @CodBarras
    -- LINE 48
    INSERT INTO [s].[dbo].[Infolog_ArtigoEAN] 
    SELECT @ArtigoID,@TipoArtigo,@CodBarras
    WHERE NOT EXISTS (SELECT * FROM [s].[dbo].[Infolog_ArtigoEAN] WHERE ArtigoID = @ArtigoID AND TipoArtigo = @TipoArtigo AND CodBarras = @CodBarras)
    -- Inserts above if nox exist, update below in any case.
    UPDATE [s].[dbo].[Infolog_ArtigoEAN] SET CodBarras = '' WHERE ArtigoID = @ArtigoID AND TipoArtigo = @TipoArtigo AND CodBarras = @CodBarras

    INSERT INTO [s].[dbo].[ArtigoEAN]
    SELECT @ArtigoID,@TipoArtigo,@CodBarras
    WHERE NOT EXISTS (SELECT * FROM [s].[dbo].[Infolog_ArtigoEAN] WHERE ArtigoID = @ArtigoID AND TipoArtigo = @TipoArtigo AND CodBarras = @CodBarras)
    UPDATE [s].[dbo].[ArtigoEAN] SET CodBarras = '' WHERE ArtigoID = @ArtigoID AND TipoArtigo = @TipoArtigo AND CodBarras = @CodBarras

    END
    --
    IF @CodBarras IS NOT NULL AND (@ArtigoID IS NULL AND @TipoArtigo IS NULL) 
    BEGIN

    UPDATE [s].[dbo].[FArtigo] SET CodBarras = '' WHERE CodBarras = @CodBarras
    UPDATE [s].[dbo].[Infolog_ArtigoEAN] SET CodBarras = '' WHERE CodBarras = @CodBarras
    UPDATE [s].[dbo].[ArtigoEAN] SET CodBarras = '' WHERE CodBarras = @CodBarras

    END
END

So my question is, why is it trying to do the INSERT after line 48 when i am just ALTERING (saving) the procedure, i'm not even running it with parameters.

mardi 26 décembre 2017

Invalid Syntax - Questions and Answers don't work?

def menu():
    print ("\nthis is the menu")
    print ("is it truly though?")
    print ("'hai!' boop 'this is normal.'")
    print ("1 - a.\n2 - b.\n3 - c.\n4 - d.")
    action3 = input("Hi! ")
    *action3 = int(action3)*
    if action3 == 1:
        print ("\n'hello' hey")
        print ("eh")
        menu()

I've written this in Python 3.6.1, and I've tried to make it as simple as I can.

I've checked this as much as I can and I can't figure out what's wrong with it, however my... Python representing program thing keeps on flagging it as incorrect. I can't check it in my other one because it's currently malfunctioning and I'd like to know what's going on.

If you couldn't tell from the stars, the 'error' is in the seventh line down.

Is it wrong? If so, how?

Thank you in advance!

Why does this loop go back to the beginning?

import java.util.ArrayList;
import java.util.Scanner;

class SteppingStone4_Loops {

    public static void main(String[] args) {
       Scanner scnr = new Scanner(System.in);
       String recipeName = "";
       ArrayList<String> ingredientList = new ArrayList();
       String newIngredient = "";
       boolean addMoreIngredients = true;

       System.out.println("Please enter the recipe name: ");
       recipeName = scnr.nextLine();


       do {           
           System.out.println("Would you like to enter an ingredient: (y or n)");
           String reply = scnr.next().toLowerCase();

           /**The code should check the reply:
            *   "y" --> prompt for the ingredient and add it to the ingredient list;
            *   "n" --> break out of the loop;  
            *   anything else --> prompt for a "y" or "n"
            */

          while (true) {
             if (reply.equals("y")) {
               System.out.println("Enter ingredient name: "); 
               newIngredient = scnr.next();   
               ingredientList.add(newIngredient);
             break;
           }
             else if (reply.equals("n")) {
                System.out.println("Goodbye!");
                break;
             }

            else  
               break;
           }


            } while (addMoreIngredients);
           for (int i = 0; i < ingredientList.size(); i++) {
           String ingredient = ingredientList.get(i);
           System.out.println(ingredient);
       }
    }
}

When ran, the program returns this:

Please enter the recipe name:
Polenta
Would you like to enter an ingredient: (y or n)
y
Enter ingredient name:
Salt
Would you like to enter an ingredient: (y or n)
n
Would you like to enter an ingredient: (y or n)
5
Would you like to enter an ingredient: (y or n)

Why doesn't it break when reply = n? Why does it go back to the "Would you like to enter an ingredient"? Can someone pinpoint my mistake or perhaps suggest a different way? Thanks

2 equalities on an IF conditional like in python

I'm starting to learn javascript for front-end programming, being python my first language to learn completely.

So I'm trying to solve a while loop excersise that console-logs every number from 50-300 that is divisble by 5 and 3.

So in python i would do this:

i = 50
while i < 301:
    if i % 5 == i % 3 == 0:
        print(i)
    i += 1

And works flawlessly. I know you could use and and operator but the whole point of this question is to avoid using it.

So I try the same thing in javascript

var i = 50;
while (i < 301){
    if (i % 5 === i % 3 === 0){
        console.log(i);
    }
    i ++;
}

And somehow that wont work. However, with an && operator it does. Are double equalities in javascript not allowed? If they are, what am I missing?

Java Strings to Booleans

import java.util.Scanner;

public class ChatBot {

    public static Scanner user_input;

    public static void main(String[] args) {

        user_input = new Scanner(System.in);

        String first_name;
        System.out.println("First name please?");
        first_name = user_input.next();

        String last_name;
        System.out.println("Last name please?");
        last_name = user_input.next();

        String full_name;
        full_name = first_name +" " + last_name;

        System.out.println("Hello, " + full_name);

        String greeting;
        greeting = "How are you doing?";

        System.out.println(greeting);

        String first_convers;
        // What do I add here to make an if and else statement?
        first_convers = user_input.next();
    }

}

I am trying to create an if-else statement in the commented area so that if the user inputs "good," then something is printed out and if the user inputs "bad," then something else is printed out. I am using Eclipse Java editor, which is saying:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from String to boolean

at ChatBot.main(ChatBot.java:30)

So basically I can't convert a string to a Boolean. Could you please help me in doing this? Thank you in advance!

Can you compared a Variable to a Data Type?

int user_choice;
cout << "Enter a number from 1-10: ";
cin >> user_choice;

if (user_choice == int)//int being a data type
   cout << "Is an integer";

else
  if (user_choice == char)// char being a data type
      cout << "Is a character";

Can something like this be done? and how?

I want my stored procedure to only populate one instance of a name

I'm creating a stored procedure that populates two tables tblAirport and tblCountry. tblCountry gets its country names from tblAirport but I only want one instance of the country name to show up in `tblCountry. So far for my stored procedure I have this

`DECLARE @PK INT = (SELECT PK FROM tblAirport WHERE strName = @strName)

IF @PK IS NULL INSERT INTO tblAirport (ICAOCode,IATACode,strName,strCity,strCountry,degLat,minLat,secLat,Equator,degLong,minLong,secLong,Meridian,strElevation) VALUES (@ICAOCode,@IATACode,@strName,@strCity,@strCountry,@degLat,@minLat,@secLat,@Equator,@degLong,@minLong,@secLong,@Meridian,@strElevation) SET @PK = (SELECT PK FROM tblAirport WHERE strName = @strName);

IF EXISTS (SELECT * FROM tblCountry WHERE strCountry = @strCountry) SET @strCountry = @strCountry + 'x'

INSERT INTO tblCountry (strCountry) VALUES (@strCountry)`

I tried using IF EXISTS (SELECT * FROM tblCountry WHERE strCountry = @strCountry) SET @strCountry = @strCountry + 'x' just to show any duplicate countries but I don't know how to eliminate the duplicates from my table. I'm new to SQL and I've only learned the IF EXISTS function. Any suggestions would be great. Thank you!

Creating Multiple If, And, Or Statements

I am trying to create a formula for tracking candidates who are clear, not clear, or pending for hire. The result is based on a combination of answers that we type in columns E and G. Here is my formula:

=IF(E3="Fail",IF(G3="Fail","Not Clear"),IF(E3="Clear",IF(G3="Neg","Completed"),IF(e3=”Pending”,If(g3=”Pending”,”Pending”),IF(e3=”Pending”,if(G3=”Neg”,”Pending”),if(e3=”Clear”,if(g3=”Pending”,”Pending”),If(e3=”Pending”,if(g3=”fail”,”Not Clear”),If(e3=”Fail”,If(G3=”Pending”,”Not Clear”),if(e3=”Fail”,If(g3=”Neg”,”Not Clear”),if(e3=”Clear”,If(g3=”Fail”,”Not Clear”,”Pending”))))))))))

I've tried a less involved formula, but it doesn't give me the correct answer for anything with "Fail" in E or G. =IF(E11="Fail",IF(G11="Fail","Not Clear"),IF(E11="Clear",IF(G11="Neg","Completed","Pending"),IF(E11="Pending",IF(G11="Pending","Pending"))))

I've tried it with the IF/OR statement, and also with the IF/And Statements, but getting error messages.

I've tried to build a Matching table on a separate tab called "lookup" to do a match lookup, but I'm not that experienced with that formula.

Any help is appreciated as I am trying to streamline as well as improve upon our current process here on our team.

Excel - Multiple Conditions with 2 variables

I am working on a excel data set whereby I have two variables - 1) One time Spend 2) Installment Spend. Now, the observations under these two variables contain 4 possibilities. A - One time Spend>0,Installment Spend=0 B - One time Spend=0,Installment Spend>0 C - One time Spend=0,Installment Spend=0 D - One time Spend>0,Installment Spend>0. I want to create a new variable called Spend type which can classify the Spend based on A-Onetime Spend, B-Installment Spend, C-No Spend, D-Both One time and Installment. Can anybody help me with creating this new variable in excel?

enter image description here

Cant Detect if mouse button is held or just tapped once

Well i made a bunny that teleports on tap and i want to make it so if you hold for more than 0.3f a bubble activates and protects it i tried multiple code variates but i cant get it to work in some situation the bunny teleports and activates the bubble after and in others it doesnt i know its something simple and i just have to adjust the if / else if so i will be thankfull for eny help

using UnityEngine;
using System.Collections;

public class tap : MonoBehaviour {
// Use this for initialization
public GameObject Bunny;
public GameObject BunnyUpEffect;
public GameObject BunnyDownEffect;
public static bool IsHeld = false;
float TimeHeld = 0f; 
void Start () {
}

// Update is called once per frame
void Update () {

    if (Input.GetMouseButton (0)) {
        TimeHeld += Time.deltaTime;
        if (TimeHeld > 0.3f) {
            BubbleScript.BubbleActive = true;
            IsHeld = true;
        }
    }

    else {
        BubbleScript.BubbleActive = false;
        IsHeld = false;
        TimeHeld = 0f;
        if (Input.GetMouseButtonDown(0) && IsHeld == false) {

            if (BunnyScript.BunnyAlive == true) {
                if (BunnyScript.RunBottom == true) {
                    if (Stats.Energy > 0) {
                        BunnyUpEffect.GetComponent<BunnyUpEffect> ().Up ();
                    }
                } else if (BunnyScript.RunBottom == false) {
                    BunnyDownEffect.GetComponent<BunnyDownEffect> ().Down ();
                }
                Bunny.GetComponent<BunnyScript> ().ChangePos ();
            }
    }
}
}
}

How can i use if/else statement in iMacros? (Captcha Control)

I want to use if/else statement in iMacros for captcha control. I have tried many times before. I made Macro 1 and Macro 2 and add if/else statement but it did not work. This is code ;

VERSION BUILD=8970419 RECORDER=FX
TAB CLOSEALLOTHERS
SET !EXTRACT_TEST_POPUP NO
SET !ERRORIGNORE YES
SET !TIMEOUT_PAGE 25
TAB T=1
URL GOTO= [ MY URL ]
TAG POS=1 TYPE=A ATTR=TXT:Skip<SP>Ad
SET !TIMEOUT_PAGE 120
WAIT SECONDS=7
FILEDELETE NAME=C:\Users\Dtractus\Desktop\deneme\captcha.png
ONDOWNLOAD FOLDER=C:\Users\Dtractus\Desktop\deneme\ FILE=captcha.png
TAG POS=1 TYPE=DIV ATTR=ID:adcopy-puzzle-image-captchaShortlink CONTENT=EVENT:SAVE_ELEMENT_SCREENSHOT
TAB OPEN
TAB T=2
URL GOTO=http://ift.tt/2pyMaec
TAG POS=1 TYPE=INPUT:FILE FORM=ACTION:http://ift.tt/2DTwJ3p ATTR=NAME:captcha CONTENT=C:\Users\Dtractus\Desktop\deneme\captcha.png
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://ift.tt/2DTwJ3p ATTR=NAME:key CONTENT=[ MY KEY]
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://ift.tt/2DTwJ3p ATTR=NAME:secret CONTENT=[ MY SECRET ]
TAG POS=1 TYPE=INPUT:SUBMIT FORM=ACTION:http://ift.tt/2DTwJ3p ATTR=*
SET !TIMEOUT_STEP 25
SET !EXTRACT NULL
TAG POS=1 TYPE=DECAPTCHA ATTR=* EXTRACT=TXT
TAB CLOSE
TAG POS=1 TYPE=INPUT:TEXT FORM=ID:link-view ATTR=ID:adcopy_response-captchaShortlink CONTENT=
WAIT SECONDS=3
TAG POS=1 TYPE=BUTTON FORM=ID:link-view ATTR=ID:invisibleCaptchaShortlink

After this code, if captcha is wrong, it gives a warning like this;

"The CAPTCHA was incorrect. Try again"

I want to check this warning after this code. If the captcha is correct I want to continue the code below. If captcha is wrong again, I want you to repeat captcha solve again.

SET !TIMEOUT_STEP 25
TAG POS=1 TYPE=A ATTR=TXT:Get<SP>Link
SET !TIMEOUT_PAGE 120
FILEDELETE NAME=C:\Users\Dtractus\Desktop\deneme\captcha.png
ONDOWNLOAD FOLDER=C:\Users\Dtractus\Desktop\deneme\ FILE=captcha.png
TAG POS=1 TYPE=DIV ATTR=ID:adcopy-puzzle-image CONTENT=EVENT:SAVE_ELEMENT_SCREENSHOT
TAB OPEN
TAB T=2
URL GOTO=http://ift.tt/2pyMaec
TAG POS=1 TYPE=INPUT:FILE FORM=ACTION:http://ift.tt/2DTwJ3p ATTR=NAME:captcha CONTENT=C:\Users\Dtractus\Desktop\deneme\captcha.png
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://ift.tt/2DTwJ3p ATTR=NAME:key CONTENT=[ MY KEY ]
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://ift.tt/2DTwJ3p ATTR=NAME:secret CONTENT=[ MY SECRET]
TAG POS=1 TYPE=INPUT:SUBMIT FORM=ACTION:http://ift.tt/2DTwJ3p ATTR=*
SET !TIMEOUT_STEP 25
SET !EXTRACT NULL
TAG POS=1 TYPE=DECAPTCHA ATTR=* EXTRACT=TXT
TAB CLOSE
TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:NoFormName ATTR=ID:adcopy_response CONTENT=
TAG POS=1 TYPE=INPUT:SUBMIT FORM=NAME:NoFormName ATTR=*

MYSQL complex IF NOT EXIST SELECT INSERT CLAUSE

I am making an attempt at writing a MySql conditional statement which then runs a set of commands, I keep coming up with error but enable to understand the issue. I have used recommendations from different topics here but still have no success, my last resort will be to run all queries individually which won't be efficient.

$SQL = "IF NOT EXISTS (SELECT id FROM members WHERE email = '$email' LIMIT 1) THEN

        INSERT INTO members (first, last, email )
        VALUES ('$first_name', '$last_name', '$email');
        SET @USER_ID = LAST_INSERT_ID();

        INSERT INTO babylon (user_id, crew )
        VALUES (@USER_ID, '$crew');

        INSERT INTO movement (badge, date)
        VALUES (@USER_ID, NOW())
        SET @BADGE_ROOM_CODE = LAST_INSERT_ID();

        INSERT INTO messages (thread_id, sender_id)
        VALUES (@BADGE_ROOM_CODE, '@USER_ID');

ELSE

        SELECT id AS USER_ID FROM members WHERE email = '$email' LIMIT 1
        SET @USER_ID = USER_ID;

        INSERT INTO movement (badge, date)
        VALUES (@USER_ID, NOW())
        SET @BADGE_ROOM_CODE = LAST_INSERT_ID();

        INSERT INTO messages (thread_id, sender_id)
        VALUES (@BADGE_ROOM_CODE, @USER_ID);

END IF";

mySQLQuery($SQL);

php foreach radio button with value from database in edit mode

So I have this table than you can choose which customer representative you want from the group. (Can only choose 1, so I use radio button).

My code is like:

<tbody>
      <tr>
      @foreach($customerDetails as $item)
           <td><input name="main_customer_id" type="radio"
           @if(empty($customer_group->main_customer_id)) 
                 value=""
                 @if($item->customer_id == 1)
                     checked
                 @endif
           @endif></td>
           <td></td>
           <td> </td>
           <td></td>
           <td></td>
           <td>  </td>
           <td></td>
           <td></td>
           <td></td>
      </tr>
      @endforeach
</tbody>

I assigned customer_id as value in radio button, I could use some code like

@if($customer_group->id == 1)
    checked
@endif

But the value is dynamic, How do I do it?

lundi 25 décembre 2017

Python Logical Expression If value == ( value1 or value2 ) [duplicate]

This question already has an answer here:

I would like some explanation about this part of code :

item = {"ninja":"bubulle"}

#Case1
if item["ninja"] == ( "bubulle" or "baballe"):
    print("It works here")

#Case2
if item["ninja"] == ( "baballe" or "bubulle"):
    print("It does not works here")

#Case3
if item["ninja"] in ["baballe","bubulle"]:
    print("It works here, but i understand this one :3")

I understand easely Case 3, but i don't understand why Case 2 does not work, can someone explain me ?

Thanks, BR, Bubble Knight

Return multiple values from array when if condition satisfies multiple times

I want to return multiple values from for loop and if my condition satisfies more than one time

for(var i=0;i<graphVariableCount;i++)
  {
     if(commandResponse.GenericName == graphVariables[i].variable.index)
     {
        return graphVariables[i].variable.index;
     }
  }  

In above code i am able to return only one value. If GenericName of graphVariable[i].variable.index is same for 4-5 variables. Then how am i able to return that values.

If statement in List-Python

Essentially, I'm creating a card game, that has a list that tracks all the card numbers. So I need an if statement to check if the list is in order from greatest to smallest, but I don't know how to do this.

PHP If or not woking in textbox

Hi!

So I have an if function and I'm using or in it. It's not working. When I entere texts in the textbox it doesn't say it's correct if it's correct.

It's a quiz sample file.

When I run it it only say correct if I wrote the first answer in the textbox and it doesn't say correct if I write the second answer.

   <?PHP
    $verbs = array(
        'Aller',
        
        
    );
    $verb = array_rand($verbs);
    $averb =  $verbs[$verb];
    $sujets = array(
        'Je',
        'Tu',
       
        
    );
    $sujet = array_rand($sujets);
    $asujet =  $sujets[$sujet];

    $negposs = array (
        
        'Positive',
        );
        $negpos = array_rand($negposs);
    $anegpos =  $negposs[$negpos];
        echo "$asujet + $averb => Sentence: $anegpos";
        echo '<form action="quiz.php" method="POST">';
        echo "<p>Write everything in lowercase</p>";
        echo "<input type='text' name='ans' requird>";
    echo '<p><input type="submit" value="Refresh Page"</p>';
    echo "</form>";
        
    //Check Answer
    $ans = $_POST["ans"];
    echo "<p>$ans</p>";
    if (isset($_POST["ans"])){
        if ($averb == "Aller"){
            if ($anegpos == "Positive"){
                if ($asujet == "Je"){
                    if ($ans == "je suis allé" || $ans == "je suis allée"){
                        echo "Correct!";
                        echo "<p>$averb</p><p>$asujet</p>";
                        
                    } else {
                        echo "Wrong";
                    }
                } elseif ($asujet == "Tu"){
                     if ($ans == "tu es allé" || $ans == "tu es allée"){
                        echo "Correct!";
                        
                    } else {
                        echo "Wrong";
                    }
                } elseif ($asujet == "Il/Elle/On"){
                     if ($ans == "il a allé" || $ans == "elle a allée" || $ans=="on a allé"){
                        echo "Correct!";
                        
                    } else {
                        echo "Wrong";
                    }
                } elseif ($asujet == "Nous"){
                     if ($ans == "nous sommes allés" || $ans == "nous sommes allées"){
                        echo "Correct!";
                        
                    } else {
                        echo "Wrong";
                    }
                } elseif ($asujet == "Vous"){
                     if ($ans == "vous êtes allés" || $ans == "vous êtes allées"){
                        echo "Correct!";
                        
                    } else {
                        echo "Wrong";
                    }
                } elseif ($asujet == "Ils/Elles"){
                     if ($ans == "ils sont allés" || $ans == "elles sont allées"){
                        echo "Correct!";
                        
                    } else {
                        echo "Wrong";
                    }
                }
            }
        }
    }
    ?>

Any help appreciated. Thanks Regards

Nesting if clauses vs cascade return vs assertion

When negative evaluation in if clause will cause a return call inside a function/method, what is more recommended in Python, to nest the if clauses or to utilise the inverse evaluation and call the function return? e.g.:

if required_condition_1:
    if required_condition_2:
        if required_condition 3:
            pass
        return 'error for condition 3'
    return 'error for condition 2'
return 'error for condition 1'

Or:

if not required_condition_1:
    # preparation...
    return 'error for condition 1'

if not required_condition_2:
    # preparation...
    return 'error for condition 2'

if not required_condition_3:
    # preparation...
    return 'error for condition 3'

# if runtime reaches this point it means that it has passed all conditions

I have also thought about assertion:

try:
    assert(required_condition_1)
    try:
        assert(required_condition_2)
        # do tasks
    except AssertionError:
        # error for condition 2
except AssertionError:
    # error for condition 1

Even though I think this last way is not pretty recommendable as in treating exceptions.

I know this might seem primarily opinion-based, but for me it is not since all languages have style guidelines that produce a more sustainable, scalable and readable environment depending on its characteristics and functionalities. I would like to know what if there is a recommended way of treating this matter inside methods and why.

Execute Code Between If and Else-if Statement in Java

I got this code:

if (conditionX) {

                    doX();
                }



else if (conditionY) {
                    boolean isSomethingTrue = findOutIfSomethingIsTrue();
                    if (anotherConditionIsTrue) {
                        doY();
                    }
                }


boolean conditionXYZ = checkIfXYZIsTrue();

else if (conditionXYZ != true) {  // <- eclipse wants me to delete this 'else' statement

                    doXYZ();

                }

When I run this code eclipse complains that "Syntax error on token "else", delete this token". I understand this is because I have the code:

boolean conditionXYZ = checkIfXYZIsTrue();

between both else if statements. But I cannot check the value of conditionXYZ unless I set the value of conditionXYZ in between both else if statements.

The only other similar question I found on SO is this one and it suggests to use two if statements. The problem is I don't want conditionXYZ to be evaluated if conditionY is true.

My other option is to use two if statements and add a return statement for each if statement. But I do not find this solution to be elegant in terms of code design.

My third option is to checkIfXYZIsTrue() before executing any of the if statements but this is not efficient because if conditionY is true we don't need to check conditionXYZ.

Any ideas?

Thanks in advance

R : Loop process takes so long, how can I inhance the speed of loop process?

#for one
setwd("C:/Users/jeongah/Desktop")
select_index <- read.csv("select_index.csv", header = TRUE)
select1_sum <- 0
for (j in 1:5205){

  select_index[j,16]<- 0
  select1_sum <- 0
for(i in 1:15){
  select1_sum <- select1_sum + select_index[j,i]
}
  select1<-(select1_sum/15)
  select_index[j,16]<- select1
}

#for two-------------------17
select2_sum <- 0
select2_subsum <- 0
for (j in 1:5205){

  select_index[j,17] <- 0 # 초기화
  select2 <- 0 # 초기화
   for(i in 1:14){
    select2_subsum <- 0 # 초기화
    for(k in i+1:15){
      select2_subsum <- select_index[j,i] # subsum 초기값 설정
      denon <- 1  # 분모 초기화
      if(select_index[j,i] <= select_index[j,k]){
        denon <- denon+1
        select2_subsum <- select2_subsum+select_index[j,k] # 분모 1 더해고 분자도 더해줌
        select2_sum <- select2_sum + (select2_subsum/denon)       # 평균낼 선택조합을 더함
      }

            else{
        select2_subsum <- select2_subsum # 그대로 
        select2_sum <- select2_sum + (select2_subsum/denon)       # 평균낼 선택조합을 더함
      }



    }
  }
  select2 <-(select2_sum*0.5/choose(15,2)) # 품목 수준으로 평균내기
  select_index[j,17]<- select2
  select2_sum <- 0 # 선택조합의 합 초기화
}



#for three---------------------------------------------------------------------------------------------18-----------

select3_sum <- 0
select3_subsum <- 0
select3_compare <- 0
j <- 0
i <- 0
k <- 0
l <- 0
for (j in 1:5025){

  select_index[j,18] <- 0 # 초기화
  select3 <- 0 # 초기화
  for(i in 1:13){
    select3_subsum <- 0 # 초기화
    denon <- 1  # 분모 초기화
    for(k in i+1:14){

      select3_compare <- select_index[j,i]
      select3_subsum <- select3_compare # subsum 초기값 설정

      for(a in 3:15){


       if(select3_compare <= select_index[j,a]){
         select3_compare <- select_index[j,a]
         denon <- denon+1
         select3_subsum <- select3_subsum+select3_compare
       }
        select3_sum <- select3_sum + (select3_subsum/denon)
      }

      if(select3_compare <= select_index[j,k]){
        select3_compare <- select_index[j,k]
        denon <- denon+1
        select3_subsum <- select3_subsum+select3_compare # 분모 1 더해고 분자도 더해줌
      }
      else{
        select3_subsum <- select3_subsum # 그대로 둠
      }

      select3_sum <- select3_sum + (select3_subsum/denon) # 평균낼 선택조합을 더함
    }
  }
  select3 <-(select3_sum/choose(15,3)) # 품목 수준으로 평균내기
  select_index[j,18]<- select3
  select3_sum <- 0 # 선택조합의 합 초기화
}

# for four -----------------------------------------------------------------------------19

select4_sum <- 0
select4_subsum <- 0
select4_compare <- 0
j <- 0
i <- 0
k <- 0
a <- 0
b <- 0
for (j in 1:5025){

  select_index[j,19] <- 0 # 초기화
  select4 <- 0 # 초기화
  for(i in 1:12){
    select4_subsum <- 0 # 초기화
    denon <- 1  # 분모 초기화

    for(k in i+1:13){
      select4_compare <- select_index[j,i]
      select4_subsum <- select4_compare # subsum 초기값 설정

      for(a in 3:14){

        for(b in 4:15){

          if(select4_compare <= select_index[j,b]){
            select4_compare <- select_index[j,b]
            denon <- denon+1
            select4_subsum <- select4_subsum+select4_compare
          }
          select4_sum <- select4_sum + (select4_subsum/denon)
        }

        }


        if(select4_compare <= select_index[j,a]){
          select4_compare <- select_index[j,a]
          denon <- denon+1
          select4_subsum <- select4_subsum+select4_compare
        }
        select4_sum <- select4_sum + (select4_subsum/denon)
      }

      if(select4_compare <= select_index[j,k]){
        select4_compare <- select_index[j,k]
        denon <- denon+1
        select4_subsum <- select4_subsum+select4_compare # 분모 1 더해고 분자도 더해줌
      }
      else{
        select4_subsum <- select4_subsum # 그대로 둠
      }

      select4_sum <- select4_sum + (select4_subsum/denon) # 평균낼 선택조합을 더함
    }
  }
  select4 <-(select4_sum/choose(15,4)) # 품목 수준으로 평균내기
  select_index[j,19]<- select4
  select4_sum <- 0 # 선택조합의 합 초기화


  # for five-----------------------------------------------------------------------------------20

  select5_sum <- 0
  select5_subsum <- 0
  select5_compare <- 0
  j <- 0
  i <- 0
  k <- 0
  a <- 0
  b <- 0
  for (j in 1:5025){

    select_index[j,20] <- 0 # 초기화
    select5 <- 0 # 초기화
    for(i in 1:12){
      select5_subsum <- 0 # 초기화
      denon <- 1  # 분모 초기화

      for(k in i+1:13){
        select5_compare <- select_index[j,i]
        select5_subsum <- select5_compare # subsum 초기값 설정

        for(a in 3:14){

          for(b in 4:15){

            for(c in 5:15){
              if(select5_compare <= select_index[j,c]){
                select5_compare <- select_index[j,c]
                denon <- denon+1
                select5_subsum <- select5_subsum+select5_compare
              }
              select5_sum <- select5_sum + (select5_subsum/denon)
            }


            if(select5_compare <= select_index[j,b]){
              select5_compare <- select_index[j,b]
              denon <- denon+1
              select5_subsum <- select5_subsum+select5_compare
            }
            select5_sum <- select5_sum + (select5_subsum/denon)
          }

        }


        if(select5_compare <= select_index[j,a]){
          select5_compare <- select_index[j,a]
          denon <- denon+1
          select5_subsum <- select5_subsum+select5_compare
        }
        select5_sum <- select5_sum + (select5_subsum/denon)
      }

      if(select5_compare <= select_index[j,k]){
        select5_compare <- select_index[j,k]
        denon <- denon+1
        select5_subsum <- select5_subsum+select5_compare # 분모 1 더해고 분자도 더해줌
      }
      else{
        select5_subsum <- select5_subsum # 그대로 둠
      }

      select5_sum <- select5_sum + (select5_subsum/denon) # 평균낼 선택조합을 더함
    }
  }
  select5 <-(select5_sum/choose(15,5)) # 품목 수준으로 평균내기
  select_index[j,20]<- select5
  select5_sum <- 0 # 선택조합의 합 초기화

It seems this code has no error, but it takes so long. I've heard there is a method to get the loop process faster. would you give me a hand? I wish I could upload the data but it's too big to upload. Full codes are stretched to the cases of 15 countries selection.

let me specify my question, if there are 15 countries, "a, b, c ... o". each countries has index value for each product from 2 to 7. and For product 1(there is no label for it, just numeric value), if we do with 3 countries, country A has 2, country B has 7 and country C has 4. the calculation process is like this. the first value would be 2. and the value of B is higher than A, so their average would be 2+7/2. but the value of C is lower than B so it would be thrown away. the number of cases according to the number of selected countries is 15 C(Combination) n The all calculation cases would be 2^15-1.

How to use loop for multiple if coniditions

labels[(x, y)] return a value on coordinate(x) and coordinate(y).
labels[(x, y)] value is actually representing a different shapes in image and after detection each shape is being saved as a different image. for every shape or component i am using multiple if condition for example if labels[(x, y)]==0: SAVE IT AS DIFFERENT IMAGE but number is increasing whenever there are more shapes in an image. so far i have used 7 if conditions. how can i solve this problem by only one if condition.

for (x, y) in labels:
                component = uf.find(labels[(x, y)])
                labels[(x, y)] = component
                print (format(x) +","+ format(y)+ " " +format(labels[(x, y)]))
                ###################
                if labels[(x, y)]==0:
                    Zero[y][x]=int(255)
                    count=count+1
                    if count<=43:
                        continue
                    elif count>43:
                        Zeroth = Image.fromarray(Zero)
                        Zeroth.save(os.path.join(dirs, 'Zero.png'), 'png')
                #############
                if labels[(x, y)]==1:
                    One[y][x]=int(255)
                    count1=count1+1
                    if count1<=43:
                        continue
                    elif count1>43:
                        First = Image.fromarray(One)
                        First.save(os.path.join(dirs, 'First.png'),'png')

    irs, 'First.png'),'png')