mardi 31 décembre 2019

Python - Dictionary - If loop variable not changing

''' Created on Dec 24, 2019

Project is about to convert short forms into long description and read from csv file example: user enters LOL and then it should response 'Laugh of Laughter' Expectation: Till the time time user enter wrong keyword computer keep on asking to enter short form and system answers it's long description from CSV file I considered each row of CSV file as dictionary and broke down into keys and values Logice Used: - Used while so, that it keeps on asking until short coloumn didn't finds space, empty cell. But issue is after showing successfull first attempt comparision in IF loop is not happening because readitems['short' ] is not getting updated on each cycle

AlisonList.csv Values are: short,long lol,laugh of laughter u, you wid, with '''

import csv
from lib2to3.fixer_util import Newline
from pip._vendor.distlib.util import CSVReader
from _overlapped import NULL

READ = "r"
WRITE = 'w'
APPEND = 'a'

# Reading the CSV file and converted into Dictionary

with open ("AlisonList.csv", READ) as csv_file:
readlist = csv.DictReader(csv_file)

# Reading the short description and showing results

    for readitems in readlist:        
    readitems ['short'] == ' '        
    while readitems['short'] !='' :
    # Taking input of short description            
    smsLang = str(input("Enter SMS Language :  "))
    if smsLang == readitems['short']:
    print(readitems['short'], ("---Means---"), readitems['long'])
    else:
    break

Python if else condition in one line syntax

I know this question has been asked lots of times but I still cannot get the syntax right to get it to one line:

string = 'abcdea'
ab = []

for c in list(string):
    if c in ['a','b']:
        ab.append(c) 

One line (does not work):

ab.append(c) if c in ['a','b'] for c in list(string)

Excel IF "TEXT" THEN OPERATION

I need an IF function with the condition that if the value of the cell A1 is the letter "G", then the value of the cell B1 (which is in the accounting number format $) will become negative (multiply by -1) but then if the cell A2 (and so on) contains the letter "I", the number will remain positive.

I have the following but it's not working

IF(A1="G",B1*-1,B1)

Is there a way to store data into different structures depending on the file being read?

I'm attempting to write a program that will (in part) read data from three different .txt files into three different structures, so they can be used to determine the states of various appliances. Initially I wrote a version of the code that used a single file and it worked fine, the problem is trying to add options to the code.

I have the code to read the file:

void ReadDataFile(char *location) {
int t=0, k;
char src[100]={};

strcat( strcat(src, MYPATH), location);

ptr = fopen(src,"r");

if(ptr == NULL)
{
    printf("Error!\n");
    exit(1);
}
printf("Success!\n");

From here I'm trying to use if statements to determine where data is stored. An example of the first one is:

if(location == "living_room.txt") {

    printf("Filepath found!\n");

while ((!feof(ptr)) && (t<24)) {
    //read time
    fscanf(ptr, "%s", &(*ptr2)[t].LR.hour);
    //read temperatures
    fscanf(ptr, "%f%f", &(*ptr2)[t].LR.eTemp, &(*ptr2)[t].LR.iTemp);
    //read humidity
    fscanf(ptr, "%f",  &(*ptr2)[t].LR.hum);
    //read motion data
    for ( k=0; k<6; k++)
        fscanf(ptr,"%f",  &(*ptr2)[t].LR.mot[k]);

    t++;

} }

I can't figure out what should be in the arguments for the if statement (if this is a sensible approach).

Thanks in advance.

Dropdown query has no error, but returns no results

I'm hoping to allow others to sort through the data using some dropdowns, but they shouldn't have to use all of them if they don't need to.

My query function:

=QUERY(CATALOG!A2:I259,"SELECT * WHERE 1=1 "&IF(A2="Any",""," AND B = '"&A2&"' ")&IF(B2="ANY",""," AND C = '"&B2&"' ")&IF(C2="Any",""," AND D = '"&C2&"' ")&IF(D2="Any",""," AND E = '"&D2&"' ")&IF(E2="Any",""," AND F = '"&E2&"' ")&IF(F2="Any",""," AND G = '"&F2&"' ")&IF(G2="Any",""," AND H = '"&G2&"' "),1)

Whenever I ran this, there wasn't an error but the query didn't give any items.

I initially only tested one of the dropdowns but received nothing. I plugged in a known product into the inputs and still received nothing.

Link to copy of the spreadsheet with dataset and function https://docs.google.com/spreadsheets/d/1s3tOm_6g8n66HT9md3EAXY7XwbkpmPggYhxdF-zv5ok/edit?usp=sharing

Suggest me to find best programming/code practice in JAVA

I want to find out some coding tips to improve my code style and formats.

for example we are using ternary instead of if-else conditions just like.

With if-else condition.

String name = "Meet";
String desc;
if(name == null){
    desc = "Hello Guest";
} else {
    desc = "Hello " + name;
}

With ternary operator

String name = "Meet";
String desc = "Hello " + ((null == name) ? "Guest" : name);

Evalueting problem condition in a verilog description

Good morning all !!

I allow myself to turn to you today after several to seek the solutions without success.

Indeed I am in a rather material project where it is necessary to set up a dating device using a CPLD card.

One of the functions to perform is the description of an SPI. It is a question of describing the SPI in such a way that we can have 4 states at the output (00, 01, 10 and 11) and this according to two inputs which are the CS and the CLOCK. For this, I use verilog as language.

The problem is that I cannot evaluate this condition in order to access the fourth state which would allow me to count down the 12 bits of data to be transmitted. I enclose the description and the timing diagram where I forced the entries.

Thank you all in advance.

Result

Here is the description

Code

lundi 30 décembre 2019

java method returning false - and asking question until it is returned as true in method [closed]

when check an answer and it comes out as false (i check in a boolean express located in a method) - does it ask the question again in the main method until it is true? keep in mind that i returned the true/false statement. Also if you say no, how could I make it so that question will be asked until the statement is true.

All help is welcomed. Sorry if question is unclear as I am a beginner coder. Please ask for clarification if you require it.

Thank you!!!

I have problem with my value javascript element id inside php condition

Example i have variable in javascript

var a = "60";
var b = "60";
document.getElementById('a').innerHTML = a;
document.getElementById('b').innerHTML = b; 

And i want pass the element id in php code and then compare a and b

<?php
  $a = '<p id="a"></p>';
  $b = '<p id="b"></p>';

  echo $a; //this result is 60
  echo $b; //this result is 60

  if($a == $b){
     echo 'true';
  } else {
     echo 'false';
  }
?>

my expetasion the result will be true but the reality is false, anything wrong with my code?, i tried to parse the variable and this method not working.

Formula Moving Data To Second Page If Criteria in Range is Met

I'm working on a Google Sheet Project that will move data from one page to another. I need the formula to search a range ( 'Booth Placement'!O2:O1000=133), if a cell is equal to the set value it will then write the data from the same row 'Booth Placement'!A2:A1000.

I know the IF can only work for one column and not a range spanning multiple columns. What should I switch the formula below?

=IF('Booth Placement'!O2:O1000=133,'Booth Placement'!A2:A1000,"")

I am trying to keep this formula as simple as possible since I will have to change the value it is searching for on each cell on the second page. I've googled this for two days and I'm pretty sure I'm just missing the obvious. Any/All Help is appreciated.

for loop and multiple if statements in one line?

Is there a way to write something like this in one line?

For x in list: 
   if condition1: 
       (...) 
   elif condition2: 
       (...) 
   else: 
       (...) 

Another way of asking is, is it possible to combine following list comprehensions?

(...) for x in list and,

123 if condition1 else 345 if condition2 else 0

Can't figure out why my ROT13 converter works with lowercase but it doesn't work with uppercase

I can't figure out why my ROT13 converter doesn't work with uppercase letters. It works with lowercase letters. I've been trying to find the issue for a while now but with no luck.. Thanks for your help.

Here's the code


var rot13 = str => {

  let alphabet = 'abcdefghijklmnopqrstuvwxyz';
  let alphabetUp = alphabet.toUpperCase();
  let ci = [];

  for (let i = 0; i < str.length; i++) {

    let index = alphabet.indexOf(str[i]);


    // for symbols
    if (!str[i].match(/[a-z]/ig)) {

      ci.push(str[i])
      // for letters A to M
    } else if (str[i].match(/[A-M]/ig)) {
      //lowercase
      if (str[i].match(/[a-m]/g)) {
        ci.push(alphabet[index + 13])
        //uppercase (doensn't work)       
      } else if (str[i].match(/[A-M]/g)) {
        ci.push(alphabetUp[index + 13])
      }
      // for letters N to Z
    } else if (str[i].match(/[n-z]/ig)) {
      //lowercase
      if (str[i].match(/[n-z]/g)) {
        ci.push(alphabet[index - 13])
        //uppercase (doensn't work)       
      } else if (str[i].match(/[N-Z]/g)) {
        ci.push(alphabetUp[index - 13])
      }
    }

  }

  return ci.join("");
}

How to correctly code max, min, and avg in this code?

//I cannot figure out why my code is 1) giving me a null output 2) not calculating the max, min values, and average values. Any help? There are two classes in my code, and I'm supposed to find the average, max, and min of a set of values. -->

public class CirclesV8
{
//declaration of private instance variables
private double myRadius, mySphere; 
private double myArea = 0, total = 0; 

//instance variables for totals average 
private double MyTotal = 0; 
private double MyAverage = 0;

//constructor for objects of type CirclesV8
public CirclesV8(int r, int s)
{
    myRadius = r;
    mySphere = s; 
    MyTotal = total;
} 

//getter method for radius and total
public double getRadius()
{
    return myRadius; 
}

public double getSphere()
{
    return mySphere; 
}

public double getTotal()
{
    return MyTotal;
}

//mutator method for the area, average, and circumference
public void calcArea()
{
    myArea = Math.PI * (Math.pow(myRadius, 2)); 
}
public double getArea()
{
    return myArea; 
}

public void calcSurfaceArea()
{
    mySphere = (Math.pow(myRadius, 2)) * Math.PI * 4; 
}
public double getSurfaceArea()
{
    return mySphere;
}

public void calcAvg()
{
    MyAverage = MyTotal / 5; 
}

public double getAvg()
{
    return MyAverage; 
}

//setter method for myTotal
public void setTotal(double total)
{
    MyTotal = total;
}

// returns a String of the object's values. The format() method is similar to printf().
public String toString()
{
    return String.format("%12d %14.1f %13.1f 12.1f", myRadius,
                                                     myArea,
                                                     mySphere,
                                                     MyAverage);
}
}

import java.util.Scanner;
public class V8Tester
{
public static void main(String[] args) 
{
    //create scanner object 
    Scanner in = new Scanner(System.in);               

    //initialize variables 
    int radius1, radius2, radius3, radius4, radius5; 
    int sphere1, sphere2, sphere3, sphere4, sphere5; 
    double Average = 0;
    double total = 0; 
    double min = Integer.MAX_VALUE;
    double max = Integer.MIN_VALUE;


    System.out.println("Please enter five radiuses separate by space (ex. 6 12)"); 
    radius1 = in.nextInt();
    radius2 = in.nextInt();
    radius3 = in.nextInt(); 
    radius4 = in.nextInt();
    radius5 = in.nextInt();

    System.out.println("Please enter another 5 radiuses separate by space (ex. 6 12)"); 
    sphere1 = in.nextInt();
    sphere2 = in.nextInt();
    sphere3 = in.nextInt(); 
    sphere4 = in.nextInt();
    sphere5 = in.nextInt(); 

    //Create array of objects                         
    CirclesV8 [] circles = {new CirclesV8(radius1, sphere1), 
                            new CirclesV8(radius2, sphere2),
                            new CirclesV8(radius3, sphere3),
                            new CirclesV8(radius4, sphere4),
                            new CirclesV8(radius5, sphere5)}; 

   //call methods                 
    for(int index = 0; index < circles.length; index++)
    {
        circles[index].calcArea();
        circles[index].calcSurfaceArea();
        circles[index].calcAvg(); 

        //store totals for calculating average 
        total += circles[index].getTotal();

        //calc max and min
        if(circles[index].getTotal() < min)
              min = circles[index].getTotal();
        if(circles[index].getTotal() > max)
              max = circles[index].getTotal();
    }

    //set total values & call average methods to calculate averages using one of the objects
    circles[4].setTotal(total); 
    circles[4].calcArea();
    circles[4].calcSurfaceArea(); 
    circles[4].getAvg();

    //Circle Colors
    System.out.println("Color of Circle #1: ");
    String circle1 = in.next(); 

    System.out.println("Color of Circle #2: ");
    String circle2 = in.next();

    System.out.println("Color of Circle #3: ");
    String circle3 = in.next(); 

    System.out.println("Color of Circle #4: ");
    String circle4 = in.next();

    System.out.println("Color of Circle #5: ");
    String circle55 = in.next();

    String[] array = new String[5];
    array[0] = circle1;
    array[1] = circle2; 
    array[2] = circle3;
    array[3] = circle4;
    array[4] = circle55;

    //Sphere Colors
    System.out.println("Color of Sphere #1: ");
    String sphere11 = in.next(); 

    System.out.println("Color of Sphere #2: ");
    String sphere22 = in.next();

    System.out.println("Color of Sphere #3: ");
    String sphere33 = in.next(); 

    System.out.println("Color of Sphere #4: ");
    String sphere44 = in.next();

    System.out.println("Color of Sphere #5: ");
    String sphere55 = in.next();

    String[] arr = new String[5];
    array[0] = sphere11;
    array[1] = sphere22; 
    array[2] = sphere33;
    array[3] = sphere44;
    array[4] = sphere55;

    int i = 1;
    System.out.println(" Color     Radius       Surface Area       Area");
    System.out.println("==============================================================");
    for(int index = 0; index < circles.length; index++)
    {            
        System.out.printf("%4s %10.1f %14.1f%n", array[index],
                                                 circles[index].getRadius(),
                                                 circles[index].getArea(),
                                                 i++); 
    }
public class CirclesV8
{
    //declaration of private instance variables
    private double myRadius, mySphere; 
    private double myArea = 0, total = 0; 
    
    //instance variables for totals average 
    private double MyTotal = 0; 
    private double MyAverage = 0;
    
    //constructor for objects of type CirclesV8
    public CirclesV8(int r, int s)
    {
        myRadius = r;
        mySphere = s; 
        MyTotal = total;
    } 
    
    //getter method for radius and total
    public double getRadius()
    {
        return myRadius; 
    }
    
    public double getSphere()
    {
        return mySphere; 
    }
    
    public double getTotal()
    {
        return MyTotal;
    }
    
    //mutator method for area, average, and circumference
    public void calcArea()
    {
        myArea = Math.PI * (Math.pow(myRadius, 2)); 
    }
    public double getArea()
    {
        return myArea; 
    }
    
    public void calcSurfaceArea()
    {
        mySphere = (Math.pow(myRadius, 2)) * Math.PI * 4; 
    }
    public double getSurfaceArea()
    {
        return mySphere;
    }
    
    public void calcAvg()
    {
        MyAverage = MyTotal / 5; 
    }

    public double getAvg()
    {
        return MyAverage; 
    }
  
    //setter method for myTotal
    public void setTotal(double total)
    {
        MyTotal = total;
    }
    
    // returns a String of the object's values. The format() method is similar to printf().
    public String toString()
    {
        return String.format("%12d %14.1f %13.1f 12.1f", myRadius,
                                                         myArea,
                                                         mySphere,
                                                         MyAverage);
    }
}
    

this gives me a null output

    for(int index = 0; index < circles.length; index++)
    {            
        System.out.printf("%4s %10.1f %20f", arr[index],
                                             circles[index].getRadius(),
                                             circles[index].getSurfaceArea(),
                                             i++); 
    }
    System.out.println("==============================================================");

I can't get this to print values

    System.out.printf("%20s%n", "Minimum: ", max); 
    System.out.printf("%20s%n", "Maximum: ", min); 
    System.out.printf("%20s%n", "Average: ", circles[4].getAvg()); 
   }
   }

Google Sheets sparkline, with importrange, with condition am I able to do this?

So I have two google sheets books. Book1 and Book2.

I currently have Book1 importing some info off Book2 to create a small sparkline graph. It's pulling information from Book2 column A3 through G3 to create a small graph.

My current code is (in a Book1 cell)

=SPARKLINE(IMPORTRANGE("Book2","Sheet1!A3:G3"), 
{"charttype","bar";"max",100;"color1","Green";"color2","red"})

However, I'd like this sparkline and importrange only to work IF a condition on Book1 is met.

So in Book1 if a cell has a condition (example) TRUE, then the formula above (which is in another cell in Book1) would apply and it would go ahead and import from Book2 and create the graph in Book1.

I'm not sure how to make a condition on my formula. I've tried IF statements without success. Hoping somebody out there could teach me something today.

How could I make a dynamic banner change background color with JS based on a image?

I'm making some dynamic banners and I wanted to reduce the number of variants with eliminating the color variations. I was thinking about changing the background color and text color based on what logo that get fetched from the feed. There are only two logo variations. Therefore I thought an If/else statement would do the trick. But I cant get it to work. I need an ELI5 on the solution since I'm pretty new to JS. `

<body onload="choseBG();" id="banner">    

<script>
        function choseBG(){    
            console.log(bgImg);

            if(bgImg = 'assets/NoBorder.png'){
                document.getElementById('banner').style.backgroundColor = '#CCCCCC'
            }else{
                document.getElementById('banner').style.backgroundColor = '#f20403'
            }}
    </script>`

Add string to each item in python list based on condition

I want to add the string " Equity" to each item in a list if the third last character in the item is " ". Otherwise, I would like to add " Index". Ideally, I don't want to use loops if there is a way.

For Example, I want the list below

list = ['VOD LN','HSBA LN', 'DOKA SS','SXNE' 'KERIN FH','YORK GY','SXNP']

to look like the list below

list = ['VOD LN Equity','HSBA LN Equity', 'DOKA SS Equity','SFNE Index' 'KERIN FH Equity','YORK GY','SXKP Index']

Any idea how i can do this?

Thanks!

How can I use for in if?

How can I get this working? for wont count up in if.

      if (data.tSwitch2 == 1) {
        for(int b=1;b<4;b++){
          unsigned long current_time=millis();
          if(current_time - timestamp > interval){
            Serial.println(b);
            leds[b].setRGB(255,255,0);  // Setze Scheinwerferfarbe HIER!!!
            leds[b].fadeLightBy(ledbrightness);
            timestamp = current_time;
            // don't forget FastLED.show(), to output the colors
          }
          FastLED.show();
            }
      }

If clause and another choice, if choice is not made in x seconds [duplicate]

This question already has an answer here:

Is it possible to make an if clause, that fires after x seconds if user did not enter an input?; Someone has a choice between 2 options. If he enters one of them it fires. If he does not enter option within 30 seconds, another choice (none of the 2 options) fires.

How to assign values of different types to a variable inside if statements and then use this variable after the if statements?

I am retrieving different types of documents from database, and assigning the received data to the variable items. Different methods are used to retrieve different document types, hence the need for if statements. I cannot initialize items before the if statements, because I don't know beforehand what type of document the user is retrieving. The problem is that I therefore cannot use items after the relevant īf statement has been executed. How to solve this issue? A simplified method:

public ActionResult ExportToExcel()
{
  ...
  if (request.docType == "docType1")
  {  
    var items = _provider.GetDocumentsOfType1(request);
  }
  else if (request.docType == "docType2")
  {
    var items = _provider.GetDocumentsOfType2(request);
  }
  else if ...

}

After retrieving the data, I would need to do some formatting based on what data is in the items variable, and of course return the data. It seems that the only viable thing is to replace the if statements with separate methods, and call the formatting etc. methods from there. But can it all be done within a single method?

dimanche 29 décembre 2019

Primzahl funktioniert nicht ganz

(break;) funktioniert nicht, auch für einige Zahlen gibt true und false wie z.p 21 ergibt : 21 ist eine Primzahl! 21 ist keine Primzahl! 21 ist eine Primzahl! 21 ist eine Primzahl! 21 ist eine Primzahl! 21 ist keine Primzahl!

auch 97: 97 ist eine Primzahl! 97 ist eine Primzahl! 97 ist eine Primzahl! 97 ist eine Primzahl!

"use strict"; 
var zahl= parseInt (prompt ("Geben Sie eine Zahl ein"));
var prim;

if (isNaN (zahl))
{
alert("Geben Sie eien gültige Zahl ein!");
zahl= parseInt (prompt ("Geben Sie eine Zahl ein"));
}

    for (let i =2;i<zahl;i++)
    { 
      prim = true;
        for ( let zaehler = 2; zaehler < Math.sqrt(zahl) + 1; zaehler++)
        {
            if ( zahl % i == 0 )
            {
            prim= false;
            document.write( zahl  + "       " +  "   ist keine Primzahl!" + "<br>");
            break;
            } else 
                {
                document.write( zahl  + "       " +  "   ist eine Primzahl!" + "<br>");
                break;   
                }
        }         
    }


</script>

Not sure why this if statement's "else" fails to work

I am using BeautifulSoup/requests and Tkinter to web scrape stock values off of Yahoo Finances. I set up my program to scrape values if the user types words in the GUI entry box, and everything else should return a "Not Found".

However, there is a problem. My program follows the if statements properly, but with the "else" it fails to update. After spending a while looking through my code, I am not sure why this occurs.

If someone could help me, I would much appreciate it!

from bs4 import BeautifulSoup
import requests
import tkinter

headers = {"User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) Apple Webkit/605.1.15 (KHTML, like Gecko) Version/12.0.1 Safari/605.1.15"}


# *** Functions pertaining to the GUI application ***

# Resets the data fields after submission
def ResetData():
    user_company.delete('0', 'end')

#  *** Functions pertaining to the web scraping of Yahoo Finances ***

def ChooseValue():
    global output_value

    try:
        if user_company.get().upper() == "DOW JONES":
            getDOW()
        elif user_company.get().upper() == "APPLE":
            getApple()
        elif user_company.get().upper() == "NASDAQ":
            getNASDAQ()
        elif user_company.get().upper() == "S&P 500":
            getSP()
        else:
            output_value.config(text = "Not Found!", fg = "green")

    except Exception:
        output_value.config(text = "ERROR!", fg = "red")

    output_value.config(text = "$" + str(value), fg = "blue")
    ResetData()

# Extracts the DOW Jones Industrial Average
def getDOW():
    global value
    URL = "https://finance.yahoo.com/quote/^DJI?p=^DJI"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

# Exracts NASDAQ index 
def getNASDAQ():
    global value
    URL = "https://finance.yahoo.com/quote/^IXIC?p=^IXIC"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

# Extracts S&P 500 index
def getSP():
    global value
    URL = "https://finance.yahoo.com/quote/^GSPC?p=^GSPC"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

# Extracts Apple Inc. (AAPL)
def getApple():
    global value
    URL = "https://finance.yahoo.com/quote/AAPL?p=AAPL"
    r = requests.get(URL, headers = headers)

    soup = BeautifulSoup(r.content, "html.parser")

    value = soup.find("span", class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()

def main():
    global user_company, output_value

    window = tkinter.Tk()
    window.title("Stock Value Search")

    output_value = tkinter.Label(window, text = "             ", fg = "blue")
    output_value.pack()

    user_company_label = tkinter.Label(window, text = "Enter company/index: ")
    user_company_label.pack()

    user_company = tkinter.Entry(window)
    user_company.pack()

    processButton = tkinter.Button(window, text = "Search", command = ChooseValue)
    processButton.pack()

    window.mainloop()

main()

I'm having confusion about if-statement in javascript

I have a condition in javascript like this :

var a = '60';
var b = '500';

if(a < b) {
  console.log('true');
} else {
  console.log('false');
}

but the result is false, my expectation should be true, but i tried to compare with php code :

<?php 

  $a = '60';
  $b = '501';

  if($a < $b) {
    echo 'true';
  } else {
    echo 'false';
  }

?>

and the result is true, if in javascript there is no else if condition it will automatically read to the false condition if the value is not true?

Parts of if statement not being exectued

I am using the Zdog library to create 3d objects in javascript. In the function that controls my animations I am trying to have a particle move around randomly and then after an interval return back to its original point. Here is my code:

if (radioOn == true){
  radio.zoom = size;
  path = [Math.floor((Math.random() * 3 - 1)),Math.floor((Math.random() * 2)),Math.floor((Math.random() * 2 - 1))];
  origin[0] += path[0];
  origin[1] += path[1];
  origin[2] += path[2];
  lightning.translate.x += path[0];
  lightning.translate.y -= path[1];
  lightning.translate.z += path[2];
  timer++;
  }
if (timer == 20){
  timer = 0;
  lightning.translate.x -= origin[0];
  lightning.translate.y += origin[1];
  lightning.translate.z -= origin[2];
  origin = [0,0,0];
}

I have put alerts in the second if statement and timer is getting reset but origin is not. Also the particle initially does what I need but after it gets reset it will no longer move.

PHP if Statement never true

I'm really stuck at this point.

What I'm trying to do is that I generate a table with information from my database.

And behind every information there is a button to change the saved data.

The name of my button is the ID of the current data.

<form method='POST'>
  <button type='button' name='".$zeile['ID']."' onclick='edit()'>EDIT BUTTON</button>
</form>

So, if I click on the button my div form shows up which looks like this:

<div id="edit" onclick="off()">
<form class="newmitarbeiter" method="POST">
 <label>EDIT THIS DATA</label>
 <label>Name: </label>
 <input type="text" name="nachname" value="<?php echo $firstname ?>"></input>
 <label>Vorname: </label>
 <input type="text" name="vorname" value="<?php echo $lastname; ?>"></input>
 <label>Abteilung: </label>
 <input type="text" name="abteilung" value="<?php echo $section; ?>"></input>
 <label>Stockwerk: </label>
 <input type="text" name="stockwerk" value="<?php echo $floor; ?>"></input>
 <br/><br/>
 <input name="hinzufuegen" type="submit" value="Abspeichern" class="hinzufuegen" ></input>
 <input name="abbrechen" type="submit" value="Abbrechen" class="abbrechen" ></input>
</form>
</div>

I want that the value of the data is already in the form. And to know which EDIT button I've clicked I run a loop which checks if the clicked button's name is a specific number.

    for($i = 1; $i < 100; $i++){
     if(isset($_POST[$i])){

         SQL query which defines my variables in the form above

        }
    }

My problem now is, that I get an error message that my variables in the form are not defined. I guess that the if statement never gets true but I don't even know why.

I'd be really thankful if anyone can help me.

Thank you in advance.

Hi I need to write a function that receives an integer from the user and validates that it’s larger than 10 If not, ask for it again [duplicate]

This question already has an answer here:

I need to write a function that receives an integer from the user and validates that it’s larger than 10 If not, ask for it again. I need to do this using loop and python. The code works if I enter a number bigger than then but it does not reiterate the question if I write a number smaller than 10

Number = int(input("Please enter a number larger than 10: "))
while (Number < 10):
    print("Please enter a number larger than 10")
    exit()
else:
    print("Thank you")

Execute code only if one of the if statements ran

Take a look at this example code.

boolean check = false;

if (condition) {
    do x;
    check = true;
}
else  if (condition2) {
    do y;
    check = true;
}
else if (condition3) {
    do z;
    check = true;
}

if (check) {
    do a;
} else {
    do b;
}

There has to be a better way to do this than a boolean variable, no? I mean it works, but it looks kind of messy to me.

function works without a reason

the title says it all

choosed = input("Хотите ли вы купить эти поножи? Y - да, N - нет")
if choosed == 'Y':
    player_gold = player_gold - price
    player_leggings.pop(0)
    player_leggings.pop(0)
    player_leggings.append(leggings[0])
    player_leggings.append(leggings[1])
    time.sleep(2)
    print("Вы купили",player_leggings[1],"!")
    time.sleep(2)
    print("У вас осталось",player_gold,"золота.")
if choosed == 'N':
    time.sleep(2)
    print("Вы отклонили предложение и вы вышли из деревни в лес!")

what it does:

Хотите ли вы купить эти поножи? Y - да, N - нет (i typed Y)

Вы купили кожанные поножи ! (the function if choosed == Y works)

У вас осталось 25 золота.

Вы отклонили предложение и вы вышли из деревни в лес! (for no reason function if choosed == n is starting to work)

This works in PyCharm.

Looping with if statement in batch

I write a batch file to store the error message using the if loops. But there is no result coming out from the index 0. I am feeling so weird about it and I have been scratching my head the whole day. Here is the code:

:loops
  IF DEFINED result[%num1%] (
REM call echo number %num1% %%result[!num1!]%%
REm call echo Time    : %%result[!num1!]:~9,8%%
REM call echo Value  : %num1%
REM call SET timeInLog[!num1!]=%%result[!num1!]:~9,8%%


call SET nHour=%%result[!num1!]:~9,2%%
call SET nMins=%%result[!num1!]:~12,2%%
call SET nSec=%%result[!num1!]:~15,2%%
call SET timeinlog=%nHour%%nMins%%nSec%
call echo %num1% and time : !timeinlog!
SET /A num1+=1
goto :loops
)
pause

The result is:

0 and time :
1 and time : 090747
2 and time : 112418
3 and time : 121641
4 and time : 181427
Press any key to continue . . .

Function that changes number in string to int

I'm trying to code a function in c that changes a number in string to an integer. For example "one" to 1. This is my code so far but it is not working how its supposed to and I can't find the problem.

int toint(char value[10], int num){

    if(strcmp(value, "Zero") == 0){
        num = 0;
    }else if(strcmp(value, "One") == 0){
        num = 1;
    }else if(strcmp(value, "Two") == 0){
        num = 2;
    }else if(strcmp(value, "Three") == 0){
        num = 3;
    }else if(strcmp(value, "Four") == 0){
        num = 4;
    }else if(strcmp(value, "Five") == 0){
        num = 5;
    }else if(strcmp(value, "Six") == 0){
        num = 6;
    }else if(strcmp(value, "Seven") == 0){
        num = 7;
    }else if(strcmp(value, "Eight") == 0){
        num = 8;
    }else if(strcmp(value, "Nine") == 0){
        num = 9;
    }else if(strcmp(value, "Ten") == 0){
        num = 10;
    }

    return num;
}

This is where the function its called. It's being called from a for loop in another function so that I can sort an array of numbers in string in ascending order.

    int lastval;

    toint(array[i-1], lastval);

    printf("%d", lastval);

    int val = rand() % 10 + lastval;

Excel VBA code to run a loop only if the value in column 16 of the active sheet is > 0

This is my first experience writing any kind of code. I have been building a tracking system for my work in Excel. I have everything that I want currently working except I have a user form that when you click the command button it will look at my current inventory table (the table has a column (16 or P) that list how many cases of a product we should order to get us to our target stock quantity) and return a list of products and what we need to order. I have the form so it works, It populates a list box on the form with all the info that I want, but I would like it to exclude any rows that the table says we don't need to order. Here is my current code.

Private Sub CommandButton1_Click()
    Dim ws As Worksheet
    Dim i As Integer
    Set ws = Worksheets("Current")
    lstProd.Clear
    lstProd.ColumnCount = 9
    Dim LastRow As Long
    LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

    For i = 1 To LastRow
        lstProd.AddItem ws.Cells(i, 1).Value
        lstProd.List(i - 1, 1) = ws.Cells(i, 2).Value
        lstProd.List(i - 1, 2) = ws.Cells(i, 3).Value
        lstProd.List(i - 1, 3) = "$" & Format(ws.Cells(i, 4).Value, "0.00")
        lstProd.List(i - 1, 4) = ws.Cells(i, 5).Value
        lstProd.List(i - 1, 5) = ws.Cells(i, 6).Value
        lstProd.List(i - 1, 6) = ws.Cells(i, 9).Value
        lstProd.List(i - 1, 7) = ws.Cells(i, 14).Value
        lstProd.List(i - 1, 8) = ws.Cells(i, 16).Value
    Next i
End Sub

I have tried a lot of if ws.cells(i, 16) = "0" and For ws.cells..... but always end up with different errors. I know it is something simple that I am missing but it has just eluded me so I thought I would break down and ask for help.

Using if-else statement in XSLT for-each

I have a xslt document. And i want use if statement in this document. My code is:

<xsl:for-each select="cbc:ProfileID"> 
    <xsl:apply-templates/>

    <xsl:if test="cbc:ProfileID='code1'">
        <xsl:text>A</xsl:text>
    </xsl:if>
    <xsl:if test="cbc:ProfileID='code2'">
        <xsl:text>B</xsl:text>
    </xsl:if>

</xsl:for-each>

I want if returned value is code1 then write A and if returned value is code2 then write B.

How can i do this?

Multiline Formatting of else Statements in C/C++ without Braces

I am rewriting some C++ code, I have the following

if (ConfidenceBias.value > 0) *normalInfo = tree.setDataField(NormalSigs(), *samples, *sampleData, density, pointWeightSum, ConversionAndBiasFunction);
else *normalInfo = tree.setDataField(NormalSigs(), *samples, *sampleData, density, pointWeightSum, ConversionFunction); ThreadPool::Parallel_for(0, normalInfo->size(), [&](unsigned int, size_t i) { (*normalInfo)[i] *= (Real)-1.; });

I assume that this is equivalent to

if (ConfidenceBias.value > 0) 
{
    *normalInfo = tree.setDataField(NormalSigs(), *samples, *sampleData, density, pointWeightSum, ConversionAndBiasFunction);
}
else 
{
    *normalInfo = tree.setDataField(NormalSigs(), *samples, *sampleData, density, pointWeightSum, ConversionFunction);  
}

ThreadPool::Parallel_for(0, normalInfo->size(), [&](unsigned int, size_t i) { (*normalInfo)[i] *= (Real)-1.; });

but there is a slight conern that the compiler is interpreting the original as

if (ConfidenceBias.value > 0) 
{
    *normalInfo = tree.setDataField(NormalSigs(), *samples, *sampleData, density, pointWeightSum, ConversionAndBiasFunction);
}
else 
{
    *normalInfo = tree.setDataField(NormalSigs(), *samples, *sampleData, density, pointWeightSum, ConversionFunction);  
    ThreadPool::Parallel_for(0, normalInfo->size(), [&](unsigned int, size_t i) { (*normalInfo)[i] *= (Real)-1.; });
}

I cannot find a reference to what the VSVC compiler does anywhere. Which is it?

C# Is there any better way to use Switch-Case / If-Else on generic types

I am currently trying to get some casting on generic types done. So the base idea is to have a method which accepts a generic Type and does different stuff depending on which type gets passed in.

For simplicity reasons I will just showcase the use of float, bool and default

The setup looks something like this (where T is a generic type defined by the class itself):

protected T DoStuff(T value)
{
   switch (value) {
      case float floatValue:
         float result = DoFloatStuff(floatValue);
         switch (result) {
            case T output:
               return output;
         }
      case bool boolValue:
         bool result = DoBoolStuff(boolValue);
         switch (result) {
            case T output:
               return output;
         }
      default:
         return value;
   }
}

Where DoFloatStuff and DoBoolStuff are just methods that have 1 parameter and a return type of their types respectively.

If I don't do it like that (I tried some typeof() casting before), the compiler always complains that it cannot cast from T to float and vice versa, even tho I made sure that would be the case with some Case-Switch / If-Else statements.

Does anybody know some better way to do this?

Thanks in advance, BOTHLine

Edit: Since a lot of people said kind of the same thing, that I either shouldn't use generics at all in a case like that or my methods would need to be more generic themselves.. My problem here is that I need to use 3rd party methods to handle the special cases I'm checking for (in this case the float and bool types). For the default case I already handled everything in a generic way. But for some defined types I just can't do that.

So to go a little more in detail why that's the case: I'm currently working on a Plugin for the "Unity Engine". Unity has built in methods to display types (kind of all primitive types and some Unity-specific types). I have a generic Wrapper class which should be able to contain any types. But then when I want to display the content of that wrapper in the GUI that Unity Editor offers, I have to use the built-in methods to display the primitives (something like UnityEditor.EditrGUI.FloatField()). Without those methods I am never able to display anything. Anything else which can be broken down to those types can then be displayed in a more generic way.

Is there a way to filter xml by an id attribute in elementtree using python

I am new to python and elementtree in particular and am trying to filter some information from an xml. I have managed to locate the information I need fo every TX id (coordinates), however I want to filter this to just Tx id "TxA". Ive included a section of the xml file and the code below with some comments to help show the problem. Any help or guidance is greatly appreciated.

All lists were previously set up (hence appending) Sections commented, do work for all Tx ids however I am now going back to try and filter Subelm.attrib gives the Tx id. Ive shown two attempts ive made in the code on lines 5-8

<TX id="TxA">
  <Tx_WGS84_Longitude>-105.0846057</Tx_WGS84_Longitude>
  <Tx_WGS84_Latitude>42.9565772</Tx_WGS84_Latitude>
  <Tx_Easting>678133.8818</Tx_Easting>
  <Tx_Northing>895120.939</Tx_Northing>
  <Channel id="3">
    <Ant_Config> =</Ant_Config>
    <Ant_name>Tx_ant_name1</Ant_name>
    <Ant_Electrode_1>TxAEL1<Ant_Easting>678135.1069</Ant_Easting><Ant_Northing>895248.2057</Ant_Northing></Ant_Electrode_1>
    <Ant_Electrode_2>TxAEL2<Ant_Easting>678137.0213</Ant_Easting><Ant_Northing>891059.2502</Ant_Northing></Ant_Electrode_2>
  </Channel>
  <Channel id="1">
    <Ant_Config> =</Ant_Config>
    <Ant_name>Tx_ant_name2</Ant_name>
    <Ant_Electrode_1>TxAEL1<Ant_Easting>678135.1069</Ant_Easting><Ant_Northing>895248.2057</Ant_Northing></Ant_Electrode_1>
    <Ant_Electrode_2>TxAEL2<Ant_Easting>678137.0213</Ant_Easting><Ant_Northing>891059.2502</Ant_Northing></Ant_Electrode_2>
  </Channel>
</TX>
<TX id="TxB">
  <Tx_WGS84_Longitude>-105.08459550832</Tx_WGS84_Longitude>
  <Tx_WGS84_Latitude>42.9506068474998</Tx_WGS84_Latitude>
  <Tx_Easting>678135.4896</Tx_Easting>
  <Tx_Northing>893006.9206</Tx_Northing>
  <Channel id="3">
    <Ant_Config> =</Ant_Config>
    <Ant_name>Tx_ant_name1</Ant_name>
    <Ant_Electrode_1>TxBEL1<Ant_Easting>678135.6131</Ant_Easting><Ant_Northing>893055.2569</Ant_Northing></Ant_Electrode_1>
    <Ant_Electrode_2>TxBEL2<Ant_Easting>678138.3127</Ant_Easting><Ant_Northing>888854.3852</Ant_Northing></Ant_Electrode_2>
  </Channel>
  <Channel id="1">
    <Ant_Config> =</Ant_Config>
    <Ant_name>Tx_ant_name2</Ant_name>
    <Ant_Electrode_1>TxBEL1<Ant_Easting>678135.6131</Ant_Easting><Ant_Northing>893055.2569</Ant_Northing></Ant_Electrode_1>
    <Ant_Electrode_2>TxBEL2<Ant_Easting>678138.3127</Ant_Easting><Ant_Northing>888854.3852</Ant_Northing></Ant_Electrode_2>
  </Channel>

for child in root:
if child.tag=='Layout':
    for subelm in child:
        if subelm.tag=='TX':
            for name in subelm.iter('TxA'):
                print (subelm.attrib)
            if ('id' in subelm.attrib.text): 
                print (subelm.attrib.text)
                for channel in subelm:
                    for electrode in channel:
                        for electrode1 in electrode.iter('Ant_Electrode_1'):
                            for electrode1 in electrode.iter('Ant_Easting'):
                                x1t.append(electrode1.text)
                            for electrode1 in electrode.iter('Ant_Northing'):
                                y1t.append(electrode1.text)
                        for electrode2 in electrode.iter('Ant_Electrode_2'):
                            for electrode2 in electrode.iter('Ant_Easting'):
                                x2t.append(electrode2.text)
                            for electrode2 in electrode.iter('Ant_Northing'):
                                y2t.append(electrode2.text)

Prevent "If Not cl Is Nothing Then" from skipping lines of code if cl is nothing (Instead, make it search for other criteria)

How do I make it search for another word like "Walmart" if it doesn't find "Target" and make it search for another word like "Dillions" if it doesn't find "Target" and so on...

Set cl = Range("D:D").Find("Target") If Not cl Is Nothing Then cl.Select cl.Resize(1, 2).Select Selection.Copy ActiveSheet.Paste Destination:=Range("G1") End If

samedi 28 décembre 2019

Error in if (randomNumber <= p) { : missing value where TRUE/FALSE needed in R Studio

I get a problem when I run this program in R. anybody help me to solving this problem..?

par_1<-cbind(c(5.038159),c(3.899621))
par_2<-cbind(c(2.435457),c(13.89517))
tau<-365

  cdf2 <- function(x, help) {
    pgamma(x, shape=par_1[1], scale=par_1[2]) *
      pgamma(x, shape=par_2[1], scale=par_2[2])-help
  }

nextEventTime <- function(censoring) {
    randomNumber <- runif(n=1, min=0, max=1)
    pnew <- randomNumber * (1 - cdf2(censoring, 0)) + cdf2(censoring, 0)
    uniroot(f=cdf2, interval=c(0, 1000*tau), help=pnew)$root
  }
 hazardRate1 <- function(t) {
    dgamma(t, shape=par_1[1], scale=par_1[2]) /
      (1 - pgamma(t, shape=par_1[1], scale=par_1[2]))
  }
  hazardRate2 <- function(t) {
    dgamma(t, shape=par_2[1], scale=par_2[2]) /
      (1 - pgamma(t,shape=par_2[1], scale=par_2[2]))
  }
  nextEventType <- function(t) {
    p <- hazardRate1(t)/(hazardRate1(t)+hazardRate2(t))
    randomNumber <- runif(n=1, min=0, max=1)
    if (randomNumber <= p) {1} else {2}
    }


baris<-c(1:20000)
nexteventtime<-rep(0,time=20000)
nexteventype<-rep(0,time=20000)
dfnexteventime<-data.frame(baris,nexteventtime,nexteventype)
for(i in 1:nrow(dfnexteventime)){
dfnexteventime$nexteventtime[i]<-nextEventTime(dfnexteventime$nexteventtime[i])
dfnexteventime$nexteventype[i]<-nextEventType(dfnexteventime$nexteventtime[i])
}
View(dfnexteventime)

When I run this program, this program will error & produce output like this

Error in if (randomNumber <= p) { : missing value where TRUE/FALSE needed

I think this problem because t value in nextEventType(t) function can't zero (t!=0). But nextEventTime(dfnexteventime$nexteventtime[i]) never produce zero value, when I run this part for 10 times,

baris<-c(1:20000)
nexteventtime<-rep(0,time=20000)
nexteventype<-rep(0,time=20000)
dfnexteventime<-data.frame(baris,nexteventtime,nexteventype)
for(i in 1:nrow(dfnexteventime)){
dfnexteventime$nexteventtime[i]<-nextEventTime(dfnexteventime$nexteventtime[i])
}

without nextEventType function. This part never produce 0 value. So, I confuse, what is a problem?.

I want result nextEventType(t) produce not zero value. because if using zero value will be Error in if(ramdonNumber <= p) { :...

google sheets if function when true send a value of another cell

I'm trying to create if function that If the condition is met then the result value will be taken from another cell ?

I'm trying to wrap my head on it but cant figure it out.

thanks guys, really appreciate it

Output taxonomy terms - show none if none selected

I've got a working shortcode that outputs the terms of a taxonomy as image thumbnails.

It works great, BUT when none of the taxonomy terms are selected, it outputs ALL terms.

My current code is as follows:

add_shortcode( 'book-accreditation', 'book_accreditation_output' );
function book_accreditation_output($atts){

    ob_start();
    echo '<div id="book-terms-wrap"><ul class="book-terms">';

    global $post;
    $taxonomy = 'book_accreditation';
    $post_terms = wp_get_object_terms($post->ID, $taxonomy, array('fields' => 'ids'));

    $terms = get_terms( $taxonomy, array(
    'hide_empty' => false,
    'include'  => $post_terms
      )
  );

  foreach($terms as $term){
    $thumbnail = get_field('bkk_taxonomy_image', $term->taxonomy . '_' . $term->term_id);
    $thumbnail = $thumbnail['url'];
    $name = $term->name;
    $url = get_term_link($term, $taxonomy);
    echo '<li><img src="' . $thumbnail . '" class="accreditation-image"></li>';
  }
    echo '</ul></div>';
    $output = ob_get_clean();
    return $output;
}

I'm trying to fix this with if (!empty()) variable targeting the $terms, but i'm probably not putting the code correctly.

So if NO terms are selected, then nothing should output.

I'm adding the code as follows:

add_shortcode( 'book-accreditation', 'book_accreditation_output' );
function book_accreditation_output($atts){

  if (!empty($terms)) {
    ob_start();
    echo '<div id="book-terms-wrap"><ul class="book-terms">';

    global $post;
    $taxonomy = 'book_accreditation';
    $post_terms = wp_get_object_terms($post->ID, $taxonomy, array('fields' => 'ids'));

    $terms = get_terms( $taxonomy, array(
    'hide_empty' => false,
    'include'  => $post_terms
      )
  );

  foreach($terms as $term){
    $thumbnail = get_field('bkk_taxonomy_image', $term->taxonomy . '_' . $term->term_id);
    $thumbnail = $thumbnail['url'];
    $name = $term->name;
    $url = get_term_link($term, $taxonomy);
    echo '<li><img src="' . $thumbnail . '" class="accreditation-image"></li>';
  }
    echo '</ul></div>';
    $output = ob_get_clean();
    return $output;
  }
}

But this won't work unfortunately, what am I doing wrong here?

How to track nested if

I have a VBA code with a lot of Nested If's and GoTo's. The code is poorly indited so its difficult to read which If's don't have else's etc..

Is there a way to highlight the If and the corresponding Then and Else's to figure out where an If statement ends and which one is open?

How to generate a payroll condition using array formula

I want to make a condition that if the day is more than or equal 16 and less than or equal 31 the formula returns the same month adding to it the word payroll and if the day is from 1 to 14 formula returns previous month adding to it the word payroll

The equation is working but without the array formula and I need it in array to auto drag

Here is the equation without the array formula:

=IF(A2="","",if(AND(B2>=16,B2<=31),TEXT(DATE(2019,C2,1),"MMM"),TEXT(DATE(2019,C2-1,1),"MMM"))&" Payroll")`

Here is the equation in the array formula:

=ARRAYFORMULA(IF(ROW(A:A)=1,"Payroll Array",IF(A:A="","",if(AND(B:B>=16,B:B<=31),TEXT(DATE(2019,C:C,1),"MMM"),TEXT(DATE(2019,C:C-1,1),"MMM"))&" Payroll")))

here is a sample datasheet to see the difference as the array formula doesn't return the correct value I need: Link

Google Sheets how to write multiple things in a cell

Is there and easy ways to make things like this work:

=IF(TRUE, " " " ", " ")

Or with a method in it:

=IF(TRUE, " This is the Name " VLOOKUP(NAME_ID, NAME!$A$4:$B, 2 FALSE), " ")

Javascript Functions/ innerHTML

So I'm trying to create a function that when the user clicks on a button or whereever I use the onclick method my problem is I have zero IDEA why my function won't work. I'm like 90% sure it worked yesterday and all I did was turn on my macbook......So I can get document.........innerHTML to work abstractly or in a void....but when I added it to this function it stopped working....I'm sure I did something I'm just not sure what.

    const insurances = ["amica", "travelers","national general","infinity","cincinatti"];

Honestly the only thing I can think that I changed was I made the insurance array a const instead of defining that inside the function but I can't imagine that's my issue.

   '''
   function cashBack1() {
    var amount=1;
    var statement = "Congratulations you just qualified for up to!! $";
    var insurance= document.getElementById('insurance').value;

    insurance = insurance.toLowerCase;

    amount = !insurances.includes(insurance) ? "$200" : "$300";

    alert("");
    document.getElementById('lilDiv').innerHTML = statement + amount;
  } 
  '''

My second problem is I can't get my and or statements right.....if you notice

     '''
    amount = !insurances.includes(insurance)? "200" :"$300";
    '''

I'm attempting to get it to an if statement but I started following vs code's suggestions lol. Here's the original version of the function

    '''
    function cashBack() {
      var amount=1;
      var statement = "Congratulations you just qualified for up to!! $";
      var insurance= document.getElementById('insurance').value;
      insurance = insurance.toLowerCase;
      if(!insurances.includes(insurance)){
      amount = "$200";
      }else {
      amount = "$300";
    } 
    alert("");//I added this alert just to see if it's making down to this part of the code..
             // It's not......
    document.getElementById("lilDiv").innerHTML = statement + amount;
     }
   '''

So I guess in conclusion this is a double part question. I need help in properly forming my if statement so I can get it to check if the user entered on of the target companies and they receive 300 cash back shown in an empty div.....if it isn't it should state that they receive 200 cash back. Help! THANKS IN ADVANCE

logical operators and if statements combination

I'm looking if there is an alternative to write this code cleaner and efficient. My goal is to set different values based on the hour of the day.

var hour = new Date().getHours();
var user = 'User4';

if (hour >= 4 && hour < 6) {
    user = 'User1';
}
if (hour >= 6 && hour < 13) {
    user = 'User2';
}
if (hour >= 13 && hour < 19) {
    user = 'User3';
}
if (hour >= 19) {
    user = 'User4';
}

I found this article online https://blog.wax-o.com/2015/05/an-alternative-to-if-else-and-switch-in-javascript/ but I couldn't achieve logical operators into this.

let values = {
    a: 1,
    b: 2,
};
let foo = values[ bar ] || 3;

Really appreciate your help! Thanks 😗

pictureBox.Image condition isn't true even though picture is loaded

Code:

private async void pictureBox5_Click(object sender, EventArgs e)
    {
        if (pictureBox5.Image == Uny.Properties.Resources.Uny_Slider_one)
        {
            pictureBox5.Image = Uny.Properties.Resources.activating_gif;
            await Task.Delay(600);
            pictureBox5.Image = Uny.Properties.Resources.Uny_Slider_two;
            LogStatus = 1;
            await Task.Delay(3000);
        }
        if (pictureBox5.Image == Uny.Properties.Resources.Uny_Slider_two)
        {
            pictureBox5.Image = Uny.Properties.Resources.deactivating_gif;
            await Task.Delay(600);
            pictureBox5.Image = Uny.Properties.Resources.Uny_Slider_one;
            LogStatus = 0;
        }
    }

All the images were imported in the Resources & all the names are correct. pictureBox5 is normally set to Uny_Slider_One, I just don't see the error? I even said picturebox5.Image = Uny.Properties.Resources.Uny_Slider_one; directly after InitalizeComponent();!

vendredi 27 décembre 2019

Cannot invoke equals(string) on the primitive type char [duplicate]

This question already has an answer here:

In the if statement in my User class it says cannot invoke equals(String) on the primitive type char what is the problem?

My rock paper scissors code

Or Statement Not working-can someone tells me why is it not working

function CheckWeekNum() {
  var weeknumber = 52;

  if(cur_year == 2019 || cur_year == 2026){
    weeknumber = 53;
    ssForReportSheet.getRange("A53").setValue("Week 53");
    ssForSpecialReportSheet.getRange("A53").setValue("Week 53");
  }

  if(cur_year !== 2019 || cur_year !== 2026){ 
    ssForReportSheet.getRange("A53").setValue("");
    ssForSpecialReportSheet.getRange("A53").setValue("");  
  }

  if(cur_week == weeknumber){
    ssForReportSheet.getRange(1,3,LastRow,1).setValue.clear;
    ssForSpecialReportSheet.getRange(1,3,LastRow,1).setValue("");
  }
}

Write Login and registratiin program in java?

just help me please. How to write a program in java, that from a few for example registration, that we have to define first, one as an input is taken, matched and said success, else looping for a few time till the correct one is input or the program stops. Secondly there are numbers of subjects to be selected not more than 5 and less than 3.

If u people helped me. That would be very kind of yoh. Thank you.

how do I fix this error, "There is no arguments given that corresponds to the required formal parameter"?

I was to call a method within an else if to use for if users age is < 21 or|| >75 output message box. this error is coming up when i try to call the method

this is my code

 public int GetAge(string DOB, DateTime startDate)
    {
        int driverAge = startDate.Year - DateTime.Parse(DOB).Year;

        if (startDate.Month < DateTime.Parse(DOB).Month || (startDate.Month == DateTime.Parse(DOB).Month && startDate.Day < DateTime.Parse(DOB).Day))
        {
            driverAge--;

        }
            return driverAge;

    }

...

else if (GetAge())
        {

        }

Flutter returning multiple widgets when i want only 1

I am trying to return 1 widget saying that there are no messages to be displayed and i have a if condition to test it out to stop it when theres more than 1, but flutter is ignoring that if and creating multiple widgets.

Here is the code for the if statement:

 if (_messages?.length == null && nullCount == false) {
  nullCount = true;
  print(nullCount);
  return SliverChildBuilderDelegate((BuildContext context, int index) {
    return createNullMessageCard();
  });
}

Here is the code for the createNullMessageCard():

createNullMessageCard() {
print('no messages');
return Center(
    child: Container(
  width: 600,
  child: InkWell(
    child: Container(
      width: 900,
      color: Colors.grey[200],
      child: Padding(
        padding: const EdgeInsets.fromLTRB(12, 0, 12, 0),
        child: Center(
          child: Container(
            width: 600,
            child: Column(
              children: <Widget>[
                ListTile(
                  leading: CircleAvatar(
                    child: Icon(
                      Icons.notifications,
                      color: Colors.red[400],
                    ),
                    backgroundColor: Colors.grey[200],
                  ),
                  title: Text(
                    Translations.of(context).trans('nomessages'),
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.black,
                    ),
                  ),
                ),
                Divider(
                  color: Colors.black54,
                ),
              ],
            ),
          ),
        ),
      ),
    ),
   ),
 ));
}

Thank you for your time and attention

Differences between contains and indexOf, Java

I am doing the following programming exercise: The old switcheroo. The statement is:

Write a function

Kata.Vowel2Index("this is my string") == "th3s 6s my str15ng"

Kata.Vowel2Index("Codewars is the best site in the world") == "C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld"

Your function should be case insensitive to the vowels.

I have doubts when the input is an empty string, I mean when we test with:

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class KataTest {
  @Test public void test4() {
    assertEquals("", Kata.vowel2Index(""));
  }

}

My question is, why if we use contains, we have to check if input string is empty?

import java.util.*;
public class Kata {
  static final String VOWELS = "AEIOUaeiou";
  public static String vowel2Index/*🔡➡️👆*/(String s) {
    if(s==null || s.equals("")) return "";
    String[] letters = s.split("");

    for(int i = 0; i < letters.length; i++){
      if(VOWELS.contains(letters[i])){
        letters[i] = String.valueOf(i+1);
      }
    }
    return String.join("",letters);
  }
}

Or check if the current string inside the loop is empty:

import java.util.*;
public class Kata {
  static final String VOWELS = "AEIOUaeiou";
  public static String vowel2Index/*🔡➡️👆*/(String s) {
    String[] letters = s.split("");

    for(int i = 0; i < letters.length; i++){
      if(letters[i] != "" && VOWELS.contains(letters[i])){
        letters[i] = String.valueOf(i+1);
      }
    }
    return String.join("",letters);
  }
}

But we can omit the previous condition when we use indexOf:

import java.util.*;
public class Kata {
  static final String VOWELS = "AEIOUaeiou";
  public static String vowel2Index/*🔡➡️👆*/(String s) {
    String[] letters = s.split("");

    for(int i = 0; i < letters.length; i++){
      if(VOWELS.indexOf(letters[i]) > 0){
        letters[i] = String.valueOf(i+1);
      }
    }
    return String.join("",letters);
  }
}

I have also read:

What are the differences between contains and indexOf?‽?

Spreadsheet: Find the next Wednesday (Excel / Google Sheets)

I'm trying to display the date of the first upcoming Wednesday, to show the start time of a weekly event.

If it's Sunday 15/12/2019 then it would return Wednesday 18/12/2019.

If it's Monday 16/12/2019 then it would return Wednesday 18/12/2019.

If it's Wednesday 18/12/2019 then it would return Wednesday 25/12/2019.

I tried this function:

=TODAY()+(7-(WEEKDAY(TODAY(),3)-2))

(To test, I replaced TODAY() with A1 where A1 is a custom date: =A1+(7-(WEEKDAY(A1,3)-2)))

but on Mondays and Tuesdays it returns next week's Wednesday, rather than this week's.

So I solved it like this:

=IF((WEEKDAY(TODAY(),3)-2)<0, TODAY()-(WEEKDAY(TODAY(),3)-2), TODAY()+(7-(WEEKDAY(TODAY(),3)-2)))

(Test function: =IF((WEEKDAY(A1,3)-2)<0, A1-(WEEKDAY(A1,3)-2), A1+(7-(WEEKDAY(A1,3)-2))))

but this leaves me with a big chunky IF-function.

Since I am trying to keep the date as a variable to use in more complicated formulas, is there no way to more easily adjust the first function, without using complicated IFs?

I am trying to print some corresponding values to a character but condition always going to else

I am trying to print some values specified in if condition but compiler throws errors that this variable is not declared in this scope.

```

#include <bits/stdc++.h>
using namespace std;

int main()
{
  char i, p, P, z, Z, e, E, d, D;
  cin>>i;

  if(i==p || i==P)
    cout<<"PrepBytes";

  else if(i==z || i==Z)
    cout<<"Zenith";

  else if(i==e || i==E)
    cout<<"Expert Coder";

  else if(i==d || i==D)
    cout<<"Data Structure";

  else
    cout<<"Wrong Input";

  return 0;
}

Output:-

PS E:\C++> .\a.exe
d
Wrong Input

Making use of dict.get for if elif and else in List Comprehension

I wanted to implement if elif and else inside a list comprehension and in this stackoverflow answer I found a way of doing the same.

So let me explain what the issue is:

As per the answer, the dict.get() can be used in following way to use conditionals in list comprehension:

>>> d = {1: 'yes', 2: 'no'}
>>> [d.get(x, 'idle') for x in l]
['yes', 'no', 'idle', 'idle', 'idle']

Seems nice and good. But I am running into a different kind of problem. So I need to use the same method to work with the index of some other list. Allow me to explain:

perc = np.array([0, 0.25, 0.5, 0.75, 1])

d= {0: 0, len(perc):1}

result = [d.get(x, (perc[x-1]+perc[x])/2) for x in range(len(perc)+1)]

So in short I want my output to be 0 and 1 for x being 0 and len(perc), or else average of previous value and current value.

Now, this is giving me an error:

IndexError: index 5 is out of bounds for axis 0 with size 5

My question is, wasn't dict.get(key[, default])defined as:

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

Now clearly 5 as a key is in the dictionary as len(perc)=5, then why the default condition is being checked first, which obviously will give an error as there is no 5th index in the array perc.

How to compare strings in PyQt5 in Python?

I want to make a GUI app usin PyQt5, where if you click a button then some random text will appear in the label. If that random text will be equal to Whats up? then it will type True in the terminal. Else, it will print False.

However I am getting False every time...

Here is my code:

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
import sys
import random

lis = ["Hello world", "Hey man", "Yo buddy", "Go to hell", "Whats up?"]

class MyWindow(QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.initUI()
        self.setGeometry(200,200,300,300) 
        self.setWindowTitle("WhatsApp Sheduled")

    def initUI(self):
        self.label = QLabel(self)
        self.label.setText("My first label")
        self.label.move(120, 120)

        self.b1 = QtWidgets.QPushButton(self)
        self.b1.setText("Click here")
        self.b1.clicked.connect(self.clicked)

    def clicked(self):
        self.label.setText(random.choice(lis))
        if self.label == "Whats up?":
            print("True")
        else:
            print("False")

def clicked():
    print("Clicked!")

def main():
    app = QApplication(sys.argv)
    win = MyWindow()

    win.show()
    sys.exit(app.exec_())

main()  # It's important to call this function

Any help would be appreciated...

Please just tell me how to do that. I am new to GUI, so didn't know much.

Masking the input in if condition batch process

If I use below simple code to mask input in command prompt and put in a batch file it works as expected:

Working code:

echo off
set "psCommand=powershell -Command "$pword = read-host 'Enter Password' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p

echo %password%
pause

But when I put the similar thing to mask input inside if condition as below it does not work:

@echo off
setlocal enabledelayedexpansion
cd /d "C:\Program Files\IIS\Microsoft Web Deploy V3"
echo Please select any option from below list:
echo 1. Get The Dependencies
echo 2. Export the IIS settings
echo 3. Import the IIS settings
set /p INPUT=""

IF /I '%INPUT%'=='1' (msdeploy -verb:getDependencies -source:metakey=lm/w3svc)

IF /I '%INPUT%'=='2' (echo Please provide the path to export IIS settings:
set /p EXPORTPATH=""

set "psCommand=powershell -Command "$pword = read-host 'Enter Password' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p

echo %password% !EXPORTPATH!
msdeploy.exe -verb:sync -source:apphostconfig -dest:package=!EXPORTPATH!\IISPackage.zip,encryptPassword=%password%> DWSpackage7.log
echo LINE IS EXECUTED
)

IF /I '%INPUT%'=='3' (echo Please provide the zip file with complete path to import IIS settings:
set /p IMPORTPATH=""
echo Please provide the password to import the iis settings:
set /p IMPORTPASSWORD=""
msdeploy.exe -verb:sync -source:package=!IMPORTPATH!,encryptPassword=!IMPORTPASSWORD! -dest:apphostconfig> DWSpackage7.log
)
pause

Please have a look and suggest me where I'm doing mistake or if I'm missing anything.

jeudi 26 décembre 2019

need an if, if_else, or for statement to replace unwanted numbers in data.frame [duplicate]

This question already has an answer here:

Using R, what ifelse, if_else, if, for, or other statements should be used on a data.frame to find the negative numbers and replace them with the positive number 0.001? Said another way, replace all negative numbers in the data.frame with the positive number 0.001. A base R, plyr or dplyr function would work.

set.seed(1)

dfTest <- data.frame(replicate(5, sample(c(-10:99), 7, rep = TRUE)))

In MS-Excel, the code might be =if(x<0, 0.001, x). There are several R examples for lists, just not many applicable for data.frames. Thanks.

use if else statement to effect all items appended to a empty Array

My swift code right now uses func addbox to append imageviews to a empty array of imageviews. When the user taps button widthActivatorBtn it should allow the user to select on a imageview and change the width of the imageveiew. It works but only if the widthActivatorBtn was selected and selectNum is changed to 3. I can affect imageview placed on after selectNum was changed to 3 but not the imageviews before it. Check out my gif and you can see the problem. When selectNum is changed to 3 all imageviews should be able to have their width changed via slider.

enter image description here

import UIKit

class ViewController: UIViewController {

    var slider = UISlider()
    var ht = -90
    var widthSize = 80
    var emptyArray = [UIImageView]()
    var addImageview = UIButton()
    var width = UIButton()
    var currentView: UIView?
    var selectNum = Int()

    override func viewDidLoad() {
        super.viewDidLoad()
        [addImageview,slider,width].forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview($0)
            $0.backgroundColor = .systemOrange
        }

        addImageview.setTitle("add imageview", for: .normal)

        width.setTitle("change width", for: .normal)
        addImageview.frame = CGRect(x: view.center.x-115, y: view.center.y + 200, width: 160, height: 40)
        slider.frame = CGRect(x: view.center.x-115, y: view.center.y-200, width: 160, height: 40)

        width.frame = CGRect(x: view.center.x-115, y: view.center.y + 100, width: 160, height: 40)
        addImageview.addTarget(self, action: #selector(addBOx), for: .touchUpInside)
        width.addTarget(self, action: #selector(widthActivatorBtn), for: .touchUpInside)
        slider.addTarget(self, action: #selector(ji), for: .valueChanged)
        slider.minimumValue = 10
        slider.maximumValue = 150

    }

    @objc func widthActivatorBtn() {

        width.backgroundColor = .systemPink

        selectNum = 3
    }

    @objc func addBOx() {


        let subview = UIImageView()


        subview.isUserInteractionEnabled = true
        emptyArray.append(subview)
        view.addSubview(subview)

        subview.frame = CGRect(x: view.bounds.midX - 0, y: view.bounds.midY + CGFloat(ht), width: CGFloat(widthSize), height: 35)
        subview.backgroundColor = .purple


        ht += 50
        emptyArray.append(subview)

        if  selectNum == 3{
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGestured(_:)))
            subview.addGestureRecognizer(tapGesture)

        }


    }

    @objc func handleTapGestured(_ gesture: UIPanGestureRecognizer) {
        currentView = gesture.view

    }


    @objc func ji(sender : UISlider){
        widthSize = Int(slider.value)
        currentView?.bounds.size.width = CGFloat(slider.value)

    }

}

How to clear an interval in an if statement

So, I'm working on a game called Mini Arcade which features a bunch of different minigames. I found a way to create a fade effect after I click a button to go to another page. The fade effect seems to work properly, but after going to the console of the page, the fade interval doesn't clear like it's supposed to when the opacity variable hits 0, which makes the opacity of the object go into the negatives. This is a problem because once I begin making buttons that fade back to the homepage, the homepage will still be fading out, while fading in at the same time, which is a big problem.

if(opacity == 0){
clearInterval(fadeOut);
}

As you can tell, it's just a simple if statement within my fade out function. Sorry if I didn't explain this well, but I could really use some help. Thanks.

How to simplify a big if statement in C#?

Current in my code, if statement is too big and many repetitions.

if (!String.Equals(node.Name, "A", StringComparison.OrdinalIgnoreCase)
 && !String.Equals(node.Name, "B", StringComparison.OrdinalIgnoreCase)
 && !String.Equals(node.Name, "C", StringComparison.OrdinalIgnoreCase)
 &&  ... 

I would like to make it concise. But my idea is only to create a function and passing List or Array as param.

List<String> target = new List<String>() { "A", "B", "C" ... };
MultipleStringCompare(node.Name, target, , StringComparison.OrdinalIgnoreCase);

Is there any more beautiful way to make it simple without making any function in modern C# syntax?

Code bugging with "if" condition statement in android

I use if to not to execute some code but that code is executed anyway,even when the condition is saying to not execute.

    private void processImage(FirebaseVisionImage image){
    Log.d("Works122", "esad2123vrth12ing worked2313   "+isDetected);


    if (!isDetected && permitScan){

        Log.d("Works122", "sd12222worked2313     "+isDetected);

        detector.detectInImage(image)
                .addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
                    @Override
                    public void onSuccess(List<FirebaseVisionBarcode> barcodes) {

                        Log.d("Works122", "trembotest     "+isDetected);
                        processResult(barcodes);

                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {

                Log.d("work12", "failure2");

            }
        });

    }else {
        Log.d("Works122", "failuresq1we2");

    }

}


    private void processResult(List<FirebaseVisionBarcode> firebaseVisionBarcodes){

    Log.d("work12", "evrth12ing worsadsadasked2313    "+firebaseVisionBarcodes.size());

    if(firebaseVisionBarcodes.size() > 0){


        isDetected = true;

        FirebaseVisionBarcode item = firebaseVisionBarcodes.get(0);


            Log.d("work12", "evrth12ing worked2313");

            int value_type = item.getValueType();
            switch (value_type) {

                case FirebaseVisionBarcode.TYPE_TEXT:

                    {

                    Log.d("work12", "evrthing worked  "+item.getRawValue());


                    }
                break;

                case FirebaseVisionBarcode.TYPE_WIFI:
                {

                    Log.d("Works122","Wifi "+ isDetected);

                    AlertDialog diaBox = AskOption();
                    diaBox.show();



                }

                default:
                    break;

            }



    }

}

I run this code and the "If" statment is executed even when "isDetected" is true and after some time is not executed anymore,starts working right like it should be.

That's the Log when I run:

    ***2019-12-26 20:02:53.425 720-720/com.vizuprice.vizuprice D/Works122: trembotest     false
    2019-12-26 20:02:53.425 720-720/com.vizuprice.vizuprice D/Works122: Wifi true
    2019-12-26 20:02:53.441 720-1025/com.vizuprice.vizuprice D/Works122: esad2123vrth12ing worked2313   true
    2019-12-26 20:02:53.441 720-1025/com.vizuprice.vizuprice D/Works122: failuresq1we2
    2019-12-26 20:02:53.507 720-1025/com.vizuprice.vizuprice D/Works122: esad2123vrth12ing worked2313   true
    2019-12-26 20:02:53.507 720-1025/com.vizuprice.vizuprice D/Works122: failuresq1we2
    2019-12-26 20:02:53.570 720-1025/com.vizuprice.vizuprice D/Works122: esad2123vrth12ing worked2313   true
    2019-12-26 20:02:53.570 720-1025/com.vizuprice.vizuprice D/Works122: failuresq1we2
    2019-12-26 20:02:53.605 720-720/com.vizuprice.vizuprice D/Works122: trembotest     true
    2019-12-26 20:02:53.605 720-720/com.vizuprice.vizuprice D/Works122: Wifi true
    2019-12-26 20:02:53.629 720-1025/com.vizuprice.vizuprice D/Works122: esad2123vrth12ing worked2313   true
    2019-12-26 20:02:53.629 720-1025/com.vizuprice.vizuprice D/Works122: failuresq1we2
    2019-12-26 20:02:53.645 720-1025/com.vizuprice.vizuprice D/Works122: esad2123vrth12ing worked2313   true
    2019-12-26 20:02:53.645 720-1025/com.vizuprice.vizuprice D/Works122: failuresq1we2
    2019-12-26 20:02:53.735 720-1025/com.vizuprice.vizuprice D/Works122: esad2123vrth12ing worked2313   true
    2019-12-26 20:02:53.735 720-1025/com.vizuprice.vizuprice D/Works122: failuresq1we2
    2019-12-26 20:02:53.778 720-1025/com.vizuprice.vizuprice D/Works122: esad2123vrth12ing worked2313   true
    2019-12-26 20:02:53.778 720-1025/com.vizuprice.vizuprice D/Works122: failuresq1we2
    2019-12-26 20:02:53.805 720-720/com.vizuprice.vizuprice D/Works122: trembotest     true
    2019-12-26 20:02:53.805 720-720/com.vizuprice.vizuprice D/Works122: Wifi true
    2019-12-26 20:02:53.841 720-1025/com.vizuprice.vizuprice D/Works122: esad2123vrth12ing worked2313 

  true***

Look even with the variable being "true" the code still runs for a while and I don't know why.

Why are two values in 'increasePower()' being reset?

I am trying to create a game using HTML canvas and javascript. However, I'm still fairly new to JavaScript and I don't understand why the values (this.power & this.origin.y) are being reset to their initial constructor values.

My aim is to try and get the code to go inside the 'else if' statement, which will then run the onShoot function. However since the values are being reset after the user unclicks the mouse, it does not go into the else if statement. (Note that if I hold the left button on the mouse, the values are correctly incremented, they are only reset when I let go of the mouse click)

here is the class which holds 'increasePower()':

const hand_origin = new Vector(13.5, 80);

function Hand(position, onShoot) {
    this.position = position;
    this.origin = hand_origin.copy();
    this.power = 0;
    this.onShoot = onShoot;
}

Hand.prototype.update = function () {

    // Counter represents the number of clicks made by the user
    if ((counter >= 3) && (mouse.left.down)) {
        this.increasePower();
    } else if (this.power > 0) {
        this.shoot();
    } else {
        console.log("inside final else case " + this.power)
    }
}

Hand.prototype.draw = function () {
    Canvas.drawImage(items.hand, this.position, this.origin,);
}

Hand.prototype.increasePower = function () {
    this.power += 100;
    this.origin.y += 0.1;
}

Hand.prototype.shoot = function () {
    this.onShoot(this.power, this.rotation);
}

An instance of the hand class is created in another file :

function CarromWorld(){
    this.striker = new Carrom_men(new Vector(294.5,512.5));
    this.hand = new Hand((new Vector(294.5, 512.5)), this.striker.shoot) 
}

// the postions of the objects will be changed here 
CarromWorld.prototype.update = function(){
    this.hand.update();
    this.striker.update();
    this.hand.position = this.striker.position;
}

//objects will be drawn here 
CarromWorld.prototype.draw = function(){
    Canvas.drawImage(items.board, {x:0, y:0});
    this.hand.draw();
    this.striker.draw();
}

Since I am trying to create an animation, I use the requestAnimationFrame to create the game loop:

//This class is handling the overall game 

function Game() {
}

//Used to initialise everyhting in the game
Game.prototype.init = function(){
    this.carromWorld = new CarromWorld();
}

Game.prototype.start = function(){
    mainGame.init();
    mainGame.loop();
}

// all of the animations will occur in this method
//First want to clear the object for each frame and then want to draw the updated versions of the objects
Game.prototype.loop = function(){ 
    Canvas.clearScreen();

    //Calling two of the mehtods from the carromWorld Class, this way the code stays concise and allows all the obejcts' psotions to be updated
    mainGame.carromWorld.update();
    mainGame.carromWorld.draw();
    //want the button to be set to false again
    mouse.reset(); 
    requestAnimationFrame(mainGame.loop)
}

//Creating a new game
let mainGame = new Game();

C#: After running program and the input is answered with an if statement, how do i get the program to keep asking the question?

I asked a question in the WriteLine form that requires a numbered input, converted it to an int, used that int in an if-else, and I want the question to be re-asked afterward. Any idea?

Example:

Console.WriteLine("What hour is it?: ");
int hour = Convert.ToInt32(Console.ReadLine());

if (hour > 0 && hour < 12)
{
    Console.WriteLine("It's morning.");
}

if (hour > 12 && hour < 18)
{
    Console.WriteLine("It's evening.");
}
else if (hour > 18 && hour < 24)
{
    Console.WriteLine("It's night.");
}
else
{
    Console.WriteLine("Invalid Input.");
}

Javascript Switch Statement multiple cases return the values

I have a json object I am getting my data from with the values (Cow: 'Yes', Chicken: 'NULL') and (Cow: 'Yes', Chicken: 'Yes') etc. I would like to display only the values that have 'Yes' and then their value. Currently I only can return the first case that includes 'Yes', for example it just returns 'Cow', however the goal is to return 'Cow, Chicken' if both have the 'Yes' value. What am I doing wrong here? Or if there is a better method, thank you for your help.

switch ("Yes") {
    case popup.properties.Beef:   return "<span>Cows</span>";
    case popup.properties.Pork: return "<span>Pigs</span>";
    case popup.properties.Sheep:  return "<span>Sheep</span>";
    case popup.properties.Goat: return "<span>Goats</span>";
    case popup.properties.Lamb:  return "<span>Lambs</span>";
    case popup.properties.Rabbit: return "<span>Rabbit</span>";
    case popup.properties.OtherMeat:  return "<span>Other</span>";
    case popup.properties.Chicken: return "<span>Chicken</span>";
    case popup.properties.Turkey:  return "<span>Turkey</span>";
    case popup.properties.Duck: return "<span>Duck</span>";
    case popup.properties.Goose:  return "<span>Geese</span>";
    case popup.properties.Pheasant: return "<span>Pheasants</span>";
    case popup.properties.Quail:  return "<span>Quail</span>";
    case popup.properties.OtherPoultry:  return "<span>Other Poultry</span>";
    default:      return "";
}

Even though my if statement is satisfied this wont work [closed]

I'm trying to change all the values of my array that are "merger" to the "company" why won't it work?

  mergingComp = document.getElementById("merger").value;
  console.log(mergingComp);
      for (i=0;i<arrTotal.length;i++){
        if (arrTotal[i] == mergingComp) {
          arrTotal.splice(i,1,company);
        }
      }

select the Rows which contains same text in last two columns of data frame in python pandas

I have a data frame which looks below

import pandas as pd

k={'ID':[1,2,3,4,5,6],'m1':['jj','nn','jj','nn','nn','nn'],
   'm2':['jj','nn','nn','jj','jj','jj'],
   'm3':['jj','','nn','jj','jj','jj'],
   'm4':['nn','','nn','jj','jj','jj'],
   'm5':['nn','','','jj','jj','nn'],
   'm6':['','','','jj','jj','nn']}

df=pd.DataFrame(data=k)

ID  m1  m2  m3  m4  m5  m6
1   jj  jj  jj  nn  nn  
2   nn  nn              
3   jj  nn  nn  nn      
4   nn  jj  jj  jj  jj  jj
5   nn  jj  jj  jj  jj  jj
6   nn  jj  jj  jj  nn  nn

we have to select the ID which contains 'nn' in last two columns but the last column for each row(ID) is different

I want the result as follows

ID  last1   last2   last two columns are nn
1   nn       nn         yes
2   nn       nn         yes
3   nn       nn         yes
6   nn       nn         yes 

scanf() in loop with a conditional does not work

I'm making a simple program that returns the sum of the sizes of user input. User first inputs an int for amount of sizeof() sums to add Followed by an input and char for data type. This all works, BUT, what fails is if user types in anything other than 'c', 'd' or 'i' loop breaks and prints "invalid tracking code type."

My program fails on the conditional - even though the scanf() correctly obtains the char, it still fails.

FOR EXAMPLE:

INPUT:

3
10 i
7 c
12 d

OUTPUT

143 bytes

INPUT

1
1 o

OUTPUT

invalid tracking code type

how can you compare a user input using scanf in a loop?

#include <stdio.h>

int main()
{
    int num, input, i, sum;
    int invalid = 1;
    sum = 0;
    i = 0;
    char type;

    printf("give me a num!\n");
    scanf("%d", &num);

    while(i < num)
    {
        printf("int and char?\n");
        //scanf("%d", &input);
        //scanf(" %c\n", &type);
        if (scanf("%d %c", &input, &type) != 2)
        {
            printf("TYPE IS: %c\n", type);


        }
        printf("TYPE IS: %c\n", type);
        if(type != 'c' || type != 'd' || type != 'i')
        {
            printf("invalid tracking code type");
            invalid = 0;
            break;
        }
        i++;
        //printf("what is i? %d\n", i);
        sum = (sizeof(input)) + sum;
        printf("IT's the sum %d\n", sum);

    }

    if(invalid != 0)
    {
    printf("%d bytes", sum);
    }

    return 0;
}

There are a number of other posts that answer similar issues, but wasn't able to find anything specifically for this issue.

I've tried a number of things such as separating the scanf(), using different types of operators for the conditional. It works fine without the conditional, but with the conditional it always returns "invalid tracking code type" even when they are correct.

How to use ascii code of argv while making a conditional statement?

I'm a beginner. So i'm trying to make to conditional statement to make sure that argv is a positive int. For that I need ascii code of argv[1]. And I was planning to make an if condition statement which will be executed only if argv[1]/ascii codes of 0-9 is 1.

Need to apply formula to certain blank cells

hey guys so I have a formula here where it is supposed to only activate if a cell in the B column is blank and when a cell in the A column is not blank. When it does activate it takes the value in A and puts it in the blank B cell. here is the code:

 =IF(AND(not(isblank(A)),isblank(B)), B, A)

the problem I'm seeing is that I want this formula to be put on certain blank cells in the B column. is there a way for me to select all of those blanks in the B column and then add the formula to all of them at once so it doesn't mess with the cells that already have values in the B column?

Reassigning a value in an if statement in Swift

the following is printing "no user with username" but is printing retVal as "false" ( I changed function to a string just for troubleshooting, ideally this should be bool ) I am new to swift and this is absolutely driving me crazy. it is making it to the chunk of code where retVal would get reassigned, but it isn't reassigning it

static func isUserNameUnique(_ username : String) -> String {

    var retVal = "false"

    let db = Firestore.firestore()
    let newQuery = db.collection("users").whereField("userName", isEqualTo: username)
    newQuery.getDocuments { (document, error) in
        if document!.isEmpty {
            retVal = "true"
            print("No user with username")

        }
    }
    print("\(retVal)")
    return retVal
}

In if statement I am getting all files instead of the files that the condition I gave for [duplicate]

This question already has an answer here:

so in the below code I am not getting the required files instead I am getting all the files. I couldn't understand the problem.

for i in range(len(files)):
    filename,exten=os.path.splitext(files[i])
    #print(exten)
    if exten == '.jpg' or '.txt':
        print(files[i])

If Condition logical error in multiple conditions in loop with cron

I need to run 2 loops in cron which work after every 5 minutes

*/5 * * *  *

loop by cron 1. work in every 5 minutes and check if the file is uploaded or not. ($yesterday mean file with name of backdate)

1st cron-loop work fine to me, 2nd cron-loop I am not able to resolve, 2nd loop have 3 conditions

1. It should work when it found $yesterday.zip

2. It should only work once after $yesterday.zip (because its cron so it work after every 5 minutes when $yesterday.zip found)

3. it should not work 00:00 till $yesterday.zip downloaded

($yesterday file has no fix time to download so i run cron every 5 minutes)  I made this (writing below so you . guys dont think i didnt made effort and didnt say show sampel code, just need a if statement with cron include these 3 conditions)

FILE=/fullpath/$yesterday.zip
if test -f "$FILE"; then
touch /fullpath/loop2.txt ##########for loop 2
echo "I am the best"
else
cd /fullpath/
wget -r -np -nH "url/$yesterday.zip" ###########it should be 20+ mb file
find . -name "*.zip" -type 'f' -size -160k -delete ########## it will delete is some garbage downloaded
rm -rf /fullpath/loop2.txt  ########## delete the file so it stopped loop 2 for working evry 5 minutes .
fi

FILE2=/fullpath/loop2.txt
if test -f "$FILE2"; then
echo -e "Script will work only once" | mailx -v -s "Script will work only once"  myemail@gmail.com
else
echo "full script work"
touch /fullpath/loop2.txt
fi

You guys can ignore my above code and simple let me know if statement for such 3 conditons loop

mercredi 25 décembre 2019

how to change a column with both negative and positive value into two columns with negative value plus zero and positive value plus zero

My data is the following:

t  B
1  2
2 -3
3 -7  

How could i have the output like below? It means that when the data from column B is negative, the column N will equal this columnB's data,or it will equal to zero. On the contrary, when the data from column B is positive, the column P will equal this data, or it will equal to zero.

t   B  N  P
1   2  0  2
2  -3 -3  0
3  -7 -7  0

Yesterday date will compare to the filename of .txt

My codes are from some post here as well and I am using robocopy so that I can move the files instead of copy and pasting them.

Here are my information

**result** = my yesterdays date
**Source Path** = where the main file is.
**Destination Path** = where it should be move

I am trying to move a file wherein it was dated yesterday from source to destination.

set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
set "result=%yyyy%%mm%%dd%"
echo %result%

FOR /R %C:\Users\JBP-Admin\Desktop\Pugad\Forback UP% %%G IN (*.txt) DO (
set file=%%~nG

ROBOCOPY "C:\Users\JBP-Admin\Desktop\Pugad\Forback UP" "C:\Users\JBP-Admin\Desktop\Pugad\Forback UP\Destination" "*.txt" /mov
If "%result%"=="*.txt" (
    echo Filename "%file%" has been backed up
) else (
    echo Filename "%file%" nothing to back up yesterday
)

Number within r being wrongly recognized

I have a row of data that is created through ifelse statement of proper data.

 mutate(yrsatrisk = ifelse(!is.na(Age_at_death), as.numeric(Age_at_death), ifelse(!is.na(Age_at_last_update), as.numeric(Age_at_last_update), 0))

However one of the datapoints age_at_last_update = 8 but is then recognized as 80. If i sort the output, that row is set at 80, everything else recognizes it as 80 but one with if else statement that does yrsatrisk - 74 which gives an output of -66

    1060    Male    79  15  15  15  15  15  5   30  30  20
    527 979 Female  79  15  15  15  15  15  5   30  30  20
    26  828 Male    8   15  15  15  15  15  -66 30  30  -51
    150 101 Female  80  15  15  15  15  15  6   30  30  21

which is created by

"0-14atrisk" = ifelse(yrsatrisk > 14, 15, yrsatrisk),
         "15-29atrisk" = ifelse(yrsatrisk > 29, 15, ifelse(yrsatrisk > 14 & yrsatrisk < 30, (as.numeric(yrsatrisk) - 14), 0)),
         "30-44atrisk" = ifelse(yrsatrisk > 44, 15, ifelse(yrsatrisk > 29 & yrsatrisk < 45, (as.numeric(yrsatrisk) - 29), 0)),
         "45-59atrisk" = ifelse(yrsatrisk > 59, 15, ifelse(yrsatrisk > 44 & yrsatrisk < 60, (as.numeric(yrsatrisk) - 44), 0)),
         "60-74atrisk" = ifelse(yrsatrisk > 74, 15, ifelse(yrsatrisk > 59 & yrsatrisk < 75, (as.numeric(yrsatrisk) - 59), 0)),
         "75-85+atrisk" = ifelse(yrsatrisk > 74, (as.numeric(yrsatrisk) - 74) , 0),
         "0-29atrisk" = ifelse(yrsatrisk > 29, 30, yrsatrisk),
         "30-59atrisk" = ifelse(yrsatrisk > 59, 30, ifelse(yrsatrisk > 29 & yrsatrisk < 60, yrsatrisk, 0)),
         "60-85+atrisk" = ifelse(yrsatrisk > 59, (as.numeric(yrsatrisk) - 59), 0))

This is not fixed by forcing yrsatrisk with as.numeric prior to the mutate either. It currently means I have to output the data and edit it and re-input for it to work.

Any ideas?

why wont my boxes stack on top of each other as intended

I am working on a Tetris game and right now im trying to get the boxes to stack on top of each other. Like i said this is a Tetris game so i need to deactivate the shape once its done, so i push each shapes attributes to an array, then at the beginning of the down() function i iterate through the comp array, compare my current attributes to the attributes of the dead shapes within the array, if there is no match, the shape moves down. otherwise, the shape gets deactivated. This works, however the second shape overlaps the first shape by 50pxs but the rest line up perfect.

var svgNS = "http://www.w3.org/2000/svg";
var endR = 500;
var endL = 0;
var endT = 0;
var endB = 650;
var x = 0;
countO = 1;
count1 = 0;
count2 = 1000000;
var comp = [{
    id: 0,
    yPos: "650px"
}];

function createShape1() {
    var endR1 = 500;
    var endL1 = 0;
    var endT1 = 0;
    var endB1 = 650;
    var newEndR = endR1; //used to set boundaries right
    var endR10a = endR1 - 50; //used to set boundaries right
    var endR10b = endR1 + 50; //used to set boundaries right
    var newEndL = endL1; //used to set boundaries left
    var endL10a = endL1 - 50; //used to set boundaries left
    var endL10b = endL1 + 50; //used to set boundaries left
    var newEndB = endB1; //used to set boundaries bottom
    var endB10a = endB - 50; //used to set boundaries bottom
    var rotEndR = endR1 + 50; //used to set right boundaries for rotation
    var rotEndRa = endR1; //used to set right boundaries for rotation
    var rotEndL = endL1; //used to set left boundaries for rotation
    var rotEndT = endT1; //used to set top boundaries for rotation
    var rotEndB = endB1; //used to set bottom boundaries for rotation
    var elem = document.getElementById("container");
    var outer = document.createElementNS(svgNS, "svg"); //creates full transparent shape
    countO++;
    var leftG = document.getElementById("left");
    var rightG = document.getElementById("right");
    leftG.addEventListener("click", moveLeft); // click left half of screen to call moveLeft() function
    rightG.addEventListener("click", moveRight); // click right half of screen to call moveRight() function
    elem.append(outer);
    outer.id = "outer" + countO;
    outer.style.background = "grey";
    outer.style.height = "100px";
    outer.style.width = "150px";
    outer.style.left = "150px";
    outer.style.top = "0px";
    outer.style.position = "absolute";
    outer.style.transform = "rotate(0deg)"
    var t = setInterval(down, 1000); // calls down() function every second
    var xPos = parseInt(outer.style.left);
    var yPos = parseInt(outer.style.top);
    var w = parseInt(outer.style.width);
    var h = parseInt(outer.style.height);
    var ymath = yPos + h;   
    elem.addEventListener('contextmenu', rotateRight); // right click to call the rotateRight() function
    function down() {  // moves shape down by 50px
        for (let shape of comp) {
            var shapeX = parseInt(shape.xPos);
            var shapeW = parseInt(shape.width);
            var shapeY = parseInt(shape.yPos);
            var shapeH = parseInt(shape.h);
            if (ymath === shapeY) {
                clearInterval(t);
                elem.removeEventListener("contextmenu", rotateRight); // cancels rotation
                leftG.removeEventListener("click", moveLeft); // cancels moveLeft() function
                rightG.removeEventListener("click", moveRight); //cancels moveRight() function
                comp.push({
                    id: countO,
                    xPos: outer.style.left,
                    w: outer.style.width,
                    yPos: outer.style.top,
                    h: outer.style.height
                })
                randShape();
            }
        }    
        if (ymath < newEndB) {
            yPos += 50;
            ymath = yPos + h;
            outer.style.top = yPos + 'px';
            if (outer.style.transform === "rotate(90deg)") {
                newEndL = endL10a;
            }
            if (outer.style.transform === "rotate(180deg)") {
                newEndL = endL10a;
                newEndR = endR10a;
            }
            if (outer.style.transform === "rotate(270deg)") {
                newEndR = endR1;
                newEndB = endB10a;
            }
            if (outer.style.transform === "rotate(0deg)") {
                newEndB = endB1;
                newEndL = endL10b;
            }                    
        } else {
            clearInterval(t);
            elem.removeEventListener("contextmenu", rotateRight);// cancels rotation
            leftG.removeEventListener("click", moveLeft); // cancels moveLeft() function
            rightG.removeEventListener("click", moveRight);//cancels moveRight() function
        }
    }
    function rotateRight(e) { // rotates shape by 90 degrees clockwise
        e.preventDefault();
        var xmath = xPos + w;
        var xmath2 = xPos - w;
        var ymath = yPos + h;
        if (xmath < rotEndR && xmath > rotEndL) {
            if (ymath < rotEndB && yPos > rotEndT) {
                x += 90
                outer.style.transform = "rotate(" + x + "deg)";
                if (x === 270) {
                    x = -90;
                }
                outer.style.transformOrigin = "100px 50px";
                if (outer.style.transform === "rotate(90deg)") {
                    rotEndR = rotEndRa;
                }
                if (outer.style.transform === "rotate(180deg)") {
                    rotEndR = endR10b;
                }
                if (outer.style.transform === "rotate(270deg)") {
                    rotEndL = endL10b + 50;
                }
            }
        }
    }
    function moveLeft() { // shifts to the left by 50px
        var xmath = xPos;
        var ymath = yPos + h;
        if (xmath > newEndL - 50 && ymath < newEndB + 50) {
            xPos -= 50;
            xmath += w;
            outer.style.left = xPos + "px";
        }
    }
    function moveRight() { // shifts to the right by 50px
        var ymath = yPos + h;
        var xmath = xPos + w;
        if (xmath < newEndR && ymath < newEndB) {
            xPos += 50;
            outer.style.left = xPos + "px";
            ymath += h;
            xmath += w;
        }
    }
};



var shapes = [createShape1];
function randShape() {
    shapes[0]();
};

window.addEventListener("click", startGame, { once: true })

function startGame() {
    randShape()
}
.grid {
    background-image: repeating-linear-gradient(0deg, transparent, transparent 49px, #88F 49px, #88F 50px),
        repeating-linear-gradient(-90deg, transparent, transparent 49px, #88F 49px, #88F 50px);
    background-size: 50px 50px;
    top: 0px;
    height: 651px;
    position: absolute;
    width: 501px;
}

#left {
    top: 0px;
    width: 250px;
    height: 650px;
    position: absolute;
    background: transparent;
}

#right {
    left: 250px;
    top: 0px;
    width: 250px;
    height: 650px;
    position: absolute;
    background: transparent;
}
<!DOCTYPE html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tetris(test)</title>
  <link rel="stylesheet" href="styleSheets/main.css">
  <script src="js/jquery.js"></script>
  <script src="js/main.js"></script>
</head>

<body>
  <div id="container" style="height: 650px; width: 500px; background: black; position: relative">
    <div class="grid">
      <div id="left"></div>
      <div id="right"></div>
    </div>
  </div>

</body>

</html>