lundi 31 décembre 2018

How to get out of a loop

I'm reading a text file. If a specific string is not in the file, I'm trying to report a message. I keep getting the same message over again, or, not at all depending on where I put it.

I have moved this (code just above counter++; near the bottom) "else lbOne.Items.Add(txtID.Text + " does not exist.");" around to every conceivable line with no luck. I know just enough to be dangerous, so could use some help with this.

    if (rButtonFind.Checked)
        {
            int counter = 0;
            string line;
            System.IO.StreamReader file = new System.IO.StreamReader(@"F:\Quality\CMM Fixtures\fixtures.txt");

            if (new FileInfo(@"F:\09 Quality\CMM Fixtures\fixtures.txt").Length == 0)
            {
                MessageBox.Show("There is no data in the file to search." + "\n" + "There must be at least one fixture" + "\n" + " to not see this message.");
            }

                while ((line = file.ReadLine()) != null)
                {
                    if (line.Contains(txtID.Text))
                    {
                        lbOne.Items.Add(line);
                    }
                    else
                    lbOne.Items.Add(txtID.Text + " does not exist.");
                    counter++;
                }           

                file.Close();                
            }         
        }

As I said, it either lists the "does not exist" message many times, or not at all.

Why is the If/Else statement not working at the second else if statement?

Here is the code:

if(GridPane.getRowIndex(token1) == middleRow && GridPane.getColumnIndex(token1) == middleCol){
    mainGrid.getChildren().remove(token1);
        } else if(GridPane.getRowIndex(token17) == middleRow && GridPane.getColumnIndex(token17) == middleCol){
                mainGrid.getChildren().remove(token17);
        } else if(GridPane.getRowIndex(token3) == middleRow && GridPane.getColumnIndex(token3) == middleCol){
                mainGrid.getChildren().remove(token3);
        } else if(GridPane.getRowIndex(token4) == middleRow && GridPane.getColumnIndex(token4) == middleCol){
                mainGrid.getChildren().remove(token4);
        } else if(GridPane.getRowIndex(token5) == middleRow && GridPane.getColumnIndex(token5) == middleCol){
                mainGrid.getChildren().remove(token5);
        } else if(GridPane.getRowIndex(token6) == middleRow && GridPane.getColumnIndex(token6) == middleCol){...}

The above code continues similar statements.

Here is the error:

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3470)
    at javafx.scene.Scene$ClickGenerator.access$8100(Scene.java:3398)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
    ... 31 more
Caused by: java.lang.NullPointerException
    at sudoku.FXMLDocumentController.removeMiddleToken(FXMLDocumentController.java:166)
    at sudoku.FXMLDocumentController.moveToken(FXMLDocumentController.java:162)
    at sudoku.FXMLDocumentController.isMoveLegal(FXMLDocumentController.java:151)
    at sudoku.FXMLDocumentController.square33Click(FXMLDocumentController.java:447)
    ... 41 more

The error starts at the first "else if" statement following the first "if" statement. All of the code seems to make sense but is not working in the running of the program. I do not understand.

Thanks!

In Python, how do I create aliases? I want to rename "elif" as "elseif"

In C, one can use #define to make a developer's life easier. In C, it is possible to do this: #define el else. This would allow a developer to write either else or el depending on their preferences, and the compiler would replace all the "el"s with "else" during pre-compilation..

Is there anything similar in python? Is there something in python that will allow me to create aliases for my own convenience?

Removing duplicates in R based on condition

I need to embed a condition in a remove duplicates function. I am working with large student database from South Africa, a highly multilingual country. Last week you guys gave me the code to remove duplicates caused by retakes, but I now realise my language exam data shows some students offering more than 2 different languages. The source data, simplified looks like this

STUDID   MATSUBJ     SCORE
101      AFRIKAANSB   1
101      AFRIKAANSB   4
102      ENGLISHB     2
102      ISIZULUB     7
102      ENGLISHB     5

The result file I need is

STUDID   MATSUBJ    SCORE  flagextra
101      AFRIKAANS   4
102      ENGLISH     5
102      ISIZULUB    7     1

I need to flag the extra language so that I can see what languages they are and make new category for this

db2 - CASE WHEN or IF Statement in CREATE FUNCTION

Hi I've got a problem managing CASE WHEN or IF Statements in a CREATE FUNCTION Call in DB2 I tried this Statement:

CREATE OR REPLACE FUNCTION NAECHSTES_DATUM(PARAM1 CHAR(6), PARAM2 DATE)
RETURNS DATE
LANGUAGE SQL
BEGIN
    DECLARE BASEDATE DATE;
    DECLARE THATDATE DATE;
    SET BASEDATE = TO_DATE(CONCAT(PARAM1,CAST(YEAR(PARAM2) AS CHAR(4))),'DD.MM.YYYY');
    IF (BASEDATE >= PARAM2) 
    THEN SET THATDATE = BASEDATE;
    ELSE SET THATDATE = BASEDATE + 1 YEAR;
    END IF;
    RETURN THATDATE;
END 

I get this error

[-104] Auf "+ 1 YEAR" folgte das unerwartete Token "END-OF-STATEMENT". Mögliche Tokens: " END IF".. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.14.113

Similar result when I use CASE WHEN.

Do you know where the problem could be?

dimanche 30 décembre 2018

Java Prime number checking output with error

I write down a code find and count the number of prime number within a given range.

Prime number - A number divide by 1 or itself.

My code:

import java.util.ArrayList;

public class Q204 {
public static void main(String args[]) {
   Solution204 ob3=new Solution204();
    int Ans=ob3.countPrimes(10);
    System.out.println(Ans);

}
}

class Solution204{
public int countPrimes(int n){
    ArrayList<Integer>count=new ArrayList<>();
    int count_prime_no=0;
     for(int j=2;j<=n;j++){
        boolean isPrime=true;
        for(int i=2;i<=(j/2);i++){
            if(j%i==0){
                isPrime=false;
                break;
            }

        }
        if (isPrime=true){
            count.add(j);
        }
    }
    System.out.println(count);
    count_prime_no=count.size();

        return count_prime_no;
    }
 }

No number is divisible by more than half of itself. So, we need to loop through just number/2(As per my code (j/2)). If the input is 17, half is 8.5, and the loop will iterate through values 2 to 8.

There is no logical and syntactical error in my code. I revised this code almost 20 times but cannot find out the logical error.

My output is: [2, 3, 4, 5, 6, 7, 8, 9, 10] 9 Which is definitely a flaw of output.

I also debug this code line by line and see when it get 4 it go to line isPrime=false but still come to the control

 if (isPrime=true){
        count.add(j);
    }

and add 4 to the count list. I know may be something wrong in my code but as I write it may be I overlook it. If someone recheck it and tell me where is the flaw it might be very helpful me.

Thank you.

How to create a loop and move to the cell below when a condition is not met on excel or VBA?

I have a list of keywords and a list of questions on excel. I need to see IF every single keywords is found into the questions or not.

e.g.

       A                    B
   1 expense      how is my bonus calculated?
   2 business     how do i change my bank account? 
   3 bonus        how do i apply for a credit card?

I was trying to solve it with an IF statement on excel such as:

=IF(ISNUMBER(SEARCH(A1,B1)),A1,IF(ISNUMBER(SEARCH(A2,B1)),A2,IF(ISNUMBER(SEARCH(A3,B1)),A3,"no")))

but it works just for few keywords, so I was wondering if there is an alternative way as a formula or maybe an easy method on VBA to create a loop.

In other words: IF A1 is NOT on B1, look at A2, if not, look at A3, etc.

Thanks a lot to everyone will help!

Logic of if statement only reaches 9/10

The code is supposed to award the majority of 10 flips to the winner coin side. However it is only going to 9 flips and rewarding the majority out of the 9.

I have tried tempering around the numbers, but none have succeeded. upon changing the percentage to 110 the total flips only goes to 7

if(51 <= heads_counter / wins * 100 && tails_counter / wins * 100 <= 49){
            placeholder.innerText = ("Heads Wins!");
            heads_counter = 0;
            tails_counter = 0;
        //if the majority of total flips is tails, "Tails wins!" is displayed
        }else if (51 <= tails_counter / wins * 100  && heads_counter / wins * 100 <= 49){
            placeholder.innerText = ("Tails Wins!");
            heads_counter = 0;
            tails_counter = 0;
        //if flips are tied, "Tie!" is displayed
        }else if(tails_counter / wins * 100 == 50 && heads_counter / wins * 100 == 50){
            placeholder.innerText = ("Tie!")
            heads_counter = 0;
            tails_counter = 0;
        }

the flip counter should only be going to best out of 10 then reset, but they are only going to 9

Unexpected end of file error afterv adding if else statement to my WordPress content template

I've been looking at various examples of SO on how to solve this but no luck yet. Basically, I wanted to add an if else statement to my WordPress content template, which was fine previously, but now I get an Unexpected end of file message and I'm stumped as to where that might be. This is the original code:

<div class="entry-content">
    <?php 
        the_content( sprintf(
        wp_kses(
            __( 'Continue reading<span class="screen-reader-text"> "%s"</span>', 'mytheme' ),
            array(
                'span' => array(
                    'class' => array(),
                ),
            )
        ),
        get_the_title()
    ) );

    echo '<p class="btn-cc"><a href="%s" rel="bookmark">Read More</a></p>';

    wp_link_pages( array(
        'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'mytheme' ),
        'after'  => '</div>',
    ) );

    ?>
</div>

and this is what I did to it.

<div class="entry-content">
    <?php if ( is_category() || is_archive() ) {
        the_excerpt('');
            } else {
        the_content( sprintf(
        wp_kses(
            __( 'Continue reading<span class="screen-reader-text"> "%s"</span>', 'mytheme' ),
            array(
                'span' => array(
                    'class' => array(),
                ),
            )
        ),
        get_the_title()
    ) );

    echo '<p class="btn-cc"><a href="%s" rel="bookmark">Read More</a></p>';

    wp_link_pages( array(
        'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'mytheme' ),
        'after'  => '</div>',
    ) );

    ?>
</div>

So where did I make a mistake?

How to mitigate server-dependent behavior for REQUEST_URI to use it to suppress a specific shortcode

I noticed something quirky regarding when I put the following line in my PHP code:

echo strpos($_SERVER['REQUEST_URI'], "/?s=");

If the following URL is entered: https://s1.temporary-access.com/~allacros/devel/?s=tahiti the echo statement returns '16'. That's expected behavior.

However, if the following URL is entered: http://stage.world-of-waterfalls.com/?s=tahiti the echo statement returns '0'.

That's unexpected behavior, and it has consequences in that I cannot seem to use the following code to suppress the shortcode that causes an erroneous button artifact caused by that shortcode for search results pages (the only case I've seen where I'm trying to rely on this)...

if( !( empty( strpos($_SERVER['REQUEST_URI'], "/?s=") ) ) )
    remove_shortcode('uwr-button');

Anyone know why this is happening? And how to fix the code so it's agnostic to the server it's on (assuming that's the issue)?

Randint and if statements in python: error

correctPath = random.randint(1,2,3)

if chosenPath == str(correctPath):
   print("Thank you for your help")
   print("this has been altered for creative purposes")
elif chosenPath != str(correctPath):
    print("Thanks in advance.")
else:
   print ("code to be written")

Why can't you compare the value of two int type vairables? [duplicate]

This question already has an answer here:

I was just compiling some code while learning c++ and reached this on the compiler.

context: For this code which takes a 1 Dimensional vector v and a value n then tries finding this value n in v. If found returns the index of it and if not it returns -1.

int mfind(int n, const std::vector <int>& v){

int a = v.size();

for(int i=0; v[i]!=n && i<a; i++){
int index = i;
}

if(index < a){
    return index;
}
else{
    return -1;
}

}

Index and i are both integers and when compared in the if condition it outputs an error:

error: 'index' was not declared in this scope.

Is it that that you cannot compare the values of two integers ? if there is another reason to this error I would love to know why and how it is that you can compare the values of two different int type variables. many thanks.

I am new around here if I there is anything wrong with the post or layout etc let me know I will change it. Many thanks.

onClick does not workon first click

I'm trying to let a button element switch its text between 'Follow' and 'Unfollow', but why isn't the javascript reacting on the first click on the button?

HTML:

<form method="post">
    <button class="follow" onclick="this.innerHTML = follow_test(this.innerHTML)">

        Follow

    </button>
</form>

JavaScript:

    function follow_test(string) {
        if (string === 'Follow') { return ('Unfollow'); } else { return('Follow'); }
    }

How to check spreadsheet cell value with MATCH without triggering NOW() function?

Trying to create a table that checks if the room key is already taken. Google spreadsheet link.

An employee selects or enters the value into F2 cell. The formula in the G2 cell =IF(ISERROR(MATCH(F2,C4:C350,0)), "Brīvs", "Paņemts") tests whether the key is take or not. The formula runs through C column and tests for the value.

While matching, it is also triggering the formula in B4 cell. Formula in B4 being =IF(C4>0, now(), "")

Issue is, every time an employee selects/enters the value, the MATCH function triggers the now() function and overrides the newest time if it matches the search criteria.

Is there a way of testing for the value without invoking the now() function so that the time stays as it was? Limiting recalculation counts in spreadsheet settings does not aid since an employee may not enter the value correctly from the 1st time.

Tried putting the value into another cell by "=" to nearby cell and =cell(contents, cell coordinate), but these refer back to the original values and Spreadsheet would recalculate all the references.

Why does my second if statement run 2 times in a row after my first if statement is true?

Hello guys I have a problem with my checkRight() function. I tried to build a quiz webpage with js. Here is my complete code: https://www.codeply.com/go/qoCnPUDDxG My questions consists of a class with: question (string), answers(array of strings) and answer (string) attributes. If I click on the right answers my counters go very confusing up.

function checkRight (){
  $(".answer").click(function() {
       check = $(this).html();
       if(check===qAry[i].rightAnswer){
         rightCounter++;
         $(".richtigZaehler").text(rightCounter);
         i++;
         askQ();
       }
         else if(check!=qAry[i].rightAnswer){
         console.log("Update");
         wrongCounter++;
         $(".falschZaehler").text(wrongCounter);
      }
  });
}

How to copy cells to another sheet using IF AND Macro?

I would like to copy some specific columns if criterias are met. Namely if the value in row 4 is "Fælles" and the text is NOT bold.

Please take a look at my code and tell me what i do wrong. I don't have much experience with coding or VBA.

Private Sub CommandButton1_Click()

A = Worksheets("Stig Okt").Cells(Rows.Count, 1).End(xlUp).Row

For i = 34 To A

Next

If Worksheets("Stig Okt").Cells(i, 4).Font.Bold = False And Cells(i,     4).Value = "Fælles" Then

Worksheets("Stig Okt").Rows(i).Columns("A:H").Copy

Worksheets("Laura Okt").Activate

b = Worksheets("Laura Okt").Cells(Rows.Count, 1).End(xlUp).Row

Worksheets("Laura Okt").Cells(b + 1, 1).Select

ActiveSheet.Paste

End If

If Worksheets("Stig Okt").Cells(i, 4).Font.Bold = False And Cells(i, 4).Value = "Lagt ud" Then

Worksheets("Stig Okt").Rows(i).Columns("A:H").Copy

Worksheets("Laura Okt").Activate

b = Worksheets("Laura Okt").Cells(Rows.Count, 1).End(xlUp).Row

Worksheets("Laura Okt").Cells(b + 1, 1).Select

ActiveSheet.Paste

End If

Worksheets("Stig Okt").Activate


End Sub

No error occours, but it doesn't really do anything and i don't understand why?

How to copy specific equal row with specific cells in row to another sheet

sheet1 is my master sheet, I have sheet2 as truck 184 and then also have sheet3 as truck 185.

In my master sheet (sheet1) in the first column is going to determine what data will be sent to the correct sheet (truck 184 or to truck 185), so if I enter truck 184 did the run, I want it to send certain cells to sheet2 (truck 184), same for truck 185 if truck 185 did the run.

I can get it to transfer info by specific = cell conditioning, but I am not sure how to get it to determine conditioning by what sheet it it suppose to go to. So I have across the top for headers, Truck, date, Origin, Broker, Destination extra. but I only want it to send certain info from that line not all info to sheet 2 and to sheet 3 determined by what truck did what run, so I can see the master (sheet1) and have individual reports for each truck provided by master sheet. I need help please.

How to delete the entire row in a dataframe if one element equals "XYZ" [duplicate]

This question already has an answer here:

How to delete the entire row if one entry of it equals an element within an array. Any good ideas how to do this very fast?

How to put my own function in side an if statement?

I am trying to make a simple blackjack game and i want to be able to create my own function, which a can already do, and then put it inside an if statement so that if the user want's to 'stand' then it runs the function to 'stand'. However, when python reads through the code, even if the user say 'Hit', it see's all the functions and just runs all of them.

def stand():
    print("You have chosen to Stand")
    #my stand code will go here
def hit():
    print("You have chosen to Hit")
    #my Hit code will go here
def doubledown():
    print("You have chosen to Double Down")
    #my Double Down code will go here
def step():
    step = input("What would you like to do now? Stand, Hit or Double Down")
    if step == ("Stand") or ("stand"):
        stand()
    if step == ("Hit") or ("hit"):
        hit()
    if step == ("Double down") or ("down"):
        doubledown()
    else:
        step()
step()

I would like the user to be able to run the 'Hit', 'double down' or 'stand' function 1 at a time without all of them running.

samedi 29 décembre 2018

How many characters are in given array but spaces

I am trying to find out how many characters are in the given array except blanks but it's not working, k supposed to count blanks and substract them from i[characters + blanks] but it doesn't.

int i= 0;
int n= 0;
int k= 0;
char c[256] = {};
fgets(c ,256, stdin);

while(c[i] != '\0' ){
     if(c[i] == ' '){
             i++;
             k++;
             continue;}
i++;}


printf("%d",i-k);

when writing an if statement in PHP, is there a numbers equivalent to the string-length (strlen) function?

I learned how to use the string-length function <?php //example $text = "this way"; if (strlen($text) > 5//characters//){ echo "something"; }

and I want to use something like it that applies to number variables.

$text = 7;

What function would that be?

conditional statement in carousel

please I need help with this code of mine. I am trying to display only fields from my SQL table with contents in my carousel. I do not want the carousel to always slide into an empty item and display a broken photo icon at the top right corner.

                                $query = "SELECT * FROM property where id = '".$id."' ";
                                $result_new = mysqli_query($con, $query) or die("Could not execute query");
                                while ($row = mysqli_fetch_array($result_new))
                                {

                                $picture1 = "propertyphotos/".$row['picture1'];
                                $picture2 = "propertyphotos/".$row['picture2'];
                                $picture3 = "propertyphotos/".$row['picture3'];
                                $picture4 = "propertyphotos/".$row['picture4'];

                                   if(!empty($row['picture1']))
                                        {
                                           $pic1= '<div class="item active">
                                            <img class="s-property-image" src="<?php echo $picture1; ?>" />
                                            </div>';
                                        }

                                    if(!empty($row['picture2']))
                                        {
                                           $pic2= '<div class="item active">
                                            <img class="s-property-image" src="propertyphotos/<?php echo $picture2; ?>" />
                                            </div>';
                                        }

                                    if(!empty($row['picture3']))
                                        {
                                           $pic3= '<div class="item active">
                                            <img class="s-property-image" src="propertyphotos/<?php echo $picture3; ?>" />
                                            </div>';
                                        }

                                    if(!empty($row['picture4']))
                                        {
                                           $pic4= '<div class="item active">
                                            <img class="s-property-image" src="propertyphotos/<?php echo $picture4; ?>" />
                                            </div>';
                                        }

                                }
                                ?>
                                <?php echo $pic1; ?>
                            </div>

Or if there is a better to this i would love to learn. thank you

what is the recommended way to check error in rest api? [duplicate]

We are building Rest API, but we're not able to decide how we should show the errors, what is more common and easy to use.

1)

$request = class->function();
try{
//success
}catch(Exception $e){
echo $e->getMessage();
}

vs

$request = class->function();
if($request['status']){
//success
}else{
echo $request['error']['message'];
}

2) If we decide to go with if/else then which key is more common, and easy to use? $request['status'] or $request['state'] or something you can recommend.

We also looked for best practices of designing API but none of them mentioned this case.

Using an If/Else statement with toString but boolean is only read as false [duplicate]

This question already has an answer here:

I'm still a basic programmer and am starting on a small program to help me with workouts. In my code, I'm using a boolean to determine two different statements in my toString method. However, I'm having trouble getting the if/else statement to read the boolean as true when necessary and as a result only the false toString statement is being printed on the console. What am I doing wrong?

package workoutPackage;

import java.util.Scanner;

public class WorkoutRegimeMenu {

    public static void main(String[] args) {
        Scanner menuChoice = new Scanner(System.in);
        int choice;
        do {
            System.out.println("*****Workout Regime Menu*****\n");
            System.out.println("1. Enter todays workout information");

            choice = menuChoice.nextInt();

            switch (choice) {
            case 1:
                Scanner sInput = new Scanner(System.in);
                Scanner iInput = new Scanner(System.in);
                boolean bWalk = false;

                System.out.println("What is the date of this workout?");
                String date = sInput.nextLine();

                System.out.println("What was your weight the morning of the workout? (in pounds)");
                int weight = iInput.nextInt();

                System.out.println("Did you walk at least an hour on this day? (y or n)");
                String walk = sInput.nextLine();
                if(walk == "y") {
                    bWalk = true;
                }
                WorkoutInformation enterInfo = new WorkoutInformation();
                enterInfo.setInfo(date, weight, bWalk);
                System.out.println(enterInfo);
                break;

            default:
                System.out.println("Please enter one of the numbered choices above");
                break;
            }
        } while (choice != 0);
    }
}



package workoutPackage;

public class WorkoutInformation {
    private String date;
    private int morningWeight;
    private boolean walk;

    public void setInfo(String workoutDate, int weight, boolean bWalk) {
        this.date = workoutDate;
        this.morningWeight = weight;
        this.walk = bWalk;

    }
    public String toString() {

        if (walk == true) {
            return String.format("On %s you weighed %d pounds, walked for about an hour, and then performed your workouts.", date, morningWeight);
        } else {
            return String.format("On %s you weighed %d pounds and then performed your workouts.", date, morningWeight);
        }
    }
}

If walk is true, then the first toString statement should print. However it is always read as false so only the second toString statement is printed.

Adding numbers in an Array with a given condition

I have numbers in an array, odd and even, I have to add the odd ones with one another and the even ones wit one another. I am very confused as to how to go about this because of the parameters and conditions given:

In my Adder.h file I have the following:

@interface ConditionalAdder : NSObject

- (instancetype)initWithNumbers:(NSArray *)numbers;

- (int)sumWithCondition:(NSString *)condition;

@end

In my Main.m file I have the following code:

#import "ConditionalAdder.h"

int main(int argc, const char * argv[]) {
  @autoreleasepool {

    ConditionalAdder *adder1 = [[ConditionalAdder alloc] 
    initWithNumbers:@[@1, @2, @3, @4, @5]];
    NSLog(@"%i", [adder1 sumWithCondition:@"even"]);
    NSLog(@"%i", [adder1 sumWithCondition:@"odd"]);

    ConditionalAdder *adder2 = [[ConditionalAdder alloc] 
    initWithNumbers:@[@13, @88, @12, @44, @99]];
    NSLog(@"%i", [adder2 sumWithCondition:@"even"]);

    ConditionalAdder *adder3 = [[ConditionalAdder alloc] 
    initWithNumbers:@[]];
    NSLog(@"%i", [adder3 sumWithCondition:@"odd"]);
  }

  return 0;
}

I know that this method:

- (int)sumWithCondition:(NSString *)condition;

Should return an integer, but what string am I supposed to pass through the parameter?

While and if looping with pandas

I'm having problems to understand where is my mistake. I'm trying to get an input from the user > if "yes" - show some data from a DataFrame > if "no" keep going with the program.

Inside of if "yes" there's another question "Do you want more data?", and once again > if "yes" keep showing > if "no" leave both loops and continue with the program.

def display_data(df):
        n = 0
        raw_in = input('\nWould you like to see some raw data? yes or no.\n').lower()
        if raw_in in ['yes','no']:
            if raw_in == 'yes':
                raw_data = df.iloc[n:n+5,:]
                n += 5
                print(raw_data)
                raw_in = input('\nMore data? yes or no.\n').lower()
                if raw_in not in ['yes','no']:
                    print('\nInvalid option.\n')
                    display_data(df)
                else:
                    pass

That's what I've tried. I keep changing from while to if or their position, but I don't find the solution.

C++ expected unqualifed-id before 'if' and expected unqualifed-id before 'else'

I am new to c++, and i use Codeblocks as IDE. I get these two errors "expected unqualifed-id before 'if'" and "expected unqualifed-id before 'else'". I searched around a lot and gotten nothing. My goal is for the story to progress after the users choices so they choose the genre and get a specific story. I am open for any critics because i only want to get better.

#include <iostream>

using namespace std;

void Story(){
char genre;
cout << "Hello!" << endl;
cout << "I will now tell you a story that will change according to your 
choices" << endl;
cout << "Beware!" << endl;
cout << "" << endl;
cout << "Lets start the story" << endl;
cout << "Your first choice is the genre" << endl;
cout << "Adventure or Post Apocalypse: " << endl;
cout << "If you want Adventure type A or P for Post Apocalypse: " << endl;
cin >> genre;
}
if(genre == 'A'){
Adventure();
}
else if(genre == 'P'){
PostApocalypse();
}
string Adventure(){
cout << "Adventure" << endl;
return 0;
}
string PostApocalypse() {
cout << "Post Apocalypse" << endl;
return 0;
}
int main(){
Story();
return 0;
}

Thanks in advance and sorry for my bad english

How do i create unique updating list if criterie is met in another worksheet?

So i want to copy a certain range of coloumns to another worksheet if certain criterias are met with a comman button. Namely if D36:D160 is "Fælles" or "Lagt ud" then coloumns A:H in this region should be copied to another worksheet in the workbook in the same region. However, it has to go in the first blank space and be the unique values. Worksheet "Stig Jan"

Worksheet "Laura Jan"

As the list is updating it has to copy to the other without copying the same data.

Please bear in mind that i am just a humble carpenter making a budget for me and my partner in my spare time. I have tried looking for similiar questions and lessons on here and youtube, but haven't found the soulution.

Private Sub CommandButton1_Click() A = Worksheets("Stig Jan").Cells(Rows.Count, 1).End(xlUp).Row

For i = 34 To A

If Worksheets("Stig Jan").Cells(i, 4).Value = "Fælles" Then

Worksheets("Stig Jan").Rows(i).Columns("A:H").Copy

Worksheets("Laura Jan").Activate

b = Worksheets("Laura Jan").Cells(Rows.Count, 1).End(xlUp).Row

Worksheets("Laura Jan").Cells(b + 1, 1).Select

ActiveSheet.Paste

Worksheets("Stig Jan").Activate

End If

Next

End Sub

I have succesfully been able to copy it to the other area if the "Fælles" criteria is met. I don't know how to add the "Lagt ud" criteria. And then when i click the the button it just copies the same values over and over again.

I hope you understand my question.

Thank you for taking your time to read this! :)

Existe algum tipo de tabela, para mostrar a ultima vez atualizado dado de uma linha no MongoDB

Eu tenho um app em Angular 7+ full STACK MEAN Com mongoDB, E estou listando umas informacoes, que sao constantemente atualizadas. Eu queria poder colocar uma tabela onde diga Se uma linha nao atualizar, me mostre a quanto minutos esta Offline

jQuery: Conditional statement and length on each element where attr contains number

Trying to get a count of each label element that has the class "active" and it's input attr, "data-price", contains just a number/price between the [&quot;&quot].

So, if tot element count is > 0, do something...

HTML

<ul class="elem-ul">
    <li class="elem-li">
        <label class="elem-label active">    
            <input class="elem-input" data-price="[&quot;100&quot;]" type="checkbox">
       </label>         
   </li>
    <li class="elem-li">
        <label class="elem-label active">    
            <input class="elem-input" data-price="[&quot;400&quot;]" type="checkbox">
       </label>         
   </li>
    <li class="elem-li">
        <label class="elem-label active">    
            <input class="elem-input" data-price="[&quot;&quot;]" type="checkbox">
       </label>         
   </li>
    <li class="elem-li">
        <label class="elem-label">    
            <input class="elem-input" data-price="[&quot;&quot;]" type="checkbox">
       </label>         
   </li>
</ul>

vendredi 28 décembre 2018

My try catch function won't work as expected

My program is supposed to take the given value and find the other value with it. However, my try catch statement doesn't seem to be working. It never does the first 2 if statements which are the most essential parts of the program. The 3rd one does work when you input both values. Thanks in Advance.

    public void calculate(View view) {
    EditText length_find = findViewById(R.id.feet);
    EditText pounds_find = findViewById(R.id.pounds);

    try {
        int length_int = Integer.parseInt(length_find.getText().toString());
        int pounds_int = Integer.parseInt(pounds_find.getText().toString());

        double d = .29;
        double length = length_int;
        double pounds = pounds_int;
        double w = 24.5 / 12;
        double h = .002 / 12;

        //This Calculates if Pounds are given
        if ((length_find).getText().toString().trim().length() <= 0){
            Toast.makeText(MainActivity.this, "Given Pounds", LENGTH_LONG).show();
            double v = pounds / d;
            length = v / w / h;
            final TextView mTextView = (TextView) findViewById(R.id.length_show);
            mTextView.setText((int) length);
        }


        //This Calculates if Length is given
        if ((pounds_find).getText().toString().trim().length() <= 0){
          Toast.makeText(MainActivity.this, "Given Length", LENGTH_LONG).show();
          double v = length * w * h;
          double answer_pounds = v * d;
          final TextView mTextView = (TextView) findViewById(R.id.pound_show);
          mTextView.setText((int) answer_pounds);
        }
        if((pounds_find).getText().toString().trim().length() > 0 && (length_find).getText().toString().trim().length() > 0){
            Toast.makeText(MainActivity.this, "Whata hell you need me for mate!", LENGTH_LONG).show();
        }

    }
    catch(Exception ex) {
            Toast.makeText(this, "Error", 
            Toast.LENGTH_SHORT).show();
        }

Print biggest and smallest numbers ,until -1 is given

It works, but if you don't enter any number smaller than 0 it doesn't print the smaller value and prints 0.

int max = 0;
int min = 0;
int a;

printf("Enter a number:\n");
scanf("%d", &a);

while (a != -1){
        if (a < min){
            min = a;
        }

        if (a > max){
            max = a;
        }
        scanf("%d", &a);
}
printf("Your largest number is %d. Your smallest number is %d.", max, min);

c++ if statement malfunction

why are my else if loops not working the code when ran skips over the else statement and executes the if statement even if it is not true

   #include<iostream>
    using namespace std;
    int a;
    int b;
    char operation;
    int sum;
    int sub;
    int mul;
    int divide;
    int mod;
    int main()
    {
    cout<< "enter a number \n";
    cin >> a>>operation>>b;
    if (operation= '')
    {
        sum=a+b;
        cout << a<<operation<<b<<sum;
    }
    else if (operation= '-')
    {
        sub=a-b;
        cout << a<<operation<<b<<sub;
    }
    else if (operation= '/')
    { if(b==0){
        cout<<"You cannot divide by zero";
    }
        else{divide=a/b;
        cout << a<<operation<<b<<divide;}
    }else if (operation= '*')
    {
        mul=a+b;
        cout << a<<operation<<b<<mul;
    }
    else if (operation= '%')
    {
        mod=a%b;
        cout << a<<operation<<b<<mod;
    }
    else{
        cout<<"Invalid input";
    }

        return 0;
    }

the output is always just adding the numbers no matter what sign the input has it wont go over my else if statements even if the operation isnt + infact even if i use a wrong operation it just adds the two numbers

If-else statements Python

I was wondering why we write "elif", if we could just write "if" for a "elif" statement.

Just a question of curiosity, why do we write "elif e == (f + 10)" instead of just "if e == (f+10)"?

e = 20

f = 10

elif e == (f + 10):
    print("e is 10 more than f")

Why can't I replace the "elif" with "if" and tell me why that wont work if I replace with my adulation.

is it possible to use if-else statements in mocha's it() function individually?

I recently started with mocha and wanted to know if we could use if else statements for conditional testing. I want to be able to use conditions in ever it() function in order to put assertions on Json data received in response to that getprojection() function call.

I have posted a code as an example to illustrate what I am trying to achieve. Any help would be appreciated. Thanks!!

var assert = require('chai').assert;
var expect = require('chai').expect;
var should = require('chai').should();
// var projection = require('');
var projectionsTest = require('./getProjection')



    describe("Annual Tax Projection", function () {
        describe("Current Year Tax - #2018", function () {
            it("should return correct taxable Income", function (done) {
                projectionsTest.getProjection('params', 'params', function (projections) {
                    if (grossIncome <= deductions){
                        assert.deepEqual(projections[2018].taxableIncome, 0)
                    }else throw new Error("There is something wrong with tax calculation")
                    done(Error);
                });
            });
            it("should check federal tax is calculated correctly", function (done) {
                projectionsTest.getProjection('params', 'params', function (projections) {
                    if (taxableIncome === 0 || taxBracket ===10){
                        assert.deepEqual(projections[2018]. )
                    }else
                    done(Error);
                });
            });
        });
    })

Does AND(&&) inside an If-Statement get checked in the order I type it?

Let's say I have this code:

if(number_a==1 && number_b==2) {
doStuff();
}

Will my code run any faster, If i split it up into:

if(number_a==1){
    if(number_b==2){
        doStuff();
    }

}

Or does the computer run the code in the exact order I gave it, checking a first, and instantly moving on if a isn't 1 ? Or is there a chance the computer checks b first, or checks both(even if a isn't 1)?

Imacros Javascript iim function to compare value If or Else if

My configuration is OS: windows 7 ultimate Estension: imacros 8.9.7 Browser: Firefox 56

I have a variabile with my ip address example

    var1 = 123.123.123.123

I have a csv file with all bad ip address to compare with my ip (var1)

list of bad ip to compare with var1:

    badip.csv 
    111.111.111.111
    112.112.112.112
    113.113.113.113
    114.114.114.114
    115.115.115.115
    116.116.116.116
    117.117.117.117
    118.118.118.118
    119.119.119.119
    120.120.120.120

Now I need with imacros (iim or js) to compare my ip addres (var1) with all badip saved in csv, and only after comprare my ip address (var1) with all bad ip saved in csv if my ip address (var1) is NOT present in badip.csv list go on mysite.com.

I need to compare my ip address (var1) with all badip and only if my ip address (var1) is NOT present in badip.csv list the macro continue loading mysite.com.

If my ip address (var1) is present in badip.csv the macro must not continue or stop.

I want favorite button for different stories to work properly

I am facing a problem in PHP Laravel project. I have a favorite button for stories. Different users will have an option to make favorite the story they liked. "Stories" and "Favorite_Story" have separate tables. I have fetched all stories from the stories table, and fav_story from "fav_story" table, based on user_id.

This is my controller code

public function fanfiction(){
    $user_id = session('userid');
    $data['stories'] = DB::Table('stories')->orderBy('story_id', 'des')->get();
    $data['fav_story'] = DB::Table('favorite_story')->where('user_id', $user_id)->get();
    return view('fanfiction', $data);
}

This is my view code

@foreach($stories as $row)
                <?php $story_id = $row->story_id; ?>
                <article class="post excerpt">
                    <a href="" id="featured-thumbnail">
                        <div class="featured-thumbnail">
                            @if($row->img == '')
                            <img class="img-responsive" width="30%" src="" alt="Story Image" />
                            @else
                            <img class="img-responsive"  width="30%" src="" alt="Story Image" />
                            @endif
                        </div>                      
                    </a>
                    <div class="post-content" style="text-align:justify;">
                        ;
                        <h3></h3>
                    </div>

                    <div class="readMore">
                        @if(Session('username'))
                            @foreach($fav_story as $row1)
                                @if($row1->story_id == $story_id)
                                <a href="" style="background:#59AAE1;" > Unfavorite</a>
                                @elseif($story_id)
                                    <a href="" style="background:#1dbf73;" > Favorite</a>
                                @endif
                            @endforeach
                        @endif
                    </div>
                </article>
                @endforeach

The stories which are marked as a favorite story will show an unfavorite button with that specific story, which will be made favorite on again click on that button. The problem is, it shows both favorite and unfavorite button with that specific story and not button for favorite is shown which needs to have this button to make it as favorite. Please help me asap. Thank you

Find out unique factor using java

Problem: Print all unique combination of factors (except 1) of a given number.

For example: Input: 12

Output: [[2, 2, 3], [2, 6], [3, 4]]

My Solution:

public class Unique_factor {
public static void main(String args[]){
    int number=12;
    ArrayList<ArrayList<Integer>>combination=new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer>abc=new ArrayList<>();
    for(int i=2;i<=number;i++){
        if(number%i==0){
            abc.add(i);
            int result=number;
            for(int j=i;j<=(number/i);j++){
                if(result%j==0) {
                    result = result / j;
                    abc.add(j);
                }

            }


        }

    }

    //System.out.println(combination);
    System.out.println(abc);
}
}

Output:

[2, 2, 3, 3, 3, 4, 4, 6, 12]

As per my code it print out all the possible factor of 12. J loop iterate until the (number/i). I create a list of list type arraylist combination to create a list of list. But don't know how to utilize it? Where should I change my code?

How to prevent Java Script function from refreshing the page (on it's own) after execution

I am trying to create a function that takes the information from a dropdown list and according to the chosen option it shows an element after a successful submission of the form. The function works fine but after it is executed it automatically refreshes the page even though there is no command telling it to refresh causing the element to disappear in a blink of an eye after submission

I have tried to achieve the same thing using the switch statement but it results the same way which makes me think that something else may be causing it

<div id="container" align="center"><br />

<form action="#" method="POST">
<input type="text" class="fields" name="userid" placeholder="Enter user ID here" />
<select id="selectOptions" class="dropdown">
    <option value='name'>Name</option>
    <option value='username'>Username</option>
    <option value='password'>Password</option>
    <option value='email'>Email</option>
    <option value='privilege'>Privilege</option>
</select>
<button class="regbutton" onclick="openChange()">Submit</button>
</form>

<script>
function openChange(){
    var option = document.getElementById("selectOptions");
    var value = option[option.selectedIndex].value;

        if(value = "name"){
            document.getElementById("1").style.display = "initial";
        }
        else if(value = "username"){
            document.getElementById("2").style.display = "initial";
        }
        else if(value = "password"){
            document.getElementById("3").style.display = "initial";
        }
        else if(value = "email"){
            document.getElementById("4").style.display = "initial";
        }
        else if(value = "privilege"){
            document.getElementById("5").style.display = "initial";

        }
}
</script>
</div>

<label id="1" class="option"><input type="text" class="fields" placeholder="Enter new name" /></label>
<label id="2" class="option"><input type="text" class="fields" placeholder="Enter new username " /></label>
<label id="3" class="option"><input type="text" class="fields" placeholder="Enter new password" /></label>
<label id="4" class="option"><input type="text" class="fields" placeholder="Enter new email" /></label>

I expect this function to show the proper element according to the chosen option and then end but it actually refreshes the page after it executes it's primary function

Is there a way to let biggest value on X (out of X, Y, Z) decide value on V in R?

I have a dataset (ft.mutate.topics) with five variables (four numeric are ft_technical, ft_performative, ft_procedural and ft_moral). The fifth is "topic_lab" and I would like for it to take on the name (as a character) related to the variable with the highest value of the four other.

I have tried the following with a combination of if-commands:

if (ft.mutate.topics$ft_technical > ft.mutate.topics$ft_performative &
    ft.mutate.topics$ft_technical > ft.mutate.topics$ft_procedural &
    ft.mutate.topics$ft_technical > ft.mutate.topics$ft_moral)
  ft.mutate.topics$topic_lab = "technical"

if (ft.mutate.topics$ft_performative > ft.mutate.topics$ft_technical &
    ft.mutate.topics$ft_performative > ft.mutate.topics$ft_procedural &
    ft.mutate.topics$ft_performative > ft.mutate.topics$ft_moral)
  ft.mutate.topics$topic_lab = "performative"

if (ft.mutate.topics$ft_procedural > ft.mutate.topics$ft_performative &
    ft.mutate.topics$ft_procedural > ft.mutate.topics$ft_technical &
    ft.mutate.topics$ft_procedural > ft.mutate.topics$ft_moral)
  ft.mutate.topics$topic_lab = "procedural"

if (ft.mutate.topics$ft_moral > ft.mutate.topics$ft_performative &
    ft.mutate.topics$ft_moral > ft.mutate.topics$ft_procedural &
    ft.mutate.topics$ft_moral > ft.mutate.topics$ft_technical)
  ft.mutate.topics$topic_lab = "moral"

It says: "the condition has length > 1 and only the first element will be used" and substitutes the whole variable with "performative" because it is has the highest value in row 1. Anybody know what is up?

Thank you!

Why is this if-statement true? Different arry address

I don't understand why this if-statement is true can someone explain it to me?

int a[8][8] = {0};

if(&a[7][0] == &a[0][0] || &a[5][1])
    printf("true\n");

How to apply a equation to specific rows in a matrix

If I have a matrix m like,If I have a matrix m like:,If I have a matrix m like:

m=[0   340.216815000000
1.56250000000000    570.718050000000
4.68750000000000    769.256473000000
7.81250000000000    1176.42951000000
10.9375000000000    1632.88855600000
18.4375000000000    2099.99990500000
25.9375000000000    2099.99990500000
33.4375000000000    2099.99990500000
40.9375000000000    2099.99990500000
48.4375000000000    2099.99990500000
0   331.115127000000
1.53698699999995    510.419428000000
4.61084000000005    719.346166000000
7.68469200000004    1145.58672900000
10.7585449999999    1583.81915100000
18.1358640000001    2099.99990500000
25.5130620000000    2099.99990500000
32.8903809999999    2099.99990500000
40.2675780000000    2099.99990500000
47.6448969999999    2099.99990500000];

and a matrix n like:

n=[0    159.846351000000
1.52099599999997    343.757153000000
4.56286599999999    412.372440000000
7.60473600000000    926.872313000000
10.6466060000000    1063.47274800000
17.9471440000000    1079.82945400000
25.2475589999999    1200.00004800000
32.5480960000000    1200.00004800000
39.8486330000001    1200.00004800000
47.1491699999999    1200.00004800000
0   186.247796000000
1.49536100000000    386.090606000000
4.48608399999989    477.258742000000
7.47680700000001    775.100648000000
10.4676509999999    1004.91941000000
17.6453859999999    1075.44088400000
24.8232419999999    1200.00004800000
32.0009769999999    1200.00004800000
39.1787110000000    1200.00004800000
46.3565670000000    1200.00004800000];

how to build a vector E which matches that when m(:,1) is lower than 10, then use this formula:

(m(:,2).^2).*(3*(n(:,2).^2));

and when 10 < m(:,1) <= 25, use:

(m.*2)

the results would be this:

E = [8872341649.18581
115469679048.928
301885906398.286
3566916094097.57
3265.77711200000
4199.99981000000
4199.99981000000
4199.99981000000
4199.99981000000
4199.99981000000
662.230254000000
1020.83885600000
1438.69233200000
2291.17345800000
3167.63830200000
4199.99981000000
4199.99981000000
4199.99981000000
4199.99981000000
4199.99981000000];

how to subtract a value in a matrix which match a matrix condition?

% How to obtain matrix Md from matrix M matching next conditions:

% if M is:

M=[0.000000 1188.000000 340.216815
0.000000    1186.437500 570.718050
0.000000    1183.312500 769.256473
6.500000    1188.500000 331.115127
6.500000    1186.963013 510.419428
6.500000    1183.889160 719.346166
13.000000   1189.000000 325.858265
13.000000   1187.488647 426.599681
13.000000   1184.465942 671.896040
19.500000   1189.000000 330.567837
19.500000   1187.529785 383.856624
19.500000   1184.589478 643.279493
26.000000   1190.000000 333.606362
26.000000   1188.539795 381.784469
26.000000   1185.619263 648.680568];

% Find the maximum value of M(:,2) when M(:,1) is equal to (0, 6.5.. 26) this is:

for i=0:6.5:26
ind = M(:,1) == i;
max(M(ind,2))
end

% obtaining

ans = 1188
ans = 1188.5
ans = 1189
ans = 1189
ans = 1190

% The idea is to use these maximun values in order to substract them to the other values in M(:,2) when M(:,1) is equal to (0, 6.5.. 26). For example: the max value in M(:,2) when M(:,1)=0 is 1188, then we would substract to 1188: 1188, 1186.437500 and 1183.312500 which are the values of the M(:,2) column matching M(:,1)=0.

1188-1188 = 0.0000
1188-1186.437500 = 1.5625
1188-1183.312500 = 4.6875

% Then make the same sense with 6.5, 13..26. The Result would be:

Md=[0.000000    0.0000  340.216815
0.000000    1.5625  570.718050
0.000000    4.6875  769.256473
6.500000    0.0000  331.115127
6.500000    1.5370  510.419428
6.500000    4.6108  719.346166
13.000000   0.0000  325.858265
13.000000   1.5114  426.599681
13.000000   4.5341  671.896040
19.500000   0.0000  330.567837
19.500000   1.4702  383.856624
19.500000   4.4105  643.279493
26.000000   0.0000  333.606362
26.000000   1.4602  381.784469
26.000000   4.3807  648.680568];

VB.net Create Date Killswitch (Compare two Dates)

Id like to implement a killswitch based on a date into my app so that Itll stop working by a certain time. Therefore I figured out on date (eg. 1st of February 2019). Once the Date of the system where my app is running on is greater than the Killswitch date, I want it to stop working. I tried

If Today.Date.toString() >= "02/01/2019" Then
End
Else
...

That didnt work. The problem I have is that the date format is different on each computer, some have MM/dd/YYYY, some dd/MM/YYYY and some YYYY/MM/dd. Is it still possible to convert all dates to a universal format and compare them?

Using Leaf, the else condition isn't properly executed though the if one is

I have a simple Leaf template that I'd like to display Hello World in.

#if(false) {
<title> All hail Apodron.</title>
} #else {
<title> Hello World </title>
}

the page has no title and displays as:

#else {Helloward}

However, if I change this to:

#if(true) {
<title> All hail Apodron.</title>
} #else {
<title> Hello World </title>
}

then the title does display, but the page STILL shows up as:

#else {Helloward}

I also tried various syntaxes, such as:

##else { <title> Hello World </title> } and #else() { <title> Hello World </title> } or even ##else() { <title> Hello World </title> }

This seemed very basic, and I believe I followed the documentation.

jeudi 27 décembre 2018

Google Script to execute IF Statement in a loop for date value

I'm working on a script to automate a daily copy+paste (as value) function. I've worked through it piece-by-piece and my final issue is the looped if-statement that looks at the date relative to today's date.

You can see that in column B is my 'Date' column and in row 1 column AN I entered a today() function.

Essentially, everyday I copy and paste (as value) any rows (columns I - AM) that match 'today's' date, highlight them grey and then hide the rows. Once I can set up the if-statement for the loop to recognize the correct rows, I can set a daily trigger in the morning to run the function.

The code is below - any and all help is greatly appreciated!

function dailyUpdate() 
{
  var sht = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Copy of Results');
  var dateValues = sht.getRange(2,2,1231).getValues();
  for (r=1; r<1232; r++)
    var todayValue = sht.getRange(1,39).getValue();
    var dateValues = sht.getRange(r,2).getValues();
    if(dateValues == todayValue)
    {
      var source = sht.getRange(r,9,1,31);
      source.copyTo(sht.getRange(r,9,1,31), {contentsOnly: true});
      sht.hideRow(source)
      source.setBackground("grey");
  }
}

How to assign value to a variable depending on IF/ELSE condition in Robot?

I am trying to assign a variable the return value of the Keyword (Get Ipsec Pkt Stat) if a condition is true. The following is the syntax I am using, however my variable ${ipsec_stats} gets assigned None, even though the condition is being satisfied:

Run Keyword If    '${chassis_cluster}' == 'True'
...    ${ipsec_stat} =  Get Ipsec Pkt Stats   ${R0}     node=local
...    ELSE
...    ${ipsec_stat} =  Get Ipsec Pkt Stats   ${R0} 
[Return]    ${ipsec_stat}

Uninstall batch file not working Closes out

have the below file.

My end goal is to check for a file in a directory if this file exists don't do anything

if the file does not exist uninstall teamviewer on that pc

Here's the below script

IF EXIST C:\store\TV-DONOTDELETE.TXT

(echo Found the file won't do anything.)
pause

ELSE
(
REM Kill TeamViewer Process
taskkill /f /im teamviewer*
REM Remove Older Versions
for /d %%F in ("C:\Program Files\TeamViewer\*") do "%%F\uninstall.exe" /S
for /d %%F in ("C:\Program Files (x86)\TeamViewer\*") do "%%F\uninstall.exe" /S
REM Remove Newer Versions
"C:\Program Files\TeamViewer\uninstall.exe" /S
"C:\Program Files (x86)\TeamViewer\uninstall.exe" /S

echo removed teamviewer you can thank me later
)
pause

I want to convert the last output into an array in c++

I have this code and i want the last output it shows to be converted in an array so that it makes my work easy

At first it asks for the column number and then prints that column vertically in a respective order The final output is a table that is actually more than one output and i want it converted into an array

#include<iostream>

#include<stdio.h>
using namespace std;

main()

{

int e[100];
int f[100];
int n;

cout << "THINK OF A NUMBER AND ENTER THE NUMBER OF ALPHABETHS IT 
CONTAINS" << endl;
cin >> n;
char a[7]={'A','E','I','M','Q','U','Y'};
char b[7]={'B','F','J','N','R','V','Z'};
char c[6]={'C','G','K','O','S','W'};
char d[6]={'D','H','L','P','T','X'};


for(int i=0;i<7;i++)
{
    cout << a[i] << " "<< b[i] << " " << c[i] << " " << d[i];
    cout << endl;
}

for(int i=0;i<n;i++)

{
cout << "Enter the column number of alphabet number ["<<i<<"]"<<"of your 
word" << endl ;
cin>> e[i];
}
cout << endl;

for(int i=0;i<7;i++)
{
if(e[i]==1)
{

for(int i=0;i<7;i++)
  {
    cout << a[i] <<" " ;
  }
cout << endl;
}
else if(e[i]==2)
{

  for(int i=0;i<7;i++)
  {
       cout << b[i] <<" " ;
  }
cout << endl;
}
else if(e[i]==3)
{
    for(int i=0;i<7;i++)
    {

    cout << c[i] <<" " ;
    }
cout << endl;
}
else if(e[i]==4)
{
    for(int i=0;i<7;i++)
    {
    cout << d[i] <<" " ;
    }
cout << endl;
}
}

}

Printing numbers in correct way

I'm getting data from 'http://p****.i*****.fi/food.txt' which is just numbers under each other like this, 1
2
3
4, but it prints those numbers next to each other like this 1 2 3 4, is there a way to print it as it is ?

function Doc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "http://p****.i*****.fi/food.txt", true);
  xhttp.send();
}
<div id="demo">
<button type="button" onclick="Doc()">Content</button>
</div>

How to prevent / escape access restriction as a logged in / registered user?

If a page has a restriction for not registered users trying to access your page such as

if (!isset($_SESSION['username'])){
    header('location: login.php');
    exit;
}

it means that each time your login session is not set you should be redirected to the login page, but if you have the right combination of the required information the code should set a session for you and let you pass through this restriction as a registered user to the website you are trying to access.

Well, this is not happening in my case, after i sat a restriction for anyone trying to access the website manually (which is the code above) i got restricted to access the website even as a registered user even when i try to log in with existing username and password...

So basically it keeps redirecting me to the login.php no matter what i do and I am looking for a way to access my landing page after a successful login

Here is my login code:

<?php
session_start();
$mysqli = new mysqli('localhost','root','password','accounts');
$_SESSION['message'] = '';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
        $user = $mysqli->real_escape_string($_POST['username']);
        $pass = $mysqli->real_escape_string($_POST['password']);
        $sql = "SELECT * FROM users WHERE username = '$user' ";
        $result = mysqli_query($mysqli, $sql);
        $id = mysqli_query($mysqli,"SELECT name FROM users WHERE username = '$user'");

        while ($row = $id->fetch_array()) {
            $_SESSION['name'] = $row['name'];
        }

        if (mysqli_num_rows($result)>0){
            while($row = mysqli_fetch_array($result)){
                if(password_verify($pass, $row['pass'])){ 
                    $_SESSION['username'] = $user; 
                    $_SESSION['message'] = "Login Success!";
                    header("location: index.php");
                }
                else{
                    header("location: login.php");
                    $_SESSION['message'] = "Incorrect Password!";
                }
            }
        }
        else{
            header("location: login.php");
            $_SESSION['message'] = "Username does not exist!";
        }

}
?>

At least i am getting a "Login Success!" message at my Login page...

How to fix this JavaScript if-statement? [on hold]

My Question is about if statements. There is an if statement where you have to type in a password, and it would then verify whether that is the real password.

if(pass == "Hello") {
    window.alert("Welcome Purple!")
}
else {
    window.alert("INVALID PASSWORD")
}

(Pass is a document variable, taken from an input.)

After I typed in Hello in the input, it ran the else statement, instead of the if statement.

Can anyone tell me why this happens?

How to restrict access to your website for anyone that is not logged in?

Okay so now I am trying to restrict access to my landing page and the only way to access it should be by logging in and the code below is supposed to redirect the browser to the login page if the session is not set (a successful login sets the 'username' session)

if (!isset($_SESSION['username'])){
    header('login.php');
}

I set up a small check that would notify me if the session is set or not

if(isset($_SESSION['username'])){
        echo "Session is set!";
    }
    else{
        echo "Session not set!";
    }

and then i logged in so my code said "Session is set!", yey, now let's log out and try to access this page manually... few seconds later i land on my index page and the code says "Session not set!". So what am I doing on this page then? Shouldn't I be redirected to login.php?

So mt question here is do you know why is the (!isset... function not working and how can i fix it?

break out from nested if

I am modifying quite a large system and I want to avoid risky changes in many places.

i want to (in one case) break a nested if and proceed previous else statement. if it is possible.

if (otherBool)
{
    if(ID != 2)
    {
        html += "";
    }
    else
    {
        // break
    }
}

else if (ID == 2)
{
    html += "";
}
else
{
    html += "";
}

in this case, if otherBool is true and ID equal 2 i want in nested else make break that condition and go to previous (just like the otherBool would be false from start).

i wonder about break, because that if is inside switch.

it cannot be if(otherBool && id!=2) becaause in the nested if will be more statements.

mercredi 26 décembre 2018

Creating new column based on time value based if statement

Im trying to create a column that gives the variance or subtraction of two timestamps of two other columns.

def time_delta(df):
    if df['a_time'] > df['b_time']:
        df = (pd.to_datetime(df.a_time) - pd.to_datetime(df.b_time)) / np.timedelta64(1, 'm')
    else:
        df = (pd.to_datetime(df.b_time) - pd.to_datetime(df.a_time)) / np.timedelta64(1, 'm')
    return df

df['C'] = df.apply(time_delta, axis=1)

When I run the apply part of code the cell just keeps running with *, am I missing something?

Thanks so much

How to reservation only in available time without exposure to clash in reservation website ( ASP.NET VB)?

I have a booking page for the halls on this page (the name of the Hall, the date of booking and the time of booking "from and to"). For example, the hall "A" was booked on 12/11/2018 from 12:00 pm to 1:00 pm . So,The Hall must not be booked again during this time of the same date, except before 12:00 pm or after 1:00 pm.

Well, I've written the code but the program is going to insert even if there is a reservation. I do not know if the error was in the condition or the Query or perhaps another reason. There is no indication of fault or error, it's just not working as required.

This is my code in the Query:-

SELECT Event_ID, Start_Time, End_Time, [Date], Event_name, Number_of_Attendees, Cpr, Hall_Number, Comments
 FROM    Resevation_of_Halls
 WHERE  (Hall_Number = ?)AND
 ([Date] =? )AND
 (([Start_Time] BETWEEN ? AND ?)
 OR
 ([End_Time] BETWEEN ? AND ?))

This code it means:-

(([Start_Time] BETWEEN 'Start.text' AND 'End.text')

OR

([End_Time] BETWEEN 'Start.text' AND 'End.text'))

  • (Start.text):it's text box for start time.

  • (End.text): it's text box for End time.

I have tried:

Gridview1: it's for data insert in the database.

Gridview2: It is determined if it is possible to reserve the hall or not through the (Query "where").

Protected Sub Reserv_btn_Click(sender As Object, e As EventArgs) Handles Reserv_btn.Click



       If GridView2.Rows.Count > 0 Then
           Label1.Text = "Hall can not be reserved"
       Else
           If GridView1.Rows.Count > 0 Then

           ReservationDB.InsertParameters("Cpr").DefaultValue = Session.Item("cpr")
               ReservationDB.InsertParameters("Hall_Number").DefaultValue = HallName.SelectedValue
               ReservationDB.InsertParameters("Date").DefaultValue = Datetxt.Text
               ReservationDB.InsertParameters("Start_Time").DefaultValue = Startxt.Text
               ReservationDB.InsertParameters("End_Time").DefaultValue = Endtxt.Text
               ReservationDB.InsertParameters("Event_name").DefaultValue = Eventxt.Text
               ReservationDB.InsertParameters("Comments").DefaultValue = Commtxt.Text

               ReservationDB.Insert()

               Label1.Text = "hall was booked!!"
               Datetxt.Text = ""
               Startxt.Text = ""
               Endtxt.Text = ""
               Eventxt.Text = ""
               Commtxt.Text = ""

             End If
       End If

   End Sub

Python lists: Replacing integers with strings. Using if-statements and for-loops

I am trying to use a for-loop to replace integers within a list, with strings. I am trying to use for loops and if statements but it doesn't seem to be working. Is there an easier way to do this? The replace() method only works to replace strings with other strings.

for i in range(len(upto_100)):
    if upto_100[i] % 3 == 0 and upto_100[i] % 5 ==0:
        upto_100[i] == 'FizzBuzz'
    elif upto_100[i] % 3 == 0:
        upto_100[i] == 'Fizz;'
    elif upto_100[i] % 5 == 0:
        upto_100[i] == 'Buzz'
    else:
        upto_100[i] == upto_100[i]

print(upto_100)

How can I shorten method with if-statments?

I want to shorten this method. Could you tell me how can I make it? I tried somehow, but with bad result. Books list length is not known. It can be 10, but it can be 0 also. I need 3 books if they exist.

public List<Book> findTheLatest3Books() {
    List<Book> books = new ArrayList<>(bookRepository.findAllByOrderByDateOfCreation());
    List<Book> listOf3LatestBooks = new ArrayList<>();
    if (books.size() >= 3) {
        for (int i = 0; i < 3; i++) {
            if (books.get(i).isAvailable()) {
                listOf3LatestBooks.add(books.get(i));
            }
        }
    }
    if (books.size() == 2) {
        for (int i = 0; i < 2; i++) {
            if (books.get(i).isAvailable()) {
                listOf3LatestBooks.add(books.get(i));
            }
        }
    }
    if (books.size() == 1) {
        for (int i = 0; i < 1; i++) {
            if (books.get(i).isAvailable()) {
                listOf3LatestBooks.add(books.get(i));
            }
        }
    }
    if (books.size() == 0) {
        throw new IllegalArgumentException("No books in DB");
    }
    return listOf3LatestBooks;
}

How do i convince the code that the data i am trying to pull out of a MySQL database actually exists?

I am testing a login code and i ran into a problem where the information collected from a MySQL database can not be found even though the information exists inside the table, the code below says that there is 0 rows with the information i am trying to pull out, therefore it fails to execute it's primary function and always ends up executing the else solution

I have been googling around and tried different combinations and ways the code can be written as it is '".$username."' instead of '$username' but nothing seems to be working except in case where equal it to zero but that way it looses it's purpose and executes the primary function no matter what

$sql = "SELECT * FROM users WHERE username = '$username' AND pass = '$password' ";

$result = mysqli_query($mysqli,$sql);

if (mysqli_num_rows($result)>0){
    echo "Login Success!";
    exit();
}
else{
    echo "Login Failed";
    exit();
}

I expected to solve this problem on my own but i got totally confused and don't even know what i have tried so far and what else is there to be tried

Compare object to object in array for ShopCart Item removal

I hope this is a good question. I am working on a shopping cart project. I have been scouring the internet through different tutorials on shopping carts. I am attempting to write mine in Vanilla Javascript. I am having trouble with removing shopping cart items from session storage.

To test the functionality of what I have so far you can visit http://bit.ly/2ENK7ZA

The function that I cant get to work properly is the removeFromLocalStorage() function. For some reason when comparing an object to the object in array Im not getting back any true value even when there are many items in the cart. What am I doing wrong? I hope someone can help. Below is a copy of my JS code.

The method I am using is having identical dataset value in the remove item button generated by JS in the outPutCart() function. Then then parsing that dataset into an object and comparing it to the objects in the session storage array which is called shopItems inside the removeFromLocalStorage() function. I hope this is enough information for someone to see my problem. Thank you in advance.

 'use strict';

    const addToCartButtons = document.querySelectorAll('.shop-btn');
    let shopCart = [];



    ouputCart();

    // add listeners to cart buttons
    addToCartButtons.forEach(addToCartButton => {
    addToCartButton.addEventListener('click', () => {
        const productInfo = addToCartButton.dataset; // Get data set
        productInfo.qty = 1;    //Set quantity
        var itemInCart = false; // Set item in cart boolean


        shopCart.forEach(function(cartItem, index){  //Check if item 
in 
    cart
            if(cartItem.id == productInfo.id) {
                cartItem.qty = parseInt(cartItem.qty) + 
    parseInt(productInfo.qty);
                itemInCart = true;
            }

        });

        if(itemInCart === false) {
            shopCart.push(productInfo);
        }
        sessionStorage['sc']= JSON.stringify(shopCart);
        ouputCart();
    })
    });



    function ouputCart() {
    if (sessionStorage['sc'] != null) {
        shopCart = JSON.parse(sessionStorage['sc'].toString());

    }

    var holderHTML = '';
    var totalPrice = 0;
    var totalItems = 0

    shopCart.forEach(function(value, index){
        var subTotalPrice = value.qty * value.price
        totalPrice += subTotalPrice;
        totalItems = parseInt(totalItems) + parseInt(value.qty);
        holderHTML += `<tr>
                        <td>
                            <span class="remove-from-cart">
                            <b data-id="${value.id}" data- 
    name="${value.name}" data-price="${value.price}" data- 
    image="${value.image}" data-qty="${value.qty}">X</b>
                            </span>
                        </td>
                        <td> 
                            <div class="modal__image-container">
                                <img src="${value.image}" alt="dan 
cruz 
    painting" class="modal__image"/>
                            </div> 
                        </td>
                        <td>
                            <span>${value.name}</span>
                        </td>
                        <td>
                            ${value.qty}
                        </td>
                        <td> 

    ${numberWithCommas(formatMoney(subTotalPrice))}
                        </td>
                       </tr>`
    });


    document.querySelector('#cart-list').innerHTML = holderHTML;
    document.querySelector('.cart-total-items').innerText = totalItems;
    document.querySelector('.cart-total-price').innerText = 
    numberWithCommas(formatMoney(totalPrice));

    }

    function formatMoney(n) {
    return (n/100).toFixed(2);
    }


    function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }


    // Remove item from DOM

    document.querySelector('#cart-list').addEventListener('click', 
    removeFromCart)

    function removeFromCart(e) {
    if(e.target.parentElement.classList.contains('remove-from-cart')) {
    // e.target.parentElement.parentElement.parentElement.remove(); 
    //Remove from DOM

     //Remove from Local Storage
            removeFromLocalStorage(e.target.dataset);
     }
     }

     // remove from local storage
     function removeFromLocalStorage(removedItem){

    let shopItems;
    if(sessionStorage['sc'] == null){
        shopItems = [];
    } else {
        shopItems = JSON.parse(sessionStorage['sc'].toString());
    }

    var compare = JSON.parse(JSON.stringify(removedItem))

    shopItems.forEach(function(item, index){

        if(compare === item){
            console.log(compare);
            console.log(item);
            // shopItems.splice(index, 1);
        }

    });

    // sessionStorage['sc'] = JSON.stringify(shopItems);
    }



    //// Modal Open/Close

    const viewCart = document.querySelector('.shop__cart-reminder');
    const modal = document.querySelector('.modal');
    const modalDisplay = document.querySelector('.modal__container');
    const closeModal = document.querySelector('.modal__close');
    const keepShopping = document.querySelector('.keep-shopping');

    viewCart.addEventListener('click', function(){
    modal.style.display = 'block';
    modalDisplay.style.display = 'block';
    })

    modal.addEventListener('click', function(){
    modal.style.display = 'none';
    modalDisplay.style.display = 'none';
    })

    closeModal.addEventListener('click', function(){
    modal.style.display = 'none';
    modalDisplay.style.display = 'none';
    })

    keepShopping.addEventListener('click', function(){
    modal.style.display = 'none';
    modalDisplay.style.display = 'none';
    })

Using "each loop variables" inside if statement in SASS

I am trying to generate a bunch of styles through an each loop in SASS. The styles should only be generated, if the variable the each loop is looking at right now is set.

I tried different variable "styles", e.g.: $use-#{$type}, but I'm kinda lost.

$typo: (t1, t2);
$use-t1: 1; 
$t1-color: black;
$use-t2: 1; 
$t2-color: black;

/*FOR EACH TEST)*/
@each $type in $typo{
  @if $#{use-$type} == 1{ 
    .#{$type}{
      color: $#{$type}-color;
    }
  }
}

I would expect the variables in the first round of the each loop to be: $#{use-$type} -> $use-t1 -> 1 $#{$type}-color -> $t1-color -> black

But both throw "Expected identifier." or "Unknown variable", depending on how I try it.

best method to if/else potentially large condition

I have an older version of an ASP.NET MVC. It is an online shopping tool with thousands of products and shoppers. We want to give some customers a negotiated discount, for example 10% off. For now this is a simple if/else statement based on the user login credentials. However, potentially we could have tens of customers and this statement can get extremely long and I was wondering if there is a better method of doing this. Perhaps through a stored procedure. Basically inside our product page we have a statement similar to this:

    <if user == so@so.com 
    {
       product *.20 
    }
   else if user == no@no.com
   {
   product *.-10
   }
    else         
     product.price >

This of course is just a generalization, the actual statements are a lot more complex and have declared decimals and math functions and some conversions. But we have to apply this to the shopping cart, checkout, search results, etc. And as you can image this can get tedious to maintain, would there be an easier way to store these if/else statements and apply them to our aspx pages as text results.

Pointer compared to a number in an if-statement in C

I've got a question. I'm currently trying to solve an exercise my university gave us but something isn't working as it should be.

I have to implement a function which checks whether a number (entered by the user) is in the range of -2.5 and 2.5. If yes, it should save the number at the address of the pointer and return 0. If not, it should clear the buffer and return 1. We do not have to check for any buffer errors and we have to make sure that the value at the address of the pointer is not changed in an error.

We also have to write the main-function, which reads in the number and prints out error reports when the user enters a number which is not in the range.

Right now, I wrote both of the functions, except for the error reports in case of a wrong entered number. I didn't do that because there's in another mistake I made which is more important now than the missing text for errors. When I try my program and enter a number which is not in the range it still says that the given number is in the range. I think my mistake is in the if-statement with the pointer comparison. We did pointers in uni only a week ago, so I'm not that experienced when it comes to using them in code.

Here is my code:

#include <stdio.h>

int read_interval (double *p)
{
    int c;

    if (*p < -2.5 || *p > 2.5) {
            while ((c = getchar()) != '\n') {}
            return 1;
    } else {
            *p = *p;
            return 0;
    }
}

int main ()
{
    double number, *p;

    printf("Please enter a number between -2.5 and 2.5: ");
    scanf("%d", &number);

    p = &number;

    int status = read_interval(p);

    printf("%i", status);

    return 0;

}

I hope somebody here can help me out. I really want to improve my skills in C. Thank you in advance.

Alex

How to i make a program in arduino to change a variable from 0 to 9, then from 9 to 0 and so on?

I'm currently building a seven segments display and i want it to display all the numbers from 0 to 9, and the viceversa. I've been able to display all the numbers between 0 and 9, but i'm stuck trying to display the ones between 9 and 0. Once it gets to 9, it simply restarts from 0. Can you help me? Thank you so much in advance <3

int G = 3; // G equals to the lower segment
int H = 2; // H equals to the lower-left segment
int x = 0;
int Delay = 500;


void setup() {
pinMode(A, OUTPUT);
pinMode(B, OUTPUT);
pinMode(C, OUTPUT);
pinMode(D, OUTPUT);
pinMode(E, OUTPUT);
pinMode(F, OUTPUT);
pinMode(G, OUTPUT);
pinMode(H, OUTPUT);
}


void loop() {
    if (x < 10) {
        x = x+1;           // This is the part of the code where i'm stuck
        delay(Delay);

   }
    if (x == 10) {                 // in this part of the loop i simply dispaly a certain number on the display based on the value of x
        x = x-10; 
  }
    if(x == 0)  {
        digitalWrite(A, LOW);
        digitalWrite(B, HIGH);  
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, LOW);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(H, HIGH);
  } 

    if(x == 1)  {
        digitalWrite(A, LOW);
        digitalWrite(B, LOW);
        digitalWrite(C, HIGH);
        digitalWrite(D, LOW);
        digitalWrite(E, LOW);
        digitalWrite(F, HIGH);
        digitalWrite(G, LOW);
        digitalWrite(H, LOW); 
  }

      if(x == 2)  {
        digitalWrite(A, HIGH);
        digitalWrite(B, LOW);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, LOW);
        digitalWrite(F, LOW);
        digitalWrite(G, HIGH);
        digitalWrite(H, HIGH);
  }

    if(x == 3)  {
        digitalWrite(A, HIGH);
        digitalWrite(B, LOW);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, LOW);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(H, LOW);
  }
    if(x == 4)  {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, LOW);
        digitalWrite(E, LOW);
        digitalWrite(F, HIGH);
        digitalWrite(G, LOW);
        digitalWrite(H, LOW);
  }
    if(x == 5)  {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, LOW);
        digitalWrite(D, HIGH);
        digitalWrite(E, LOW);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(H, LOW);
  }
    if(x == 6)  {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, LOW);
        digitalWrite(D, HIGH);
        digitalWrite(E, LOW);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(H, HIGH);
  }
    if(x == 7)  {
        digitalWrite(A, LOW);
        digitalWrite(B, LOW);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, LOW);
        digitalWrite(F, HIGH);
        digitalWrite(G, LOW);
        digitalWrite(H, LOW);
  }
    if(x == 8)  {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, LOW);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(H, HIGH);
  }
    if(x == 9)  {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, LOW);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(H, LOW);
  }
}

How to filter a list with multiple criteria?

I want to filter a list based on 4 parameters. But I cannot get the expected output that I want.

If more than one parameter is not empty or null, I want the multiple if-else relation become AND.
If only one parameter has value, then the relation will be OR.

Case 1: When tagUId is not empty and status is not null

Input:
title = "", tagUId = "12", status = true, pullStatus = null

Expected Output:
Only tag with tagUId contains "12" AND status is true will be included into the result list.

Case 2: When tagUId is not empty, status is not null, pullStatus is not null

Input:
title = "", tagUId = "12", status = true, pullStatus = false

Expected Output:
Only tag with tagUId contains "12" AND status is true AND pullStatus is false will be included into the result list.

public static ArrayList<TagEntity> SearchTagsBy(String title, String tagUId, Boolean status, Boolean pullStatus){
    HashSet<TagEntity> result = new HashSet<>();
    ArrayList<TagEntity> tags = GetTagList();

    if (title.isEmpty() && tagUId.isEmpty() && status == null && pullStatus == null) {
        result.addAll(tags); //default parameters == show all tag
    }else{

        if(!title.isEmpty()){
            result.addAll(FilterTitle(tags, title));
        }

        if(!tagUId.isEmpty()){
            result.addAll(FilterTagUId(tags, tagUId));
        }

        if(status != null){
            result.addAll(FilterStatus(tags, status));
        }

        if(pullStatus != null){
            result.addAll(FilterPullStatus(tags, pullStatus));
        }

    }

    return new ArrayList<>(result);
}

private static Collection<? extends TagEntity> FilterPullStatus(ArrayList<TagEntity> tags, Boolean pullStatus) {
    HashSet<TagEntity> result = new HashSet<>();

    for (TagEntity tag: tags) {
        if (tag.getHasPulled().equals(pullStatus)){
            result.add(tag);
        }

    }

    return result;
}

private static Collection<? extends TagEntity> FilterStatus(ArrayList<TagEntity> tags, Boolean status) {
    HashSet<TagEntity> result = new HashSet<>();

    for (TagEntity tag: tags) {
        if (tag.getStatus().equals(status)){
            result.add(tag);
        }

    }

    return result;
}

private static Collection<? extends TagEntity> FilterTagUId(ArrayList<TagEntity> tags, String tagUId) {
    HashSet<TagEntity> result = new HashSet<>();

    for (TagEntity tag: tags) {
        if (tag.getUId().contains(tagUId)){
            result.add(tag);
        }

    }

    return result;
}

private static HashSet<TagEntity> FilterTitle(ArrayList<TagEntity> tags, String title){
    HashSet<TagEntity> result = new HashSet<>();

    for (TagEntity tag: tags) {
        if (tag.getTitle().contains(title)){
            result.add(tag);
        }

    }

    return result;
}

Why an if condition doesn't get triggered while reading the data using SqlDataReader?

Even though several people have asked this question before non of those solved my problem. I have a database connection, through that i am adding and retrieving to/from database. But when I read from the database I need to make the RadioButtonList to be ticked. when I debug the code the if condition is getting triggered and the correct values are retrieved but it just exits from the condition and runs the next line.

I have tried removing the while (reader.Read()) loop and changed it as reader.read(). even then the same issue occurred. I've also tried this and nothing worked!

following is my code segment

            while (reader.Read())
            {
                if (reader.IsDBNull(0))
                {

                }
                else
                {
                    result = reader["Type"].ToString();
                    if (result.Equals("X"))
                    {
                        RadioButtonList1.SelectedValue = "X";                            
                    }
                    else if (result == "Y")
                    {
                        RadioButtonList1.SelectedValue = "Y";
                    }
                    question_Tb.Text = (reader["Question"].ToString());
                    answer_One_Tb.Text = (reader["answer_One"].ToString());
                    answer_Two_Tb.Text = (reader["answer_Two"].ToString());
                    answer_Three_Tb.Text = (reader["answer_Three"].ToString());

                }
            }

I need the radio buttons to be ticked according to the value on the database while reading from database.

mardi 25 décembre 2018

python file reading line by line and check for condition and if it's not true wait until its true without skipping the line

this is my code :

for line in file :
    if(something== something):
        '''do something''' .
    else:
        '''dont skip the line and wait until condition is true then skip to 
           next line'''

Note : im chakeing number of threads in my condition

Variable won't changed in PHP (if !empty)

So i'm trying to change $page_id to 1 if there's empty, but it isn't work, i've been trying using if(empty($page_id)) and flip the if else but still not working.

$page_id=$_GET['page_id'];
    $limit=5;
    $position=null;
        if(!empty($page_id)){
            $position=($page_id-1)*$limit;
        }else{
            $page_id=1;
            $position=0;
        }?>

Expected ',' before '-' token inside if statement in C++

I am trying to remove similar consecutive terms in a vector.Got an error inside if statement ,GNU GCC Compiler.

#include<bits/stdc++.h>
using namespace std;
int main(){int n;cin>>n;vector<int> a;int k;
for(int i=0;i<n;i++){cin>>k; a.push_back(k);
if(i>=1 && a[i]==[i-1]){a.pop_back();n-=1;}} //Error in this line.
return 0;}

Error:
Expected ',' before '-' token .

What does it mean to say "if n"?

What does it mean to say if n? I don't get why if n works in an if statement. Shouldn't there be an argument such as if n == 0 or something, not just if n?

def AddMusicAtPosition(self, newMusic, n):
    if n:
        self.nextMusic.AddMusicAtPosition(newMusic, n - 1)
    else:
        newMusic.nextMusic = self.nextMusic
        self.nextMusic = newMusic

lundi 24 décembre 2018

Can't assign to operator .Multiple assignments in if statement in python

The 4th elif ending is throwing an error can't assign to operator.I am trying to design a tic tac toe game and assigning players X and 0 based upon their selection.can't assign to operator

def player_input(player):
    marker = ''
    while(marker != 'X' and marker != '0'):
        marker = input('{},choose X or 0:'.format(player))

    if(player == 'Player1' and marker == 'X'):
        temp_player1 = 'Player1' and player1_marker = 'X' and temp_player2 = 'Player2' and player2_marker = '0'
    elif(player == 'Player1' and marker == '0'):
        temp_player1 = 'Player1' and player1_marker = '0' and temp_player2 = 'Player2' and player2_marker = 'X'
    elif(player == 'Player2' and marker == 'X'):
        temp_player1 = 'Player1' and player1_marker = '0' and temp_player2 = 'Player2' and player2_marker = 'X'
    elif(player == 'Player2' and marker == '0'):
        temp_player1 = 'Player1' and player1_marker = 'X' and temp_player2 = 'Player2' and player2_marker = '0'
    else:
        pass

    return(temp_player1,player1_marker,temp_player2,player2_marker)

Save only if multiple JTextFields are not empty

I have multiple JTextFields and JComboBox in my JFrame. So whenever I click the _Add_ button it will check if the four (4) text fields in Current Medication Panel is Empty. If it is not then Execute, but it also depends if the Personal info Panel text fields are filled.

But I have a problem when I use the if and else statement, if I use the if and else:

    if(condition if the first textfield is empty) {
        // execute something like the textfield turn to red
    } else if(condition if the second textfield is empty) {
        // execute something like the textfield turn to red
    } else if(condition if the third textfield is empty) {
        // execute something like the textfield turn to red
    } else{
        // execute save information of the patient
    }

In this situation if the 1st text field is empty then it will turn to red but if both 1st and 2nd text field is empty only the 1st text field turn to red.

I also tried the if, and if and if but were should put the else whenever there is no empty or invalid input where it will execute and save the patient info like this:

   if(condition if the first textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the second textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the third textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the fourth textfield is empty) {
     // execute something like the textfield turn to red
   } else

If I use this only the last if statement only works for the else statement. So if the last statement is true then execute, but not then else statement execute which is patient save info.

Is there any thing I can do about this? or is there any tutorial for me to learn more about Java and about if and else?

passing a function in the if statement condition filed

My question is about best practice, I have a long if else statement, I am wondering if I can extract the conditions to a separate function and then pass them as the condition. Please see below =>

if (functionA (a, b)) {
    // do something
} else if (functionB (a, b)) {
    // do something else 
}

functionA (a, b) {
    return a - b === 0
}

functionB (a, b) {
    return a * b != 1
}

Syntax for testing multiple conditions in a single if statement in python 3.6 using spyder IDE

I am trying to design a Tic Tac Toe game and designed a function that tests for the winning condition.The complier is throwing the error invalid syntax at the closing bracket of if statement.Can someone please help as I am still a newbie.

def win_check(board, marker,position):
    board[position] = marker
    if((board[9]=='X' and board[6] =='X' and board[3] == 'X') or
       (board[8]=='X' and board[5] =='X' and board[2] == 'X') or
       (board[7]=='X' and board[4] =='X' and board[1] == 'X') or
       (board[7]=='X' and board[8] =='X' and board[9] == 'X') or
       (board[4]=='X' and board[5] =='X' and board[6] == 'X') or
       (board[1]=='X' and board[2] =='X' and board[3] == 'X') or
       (board[1]=='X' and board[5] =='X' and board[9] == 'X') or
       (board[7]=='X' and board[5] =='X' and board[1] == 'X') or
       ):
        print("Player choosen X is winner")
        break()

multiple conditions in single if statement