mercredi 31 octobre 2018

MS Access VBA Code on Form Field with Multiple If's to Prevent / Allow Entry Depending on Value Entered

Hello, please assist with the following:

I am trying to prevent end users from being able to enter a value in the txtPlantUsedGrams (PlantAmountUsed) field that is greater than the amount in the txtExtractionAmountAvailable (ExtractionAvailable) field, but allow entry when the txtPlantUsedGrams value is less than the amount in the txtExtractionAmountAvailable field.

The code is working in the case where PlantAmountUsed is greater than ExtractionAvailable as it triggers the msgbox and then sets the txtPlantAmountUsed field to zero. In the case where PlantAmountUsed is less than ExtractionAvailable it allows the value entered to stick (does not change it to 0), but only after the msgbox is triggered and I click ok. The ‘exit sub’ code I inserted after the first If is not working. Please help me so that the following code does not trigger the msgbox and instead exits the sub in the case where the PlantAmountUsed is less than the ExtractionAvailable. I am open to any / all ways to accomplish this. Thank you for any help:)

Location of VBA Code:

Event is being run in form (frmMedMaking) as an AfterUpdate event in the txtPlantUsedGrams field.

**VBA Code:**

Private Sub txtPlantUsedGrams_AfterUpdate()

Dim PlantAmountUsed As Integer
Dim ExtractionAvailable As Integer
Dim LResponse As Integer

PlantAmountUsed = Me.txtPlantUsedGrams
ExtractionAvailable = Me.txtExtractAmountAvailable.Value
LResponse = MsgBox("Plant Amount Used must be less than Extraction 
Available", vbOKOnly + vbCritical, "Available Extraction Amount Exceeded")

If PlantAmountUsed < ExtractionAvailable Then Exit Sub
    If PlantAmountUsed > ExtractionAvailable Then
    If LResponse = vbOK Then Me.PlantAmountUsed.Value = 0
End If

End Sub

Using Javascript if else inside MVC .cshtml page

Is there a way to use if else statment inside MVC cshtml page

 <div class="primary-content">
            if(DetectIE())
            {
            <embed data-bind="attr: { src: data.files()[currentPage()] + '#toolbar=0&amp;navpanes=0&amp;scrollbar=0' }" type="application/pdf" style="width: 100%; height: 800px !important;">
            }
            else
            {
            <object data-bind="attr: { data: data.files()[currentPage()] + '#toolbar=0&amp;navpanes=0&amp;scrollbar=0' }" type="application/pdf" width="100%" height="600px"></object>
            }
        </div>

I have a javascript code to detect if the current browser is Internet explorer or not . If it is a IE then <embed> tag is used otherwise <object> tag is used.

Any suggestions or help would be appreciated.

Thanks in advance

IF(ISERROR combined with (Mod(Month

I have a formula that matches a start month to a horizontal calendar range. This is the formula: =IF($I$17>=$F18,IF(MOD(MONTH($I$17)-MONTH($F18),$D18)=0,$E18,0),0)

When the match is found it takes a defined value and enters the value in that month. It also then extrapolate the same value every n number of months. This n number of months is defined.This is what the result looks like for the above formulaPay $375 every 2nd month starting in Nov 18

The problem I can't fix is when the "Pay every # months" is blank the result is #DIV/0!. The month frequency is blank I know that it should be fixed by using the IFERROR or IF(ISERROR function but I just can't seem to get it right. Any help will be welcomed please

OR combinator not working in Java IF statement [on hold]

if (key != (VK_RIGHT || VK_DOWN)) //in this line bluej saying that's not correctly written. i want when the user is not pressing the down or up arrow it makes the error sound.
{
playSound("error");
}

i want when the user is not pressing the down or up arrow it makes the error sound. but in bluej it shows me that the || is not working.

Check if string is starting with prefix

I would like to check with javascript if array items starts with the word "prefix".

So far I've done something like this:

let array = ["prefix-word1", "prefix-word2"];

array.forEach(function(element) {
      if (element.lastIndexOf('prefix', 0) == 0) {
        console.log('prefix');
      }
    }

For some reason I keep get an error that prefix is not defined. Please help.

VBA- If and for loop data not displaying correctly

I am trying to compare data between two columns (C57BL/6J REF) and (DBA/2J REF) against column (F64870). When I write if condition if the first statement is true it should stop the iteration and if statement is false it should go to elseif condition. But once I execute the code my results are not correct.

Sub getData()

Dim i As Long
Dim j As Long
Dim lastRow As Long
Dim data As Boolean


lastRow = Cells(Rows.Count, "A").End(xlUp).Row

j = 4
data = False

    For i = 3 To lastRow

        If Sheet1.Range("_C57BL_6J_REF").Cells(i, j) = Cells(i, j) Then

            Cells(i, j) = "A"
            data = True

        ElseIf Sheet1.Range("DBA_2J_REF").Cells(i, j) = Cells(i, j) Then
                Cells(i, j) = "B"
                data = True
         ElseIf Range("_C57BL_6J_REF").Cells(i, j) = "N" And Sheet1.Range("DBA_2J_REF").Cells(i, j) = "N" Then
                Cells(i, j) = "P"

        End If


     Next i

End Sub

enter image description here

C57BL/6J REF DBA/2J REF F64870 Expected result What I got

T C T A B C C C A A T T T A A A A A A A A A A A A C C C A A N N G P B N N N P P N N C P A N N N P P N N C P C N N C P A N N N P P N N N P P N N N P P N N N P P

Replace Value with another value in same column by Group

I have a dataset below:

       Date    Group  Value
 2015-02-15        A     10
 2015-02-23        A    422
 2015-03-02        A     89
 2015-02-15        B     32
 2015-02-23        B     11
 2015-02-15        C     30
 2015-03-02        C      2

I want to make a rule where, for each group, if a value appears for 2015-02-15, replace that value with the value of Date 2015-03-02 by group.

Expected output:

       Date    Group  Value
 2015-02-15        A     89    <----replaced
 2015-02-23        A    422
 2015-03-02        A     89
 2015-02-15        B     32    <----not replaced since 2015-03-02 doesn't exist
 2015-02-23        B     11
 2015-02-15        C      2    <----replaced
 2015-03-02        C      2  

IF EXISTS (check if json object contains unique id), UPDATE table, ELSE INSERT into table

I want to use IF EXISTS in my query to check whether an object contains a "seqId" or not. I'm trying to update or insert into a table from OPENJSON. This json object @identObj has an array of objects, some objects may have a "seqId," and some might not. The ones that have a "seqId" should update into the "case_ident_to_inv" table, if the "seqId" does not exist it should insert into that table, the "case_ident_to_inv" table. The output of inserting into the table is a unique seqId. I tried implementing an IF EXISTS statement and I thought the syntax was correct but I'm getting this error:

Incorrect syntax near 'IF'.

DECLARE @identObj NVARCHAR(MAX) = N'[
  {  
    "investigators": [
         {"importId": 177, "userId": 120, "invTypeCd": "LI", "seqId": 50}, 
         {"importId": 177, "userId": 124, "invTypeCd": "SI", "seqId": 50}, 
         {"importId": 177, "userId": 120, "invTypeCd": "RV", "seqId": 50}, 
         {"importId": 177, "userId": 123, "invTypeCd": "SI"},
     ]
   }
]';

Data for "case_ident_to_inv" table

+------------+--------+-------------+---------------+-------+
|  importId  | userId |  invTypeCd  |  caseIdentId  | seqId |
+------------+--------+-------------+---------------+-------+
| 177        | 120    | LI          | 10200         | 50    | 
| 177        | 124    | SI          | 10200         | 51    | 
| 177        | 120    | RV          | 10200         | 52    |
| 177        | 123    | SI          | 10200         |       |<--- seqId OUTPUT AFTER INSERT
+------------+--------+-------------+---------------+-------+

The caseIdentId and importId will always be the same, there can be identical userId's and invTypeCd's, seqId is always unique.

Stored Procedure

select I.*
INTO #tmpInvs
FROM OPENJSON(@identObj)
WITH (
    invs NVARCHAR(MAX) AS JSON
) AS caseIdentInvs
CROSS APPLY OPENJSON (caseIdentInvs.invs)
WITH (
    userId INT,
    invTypeCd CHAR(5),
    importId INT,
    seqId INT
) I;

WITH cte AS
(
    SELECT i.*,ci.case_ident_id AS case_ident_id, ki.inv_type_name AS inv_type_name
    FROM #tmpInvs i
    INNER JOIN case_idents ci ON i.importId=ci.import_id
    INNER JOIN kdd_inv_type ki ON i.invTypeCd=ki.inv_type_cd
)

IF EXISTS (SELECT i.seqId FROM #tmpInvs i WHERE i.seqId != NULL)
UPDATE T
SET
    inv_id = ct.userId,
    inv_type_cd = ct.invTypeCd,
    inv_type_name = ct.inv_type_name
FROM case_ident_to_inv T
INNER JOIN cte AS ct ON ct.case_ident_id = T.case_ident_id

WHERE seq_id = ct.seqId

ELSE

INSERT INTO case_ident_to_inv(inv_id, case_ident_id, inv_type_cd, inv_type_name)
SELECT userId, case_ident_id, invTypeCd, inv_type_name
FROM cte

How to display smallest and largest number from user input without an array

Is there a way that I could display the smallest and largest numbers that the user inputs without using an array? The user can input as many numbers as they want to until they decide to exit the loop. So if the user decided to input 4 numbers, lets say 4, 16, 3, 21. How would I go about it? This needs to work for however many numbers there are, for example the next person who uses the program could input 10 numbers. So, there is no guessing how many numbers a person inputs. The program itself uses a while loop.

So far the code is:

using namespace std;

int main() 
{
float game = 1,   
    score, 
    total = 0, 
    average; 

    cout << "Enter the score\n"; 

    cout << "Type -1 when you have entered all the scores for each 
    game.\n\n"; 

    cout << "Enter the score for game " << game << ": ";  
    cin >> score;

while (score != -1) 
{ 
total = total + score;
game++;  
cout << "Enter the score for game " << game << ": ";   
cin >> score; 
if (score == -1) {
game--;
}
average = total / game;
}    

cout << "\nThe total score is " << total << endl;

cout << "\n The average score is " << average << endl;

system("PAUSE");
return 0;
}

Prolog if-then-else constructs: -> vs *-> vs. if_/3

As noted in another StackOverflow answer that I can't seem to find anymore, this pattern emerges frequently in practical Prolog code:

pred(X) :-
    guard(X),
    ...
pred(X) :-
    \+ guard(X),
    ...

and many people try to condense this to

pred(X) :-
    (guard(X) ->
    ...
    ;
    ...).

However as we all know, the arrow structure destroys choice points and isn't logical.

In Ulrich Neumerkel's Indexing dif/2, a predicate called if_/3 is proposed that is monotonic and logical, however in the paper he mentions another construct which caught my eye:

The *-> construct functions exactly like the unsugared guard clause example above, and thus it seems perfect for my uses as I don't want to have a reified condition which is required by if_/3 and I don't care about extra choice points that much. If I'm not mistaken, it offers the same semantics as if_/3 but without the requirement of adding the "reification" to the condition predicate.

However in the SWI documentation for it, it claims that "this construct is rarely used," which seems weird to me. *-> seems to me like it's strictly better than -> when you're trying to do pure logical programming. Is there any reason to avoid this structure, or is there an even better alternative to the entire guard clause / negated guard clause pattern?

Python; If statements, For Loops, File Reading

To be clear, I am not asking anyone to do this for me. I am simply asking a question seeking guidance so I can continue working on this.

We are given a file that gives various weights of packages;

11
25
12
82
20
25
32
35
40
28
50
51
18
48
90

I have to create a program that will count the amount of packages, Categorize them into Small, Medium, and Large, and find the average of the weights. I know I have to use If statements, and for loops to accumulate the weight count and categorize them among each category.

The terms for what is small, med, and large is as follows;

Small < 10 lbs

Medium >= 10 lbs. and < 30 lbs

Large >= 30 lbs.

If no packages of a weight class are entered, report the message “N/A” instead of an average (if you try to divide by 0 you will get an exception).

This is the code I have so far, I cant figure out if I have to include a for loop after the if, elif, and else. Or if what I have is on track.

infile = open("packages.txt", 'r')
count = 0
line = infile.readline()
weight = int(line)
for line in infile:
    if weight < 10:
        count = count + 1
        weight = weight + int(line)
        while weight < 10:
            try:
                avg = weight / count
            except ValueError:
                print("N/A")
    elif weight >= 10:
        if weight < 30:
            weight = weight + int(line)
            count = count + 1
            avg = weight/count
    else:
        weight = weight + int(line)
        count = count + 1
        avg = weight/count

The output has to look something like this

Category    Count    Average
Small       0        N/A
Medium      7        19.9
Large       8        53.5

Again, I am not looking for someone to do this for me. I am looking for the next step and/or tweaks to what I currently have to be able to continue forward. Thank you!

PowerShell: Looping through an .ini file

I'm working on a PowerShell script that will do the following:

  1. Use a function to grab the ini data and assign it to a hashtable (basically what Get-IniContent does, but I'm using one I found on this site).
  2. Check the nested keys (not the sections, but the keys of each section) to see if the value "NoRequest" exists.
  3. If a section contains a NoRequest key, and ONLY IF the NoRequest value is false, then I want to return the name of the section, the NoRequest key, and the key's value. For example, something like "Section [DataStuff] has a NoRequest value set to false." If a section doesn't contain a NoRequest key, or the value is set to true, then it can be skipped.

I believe I've accomplished the first two parts of this, but I'm unsure of how to proceed with the third step. Here's the code I have so far:

function Get-IniFile 
{  
    param(  
        [parameter(Mandatory = $true)] [string] $filePath  
    )  

    $anonymous = "NoSection"

    $ini = @{}  
    switch -regex -file $filePath  
    {  
        "^\[(.+)\]$" # Section  
        {  
            $section = $matches[1]  
            $ini[$section] = @{}  
            $CommentCount = 0  
        }  

        "^(;.*)$" # Comment  
        {  
            if (!($section))  
            {  
                $section = $anonymous  
                $ini[$section] = @{}  
            }  
            $value = $matches[1]  
            $CommentCount = $CommentCount + 1  
            $name = "Comment" + $CommentCount  
            $ini[$section][$name] = $value  
        }   

        "(.+?)\s*=\s*(.*)" # Key  
        {  
            if (!($section))  
            {  
                $section = $anonymous  
                $ini[$section] = @{}  
            }  
            $name,$value = $matches[1..2]  
            $ini[$section][$name] = $value  
        }  
    }  

    return $ini  
}  

$iniContents = Get-IniFile C:\testing.ini

foreach ($key in $iniContents.Keys){
    if ($iniContents.$key.Contains("NoRequest")){
        Write-Output $iniContents.$key.NoRequest
    }
}

When I run the run the above code, it gives me the following expected output:

true
true
true
false

I know the INI file I'm testing with has four instances of NoRequest, and I know those are the values of them. I'm just not sure how to get the section name paired with each section that contains the NoRequest = false value while ignoring the true values.

This code snippet causes variables to give me a syntax error afterward

My code starts with:

pcperception = input("What is your character's current perception?")
if pcperception == ("1"):
  prange = (1)
elif pcperception == ("2"):
else:
  prange = (1)
print ("your range is " + str(prange)`

and if I add a variable via input afterward

tommy = input("What is your name?")

It tells me that my syntax is incorrect in declaring the variable. But if i get rid of the top code, the bottom works.

Freemarker If condition is NULL

I only want a list with schools without an end date. In SQL I use always the condtion is null, how does it work in Freemarker?

<#list mergevelden.adres_instantie_344.betrokken_instanties.betrokken_instantie as scholen>
<#if scholen.tm="null"> ${scholen.instantie.volledige_naam} ${scholen.instantie.adressen.adres.straat} ${scholen.instantie.adressen.adres.huisnummer} ${scholen.instantie.adressen.adres.postcode}  ${scholen.instantie.adressen.adres.woonplaats?upper_case}

If statement not executing properly in ByVal Target As Range

This code checks cell ranges based on the criteria provided in the Worksheet_Change(ByVal Target As Range). It works for the most part except for this one anomaly. When range SalesPrice changes it checks the loanamount value, "If my loan amount is under 271,050 and checkbox1.value is true" it goes to the next routine (this is correct behavior). But if I change the SalesPrice which re-calculates LoanAmount to a number that causes the LoanAmount to go over 271050 the MsgBox code does not execute. But if I retype the same SalesPrice again it does execute. So in order for it to work properly I have to type in the SalesPrice twice if chkbox1.value was initially checked for the code to detect that the LoanAmount is too high.

If Target.Address = "$D$5" Then 'Sales Price
If Range("LoanProgram").Value Like "*HFA Bond Miami*" And _
Range("SalesPrice").Value > 317646 Then MsgBox "Miami-Dade Bond Max Sales 
Price is $317,646"
If Range("LoanAmount").Value > 271050 And Sheets("Main").CheckBox1.Value = 
True Then
MsgBox "MDEAT Max Loan Amount is $271,050"
Sheets("Main").CheckBox1.Value = False
End If

If statement inside while loop with the same condition

Is there a better way to write the following code by eliminating the repeated condition in the if statement in C?

while (n < 0) {
   printf("Enter a positive integer: ");
   scanf("%d", &n);

   if (n < 0) {
      printf("Error: please enter a positive integer\n");
   }
}

Thank you.

R combine cell content if condition true

I want to combine the content of two cells if several conditions are true.

I have the follwoing dataframe:

df <- data.frame(page = c("a1","a1","a2","a2","a3"),
                 keyword = c("a,b,c", "a,b,c,d", "d,e,f","g","a"))

The conditions in pseudo code:

if some cells of column page are equal (e.g. a1 and a2 appear two times)
then combine the content of column keyword and delete duplicate content. 

This means in the end I need a dataframe, which looks like this:

page | keyword

a1 | a,b,c,d

a2 | d,e,f,g

a3 | a

I already tried different approaches but didnt receive the correct result. Does anybody has an idea?

'Toolkit not initialized' with io.java

I'm new with Java and NetBeans 8.2 so sorry because this is a stupid question.

I practiced simple Java tasks and finished them successfully. And now added some io.java library (which I had not used before) in my project package. But when I try to run:

 io.title("Perfect weight");
    double height = io.getDouble("Enter your height");
    double weight = 0;
    char ch = io.getChar("Enter m for man and f for woman");
    if (ch == 'f') {
        weight = height - 110;
    }
    if (ch == 'm') {
        weight = height - 100;
    }
    io.println("Your perfect weight is ", weight);

I get this error Exception in thread "main" java.lang.IllegalStateException: Toolkit not initialized

What should I do?

If value in both table then assign 1

    Table1  CompanyID  Location  #-of-employees
          5234       NY          10
          5268       DC          2
          5879       NY          8
          6897       KS          100
          8789       CA          1
          9992       OH          201
          9877       TX          15

Table2 CompanyID   #-of-Shareholders
          5234            5
          5879            2
          6897            4
          8789            2

I have two table with the column CompanyID. In table2 you can find companies that have shareholders and in table1 you can find all the companies. So in table 1 I want to add a dummy variable that assign a 1 if the companyID is in table2(which means the company has shareholders) and a 0 if not.

Expected output:
    Table1  CompanyID  Location  #-of-employees Dummy
              5234       NY          10           1
              5268       DC          2            0
              5879       NY          8            1
              6897       KS          100          1
              8789       CA          1            1
              9992       OH          201          0
              9877       TX          15           0

I tried using this query but it doesn't give me the output I expect.

SELECT CASE WHEN companyID IN table2 THEN 1
ELSE 0
END AS dummy
FROM table1

Python if statement always showing the else statement [duplicate]

This question already has an answer here:

I just started learning python and was doing a dummy project as a test but the result always go to the else statement, hope I can get help! here is the full code.

class PetLover(object):
    def __init__(self, livingPlace, hoursAtHome):
        self.p = livingPlace
        self.h = hoursAtHome

    def getRecommendation(self):
        if self.p == 'h':
            if self.h in range(18, 24):
                return "Pot bellied pig"
            elif self.h in range(10, 17):
                return "Dog"
            elif self.h in range(1, 10):
                return "Snake"
            else:
                return "No recommendation"
        elif self.p == 'a':
            if self.h in range(10, 24):
                return "Cat"
            elif self.h in range(1, 9):
                return "Hamster"
            else:
                return "No recommendation"
        elif self.p == 'd':
            if self.h in range(6, 24):
                return "Fish"
            elif self.h in range(1, 5):
                return "Ant Farm"
            else:
                return "No recommendation"
        else:
            return "No recommendation"

livePlace = input("Do you live in house(H), Apartment(A) or Dorm(D)?")
hoursHome = input("How many hours do you spend at home?")

p = PetLover(livePlace, hoursHome)

print(p.getRecommendation())

Thank you!

How to remove verbose sentences in peer if-else branch

Here I got three if-else branches in this program

int main(){
    if(condition == 1)
        functionA();
    if(condition == 2)
        functionB();
    if(condition == 3)
        functionA&B();
    }

Suppose that the value of condition only varies from 1 to 3. I wonder if there's way where condition = 3 so that I don't have to call functionA&B() but just use the former result of condition = 1 and condition = 2?

mardi 30 octobre 2018

If a website's source code contain a certain string or word, do "x". (Javascript)

Ce résumé n'est pas disponible. Veuillez cliquer ici pour afficher l'article.

python syntax if in list function

I am trying to find the proper python syntax to create a flag with a value of 'yes' if columnx contains any of the following numbers: 1, 2, 3, 4, 5.

Def create_flag(df):
    if df['columnx'] in (1,2,3,4,5)
    return df['flag']=='yes'

I get the following error.

TypeError: invalid type comparison

Is there an obvious mistake in my syntax?

Trying to read a formula from a text file, store the lines of formulas, calculate the formulas, and write the answers to a new file

Hello I am having trouble the following code: It reads from a text file that has the following:

4 * 5
3 / 4
3 - 1
2 + 3

I am specifically stuck on the comments that says Declare ArrayList of for storing tokenized formula from String line and Determine the operator and calculate value of the result.

import java.io.*;
import java.util.*;
public class ReadFileLineByLine {
 public static void main(String[] args) throws FileNotFoundException {
 String line;
 Scanner input = null;
 PrintWriter output = null;

 try {

 //open file for reading the calculated formulas "formulas.txt"
 input = new Scanner(new File("C:\\formulas.txt"));
 //open file for storing the calculated formulas "results.txt"
 output = new PrintWriter(new File("C:\\results.txt"));

 // read one line at a time 
 while( input.hasNextLine()) {
 line = input.nextLine();

 System.out.println("read <" + line + ">"); // Display message to commandline
 // Declare ArrayList of for storing tokenized formula from String line

 double result = 0; // The variable to store result of the operation
 // Determine the operator and calculate value of the result
 System.out.println(formula.get(0) + ' ' + formula.get(1) + ' ' +
 formula.get(2) + " = " + result); // Display result to command line
 // Write result to file
 output.println("Print result of " + line + " to Results.txt");
 }
 // Need to close input and output files

 input.close();
 output.close();

 }
 catch (FileNotFoundException e) {
 // Display meaningful error message
  System.out.println("File Not Found: " + e.getMessage());
 }
 }
}

If anyone could come up with the code that determines these comments I would appreciate it!

Creating a Car Rental Calculator.

my instructions on the project were as followed or here is a link to a more detailed instruction page of the assignment (https://imgur.com/a/m8KDeaY):

Use a sentinel value loop. To create a Rental Car Calculator

Ask each user for:

Type of vehicle, if the fuel tank is full, Days rented. Then Calculate the Rental cost, Taxes and, fuel charge (For each customer). [NOTE: May use something other than strings, such as 1 for an economy, 2 for a sedan, etc.]

There are six different rental options with separate DAILY & WEEKLY rates. Daily rates: Economy @ 31.76, sedan @ 40.32, SUV @ 47.56. Weekly rates: Economy @ 158.80, sedan @ 201.60, SUV @ 237.80. [NOTE: all weekly rates are 5 times the daily rates. You may use a constant, or just calculate this off the daily rental fee]

Sales tax is = to 6% on the TOTAL.

Display after each full Calculator entry: The fuel charge, subtotal, rental cost, taxes and, grand total.

Display summary data when the program exits with:

The total number of customers, Total money collected, total fuel charges. total taxes and, the average bill. Also, Include IPO, algorithm, and desk check values (design documents).

{WHAT I HAVE GOING ON SO FAR}

package tests;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Tester {

public static void main(String []args){
    int days, cus, carType, fuel, count=0;
    double dailyFee=0, nonTaxTotal=0, total=0, fullTotal=0, fuelcharge=0, taxes=0, avrg=0;
    boolean checkRunOrQuit = false, chooseTypeVehicle = false, numberOfDAysChosen = false, fuellevel = false;
    Scanner in=new Scanner(System.in);


    while ( checkRunOrQuit = false ) {
        System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
        System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
        try {
            cus=in.nextInt();
            switch ( cus ) {
                case 0: System.out.print("End of application\n"); 
                        System.out.println("Count of customers: " + count);
                        System.out.printf("Total of the Day: $ %.2f \n", fullTotal);
                        System.out.printf("Subtotal: $ %.2f \n", nonTaxTotal);
                        System.out.printf("Total taxes collected: $ %.2f \n", taxes);
                        System.out.printf("The average bill was: $ %.2f \n", avrg);
                        System.exit(0);
                break;
                case 1: checkRunOrQuit = true;
                break;
                default:
                        System.out.println("Number must be either 1 or 0");
            }
        } catch (InputMismatchException ex) {
            System.out.println("Invalid entry: ");
            in.next();
        }
    }

    Pleasebaby: while( !chooseTypeVehicle ) { // --> simplified comparison
        count++;
        System.out.print("What vehical would you like to rent?\n");
        System.out.println("Enter 1 for an economy car");
        System.out.println("Enter 2 for a sedan car");
        System.out.println("Enter 3 for an SUV");

        try {
            carType = in.nextInt();
            chooseTypeVehicle = true;
            switch ( carType ) {
                case 1: dailyFee = 31.76;
                break;
                case 2: dailyFee = 40.32;
                break;
                case 3: dailyFee = 47.56;
                break;
                default:
                    System.out.print("Number must be 1-3\n");
                    chooseTypeVehicle = false;
                    break;
            }
        } catch (InputMismatchException ex) {
            System.out.println("Answer must be a number");
            in.next();
        }
    }

    while ( !fuellevel ) {
        try {
            System.out.print("Is the fuel empty?\n");
            System.out.println("Please enter 1 for yes.");
            System.out.println("Please enter 2 for no.");
            fuel = in.nextInt();
            if (fuel <= 0 |fuel > 2.1) {
                System.out.print("Please enter a 1 or 2\n");
            } else {
                fuellevel = true;
                switch ( fuel ) {
                case 1: fuelcharge = 40.00;
                break;
                case 2: fuelcharge = 0.00;
                break;
                }
            }} catch (InputMismatchException ex) {
                System.out.println("Answer must be a number");
                in.next();
            }
        }

    while ( !numberOfDAysChosen ) {
        try {
            System.out.print("Please enter the number of days rented. (Example; 3) : ");
            days = in.nextInt();
            if (days <= 0) {
                System.out.println("Number of days must be more than zero");
            } else {
                nonTaxTotal = (dailyFee * days);
                nonTaxTotal = (nonTaxTotal + fuelcharge);
                total = (nonTaxTotal * 1.06);
                taxes = (total - nonTaxTotal);
                avrg = ( total/count );
                fullTotal+=total;
                numberOfDAysChosen = true;
            }
        } catch(InputMismatchException ex) {
            System.out.println("Answer must be a number");
            in.next();
        }
    }

    System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
    System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
    try {
        cus=in.nextInt();
        switch ( cus ) {
            case 0: System.out.print("End of application. \n");
                    System.out.println("Count of customers: " + count);
                    System.out.printf("Total of the Day: $ %.2f \n", fullTotal);
                    System.out.printf("Subtotal: $ %.2f \n", nonTaxTotal);
                    System.out.printf("Total taxes collected: $ %.2f \n", taxes);
                    System.out.printf("The average bill was: $ %.2f \n", avrg);
                    System.exit(0);
            break;
            case 1:
            break Pleasebaby;
            default:
                    System.out.println("Number must be either 1 or 0");
        }
    } catch (InputMismatchException ex) {
        System.out.println("Invalid entry: ");
        in.next();
    }


    in.close();
    System.out.println("Count of customers : " + count );
    System.out.printf("total of the Day : $%.2f \n", fullTotal);
    System.out.printf("total taxes collected : $%.2f ", taxes);

    }

}

{Questions}

  1. I was attempting to break Pleasebaby in order to loop my entire calculator again if "1" was entered. but it prompts that the label does not exist?

  2. would anyone be able to help me with the differences between my TOTAL summary data and summary data per user? It seems I have only created the TOTAL summary data and I'm unsure where to start to just make a total per user.

  3. im bad at math is there any thoughts on how I can setup my weekly rates? without messing up my total/summary info?

Piece of code not working correctly for Admin Login

I've just finished my login page, Ive made it so that it redirects an ordinary User to the Home Page while an Admin to a main page with navigation for Administrative functions. The issue is that my If statement runs and redirects back to "Home" even when the administrator credentials are entered. I'm not sure how to stop this, here is the code:

public partial class LogIn : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection
            (@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\TennisTimeDTB.mdf;Integrated Security=True;");
        SqlCommand cmd = new SqlCommand("select * from Login where username=@username and password=@password", con);
        cmd.Parameters.AddWithValue("@username", TextBox1.Text);
        cmd.Parameters.AddWithValue("@password", TextBox2.Text);
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();

        if (dt.Rows.Count > 0)
        {
            if (dt.Rows[0]["Role"].ToString() == "admin")
            {

                Response.Redirect("AdminMain.aspx");

            }
            else
            {
                Session["id"] = TextBox1.Text;
                Response.Redirect("Home.aspx");
                Session.RemoveAll();
            }
        }

I'm pretty fresh to this so if it's a simple mistake I apologise! Thanks in advance for any help!

Q: Doing multiple loops and multiple if-statements and if-else-statements | RENTAL CAR CALCULATOR PROJECT

my instructions on the project were as followed:

Instructions: Use a sentinel value loop. To create a basic Rental Car Calculator

Ask each user for:

Type of vehicle (May use something other than strings, such as: 1 for an economy, 2 for a sedan, etc.) Days rented Calculate the (For each customer):

Rental cost, Taxes, Total Due. There are three different rental options with separate rates: Economy @ 31.76, sedan @ 40.32, SUV @ 47.56. [Note: only whole day units to be considered (no hourly rates)].

Sales tax is = to 6% on the TOTAL.

Create summary data with:

The number of customers Total money collected. Also, Include IPO, algorithm, and desk check values (design documents).

{WHAT I HAVE GOING AND MY QUESTION(S)}

package tests;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Tester {

public static void main(String []args){
int count=0;
int days;
int cus;
int carType;
double dailyFee=0, nonTaxTotal, total,fullTotal=0;
boolean checkRunOrQuit = false, chooseTypeVehicle = false, numberOfDAysChosen = false;
Scanner in=new Scanner(System.in);


while ( !checkRunOrQuit ) {
    System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
    System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
    try {
        cus=in.nextInt();
        switch ( cus ) {
            case 0: System.out.println("End of application");
                    System.exit(0); // This will actually end your application if the user enters 0, no need to verify later on
            break;
            case 1: checkRunOrQuit = true;
            break;
            default:
                    System.out.println("Number must be either 1 or 0");
        }
    } catch (InputMismatchException ex) {
        System.out.println("Invalid entry: ");
        in.next();
    }
}

while( !chooseTypeVehicle ) { // --> simplified comparison
    count++;
    System.out.print("What vehical would you like to rent?\n");
    System.out.println("Enter 1 for an economy car");
    System.out.println("Enter 2 for a sedan car");
    System.out.println("Enter 3 for an SUV");

    try {
        carType = in.nextInt();
        chooseTypeVehicle = true;
        switch ( carType ) {
            case 1: dailyFee = 31.76;
            break;
            case 2: dailyFee = 40.32;
            break;
            case 3: dailyFee = 47.56;
            break;
            default:
                System.out.print("Number must be 1-3\n");
                System.out.println("Please enter 1 for an economy car");
                System.out.println("Enter 2 for a sedan car");
                System.out.println("Enter 3 for an SUV");
                chooseTypeVehicle = false;
                break;
        }
    } catch (InputMismatchException ex) {
        System.out.println("Answer must be a number");
        in.next(); // -> you forgot this one.
    }
}

while ( !numberOfDAysChosen ) {
    try {
        System.out.print("Please enter the number of days rented. (Example; 3) : ");
        days = in.nextInt();
        if (days <= 0) {
            System.out.println("Number of days must be more than zero");
        } else {
            nonTaxTotal = (dailyFee * days);
            total = (nonTaxTotal * 1.06);
            fullTotal+=total;
            numberOfDAysChosen = true;
        }
    } catch(InputMismatchException ex) {
        System.out.println("Answer must be a number");
        in.next();
    }
}
in.close();
System.out.println("Count of customers : " + count);
System.out.printf("total of the Day : $ %.2f", fullTotal);
    }
}

  1. How would I make this program loop back to prompting the user: "Press 1 to enter Rental Calculator or else press 0 to quit\". After the "days rented input is entered?

[Note: Once the days rented is input, I was wanting a total calculation but not a summary. However, I want the summary info when the program is exited.]

For-loop over list of txt.files with if conditions in R

I am struggling with creating a for loop over all txt.files in a specific repository. The goal is to merge all separately saved txt.files in a dataframe and add an ID-variable that can always be found in the txt-file-names (e.g., ID=10 for the file "10_1. Recording 01.10.2015 131514_CsvData.txt" )

txt_files <- list.files("Data/study", pattern = ".txt")  

txt_files [1] "1_1. Recording 18.09.2015 091037_CsvData.txt" "10_1. Recording 01.10.2015 131514_CsvData.txt"
[3] "100_1. Recording 02.10.2015 091630_CsvData.txt" "104_1. Recording 22.09.2015 142604_CsvData.txt"
[5] "107_1. Recording 18.09.2015 104300_CsvData.txt" "110_1. Recording 29.09.2015 081558_CsvData.txt"
[7] "112_1. Recording 21.09.2015 082908_CsvData.txt" "114_1. Recording 29.09.2015 101159_CsvData.txt"
[9] "115_1. Recording 23.09.2015 141204_CsvData.txt" "116_1. Recording 30.09.2015 110624_CsvData.txt"
[11] "117_1. Recording 01.10.2015 141227_CsvData.txt" "120_1. Recording 17.09.2015 153516_CsvData.txt"

Read in and merge txt.files

    for ( file in txt_files){
    #  if the merged dataframe "final_df" doesn't already exist, create it
    if (!exists("final_df")){
    final_df<- read.table(paste("Data/study/",file, sep=""), header=TRUE, fill=TRUE)
    temp_ID <- substring(file, 0,str_locate_all(pattern ='_1.',file)[[1]][1]-1)
    final_df$ID <- temp_ID
    final_df <- as.data.frame(final_df)
  }
  #  if the merged dataframe does already exist, append to it
  else {
    temp_dataset <- read.table(paste("Data/study/",file, sep=""), header=TRUE, fill=TRUE)
    #   extract ID column from filename
    temp_ID <- substring(file, 0,str_locate_all(pattern ='_1.',file)[[1]][1]-1)
    temp_dataset$ID <- temp_ID
    final_df<-rbind(final_df, temp_dataset)
  }
  return(as.data.frame(final_df))
}

Adjusting IF formula to include negative figures

I have two columns - Column D is a forecast and Column E is historical data

I have the following IF statement:

=IF(OR(D42=0,E42<=0),"",IF(D42>E42,"Organic Growth","Organic Decline"))

However, I need to show that even the following is "Organic Decline" but my current formula doesn't account for these:

enter image description here

Forbidding program from inputting a number less than 1 (if else / switch)

So I'm writing a program that compares box volumes... but I need to make it run so that values less than one are not printed and would prompt an error message. (i.e. "The first box is 0.5 times the size of the second box" or "The first box is 0 times the size of the second box") -- Instead I would like it to print "Error: Please enter a valid number greater than 1"

Here is the part of my code that I am trying to fix:

if (volume1 == volume2) {
        System.out.println("The first box is the same size as the second box");
    }else if(volume1 >= 0 || volume2 >= 0){
        System.out.println("Error. Please enter a valid number greater than 0");
    }else {
        String bigger = "first box";
        String smaller = "second box";
        double ratio = volume1 / volume2;
        if (volume2 > volume1) {
            bigger = "second box";
            smaller = "first box";
            ratio = volume2 / volume1;
        }
        String compare;
        switch((int) ratio) {
        case 1: compare = " is slightly bigger than "; 
        break;
        case 2: compare = " is twice the size of "; 
        break;
        case 3: compare = " is triple the size of ";
        break;
        case 4: compare = " is quadruple the size of "; 
        break;
        default: compare = " is " + (int) ratio + " times the size of ";
        break;
        }

        System.out.println("The " + bigger + compare + smaller);
    }

I hope this is enough code to explain what my issue is. From what I have learned I don't think switch statements can have conditions, and because of the way the int ratio is structured it keeps printing 0 when I test it. Any advice?

What does a chained if construct do in Java?

From reading through the Oracle iLearning Java course, I am under the impression that using a 'chained if construct' is the equivalent of using the '&&' operator. So:

 if((5 < 10) && (5 < 6)) {
    run some code;
}

is the same as:

if(5 < 10) {
  if(5 < 6) {
        run some code;
    }
}

comparing the two, I find it hard to believe. I think I am very misunderstood.

Omitting Data From Array Output Based on Value

I am formatting data that is stored in two arrays using foreach loops and an If Statement. I am happy with my current output; however, I am having one issue. I don't want categories with No data or - TBD - as a data value to be displayed.

Here is my current PHP:

<?php
 foreach ($finaltitle as $titlenumber => $titlename){
   foreach ($techData as $tsnumber => $tsname){
     if ($tsnumber == $titlenumber){
       $finaltsdata = "<b>".$titlename." (".$tsnumber.") "."</b>: ".$tsname."<br>";
       echo $finaltsdata;
   }
  }
 }
?>

And its respective output:

Vehicle Name (1) : Audi S4
Body Style (2) : 5 Door Wagon
Drivetrain (6) : All-Wheel Drive
EPA Classification (7) : Small Station Wagon
Passenger Capacity (8) : 5
Passenger Volume (9) : 90.8
Base Curb Weight (10) : 4101
EPA Fuel Economy Est - City (26) : 14
EPA Fuel Economy Est - Hwy (27) : 21
Dead Weight Hitch - Max Trailer Wt. (31) : - TBD -
Dead Weight Hitch - Max Tongue Wt. (32) : - TBD -
Wt Distributing Hitch - Max Trailer Wt. (33) : - TBD -
Wt Distributing Hitch - Max Tongue Wt. (34) : - TBD -
Engine Order Code (40) : 
Engine Type (41) : Gas V8
Displacement (42) : 4.2L/254
Fuel System (43) : SEFI
SAE Net Horsepower @ RPM (48) : 340 @ 6800
SAE Net Torque @ RPM (49) : 302 @ 3500
Trans Order Code (51) : 
Trans Type (52) : 6

So in the case of this output I wouldn't want the following categories to be displayed because they either don't have a data value or their data value equals - TBD -.

Dead Weight Hitch - Max Trailer Wt. (31) : - TBD -
Dead Weight Hitch - Max Tongue Wt. (32) : - TBD -
Wt Distributing Hitch - Max Trailer Wt. (33) : - TBD -
Wt Distributing Hitch - Max Tongue Wt. (34) : - TBD -
Engine Order Code (40) : 
Trans Order Code (51) : 

Thanks so much for your help!

Determine if Array Has Elements in IF/Then Statement In Bash

I'm trying to determine if an array has elements in an if/then statement like this:

if [[ -n "$aws_user_group" && -n "${#aws_user_roles[@]}" ]]; then
  echo "$aws_user_name,$aws_user_group,"${aws_user_roles[*]}",$aws_key,$aws_account_number" >> "$ofile"
 elif [[ -n "$aws_user_group" ]]; then
  echo "$aws_user_name,$aws_user_group,,$aws_key,$aws_account_number" >> "$ofile"
fi 

Problem is, if the array is empty it's represented by '0' as in this debug output:

   [[ -n 0 ]]

And the wrong line prints out. It prints the line that includes the 'role' output but leaves it blank.

How can I more effectively check if the array has elements so that it doesn't pass the check if the array is empty?

Having issues combining two var into one if statement

Just getting started with coding and having trouble visualizing how to write this code:

var userAge = prompt("Are you old enough to vote? Lets check, enter your age.","");
        var citizen = prompt("Are you a US citizen? Y or N","");

        if(citizen = y && userAge >= 18)  
        {
            alert("Congrats, you can vote!");
        }else
        {
            alert("Sorry you can vote just yet");
        }

        document.write("<br/>");

        if(citizen = n && userAge < 18)
        {
            document.write("but at least you have your youth");

        }else if (citizen = y && userAge > 18)

            {
            document.write("You should be registered to vote! If not, visit www.usa.gov/register-to-vote");
            }

Any insights? Thanks for your time and support.

Return a negative value

I'm trying to implement a function where I have 2 players and their payoffs depends on their actions.

def game(action1,action2):

  if action1 == "a" and action2 == "a":
     payoff1 = 1
     payoff2 = 1
  elif action1 == "a" and action2 == "b":
     payoff1 = -5
     payoff2 = 3
  elif action1 == "b" and action2 == "a":
     payoff1 = 3
     payoff2 = -5
  elif action1 == "b" and action2 == "b":
     payoff1 = 2
     payyoff2 = 2
 return payoff1 , payoff2

Then I would have strategy for this game (example):

def TitForTat(round_num, previous_action):
    if round_num == 0:
       action = "a"
    else:
       action = previous_action
  return action

def AlwaysDefect():
  return "d"

action1 = TitForTat (0,'c')
action2 = AlwaysDefect()

game (action1,action2)

This returns an error:

local variable 'payoff1' referenced before assignment

I tried to initialize them to "0" , but the same. The exact functions works very well if I have all positive values.

Python nested IF statement not iterating the entire list

I need some help in understanding why it's not iterating the complete list and how I can correct this. i need to replace some values between list B and List A to do another process. The code is supposed to give me a final list of b = ['Sick', "Mid 1", "off", "Night", "Sick", "Morning", "Night"]. I was thinking 2 nested IF's statement because it's evaluating 2 different things. My code give me ['Sick', 'Mid 1', 'off', 'Night', 'off', 'Morning', 'Night'], which is correct on the [0], but not on element[4]. I was playing in the indentation of i = i+1, but that turned out a totally different result. thanks for your help.

a = ['Sick', 'PR', '', 'PR', 'Sick', 'PR', 'PR']
b = ["off", "Mid 1", "off", "Night", "off", "Morning", "Night"]

i = 0
for x in the_list:
    for y in see_drop_down_list:
        if x =="off":
            if y == "":
                the_list[i] = "off"

            else:
                the_list[i]=see_drop_down_list[i]
i = i + 1           
print (the_list)

applescript multiple choose from list

I need a choose from list dialog, whose result shows me another choose from list dialog and returns the result. I cannot figure out why the code below does not show the second choose from list dialog.

            set hi to choose from list {"oh, hey", "sup", "bye"}
            if hi = item 1 then
                set hey to choose from list {"how are you?", "no time for sall talk"}
            end if

EXCEL IF STATEMENT AND ISNUMBER SEARCH

I am basically trying to have multiple ISNUMBER and IF statement:

DESCRIPTION CATEGORY

ALL ACCESS -- NA
AMTRAK NRT -- TRAVEL
INDEED -- Recruting

So basically. if the word has "all" put NA, if the word has "amtrak" put travel, if the word has "indeed" put "recruiting"

I'm trying with this =IF(ISNUMBER(SEARCH("amtrak",D9)),D9,"train"), IF(ISNUMBER(SEARCH("all",D9)),D9,"t")

But it's not working. IT keeps give me error "value" or I tried this one =IF((AND(ISNUMBER(SEARCH("abm",B5)),B5,"don't know")),AND(ISNUMBER(SEARCH("all",B5)),B5,"don't k")) with same error.

Thank you

Run Time Error 91 in VBA even with correct date

There were a lot of questions and answers on this error, but none seemed to resolve my issue. I have a workbook of multiple worksheets. My goal is to match up lines in two of the worksheets and print some of the data onto a blank worksheet.

I need 5 of the cells to match from one sheet to the next so I used an If statement with multiple conditions. It works fine when the criteria is met, but when it's not , it doesn't move onto the Else statement. Instead it gives me the error 91.

Sub Novar_RSL_Filter()

'Locate any orders that match on the RSL and Discrepancy Report
'Also print out any orders that are on the RSL but not the discrepancy 
report

Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim I, count As Integer
Dim found1, found2, found3, found4, found5 As Range

Set ws1 = Worksheets("Discrepancy Report")
Set ws2 = Worksheets("Required Spot Listing")
Set ws3 = Worksheets("Results")

'defines last row to check
Total = ws2.Range("I" & Rows.count).End(xlUp).Row

count = 2
For I = 2 To Total
    clientID = ws2.Range("C" & I).Value 'Get clientID value
    contractID = ws2.Range("E" & I).Value 'Get contract #
    Zone = ws2.Range("G" & I).Value 'Get Zone name
    StartDate = ws2.Range("Q" & I).Value 'Get date of event
    StartTime = ws2.Range("R" & I).Value 'Get start time of event
    Set found1 = ws1.Columns("J:J").Find(what:=clientID) 'Check for client ID in Dicrepancy Report
    Set found2 = ws1.Columns("L:L").Find(what:=contractID) 'Check for contract ID in Dicrepancy Report
    Set found3 = ws1.Columns("H:H").Find(what:=Zone) 'Check for zone in Dicrepancy Report
    Set found4 = ws1.Columns("E:E").Find(what:=StartDate) 'Check for date in Dicrepancy Report
    Set found5 = ws1.Columns("F:F").Find(what:=StartTime) 'Check for start time in Dicrepancy Report
    If (found1 = clientID) And (found2 = contractID) And (found3 = Zone) And (found4 = StartDate) And (found5 = StartTime) Then
        ws3.Range("A" & count).Value = ws2.Range("D" & I).Value
        ws3.Range("B" & count).Value = ws2.Range("E" & I).Value
        ws3.Range("D" & count).Value = ws2.Range("AA" & I).Value
        ws3.Range("E" & count).Value = ws2.Range("Q" & I).Value
        ws3.Range("F" & count).Value = "Yes" 'set Discrepancy report column for yes
        count = count + 1
    Else
        ws3.Range("A" & count).Value = ws2.Range("D" & I).Value
        ws3.Range("B" & count).Value = ws2.Range("E" & I).Value
        ws3.Range("D" & count).Value = ws2.Range("AA" & I).Value
        ws3.Range("E" & count).Value = ws2.Range("Q" & I).Value
        ws3.Range("F" & count).Value = "No" 'set Discrepancy report column 
          for no
        count = count + 1
    End If
Next I

End Sub

The error occurs when I get to the If statement and it only occurs when something can't be found. Which is fine, it just means I want it to go to the Else statement, but it keeps throwing the error.

Thanks in advance for your help!

Java -- Classes and if statements - calculated multiples

I am writing a program for a class that compares the volumes of two boxes based on user input. It must calculate the volume difference, and give the following:

  • if there is no difference, display that the volumes are the same
  • if the volume of one is less than twice the other, display that it is slightly bigger
  • if the volume of one is less than three times the other, display that it is twice the size
  • if the volume of one is less than four times the other, display that it is triple the size
  • if the volume of one is less than five the other, display that it is quadruple the size
  • otherwise, display that it is the calculated multiple ***

The program must indicate the larger box (if not the same volume) and by how much. It also must NOT display values less than one (i.e. "the first box is 0.5 times the size of the second box" is wrong)

We have a specific structure to follow which I have done. I'm almost finished, but I'm stuck on the way in which to display the calculated multiple. It doesn't make sense to overload my code with if else statements for every number a user might enter, so there must be a particular way to command the program to do the math for me. I'm also thinking I may have made an error in the display() method of my Size Calculator... I have warnings for my volume variable and I'm not sure where to call that from (I know I put volume1 and volume2 and then have just volume, I'm playing around with it to see which one works).

Here is my main class:

import java.util.Scanner;
public class Assign2 {          // main to do box volume difference 
calculation
/*
 * Author: 
 * CST 8110 
 * This program compares box volumes
 */
    public static void main(String[] args) {    // program main

        System.out.println("Size calculator - we speak volumes\n");

        Box firstBox;
        Box secondBox;
        firstBox = new Box();
        secondBox = new Box();

        System.out.println("Enter first box dimensions");

        System.out.print("Enter length: ");
        firstBox.inputLength();

        System.out.print("Enter width: ");
        firstBox.inputWidth();

        System.out.print("Enter height: ");
        firstBox.inputHeight();

        System.out.println("\nEnter second box dimensions");

        System.out.print("\nEnter length: ");
        secondBox.inputLength();

        System.out.print("Enter width: ");
        secondBox.inputWidth();

        System.out.print("Enter height: ");
        secondBox.inputHeight();


        System.out.println("\nFirst box: ");
        firstBox.displayDimensions();
        double volume1 = firstBox.calcVolume();
        System.out.println(" Volume = " + volume1);


        System.out.println("\nSecond box: ");
        secondBox.displayDimensions();
        double volume2 = secondBox.calcVolume();
        System.out.println(" Volume = " + volume2);
    }


}

Here is my Box class:

import java.util.Scanner;
public class Box {              // store a single box

    private double length;      // length value
    private double width;       // width value
    private double height;      // height value

    private Scanner input = new Scanner(System.in); // scanner for all input

public Box() {              // default (no-arg) constructor             
    this.length = 0;
    this.width = 0;
    this.height = 0;
}                           

public Box(double length, double width, double height) {    // initial constructor
    this.length = length;
    this.width = width;
    this.height = height;
}

public Box(Box copyBox) {               // copy constructor
    this(copyBox.length, copyBox.width, copyBox.height);
}

public void inputLength() {     // input length value
    this.length = input.nextDouble();       
}                                   

public void inputWidth() {      // input width value
    this.width = input.nextDouble();
}

public void inputHeight() {     // input height value
    this.height = input.nextDouble();
}

public void displayDimensions() {   // display the box in proper format
    System.out.print(this.length + " X " + this.width + " X " + this.height);
    //System.out.println("First box: " + getLength() + "X" + width + "X" + height);
    //System.out.println("Second box: " + getLength() + "X" + width + "X" + height);
    //System.out.println("");
}

public double calcVolume() {        // calculate the box volume
    double volume = this.length * this.width * this.height;
    return volume;
}

}

And my Size Calculator class:

import java.text.DecimalFormat;

public class SizeCalculator {   // calculate the difference between two box volumes

    private Box firstBox = new Box();       // first box to compare

    private Box secondBox = new Box();      // second box to compare

    private String message = new String();  // message to be displayed

    private DecimalFormat df = new DecimalFormat("0.00");   // decimal format to be used

public SizeCalculator() {           // default (no-arg) constructor
}

public void inputBoxes() {          // input the two boxes
    double length, width, height;

}

//  public void inputBox(Box){          optional method to simplify box 
//  }   

public void calculateSizes() {      // calculate difference between two boxes and store the value in message
    double length, width, height;
}

public void display() {             // display the message
    double length, width, height;

    Box firstBox;
    Box secondBox;
    firstBox = new Box();
    secondBox = new Box();

    // this.firstBox = length * width * height;

    double volume1 = firstBox.length * firstBox.width * firstBox.height;
    double volume2 = secondBox.length * secondBox.width * secondBox.height;


    if (firstBox.volume1 == secondBox.volume2) {
        System.out.println("The volumes are the same.");

    }else if (firstBox.volume < 2 * secondBox.volume) {
        System.out.println("The volume of the second box is slightly bigger than the first box");
    }else if (secondBox.volume < 2 * firstBox.volume ) {
        System.out.println("The volume of the first box is slightly bigger than the second box");

    }else if (firstBox.volume < 3 * secondBox.volume) {
        System.out.println("The volume of the second box is twice the size of the second box");
    }else if (secondBox.volume < 3 * firstBox.volume) {
        System.out.println("The volume of the second box is twice the size of the first box" );

    }else if (firstBox.volume < 4 * secondBox.volume) {
        System.out.println("The volume of the second box is triple the size of the first box");
    }else if (secondBox.volume < 4 * secondBox.volume) {
        System.out.println("The volume of the first box is triple the size of the second box");

    }else if (firstBox.volume < 5 * secondBox.volume) {
        System.out.println("The volume of the second box is quadruple the size of the first box");
    }else if (secondBox.volume < 5 * firstBox.volume) {
        System.out.println("The volume of the first box is quadruple the size of the second box");


    }else if (firstBox.volume < 6 * secondBox.volume) {     // how to write this so it displays the multiple
        System.out.println("The volume of the second box is 5 times the size of the first box");
    }else if (secondBox.volume < 6 * secondBox.volume) {
        System.out.println("The volume of the first box is 5 times the size of the second box");


}
}

}

SQL If() On getting the Next date if tomorrows data is null

Newbie to SQL Still.

I'm trying to work with a current SQL query I made.

SELECT DISTINCT Master.Order Order, Detail.Date
FROM Master INNER JOIN Details ON Master.Order = Detail.Order
WHERE Date = DATEADD(day, 1, GETDATE())
AND Detail.House = 'MX'
AND (Master.Status <> '\'
AND Master.Status <> 'S' 
AND Master.Status <> '8'
AND Master.Status <> '9')

GROUP BY  Detail.Date, Master.Order

My goal Is to have the query pull the next result if tomorrows date has no data.

I'm thinking I need to implement a IF() statement but I'm not really sure how.

Any Suggestions?

Anything Helps.

Thank you,

Sam

Trying a date within Tkinter - Python

After testing out many times and reading Stackoverflow for several hours, I decided to right this question. My Text (part of the bigger code) is below:

import pandas as pd
import datetime as dt
from tkinter import *
import tkinter.filedialog
from tkinter import messagebox

def click1():
  global a
  a = tkinter.filedialog.askopenfilename(initialdir = "/",title = "Select file", filetypes = ( ("Excel file", "*.xlsx"), ("All files", "*.*") ) )
  output1.insert(END, a)
  global a1
  a1 = output1.get() 

def load_click():
  global item_prosp
  item_prosp = pd.read_excel(a1)

def test_click():
  global ipt_dt   
  global coef
  global z
  global w
  z = item_prosp['Accrual_Start'].min()
  w = item_prosp['Accrual_End'].max()
  ipt_d = tkvar_d.get()
  ipt_m = tkvar_m.get()
  ipt_y = tkvar_y.get()  
  x = 0
  while x == 0:
    ipt = str(ipt_d + '/'+ ipt_m + '/' + ipt_y)
    try:
        ipt_dt = dt.datetime.strptime(ipt, "%d/%b/%Y")
        if ipt_dt < z or ipt_dt > w:
                messagebox.showinfo("Error", "The input date is outside scope date") 
    else:
         print("Date ok")
        x =+ 1
    except: 
        messagebox.showerror("Error", "The input date is not valid")
        ipt_d = 0
        ipt_m = 0
        ipt_y = 0
        continue

 def save_click():
   window.destroy()

 ##Tk_Main:
 window = Tk()
 window.title("File selection window")
 window.configure(background = "white")
 window.geometry("480x700")

 #File1
 label2 = Label(window, text="Select the item prospective file", bg="white").grid(row=2, column=0,columnspan=3, pady=2, sticky=W)
 output1 = Entry(window, width=60, background="gray")
 output1.grid(row=3, column=0, columnspan=3, padx=10, sticky=W)
 Button(window, text="Search", width=6, command=click1).grid(row=3, column=3, padx=5, sticky=W)

 #Question 1 - Evaluation date
 label4 = Label(window, text='Please inform the valuation date :', bg='white').grid(row=13, column=0, columnspan=3, pady=2, sticky=W)
 tkvar_d = StringVar(window)
 tkvar_m = StringVar(window)
 tkvar_y = StringVar(window)
 choices_d = ['1', '2', '3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31']
 choices_m = ['Jan', 'Feb', 'Mar','Apr','May','Jun','Jul','Aug','Sep','Oct', 'Nov', 'Dec']
 choices_y = ['2018','2019', '2020', '2021','2022','2023','2024','2025','2026','2027','2028','2029','2030']
 popupmenu_d = OptionMenu(window, tkvar_d, *choices_d)
 popupmenu_m = OptionMenu(window, tkvar_m, *choices_m)
 popupmenu_y = OptionMenu(window, tkvar_y, *choices_y)
 label5 = Label(window, text='Day :', bg='white').grid(row=14, column=0, sticky=E+W)
 popupmenu_d.grid(row=15, column=0, padx=2, sticky=E+W)
 label6 = Label(window, text='Month :', bg='white').grid(row=14, column=1, sticky=E+W)
 popupmenu_m.grid(row=15, column=1, padx=2, sticky=E+W)
 label7 = Label(window, text='Year :', bg='white').grid(row=14, column=2, sticky=E+W)
 popupmenu_y.grid(row=15, column=2, padx=2, sticky=E+W)
 Button(window, text="Test Date", width=10, command=test_click).grid(row=15, column=3, padx=5, pady=10, sticky=W)

 #Exit   
 Button(window, text="Generate", width=13, command=save_click).grid(row=20, column=0, columnspan=3, padx=10, pady=10, sticky=W)
 window.mainloop()

My need is to import a file (externally built and already structured), read 2 values from it (variables Z and W in the code) and compare it with an input variable (ipt_dt) which is a date filled in by the user through 3 dropdown menus from tkinter.

The error is that the try is not going through the if statement and it never prints out if the input is outside the scope date. Everytime I enter a date smaller than the minimum date or higher than the maximum date it returns the showerror message eventhou it pritns the "Date ok".

Anyone has any idea on how to solve this or why my fi is being ignored?

Thanks!

If Statement Ignored In Worksheet Change Byval Routine

Can anyone help me correct this code? I have it in the Worksheet_Change(ByVal Target As Range) but it only works for the if statement that evaluates the SalesPrice value of 317646. Even if i rearrange the if statement it won't execute the LoanAmount if statement.

If Target.Address = "$D$5" Then 'Sales Price
    If Range("LoanProgram").Value = "HFA Bond Miami FHA" And Range("LoanProgram").Value = "HFA Bond Miami Conv" Or Range("SalesPrice").Value > 317646 Then
        MsgBox "Max Sales Price is $317,646"
    End If

    If Range("LoanAmount").Value > 271050 & Sheets("Main").CheckBox1.Value = True Then
        MsgBox "Max Loan Amount is $271,050"
        Sheets("Main").CheckBox1.Value = False
    End If

    Call PushTo105Button
    Call Calc_MI
    Range("E6").Value = Range("D6").Value
End If

How do I add 'if' commands inside a 'why' loop

So I have some code, like this:

while loopCode == 1:
userCommand = raw_input('Type a command (type \'help\' for syntax): ')

if userCommand == help:
    print 'flight: this command will be used to list a flight'
    print 'restaurant: you will be prompted to type the name of the restaurant, and how much you will spend there'

As you see, there is an if conditional inside the while loop. But when I get prompted to input text, I'm supposed to type 'help' for the conditional to activate. But when I do that, the while loop ignores the conditional. Why is that?

R tryCatch with three possible outcomes

I'm currently working with a tryCatch within a custom function that will output a string. The tryCatch querys a database with a set of parameters to see if there is enough data, it subsequently checks to see if two columns also have enough unique values. I want there to be three different outcomes, a 'success', 'not enough data', and 'SQL error' (while also printing the SQL error). There are 3 places where it should return 'not enough data'. Currently my code works for both the success and error, but I cannot seem to get it to output 'not enough data', in the case where it should be 'not enough data' I get an error return. Any ideas as to why it is happening this way?

custfunct <- function(query_string,connect_string){
out<-tryCatch(
    {

      connection <- odbcDriverConnect(connect_string)
      initdata<- sqlQuery(connection,query_string)
      print(initdata)
      # Check if query has returned an error. print the error
      if (is.character(initdata))
        {
        print <- paste(initdata, collapse = "\n")
      }
      return ("error")

      if (nrow(initdata) >5)
      {

        print("rows more than five")
        if (length(unique(initdata$column_1)) >5)
        {

          print('unique column 1 more than 5')
          if (length(unique(initdata$column_2) >5)
          {

            print("unique column 2 more than 5")
          }

          return("success")
        }

        else
        {
          print("There are too few samples")

          return("not enough data")
        }

      }

      else
      {

        print("Either there is no data or too few samples")

        return("not enough data")
      }
    },
    error=function(errorvalue){
     return("error")
    }
    ,finally={
    }
  )
  return(out)
}

How do I define a state jquery/javascript?

 $(document).on("click", '.gifyImage', function(event) {
    var clickedImage = $(event.target);
    if(clickedImage.data('state') === "animate") {
        //set to still
        clickedImage.data('state', "still");
        // update state clickedImage.data('state', 'animate');
        clickedImage.data('state', "animate");
    } else {
        //set to animate
        clickedImage.data('state', "animate");
        //update state to still
        clickedImage.data('state', "still");
    }
    clickedImage.attr('src', clickedImage.data('still'));
    console.log(event.target);
});

Backstory to why i'm writing this function.. I have a assignment that requires me to have the gif image still and when clicked on the gif it will start to play (animate), and when i click it again it will go back to being still. This code here is giving me a error : "State is not defined"

when duplicate values found then

I want to have a query that selects all duplicate values in a column. If those value meet the conditions then I'd like the query to return only those values.

Class    Student_ID  Location
Biology     511         4A
Biology     512         15B
Biology     513         15B
English     514         6A
Biology     521         6A
Spanish     522         6A
Spanish     523         15B
Chemistry   524         4A
English     531         15B
Biology     532         4A
Chemistry   534         4A

Select all duplicate values in the class column and if among those values there is location in both 4A and 15B then assign 1.

CASE WHEN count(class) > 1 AND (Location = '4A' AND Location = '15B') THEN 1 ELSE 0 END

what is most important is how to select duplicate values without specifing for each row. Group by statement doesn't do the trick either.

IF "71" GTR "7000" yields true

According to my code, If %~1 is greater than 7000, go to ExceedError

IF "%~1" GTR "7000" GOTO ExceedError

Contents of ExceedError:

ECHO Value exceeded the maximum value. See help file.
EXIT /B

But this happened:

C:\modules>If "71" GTR "7000" GOTO ExceedError

C:\modules>Echo Value exceeded the maximum value. See help file.
Value exceeded the maximum value. See help file.

C:\modules>exit /b

What happened? Is there something wrong?

Full code: https://pastebin.com/rXg1mejy

VB.NET/JAVA- How to Create If-else Statement From a Selected Text File and Output Generated If-else statement to New Text File

Good day!

I am currently learning Machine Learning and I am not good in coding.

I am trying to convert a generated model into If-else statements. The generated model is somewhat like this:

11AM_3 = 0
|   11AM_1 = 1
|   |   4PM_1 = 3
|   |   |   4PM_2 = 0
|   |   |   |   11AM_2 = 0 : 0 (0/0)
|   |   |   |   11AM_2 = 2 : 3 (2/0)
|   |   4PM_2 = 3
|   |   |   4PM_3 = 0
|   |   |   |   11AM_2 = 3 : 1 (2/0)
|   11AM_1 = 2
|   |   4PM_1 = 9 : 1 (1/0)

Since, the generated model is big, I want to create a program that will convert a model (having the above format) into If-else statement in VB.NET OR Java and output the created If-else statement into a new text file.

Example of If-else statement in VB.NET would be

If (11AM_3=0) then
    If(11AM_1=1) then
        If(4PM_1=3) then
            If(4PM_2=0) then
                If(11AM_2=0) then
                    return 0
                Elseif(11AM_2=2) then
                    return 3
                End if
            end if
        Elseif(4PM_2=3) then
            If(4PM_3=0) then
                If(11AM_2=3) then
                    return 1
                end if
            end if
        End if
    ElseIf(11AM_2=2) then
        If(4PM_1=9) then
            return 1
        end if
    end if
end if

Q : Doing multiple loops and multiple if-statements and if-else-statements || RENTAL CAR CALCULATOR PROJECT

my instructions on the project were as followed:

Instructions: Use a sentinel value loop. To create a basic Rental Car Calculator

Ask each user for:

Type of vehicle (May use something other than strings, such as: 1 for an economy, 2 for a sedan, etc.) Days rented Calculate the (For each customer):

Rental cost, Taxes, Total Due. There are three different rental options with separate rates: Economy @ 31.76, sedan @ 40.32, SUV @ 47.56. [Note: only whole day units to be considered (no hourly rates)].

Sales tax is = to 6% on the TOTAL.

Create summary data with:

Number of customers Total money collected. Also, Include IPO, algorithm, and desk check values (design documents).

{WHAT I HAVE GOING AND MY QUESTION(S)}

package tests;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Tester {

public static void main(String []args){
int count=0;
int days;
int cus = 10; 
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
boolean F1 = false, F2 = false, F3 = false;
Scanner in=new Scanner(System.in);


while (F3 == false) {
    F3 = true;
    System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
    System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
    try {
        cus=in.nextInt();
        if (cus == 0 || cus == 1) {
            F3 = true;
        } else {
            F3 = false;
            System.out.println("Number must be either 1 or 0");
        }
    } catch (InputMismatchException ex) {
        F3 = false;
        System.out.println("Invalid entry");
        in.next();
    }
}

    if(cus == 1) { 
        while(F1 == false) {
            F1 = true;
            count++;
            System.out.print("What vehical would you like to rent?\n");
            System.out.println("Enter 1 for an economy car");
            System.out.println("Enter 2 for a sedan car");
            System.out.println("Enter 3 for an SUV");
            // 
            try {
                CarType = in.nextInt();
                if (CarType <= 0 || CarType >= 4) {
                    System.out.print("Number must be 1-3\n");
                    System.out.println("Please enter 1 for an economy car");
                    System.out.println("Enter 2 for a sedan car");
                    System.out.println("Enter 3 for an SUV");

                    F1 = false;
                } else {
                     if (CarType == 1) {
                         F1 = true;
                          DailyFee=31.76;
                } else if(CarType == 2) {
                        F1 = true;
                          DailyFee=40.32;
                } else if(CarType == 3) {
                        F1 = true;
                          DailyFee=47.56;
                }
                while (F2 == false) {
                    F2 = true;
                    try { 
                        System.out.print("Please enter the number of days rented. (Example; 3) : ");
                        days = in.nextInt();
                        if (days <= 0) {
                            System.out.println("Number of days must be more than zero");
                            F2 = false;
                        } else {

                            double x=days;
                            NontaxTotal = (DailyFee * x);
                            Total = (NontaxTotal * 1.06);
                            FullTotal+=Total;
                            F3 = true;

                        }
                    } catch(InputMismatchException ex) {
                        System.out.println("Answer must be a number");
                        F2 = false;
                        in.next();
                        }
                    }
                }
            } catch (InputMismatchException ex) {
                F1 = false;
                System.out.println("Answer must be a number"); 
            }
        }
    }
    in.close();
    System.out.println("Count of customers : " + count);
    System.out.printf("Total of the Day : $ %.2f", FullTotal);

    }
}

{MY QUESTIONS}

  1. When a letter is entered to the prompt "Press 1 to enter Rental Calculator or else press 0 to quit" it displays, an error prompt the user then asks for input again. Similarly, when a letter is inputted at the prompt "What vehicle would you like to rent?" the console continues to print lines with no stop? I do not know how to fix this?

  2. I want my program to allow multiple inputs. However after one input the console post summary data rather than looping?

lundi 29 octobre 2018

Multiple check for empty dataframe

I have a situation where I need to move the dataframe forward in code only if it is not empty. Illustrated below:

----- Filter 1 -------
Check if df.empty then return emptydf
else
----- Filter 2 ------
Check if df.empty then return emptydf
else
----- Filter 3 ------
return df

The code for the above is written as below(Just a part of code):

df = df[df.somecolumn > 2].copy()

if df.empty:
    return df

df = df[df.someother == 2].copy()

if df.empty:
    return df

df = df[df.all <= 10].copy()

return df

If I have many such filters which expect dataframe not to be empty, I need to check empty after each filter. Is there any better way of checking dataframe empty rather than checking at each level.

IS there a way to simplify this python code?

I am still in the "any technology sufficiently advanced..." phase of learning to program. This code seems clunky, and hard to update if needed. Is there a better way to go about this? It just looks completely bonkers to me, but it works... so yay?

It takes a variable from TKinter radial 1-16, and uses it select the grade1 ect variable. The grade1 variable then link to sheet names on gspread.

def go():
    subject = v.get()
    if  subject == 1:
        subject = grade1
    elif  subject == 2:
        subject = grade2    
    elif  subject == 3:
        subject = grade3
    elif  subject == 4:
        subject = grade4  
    elif  subject == 5:
        subject = grade5
    elif  subject == 6:
        subject = grade6
    elif  subject == 7:
        subject = grade7
    elif  subject == 8:
        subject = grade8
    elif  subject == 9:
        subject = grade9
    elif  subject == 10:
        subject = grade10    
    elif  subject == 11:
        subject = grade11
    elif  subject == 12:
        subject = grade12 
    elif  subject == 13:
        subject = grade13
    elif  subject == 14:
        subject = grade14
    elif  subject == 15:
        subject = grade15
    elif  subject == 16:
        subject = grade16

For loop if statement return undesired outcome at the first row

I have a code on python that tries to calculate the sample variance while I accumulate entries in each loop.

y_hat = y_df.loc[n-1]
var = []
var_sum = 0
for i in range(n):
    var_i = (g_i[i] - y_hat)**2
    var_sum += var_i
    if i == 0: 
        var_avg = var_sum
        var.append(var_avg)
    else: 
        var_avg = var_sum/i
        var.append(var_avg)

the output of the result yields very strange first rows (when i is 1), while the rest of rows are fine. Can someone help please? output of the code

Below is my entire script, essentially I am testing Monte Carlo simulation to evaluate pi.

import numpy as np
import math
import matplotlib.pyplot as plt
import random
import pandas as pd
import statistics as stats

n = 1000
k = 100

# generate u r.v. with size k*n -> (100,1000)
u = []
for i in range(k):
    u_i = np.random.uniform(size = n)
    u.append(u_i)

# put into dataframe (k*n)
u_df = pd.DataFrame(u)

# calculate g_i, g_i is a df with k*n
g_i = 4*np.sqrt(1-u_df**2)

g_sum = 0
y = []
for i in range(n):
    g_sum += g_i[i]
    y_i = g_sum/(i+1)
    y.append(y_i)

# put y into df -> n*k
y_df = pd.DataFrame(y)
y_df = y_df.reset_index(drop=True)

y_hat = y_df.loc[n-1]
var = []
var_sum = 0
for i in range(n):
    var_i = (g_i[i] - y_hat)**2
    var_sum += var_i
    if i == 0: 
        var_avg = var_sum
        var.append(var_avg)
    else: 
        var_avg = var_sum/i
        var.append(var_avg)

var_df = pd.DataFrame(var)
var_df = var_df.reset_index(drop=True)

var_df.head()

Need to ignore zeroes in IF statement

Hi i have two columns (D and E) both contain data - both include zeroes in them.

I am looking to write an IF statement categorizing whether there is "Growth" or "decline" over these two columns as one is FY17 and the other is a re forecast. However, I need to ignore the zeroes in both theses columns

Any help would be greatly appreciated.

How add if-statement to array

I have this code.

            ->add(Lang::__('users'), 'javascript:void(0)', Menu::factory()
            ->add(Lang::__('users'), ACCESS_ADMIN.'/users/index', Menu::factory()
                ->add(Lang::__('adduser'), ACCESS_ADMIN.'/users/add_user'))
            ->add(Lang::__('usergroups'), ACCESS_ADMIN.'/users/groups', Menu::factory()
                ->add(Lang::__('addusergroup'), ACCESS_ADMIN.'/users/add_group')))

I test this:

            ((Hooks::Exist('Blog') == true) ?
        ->add(Lang::__('users'), 'javascript:void(0)', Menu::factory()
            ->add(Lang::__('users'), ACCESS_ADMIN.'/users/index', Menu::factory()
                ->add(Lang::__('adduser'), ACCESS_ADMIN.'/users/add_user'))
            ->add(Lang::__('usergroups'), ACCESS_ADMIN.'/users/groups', Menu::factory()
                ->add(Lang::__('addusergroup'), ACCESS_ADMIN.'/users/add_group')))
        : ''),

but a have an error unexpected '('. How i add an if to my code...??? Thanks in advance people.

Trying to add a If Statement inside a Timer in VB 2010

I have looked but cant seem to find out why this won't work for me

I added this Code inside Timer1 in my form

dim Boolean1 as Boolean

if Boolean1 = true and WMP1.playState = WMPLib.WMPPlayState.wmppsPlaying then
WMP1.Ctlcontrols.pause()
Boolean1 = false
end if
if Boolean1 = false and WMP1.playState = WMPLib.WMPPlayState.wmppsPaused then
WMP1.Ctlcontrols.play()
Boolean1 = true
end if

Taking leading number and dash off

I have a workbook that has a priority column the values are like 3-High. I need to removed the 3- so that all that displays is High in another column.

Q : Not understanding loop process? or possible if statements?

I am working on a project that involves creating a rental car calculator.

What I am trying to do is make it to where when asked: "What vehicle would you like to rent??". if a number that is not between 1-3 is entered when the user is prompted this, then I want the program to loop back to the point of being asked vehicle type again.

Similarly, when prompted for 'Please enter the number of days rented. (Example; 3) : ' I want to only allow the user to input whole numbers. for instance, not allowing input of 3.1, 2.35, 0.35 and, etc...

here is what I have written and my attempt at these questions.

package inter;

import java.util.Scanner;

public class Inter {
public static void main(String []args){
    int count=0;
    int days;
    double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
    Scanner in=new Scanner(System.in);
    System.out.println("If there are any customer press 1 else press 0");
    int cus=in.nextInt();

    while(cus!=0){
        count++;
        System.out.print("What vehical would you like to rent?\n");
        System.out.println("Enter 1 for an economy car\n");
        System.out.println("Enter 2 for a sedan car\n");
        System.out.println("Enter 3 for an SUV");
        CarType = in.nextInt();
        if (CarType == 1) {
              DailyFee=31.76;
        }
        else if(CarType == 2) {
              DailyFee=40.32;
        }
        else if(CarType == 3) {
              DailyFee=47.56;
        }
        else if(CarType <= 0) {
            System.out.println("input is not a positive Integer ");
            System.out.println("Please enter a positive integer value: ");
            cus = 0; }
        else if(CarType > 4) {
            System.out.println("input is not a positive Integer ");
            System.out.println("Please enter a positive integer value: ");
            cus = 0; }

        System.out.print("Please enter the number of days rented. (Example; 3) : ");
        days = Integer.valueOf(in.nextLine());
        double x=days;
        NontaxTotal = (DailyFee * x);
        Total = (NontaxTotal * 1.06);
        FullTotal+=Total;

        System.out.printf("The total amount due is $ %.2f \n",Total);

        System.out.println("If there are any customer press 1 else press 0");
        cus=in.nextInt();
    }
    System.out.println("Count of customers : "+count);
    System.out.printf("Total of the Day : $ %.2f",FullTotal);
}

}

Python if statements keep skipping [duplicate]

This question already has an answer here:

To provide some context, I am looking to create a program that will encrypt and decrypt through the Caesar cipher, and I have created code for both of these functions that works quite well. However, when I try to conjoin these into one code I find that it always ignores the if statements I have in place and will always try to encrypt what the user enters. Any help would be much appreciated!

characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.`~@$£%^&*()_+-=[]{}|;:<>,/"
translated = ""

print("Welcome to Krypto! ")
decision = input("What would you like to do today? (encrypt, decrypt, info) ")
message = input("Please enter the text you would like to manipulate: ")

if decision == 'encrypt' or 'Encrypt':
      print ("Encrypt selected")
      #encryption begins

elif decision == 'decrypt' or 'Decrypt':
      print("Decrypt selected")
      #decryption begins

SQL Stored Process: If statement not behaving as expected

Attempting to create a stored process for MySQL. It contains a basic if-statement. The current script is below:

DROP PROCEDURE IF EXISTS sp_pay_raise;

DELIMITER @@
CREATE PROCEDURE sp_pay_raise
     (IN inEmpId INT,
      IN inPercentageRaise DOUBLE(4,2),
      OUT outErrorCode INT)
BEGIN
    IF (@inPercentageRaise <= 0.0) THEN
        SELECT -3 INTO errorCode
    ELSE
        SELECT -2 INTO errorCode
    END IF;
END @@
DELIMITER ;

The above doesn't work as expected. If I provide a inPercentageRaise which is less than zero, for ex.

CALL sp_pay_raise(0,-1.0, @out)
SELECT @out;

The database shows @out = -2. Is the if-statement which is written incorrectly?

Python--changing number of conditions inside if statement depending on input

So for fun I've been making the following code that essentially takes in two Pokemon, and outputs a list of Pokemon that would round out a three Pokemon team based on defenses. I have a full working code for all 18 types, but here's a smaller version I've been using for testing:

import numpy as np
import sys

#testing assuming input in fire
dict={}
dict["fire"]=np.array([1,-1,1]) 
dict["water"]=np.array([1,1,-1])
dict["grass"]=np.array([-1,1,1])

value={}
value[0]="fire"
value[1]="water"
value[2]="grass"

type1=input("First type? (no caps): ")
type(type1)
type2=input("Second type? (no caps): ")
type(type2)

poke=dict[type1]+dict[type2]

for t in range(len(poke)):
    if poke[t]<0:
        poke[t]=-1
    elif poke[t]>0:
        poke[t]=1
    else: continue

A=np.column_stack(([fire,water,grass]))

weak=any(poke<0)
p=np.linspace(0,0,len(poke))
if weak==True:
    for t in range(len(poke)):
        if poke[t]<0:
            p[t]=1
        else:
            p[t]=0
else:
    print("....your pokemon has no weaknesses....")

for u in range(0,len(poke)):
    for v in range(u,len(poke)):
        combo=A[:,u]+A[:,v]
        for t in range(0,len(poke)):
            if combo[t]<0:
                combo[t]=-1
            elif combo[t]>0:
                combo[t]=1
            else: continue
        if combo[1]==-poke[1]: #dep on values of p that are not 0
            if u==v:
                print(value[u])
            else:
                print(value[u],value[v])
        else: continue

What the code basically does is I have a series of arrays representing each type. A 1 means it resists the pokemon corresponding to that type, a -1 is weak to it, and a 0 is neutral. In the full code it accepts two dual type pokemon, adds together their arrays, and I treat it as a single entity. In the smaller code I'm taking in one and looking for one. After anything is added together I change the values back to 1's, and 0's so I can do proper comparisons.

And then the actual comparison is done by this double nested for loop that goes over every possible combination and compares it to want I want, which is basically for any value of poke[ ] that is -1, I want a matching combo[ ] value that is 1.

if combo[1]==-poke[1]:
        if u==v:
            print(value[u])
        else:
            print(value[u],value[v])
    else: continue

The issue is that I'm having trouble generalizing the code so I don't have to go back and edit it every time I want to do a new "search".

For this instance of the code:

>>First type? (no caps): fire
    Second type? (no caps): fire
    water
    water grass
    grass 

But, if I wanted to do, say a water type:

>>First type? (no caps): water
    Second type? (no caps): water
    fire

It should suggest fire, fire/grass, grass, but it doesn't because the if statement no longer points to the correct index to check. This is something I edit every time and am having trouble with when it comes to generalizing to simply input/output.

I made this value p which is an array of 0's and 1's, where 1 is a weakness and 0 is anything else:

 weak=any(poke<0)
    p=np.linspace(0,0,len(poke))
    if weak==True:
        for t in range(len(poke)):
            if poke[t]<0:
                p[t]=1
            else:
                p[t]=0
    else:
        print("....your pokemon has no weaknesses....")

I think I could probably make a way to check the values where p=1 specifically, but then the actual problem occurs. In nearly all cases there's more than one weakness, which leads to having to check 3 or 4 four conditions in the same if statement like:

if combo[1]==-poke[1] && combo[5]==-poke[5] && combo[13]==-poke[13]:

And even then that combination sometimes doesn't exist. I was thinking of printing out the weaknesses corresponding to p=1 if it's more than 3 and having some sort of user input on what they would like to check, but I can't figure out how to have the number of conditions in a single if statement vary like that. I'm also unsure how to make the current single statement point to the p indexes like I want.

I will continue to work on this but I appreciate any help I can get since I'm still pretty new.

Thank you!

How to make a text field visible depending on multiple choice questions

I am trying to make a text field visible depending on 2 multiple choice answers (both are yes/no questions). If both multiple choice answers are "no" then I need the text field to appear. But if any of the two multiple choices are switched to a "yes" then I'd need the text field to disappear.

Any help is greatly appreciated, I am new to JS.

Char equals char undesired output [duplicate]

This question already has an answer here:

I am trying to create a simple c++ program which prints out if char is Y or y, N or n or neither.

After debugging I have found out that the if(chr == 'Y' || 'y') statement is true even though char variable is 'N'. Can anybody tell me why this if statement is true and not false?

#include "pch.h"
#include <iostream>
using namespace std;

void main()
{
char chr = 'N';

if (chr == 'Y' || 'y')
{
    cout << "chr is y" << endl;

}
else if (chr == 'N' || 'n')
{
    cout << "chr is n" << endl;
}
else
{
    cout << "chr is something else" << endl;
}
}

microsoft SQl Query

I do not get the raised error after running an update statement on rentals

Begin 
     if (@check is not null)
     Begin try
    raiserror ('MOVIE HAS BEEN CHECKED IN AT AN EARLIER TIME',20,1) with log ;
    end try
    begin catch 
    select error_message()
    end catch
end

What the heck is - if( item1 ? item2) : item3 [duplicate]

This question already has an answer here:

I was looking through a java book and i remember reading something about using the ? operator for if statements an I cannot find the reading material anymore. I tried googling the topic but it yielded nothing. So how does the below piece of code

if( itemA ? itemB) : itemC

work

Efficient workaround instead of using numerous if statements?

What is a better workaround to this, rather than repeating this numerous times for 10 different elements?

Html:

 <div id="rightWrongContainer">
        <div id="q1" class="rightWrong"></div>
        <div id="q2" class="rightWrong"></div>
        <div id="q3" class="rightWrong"></div>
        <div id="q4" class="rightWrong"></div>
        <div id="q5" class="rightWrong"></div>
        <div id="q6" class="rightWrong"></div>
        <div id="q7" class="rightWrong"></div>
        <div id="q8" class="rightWrong"></div>
        <div id="q9" class="rightWrong"></div>
        <div id="q10" class="rightWrong"></div>
    </div>

Js:

  if (counter == 1 && answer == userInput){
        var green = document.getElementById("q1").style.backgroundColor="green";
      }
      else {
        var red = document.getElementById("q1").style.backgroundColor="red";
      }

How to break only one if condition and go to next if condition within foreach in php

I have an array containing some size as key, and quantity as value

  Array

[0] => Array
    (
        [design] => ODES657
        [color] => 347
        [06XL] => 2
        [mrp] => 0
        [net_qty] => 2
    )

[1] => Array
    (
        [design] => ODES665
        [color] => 303
        [04XL] => 3
        [mrp] => 0
        [net_qty] => 3
    )

[2] => Array
    (
        [design] => MSAF104
        [color] => 332
        [S] => 1
        [mrp] => 0
        [net_qty] => 3
        [XXL] => 2
    )

In my view page I want to add table header like if any of the array key contains a size key like "4XL" or "5XL", it will be printed as table head, or if no key contains that size value, no table header will be printed. So, I did a foreach loop, and write if condition to check if array key exists or not

    <th>Design</th>
                            <th>Color</th>
                            <th>S/20/6NO</th>
                            <th>M/22/7NO</th>
                            <th>L/24/8NO</th>
                            <th>XL/26/9NO</th>
                            <th>XXL/28/10NO</th>
                            <th>03XL/30</th>
                            @foreach($cart_items as $size)
                              @if(array_key_exists('04XL',$size) || array_key_exists('32/80CM',$size))
                              <?php $first = "ok"; break; ?>
                              @else
                              <?php $first = "no"; ?>
                              @endif
                              @if(array_key_exists('05XL',$size) || array_key_exists('34/85CM',$size))
                              <?php $second = "ok";break; ?>
                              @else
                              <?php $second = "no"; ?>
                              @endif
                              @if(array_key_exists('06XL',$size))
                              <?php $third = "ok"; break; ?>
                              @else
                              <?php $third = "no"; ?>
                              @endif
                              @if(array_key_exists('UNDEFINED',$size))
                              <?php $fourth = "ok";break; ?>
                              @else
                              <?php $fourth = "no"; ?>
                              @endif
                            @endforeach

                            @if($first == "ok")
                              <th>04XL/32</th>
                            @endif
                            @if($second == "ok")
                              <th>05XL/34</th>
                            @endif
                            @if($third == "ok")
                              <th>06XL</th>
                            @endif
                            @if($fourth == "ok")
                              <th>UNDEFINED</th>
                            @endif
                            <th>Total Qty</th>
                            <th>RSP Value</th>

In table data section I also do a normal foreach loop and print the data like

     @if($first == "ok")
                              @if(array_key_exists('04XL',$contain))
                                <td></td>
                              @elseif(array_key_exists('32/80CM',$contain))
                                <td></td>
                              @else
                                <td>-</td>
                              @endif
                            @endif
                            @if($second == "ok")
                              @if(array_key_exists('05XL',$contain))
                                <td></td>
                              @elseif(array_key_exists('34/85CM',$contain))
                                <td></td>
                              @else
                                <td>-</td>
                              @endif
                            @endif
                            @if($third == "ok")
                              @if(array_key_exists('06XL',$contain))
                                <td>
                              @endif
                            @endif
                            @if($fourth == "ok")
                              @if(array_key_exists('UNDEFINED',$contain))
                                <td>
                              @endif
                            @endif
                            <td></td>
                            <td></td>

On using break in if statement, this break put me out of the foreach loop, so if $first exists in array, it breaks the foreach loop, and $second, $third, $fourth become undefined. So, I want to know how to break only that if statement, go to next if statement but not breaking the foreach loop.