mardi 31 juillet 2018

Javascript .includes not working [duplicate]

Trying to get a little function going where when a client leaves a * or symbol in a certain table cell, the background color of that table cell will change.

This is all in a if is_page()) and I'm also using ACF.

I receive this error in Chrome Console:

Uncaught TypeError: cells.includes is not a function

Any assistance would be great!

My Code:

<div class="sires-table-wrap">
    <div class="grid-container">
        <div class="sires-table-title small-12 medium-12 large-12 cell">
            <h2>EAST LODDON SEMEN SIRES</h2>
        </div>
        <div class="sire-table small-12 medium-12 large-12 cell">
            <div class="grid-x grid-margin-x">

            <?php if ( have_rows( 'sire_tables' ) ) : ?>
                <?php while ( have_rows( 'sire_tables' ) ) : the_row(); ?>

                    <div class="sire-table-image small-12 medium-6 large-4 cell">
                        <?php $sire_image = get_sub_field( 'sire_image' ); ?>
                        <?php if ( $sire_image ) { ?>
                            <img src="<?php echo $sire_image['url']; ?>" alt="<?php echo $sire_image['alt']; ?>" />
                        <?php } ?>
                    </div>
                    <div class="sire-table-info small-12 medium-6 large-8 cell">
                        <?php the_sub_field( 'sire_info' ); ?>
                    </div>
                    <div class="sire-table-table small-12 medium-12 large-12 cell">
                         <?php $table = get_sub_field( 'sire_table' ); 
                         if ( $table ) { 
                             echo '<table id="sire-table">'; 
                                 if ( $table['header'] ) { 
                                     echo '<thead><tr>'; 
                                         echo ''; 
                                             foreach ( $table['header'] as $th ) { 
                                                 echo '<th>'; 
                                                     echo $th['c']; 
                                                 echo '</th>'; 
                                             } 
                                         echo '</tr>'; 
                                     echo '</thead>'; 
                                 } 

                                 echo '<tbody>'; 
                                     foreach ( $table['body'] as $tr ) { 
                                         echo '<tr>'; 
                                             foreach ( $tr as $td ) { 
                                                 echo '<td>'.$td['c'].'</td>'; 
                                             } 
                                         echo '</tr>'; 
                                     } 
                                 echo '</tbody>'; 
                             echo '</table>'; 
                         } ?> 
                     </div>

                      <script type="text/javascript">

                                var table = document.getElementById("sire-table"); 
                                var cells = table.getElementsByTagName("td");

                                if(cells.includes("*")) {

                                    cells.style.backgroundColor= "#63b2df";
                                }


                      </script>
                </div>
            </div>

                <?php endwhile; ?>
            <?php else : ?>
                <?php // no rows found ?>
            <?php endif; ?> 

    </div>
</div>

How to Nest If Statement Within For Loop When Scraping Div Class HTML

Below is a scraper that uses Beautiful Soup to scrape physician information off of this webpage. As you can see from the html code directly below, each physician has an individual profile on the webpage that displays the physician's name, clinic, profession, taxonomy, and city.

<div class="views-field views-field-title practitioner__name" ><a href="/practitioners/41824">Marilyn Adams</a></div>
              <div class="views-field views-field-field-pract-clinic practitioner__clinic" ><a href="/clinic/fortius-sport-health">Fortius Sport &amp; Health</a></div>
              <div class="views-field views-field-field-pract-profession practitioner__profession" >Physiotherapist</div>
              <div class="views-field views-field-taxonomy-vocabulary-5 practitioner__region" >Fraser River Delta</div>
              <div class="views-field views-field-city practitioner__city" ></div>

As you can see from the sample html code, the physician profiles occasionally have information missing. If this occurs, I would like the scraper to print 'N/A'. I need the scraper to print 'N/A' because I would eventually like to put each div class category (name, clinic, profession, etc.) into an array where the lengths of each column are exactly the same so I can properly export the data to a CSV file. I have tried writing an if statement nested within each for loop, but the code does not seem to be looping correctly as the "N/A" only shows up once for each div class section. Does anyone know how to properly nest an if statement with a for loop so I am getting the proper amount of "N/As" in each column? Thanks in advance!

import requests
import re
from bs4 import BeautifulSoup

page=requests.get('https://sportmedbc.com/practitioners')
soup=BeautifulSoup(page.text, 'html.parser')

#Find Doctor Info

for doctor in soup.find_all('div',attrs={'class':'views-field views-field-title practitioner__name'}):
    for a in doctor.find_all('a'):
        print(a.text)

for clinic_name in soup.find_all('div',attrs={'class':'views-field views-field-field-pract-clinic practitioner__clinic'}):
    for b in clinic_name.find_all('a'):
        if b==(''):
            print('N/A')

profession_links=soup.findAll('div',attrs={'class':'views-field views-field-field-pract-profession practitioner__profession'})
for profession in profession_links:
    if profession.text==(''):
        print('N/A')
    print(profession.text)

taxonomy_links=soup.findAll('div',attrs={'class':'views-field views-field-taxonomy-vocabulary-5 practitioner__region'})
for taxonomy in taxonomy_links:
    if taxonomy.text==(''):
        print('N/A')
    print(taxonomy.text)

city_links=soup.findAll('div',attrs={'class':'views-field views-field-taxonomy-vocabulary-5 practitioner__region'})
for city in city_links:
    if city.text==(''):
        print('N/A')
    print(city.text)

How do I change color of interactions based on interaction value using an ifelse() statement in an plotweb bipartite?

Hi I am having trouble trying to get ifelse statements to work in a normal plotweb used to color interaction based on the total quantity of interaction of each cell in the matrix. I had the same problem with the high bar colors, but since there were only a few and a straight vector, it was easy to manually code.

Here is the code I am using, I want to color interactions greater than 15 as dark turquoise and keep the rest as default grey (grey80).

I have tried many different statements but I cant seem how to figure out what to put in the [,] to signify for the function to go through every individual cell and apply the statement instead of summing them, elem,elem also doesn't seem to work. Attached is a picture of the function's output currently

plotweb(LadyNet, 
        abuns.type='additional',
        arrow="up.center",
        text.rot=90,
        col.low=c("olivedrab3"),
        col.interaction =(ifelse(LadyNet[,] < 15,'grey80','darkturquoise')), 
        col.high = c("grey10","#FF0000","grey10","#FF0000","grey10","#FF0000","grey10","grey10","grey10"),
        high.lab.dis = 0,
        ybig=1.2,
        y.width.high = .06,
        high.spacing = 0.011, 
        y.lim = c(-1,2))

Picture of Output

Adding numbers together as a result of an if statement

So I'm looking to add numbers to a string as a result of an if statement. For example;

a = 2;
b = 1;
  if($a == 2) {
     $total + 1;
    }
     if($b == 1) {
     $total + 1;
    }
    echo $total;

Obviously, these aren't my if statements but if they were to work then I would like $total to = 2? This seems sort of simple but I can't work it out?

(PHP) Can you use the outcome of an if statement in a calculation?

So I have two different prices per product in my database table. One is the "sale_price" and the other is the usual "price" of the product. I have made it so that if the "sale" column is set to "yes" in the database, then it will display the sale price of the product and vice-versa.

Here is my code that calculates the total price of the product by multiplying the quantity by the price of the product. You'll see that if $cart[sale'] is equal to 'yes' then it will create a variable called $tot: this will multiply $cart['sale_price'] of the product by $cart['quantity] else it will multiply the $cart['price'] by $cart['quantity]. This will display the total price PER PRODUCT...

<?php if($cartprod['salec'] == "yes"){

    $tot = number_format($cartprod['list_price'] * $cartprod['quantity'],2);

}else{

    $tot = number_format($cartprod['price'] *  $cartprod['quantity'],2);

}?> 

... I want to display the SUM of all of the totals in the cart but I can't seem to achieve it. Can anybody lead me in the right direction?

Reclassifying an "Add Field" with If/Else statement based on multiple fields

Like a lot of people here I was tasked with a project many have given up on because I took one Python course during my college term.

Anyways, my delima does not seem so difficult, I am just too new to Python to figure it out myself. Here goes:

I have a table of Traffic Count data with: Street Location | Direction | Dir__NB_or | Dir_SB_or and I was attempting to write a reclassification into the new field of Count.

What I am looking for is a script to say: "if direction is N or E, insert Dir__NB_or into field Count"

Is what I have, (probably horrific) but I would appreciate any help you can provide!

Alex

Reclass (Dir__NB_or , Dir_SB_or, Direction):

    if (Direction == "N"):
           return Dir__NB_or
    elif (Direction == "S"):
            return Dir_SB_or
    elif (Direction == "E"):
            return Dir__NB_or
    elif (Direction == "W"):
            return Dir_SB_or
    else:
            return "0000"

Count =

Reclass ( !Dir__NB_or! , !Dir_SB_or!, !Direction! )

VBA IF formula not working?

I have some VBA code that is working between a few workbooks

I am running into a problem where I cannot get this IF formula to apply. I am not sure how I am getting Subscript out of range error.

I have tried to use .Range("O"), .Range("O:O"), .Range("O", i) but all give the same 1004 error.

Am I using .Range() wrong? I was able to use range on a different formula so not sure why this wont work.

Sub if_after()

    Dim co_detail As Workbook
    Set co_detail = ThisWorkbook

        With co_detail.Sheets("Detail")

            For i = 2 To 100
                .Range("02").Formula = "=IF(L" & i & "=N" & i & ",'good','update')"
            Next i

        End With

End Sub

R: subsetting data to create three new subsets- using subset(), function or if/then conditional

I have been trying to subset data in a more nuanced way, to avoid excessive verbosity and redundancies. I find that I end up typing complicated conditions for subsetting, a method that is not feasible if I want to create multiple subsets of a dataframe.

Data:

> print(assm)
Speaker V1 POA V2
1     JF01  u  tt  U
2     JF01  o   r  a
3     JF01  o   t  a
4     JF01  a   r  u
5     JF01  e   l  i
6     JF01  a   j  o
7     JF01  e   s  o
8     JF01  u   l  i
9     JF01  a   j  i
10    JF01  i   y  a
11    JF01  o   g  i
12    JF01  u   m  O
13    JF01  u   l  E
14    JF01  a   t  o
15    JF01  o   r  u
16    JF01  a   l  e
17    JF01  u  tt  o
18    JF01  o   r  a
19    JF01  o   t  a
20    JF01  a   r  u
21    JF01  e   l  i
22    JF01  i   y  O
23    JF01  o   r  i
24    JF01  i   l  E
25    JF01  u   k  o
26    JF01  o   n  e
27    JF01  a   t  o
28    JF01  o   r  u
29    JF01  o   r  a
30    JF01  u   m  u
31    JF01  u   l  a
32    JF01  a   t  u
33    JF01  u  tt  o
34    JF01  o   r  a
35    JF01  o   t  a
36    JF01  a   h  e
37    JF01  u   r  e
38    JF01  o   l  i
39    JF01  i   b  o
40    JF01  o   l  e
41    JF01  e   j  u
42    JF01  a   l  e
43    JF01  u  tt  i
44    JF01  o   t  a
45    JF01  a   r  u
46    JF01  e   l  i
47    JF01  i   y  U
48    JF01  o   r  i
49    JF01  i   l  e
50    JF01  u   k  o 

I used subset() and data[] to create 3 subsets with the following conditions:

assm <- subset(assm, V1==“a"| V1=="e"| V1=="E"| V1=="i"| V1=="o"| V1=="O"| V1=="u"| V1=="U", select = Speaker:V2)
assm <- subset(assm, V2==“a”| V2==“e”| V2=="E"| V2=="i"| V2=="o"| V2=="O"| V2=="u"| V2=="U", select = Speaker:V2)

Is there a more efficient way(using regex for subsetting, for example) to avoid all the hard-coding(like using a variable)? The subsetting condition for V1 and V2 are identical, but I ended up typing things out two times.

Using very rudimentary R, this is some more subsetting I did:

assm_h <- subset(assm, (V1=="o" & V2=="i")|
                     (V1=="e" & V2=="i")|
                     (V1=="u" & V2=="i")|
                     (V1=="e" & V2=="u")|
                     (V1=="o" & V2=="u")|
                     (V1=="u" & V2=="u"))

assm_nh <- subset(assm, (V1=="i" & V2=="O")|
                      (V1=="i" & V2=="E")|
                      (V1=="i" & V2=="U")|
                      (V1=="u" & V2=="O")|
                      (V1=="u" & V2=="E")|
                      (V1==“u" & V2=="U"))

I need one more subset(assm_neu), one that contains rows that do not match the conditions that subsets assm_h and assm_nh satisfy(i.e. the rest of the data), a task that requires even more painstaking coding. My method requires painstaking typing and multiple steps.

**is there a way to make this task more efficient, so that the subsetting returns not just what is asked, but also returns a subset of the data that does not satisfy the conditions? I have read multiple posts about functions and conditionals, but none that would help me extract and create more than one dataset with a single command. **

Thanks in advance.

Function to return if is first or second half of the month

I'm learning SQL, and I'm stuck in a issue... is there a way to create a function that return if is first or second half of the month, given a specific date. For example, if date is 01/07/2018 then 0 cause is first half of the month, or if date is 30/07/2018 then 1 cause is second half of the month

Hope I was clear enough ^^'

R for loop with if else on multiple data frames

Greetings and thanks in advance for all help I have many data frame that resemble the ones below

df1

   name info
1  john    A
2   jim    B
3   tom    B
4 bill     B

dframe

  name other
1  sam   pro
2  dad   mo1
3  mom  Bxxx

frame3

   name otherinfo
1   jus         A
2    do         7
3 r pro         B
4   sir         B
5  real        na
6  pete       yes

OLFrame

   name information
1  ally          x1
2   mom          B9
3 r pro         s3B
4   tom         Bd0
5 kelly          ot
6  jojo         who
7    na          11

I would like to :

  1. take each name from the "name" collumn of dataframe "OLFrame" and look into the "name"collum of "df1"to see if the name exists
  2. create collum vector with named "df1" consisting of "1" if name from "OLFrame" exist in "df1" if not "0"
  3. reapeat the steps 1 and 2 but using "dframe" and "frame3"
  4. create a new data frame called "newOLFrame" consisting of "OLFrame" and and new columns named "df1", "dframe" and "frame3"

The desired result should look like

newOLFrame

   name information df1 dframe frame3
1  ally          x1   0      0      0
2   mom          B9   0      1      0
3 r pro         s3B   0      0      1
4   tom         Bd0   1      0      0
5 kelly          ot   0      0      0
6  jojo         who   0      0      0
7    na          11   0      0      0

I can do one at a time (below) but I have over a hundred files to look through

newOLFrame<-OLFrame
newOLFrame[,"pro1"]<-ifelse(newOLFrame$name %in% df12$name, 1, 0)

Please help. Thanks again

Python- If statements with random numbers not working

I'm very new to programming and I'm trying to write a program in python 3.6 that generates a random number as an "answer" and then the computer has to guess that answer for x number of questions. To keep track of how many questions the computer guesses right, I created a variable called 'right' and if the computer's answer equals the guess, then add one to that variable. However, it does it everytime even if it's wrong. Sorry if this seems stupid, but thank you for your help

import random
def total(x, t):
        for i in range(t):
                cor = 0
                gue = 0
                n = 0
                right = 0
                def ans():
                         cor = random.randint(1,4)
                         print(cor, 'answer')
                def guess():
                         gue = random.randint(1,4)
                         print(gue, 'guess')
                while n <= x:
                         ans()
                         guess()
                         if cor == gue:
                                 right += 1
                         n += 1 
                print(right, n)

Avoding conditionals in C

I'm tired of writing procedural programming in C. I hate to add conditionals and flags, my whole code is if else and flags. I would like to bring OOPs in C, and some good way to structure code. Any good pointers please help.

How to iterate through pandas columns and replace cells with information with the next row down

I am trying to loop through a pandas dataframe column and based on if the next row down does not include "Property Address" add the information from that next row down to the previous row. For example, if I have a column that goes from top to bottom ["Property Address", "Alternate Address", "Property Address"] I would like to take the information from "Alternate Address" and add that information to the column above it ("Property Address"). I have already double checked that there are no trailing or leading spaces and that everything is lower case so that all comparisons will work. However, I still get this error:

if i == "Property Address" and df.loc[i+1, :] != "Property Address":

TypeError: must be str, not int

Does anyone have ideas on what I can do so that this will work? I am new to Python, and I am really lost. Please let me know if there is any more information that I should provide to make answering this question easier. Thanks

Here is my code so far:

import pandas as pd
import time

df = pd.read_excel('BRH.xls') # Reads the Excel File and creates a 
dataframe 
# Column Headers
df = df[['street', 'state', 'zip', 'Address Type', 'mStreet', 'mState', 'mZip']]

propertyAddress = "Property Address" # iterates thru column and replaces 
the current row with info from next row down

for i in df['Address Type']:
  if i == "Property Address" and df.loc[i+1, :] != "Property Address":
      df['mStreet'] == df.loc[i + 1, 'street']
      df['mState'] == df.loc[i + 1, 'state']
      df['mZip'] = df.loc[i + 1, 'zip']

df.to_excel('BRHOut.xls')
print('operation complete in:', time.process_time(), 'ms')

Excel - Copy data from one cell to another if check mark using button

I have an excel workbook. In this workbook, I have 5 worksheets.

1 = List A

2 = List B

3 = List C

4 = List D

5 = Order form

My lists worksheets will be setup like this. Col A = Checkbox. Col B = Number. Col C = Description.

My end goal is to have a check box next to each item in each list. From here, I will go through each list and select the items from the list I want. Once I have chosen all of my items, I go to "Order Form" and on this worksheet is a button that I click. When I click this button, it will copy the data from Col B ONLY if there is a check mark in Col A in all the worksheets.

So, if I check A2, A4, A10, & A15 on List A and check A3, A9, & A22 on List B, and A35 on List C, when I click the button on "Order Form", the data from 'List A'!B2, 'List A'!B4, 'List A'!B10, 'List A'!B15, 'List B'!B3, 'List B'!B9, 'List B'!B22, and 'List C'!B35 get copied to 'Order Form'!E22:E30

This will need to be dynamic, since I may only check 2 items, or I may check 30.

My check in and out code using tkinter is not outputting the expected result

This code is expected to tell the user red or green and change the users label to red or green depending on whether they are check or out. To check in or out you type 1 - 4 (depending on the user) in the e entry widget. but this code just keeps all of the names red and just outputs "red" when it should be alternating.

import time
import csv
import tkinter
Users = ["1","2","3","4"]
UserDecode = ["Ben","Vicki","Steve","Sean"]
UserInOut = ["red","red","red","red"]
def login():
        Users = ["1","2","3","4"]
        UserDecode = ["Ben","Vicki","Steve","Sean"]
        UserInOut = ["red","red","red","red"]
        global e
        w = tkinter.Tk()
        root=tkinter.Frame(w)
        root.pack()
        root.destroy()
        root=tkinter.Frame(w)
        root.pack()
        for i in UserDecode:
                Num=UserDecode.index(i)
                tkinter.Label(root, text=i, fg=UserInOut[Num]).pack()
        e = tkinter.Entry(root, text="ID NUM")
        e.bind("<Return>", CheckIt)
        e.pack()
        w.mainloop()
def CheckIt(event):
        global e, Users, UserDecode, UserInOut
        In= e.get()
        e.delete(0, 'end')
        if In in Users:
                UserCheck = int(In)
                print("Found User: ", UserDecode[UserCheck - 1])
                if UserInOut[UserCheck - 1] == "red":
                        UserInOut[UserCheck - 1] == "green"
                        print(UserInOut[UserCheck - 1])
                elif UserInOut[UserCheck - 1] == "green":
                        UserInOut[UserCheck - 1] = "red"
                        print(UserInOut[UserCheck - 1])
                        print("                 ")
                        login()
                else:
                        print("no user found")
                        login()
login()

Successive conditions to subtract amount in one col from other cols

I have a df as follows. I would like to subtract col d from the other columns using the following rules:

  • No result can be negative
  • If d can be divided equally and subtracted across from a:c without generating a negative, then subtract an equal amount across cols
  • else, if d can be divided and subtracted equally from b:c and the remainder from a without generating a negative, then subtract from cols
  • else, if d can be subtracted from c, the remainder from b, and the subsequent remainder from a without generating a negative, then subtract from cols
  • else, if d can be subtracted from from b and the remainder from a without generating a negative, then subtract from cols
  • else, subtract from a

df:

structure(list(a = c(0, 6.22, 1.2, 0.22, 0.24), b = c(8.88, 1.08, 
0.25, 0, 0), c = c(13.76, 0, 19.61, 0, 0), d = c(-2.64, -0.3, 
-11.06, -0.22, -0.24)), .Names = c("a", "b", "c", "d"), row.names = c(NA, 
-5L), class = c("tbl_df", "tbl", "data.frame"), spec = structure(list(
    cols = structure(list(a = structure(list(), class = c("collector_double", 
    "collector")), b = structure(list(), class = c("collector_double", 
    "collector")), c = structure(list(), class = c("collector_double", 
    "collector")), d = structure(list(), class = c("collector_double", 
    "collector"))), .Names = c("a", "b", "c", "d")), default = structure(list(), class = c("collector_guess", 
    "collector"))), .Names = c("cols", "default"), class = "col_spec"))

starting table:

a     b     c      d
0     8.88  13.76  -2.64
6.22  1.08  0      -0.3
1.2   0.25  19.61  -11.06
0.22  0     0      -0.22
0.24  0     0      -0.24

desired result:

a     b     c      d
0     7.56  12.44  -2.64
6.22  0.78  0      -0.3
1.2   0.25  8.55   -11.06
0     0     0      -0.22
0     0     0      -0.24

Use the previous value if condition is met in R while using ifelse()

I came across an issue while converting one of if.. else condition to ifelse () in R to make the process faster. In this question, I have to use the value from the previous row if the condition is met. I was not able to replicate the same results from my code Below is the if.. else statement and its converted code.

for (i in 1:nrow(newdata)){

if ((newdata$first == 1)){
  newdata[, decvar][i] = groups + 1 - ceiling(round((newdata$cum/total) * groups, 4))
} #calculate decile; if var = 0, decile = 0
else if (newdata$first == 0){
  newdata[, decvar][i] = newdata[, decvar][i-1]
}

}

Using ifelse():

brv_trx1$decvar <- ifelse(((brv_trx1$first == 1)),(11 - ceiling(round((brv_trx1$cum/total) * 10, 4))), ifelse(((brv_trx1$first == 0)), lag(brv_trx1$decvar) ,NA))

The sample output will look something like this :

variable First Decvar

45 1 10

42 1 10

31 1 9

30 0 9

30 0 9

29 0 8

29 0 8

28 0 8

21 1 7

I was getting some output as 0, which I have no clue where it came from

V-lookup style referencing in R without merging

I have two tables. One with information on commissions payable for selling items on different websites. The other holding items which I would like to create a sale price for.

Please see both tables:

Channel <- c("DIRECT", "EBAY", "AMAZON")
Commission_percentage <- c(.1, .5, .4)
Min_commission <- c(0, 0, 2)
Processing <- c(0.05, 0.05, 0.03)

Commission_table <- as.data.frame(cbind(Channel, Commission_percentage, 
Min_commission, Processing))

The commissions table above shows commission percentages for each website, but shows that AMAZON will charge £2 minimum for each sale. It also shows another % charge for payment processing. The table below shows 5 items which are to be sold. It shows the website and also the amount paid for the item previously (cost).

Item <- c("A1", "A2", "A3", "A4", "A5")
Cost <- c(10, 14, 18.85, 20, 5)    
Channel <- c("DIRECT", "EBAY", "AMAZON", "AMAZON", "AMAZON")

Price_table <- as.data.frame(cbind(Item, Cost, Channel))

I need to create a column for the Price_table which shows the "break-even" price for each item. I need to find the applicable commission charges depending on the channel on which the item is being sold, and for the Amazon items, I need to make sure that the minimum commission of £2 is charged if the standard commission percentage is calculated to be less than this.

To clarify, the break-even price needs to be; Cost + max(commission_percentage * cost, min_commission) + (processing*(cost + max(commission_percentage * cost, min_commission)))

Ideally this needs to be memory efficient as the database is very, very large. Hence why I haven't just gone for a merge function and removed the extra columns once the price is calculated.

Many thanks, Dan

Ext Js 6.01 XTemplate if id in () condition

Is there anyway to use if id in () in the tpl template?

For example I have a for="records", which has an id field in it, and I have a data IDs defined as '1,2,3', I want to use something like to run different html.

Thanks a lot~!

Suggestion for cheking old value against new value and commenting

I am trying to compare a value in a table against a new value given in a form then giving a response of what was changed but it's giving the value if true or not

$var1 (existing value in table pulled from a search to display currently value in the form) $var2 (new value provided in form) $comment1 (the response)

this is what it looks like now:

if ($data[var1]!='$_POST[var2]')
 {
$comment1="$data[var1] changed to $_POST[$var2]";  (this will be scrubbed but I have the simple form here)
 }
else { $comment1="";}

I have tried: if($data[var1]<>'$_POST[var2]')

I have also tried adding $old_var1=$data[var1];
Then changing to if($old_var1]!='$_POST[var2]') and if($old_var1]<>'$_POST[var2]')

But the comment still shows if they are the same or not, I only want the comment to apply if they are not the same.

Where / how to determine whether chat message was sent or received (android)

Android chat app. I'm using a temporary ArrayList on the client to make sure displaying the chat bubbles work as expected. Where and how do I determine if a message was sent or received?

ChatConversationFragment:

   messageArrayList.add(new ChatConversationMessage("Hello"));
    messageArrayList.add(new ChatConversationMessage("Yeah"));
    messageArrayList.add(new ChatConversationMessage("Yeah", R.drawable.redhead_1)); 
//this last one is received because it has two inputs

ChatConversationMesssage:

/**
 * The reason we have TWO of these methods with the same name is because sent
 * messages don't have an image. We need to have a separate method for that.
 **/
public ChatConversationMessage(String sentTextMessage) {
    mSentTextMessage = sentTextMessage;
}

public ChatConversationMessage(String receivedTextMessage, int imageResourceId) {
    mReceivedTextMessage = receivedTextMessage;
    mImageResourceId = imageResourceId;
}

ConversationMessageAdapter:

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View listItemView = convertView;
    Holder holder;
    ChatConversationMessage currentMessage = getItem(position);

    if(listItemView == null) {
        holder = new Holder();

        if(currentMessage){
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.chat_conversation_txt_sent, parent, false);
        }
    }


    TextView sentText = listItemView.findViewById(R.id.textview_chat_message_sent);
    sentText.setText(currentMessage.getSentTextMessage());

    TextView receivedText = listItemView.findViewById(R.id.textview_chat_message_received);
    receivedText.setText(currentMessage.getReceivedTextMessage());

    return listItemView;
}

So I was trying to put it in an if-statement in this last class (the adapter). But I don't know what method to make and where to place it so I can return a Boolean or something to make it display different chat bubbles based on if the message was sent or received.

Why is an if statement working but not a switch statement

Title is terrible, but I wasn't too sure what to put.

I'm trying to create Switch Statement using the char index of a string and an Enum using this wrapper to get the value of the selected enum from a Description, it pretty much allows you to store a string to an enum value.

Here is my if statement

if (msgComingFromFoo[1] == Convert.ToChar(Message.Code.FOO_TRIGGER_SIGNAL.EnumDescriptionToString()))
{
    //foo
}

and here is my Switch statement

switch (msgComingFromFoo[1])
{
    case Convert.ToChar(Message.Code.FOO_TRIGGER_SIGNAL.EnumDescriptionToString()):
        break;
}

Why is it accepting the if statement and not the switch statement?

I tried converting it to a char since I'm selected an index from a string, but unfortunately i didn't work.

Error during sorting two columns in a dataframe

So I am trying to sort two columns in my two dataframes (rdw_n and rdw_p) and then trying to append them, the columns are ACCT_NUM and acct_purged_dt. The issue is, my input file contains acct_purged dt, but all acct_purged dt are blank, so When I try to sort them using below code .

rdw_n> rdw_n[with(rdw_n, order(rdw_n$ACCT_NUM, rdw_n$acct_purged_dt)), ]

This throws an error as "Error in order(rdw_n$ACCT_NUM, rdw_n$acct_purged_dt) : argument 2 is not a vector", So I can assume that this issue is occuring due to all null values in acct_purged_dt.

So I tried another approach where I an checking at the start if the acct_purged_dt is not null then do the above operation else append the dataframes.This is the code I am using

ifelse(!is.na(rdw_n$acct_purged_dt),rdw_n<- rdw_n[with(rdw_n, order(rdw_n$ACCT_NUM, rdw_n$acct_purged_dt)), ],rdw_pn <-rbind(rdw_n,rdw_p))

still the issue comes as : In is.na(rdw_n$acct_purged_dt) : is.na() applied to non-(list or vector) of type 'NULL'

What can be the resolution for this ?

conditional statements through a loop R

  unique_ref priority_201801 balance_201801 action_201801 priority_201802 balance_201802 action_201802 priority_201803 balance_201803 action_201803
1          1               3             30   text,letter               1             60        letter               2             30          text
2          2               2            -20         visit               1            -40          text               2            -40          call
3          3               3             35        letter               1             35          call               3            -50          text
4          4               0           -100          call               2              0         visit               2            100          call
  priority_201804 balance_201804 action_201804
1              99              0          text
2               0            -20         visit
3               0            -50        letter
4               0           -100          text

Above is a sample of my dataset. I want to search through each action looking for the first instance of the action "text", this will then be Week0, I then want to line up the priority's and balances of the next weeks, as Week1, Week2 etc.

Desirable output:

  unique_ref week0_priority week0_balance week0_action week1_priority week1_balance week1_action week2_priority week2_balance week2_action
1          1              3            30         text              1            60       letter              2            30         text
2          2              1           -40         text              2           -40         call              0           -20        visit
3          3              3           -50         text              0           -40       letter        No Data       No Data      No Data
4          4              0          -100         text        No Data       No Data      No Data        No Data       No Data      No Data
  week3_priority week3_balance week3_action
1             99             0         text
2        No Data       No Data      No Data
3        No Data       No Data      No Data
4        No Data       No Data      No Data

Reproducible example of data:

unique_ref=c(1,2,3,4)
priority_201801=c('3','2','3','0')
balance_201801=c('30','-20','35','-100')
action_201801=c('text,letter','visit','letter','call')
priority_201802=c('1','1','1','2')
balance_201802=c('60','-40','35','0')
action_201802=c('letter','text', 'call', 'visit')
priority_201803=c('2','2','3','2')
balance_201803=c('30','-40','-50','100')
action_201803=c('text','call','text','call')
priority_201804=c('99','0','0','0')
balance_201804=c('0','-20','-50','-100')
action_201804=c('text','visit','letter','text')

df3=as.data.frame(cbind(unique_ref,priority_201801,balance_201801,action_201801,priority_201802,balance_201802,action_201802,priority_201803,
                        balance_201803,action_201803,priority_201804,balance_201804,action_201804))

Javascript, form values

I have some variables in Javascript if statement which capture the values in a form. A check box and a couple of drop downs. Is there any way I can make the variables a bit dynamic? For example, if the user decides to select a different option then the value updates? At the moment it only captures what is currently selected on page load.

if(document.URL.indexOf("page") >= 0 && document.cookie.search('myCookie') < 0){ 


var productvalue = document.querySelector('input[name=product]:checked').value;

var amount = document.getElementById("frm-amount");
var amountValue = amount.options[amount.selectedIndex].value;

var term = document.getElementById("frm-term");
var termValue = term.options[term.selectedIndex].value;

Same formula, different results?

You are my last chance to find a solution : I have 2 cells (C6 & D6 ; 08:00:00 & 12:26:00) and a simple formula ( =D6-C6 ). This one is working properly but I have another one ( =IF(OR(C6="JF";C6="WE");"00:00";D6-C6) ) wich is quit simple but as you can see on this photo :

To help understand

The result of this second formula is quit not the same as the first one...which is weird as they have the same end ( D6-C6 )...I need either an explaination of why and a solution tu have the 4:26 end on the second formula.

I've tried this one : ( =SI(OU(C6<>"JF";C6<>"WE");D6-C6;"00:00:00") ) but the result is the same ( 0,184722222 ).

lundi 30 juillet 2018

JavaScript weird issue with else if statement

I'm making a game of Guess the Number, and I want to test if a variable guess is greater than a variable difficulty. difficulty has been taken from my HTML page, and it is not comparing correctly with guess.

//Initialize variables for player guess, guess counter and previous guesses
var guess = 0;
var guessCount = 0;
var previousGuesses = [];

function startGame() {
        
        //Calculate difficulty
        var difficulty = document.getElementById("difficulty").value;
        
        //Calculate secret number
        var secretNumber = Math.floor((Math.random() * difficulty) + 1);
        
        //Repeats while player has not guessed the secret number
        while (guess != secretNumber) {
                
                //Checks for Cancel button pressed
                guess = prompt("Enter your guess: ");
                if (guess == null) {
                        return;
                } 
                
                //Checks for empty string/no input
                else if (guess == "") {
                        alert("Please enter a number");
                }
                
                //Checks if previously guessed
                else if (previousGuesses.includes(guess)) {
                        alert("You have guessed this number before. Please try a different number.");
                }
                
                else if (guess < 1) {
                        alert("Please enter a number between 1-" + difficulty);
                }
                
                //Checks if guess is higher than secretNumber
                else if (guess > secretNumber) {
                        alert("Your guess is too high");
                        //Increments guess counter
                        guessCount++;
                        //Adds the previous guess to previousGuesses
                        previousGuesses.push(guess);
                } 
                
                //Checks if guess is lower than secretNumber
                else if (guess < secretNumber) {
                        alert("Your guess is too low");
                        //Increments guess counter
                        guessCount++;
                        //Adds the previous guess to previousGuesses
                        previousGuesses.push(guess);
                }
                
                //Checks for correct guess
                else if (guess == secretNumber) {
                        //Increments guess counter
                        guessCount++;
                        
                        //Checks for correct grammar - guesses or guess
                        if (guessCount > 1) {
                                alert("Congratulations, you guessed the correct number in " + guessCount + " guesses!");
                        }
                        else {
                                alert("Congratulations, you guessed the correct number in " + guessCount + " guess!");
                        }
                }
                
        }
        //Resets variables to play again
        guess = 0;
        guessCount = 0;
        previousGuesses = [];
}
<h1>Guess the Number</h1>

<button onclick="startGame()">Start the Game</button>

<h2>Difficulty</h2>

<select id="difficulty">
  <option value="10">Beginner</option>
  <option value="50">Intermediate</option>
  <option value="100">Hard</option>
</select>

This code works, but I want something to occur. When your guess is greater than difficulty, I want to print "Please enter a number between 1-" + difficulty. However, when I change this code:

else if (guess < 1) {
    alert("Please enter a number between 1-" + difficulty);
}

into this:

else if (guess < 1 || guess > difficulty) {...}

then what happens is that EVERY guess except 1, difficulty and anything more than difficulty is alerted by Please enter a number.

How should I fix this?

VBA Trying to overwrite matching records and move non-matching records from ws1 to ws2

It has been years since I've coded and I've tried many variations of looping. I've also spent many hours on StackOverflow, I am very greatful for the work you all put in.

I have 2 sheets, 1 workbook. Sheet1=DD and has thousands more records than sheet 2 (LC which has updated record info). All of the records from DD need to be moved to LC. However, there are many records that match from DD to LC, and the entire row from DD needs to replace the LC row. If the value in DD does not match an existing record in LC then the entire row needs to be moved to the end of LC.

Dim wsDD As Worksheet, wsLC As Worksheet 'shortens the names for each worksheet (ws) and records range (rng)
Dim rngDD As Range, rngLC As Range, colRng As Range
Dim lastRowDD As Long, lastRowLC As Long
Dim lastUIDused As Long 'holds the value of the last LC Unique ID when UniqueID col sorted by small-large
Dim ohnDD As Range, ohnLC As Range 'Old Host Number in DD or LC

Set wsDD = ThisWorkbook.Sheets("DataDump")
Set wsLC = ThisWorkbook.Sheets("LifeCycleAllRecs")
Set rngDD = wsDD.Range("A2", wsDD.Range("A" & wsDD.Cells(Rows.Count, 1).End(xlUp).Row)) 'finds & stores range of all used rows and columns in DataDump
Set rngLC = wsLC.Range("A2", wsLC.Range("A" & wsLC.Cells(Rows.Count, 1).End(xlUp).Row)) 'finds & stores range of all used rows and columns in LifeCycle

lastRowDD = wsDD.Range("A" & Rows.Count).End(xlUp).Row                              'stores last row # in DataDump
lastRowLC = wsLC.Range("A" & Rows.Count).End(xlUp).Row                              'stores last row # in LifeCycle tab

----------------- example 1-------------------
Set ohnDD = wsDD.Range("A2")
Set ohnLC = wsLC.Range("A2")
wsDD.Activate
    Range("A2").Activate
        Do Until ohnDD > lastRowDD
            Set ohnLC = wsLC.Range("A2")
                                MsgBox "ohndd " & ohnDD & "    lastrowdd " & lastRowDD
                If ohnDD = ohnLC Then
                    wsDD.Range("A" & ohnDD.Row & ":U" & ohnDD.Row).Cut wsLC.Range("H" & ohnLC.Row)
                    wsLC.Activate
                    ohnDD = ohnDD + 1
                Else
                        For Each ohnLC In wsLC.Range("X2:X" & lastRowLC)
                            wsDD.Range("A" & ohnDD.Row & ":U" & ohnDD.Row).Cut wsLC.Range("H" & lastlcrow + 1)
                            lastRowLC = lastRowLC + 1
                            ohnDD = ohnDD + 1
                        Loop
                End If

----------------- example 2-------------------
'looks only for non-matching DD records
Set ohnDD = wsDD.Range("A2")
Set ohnLC = wsLC.Range("A2")
wsDD.Activate
Range("A2").Activate
    For Each ohnDD In wsDD.Range("Q2:Q" & lastRowDD)
        For Each ohnLC In wsLC.Range("X2:X" & lastRowLC)
            If ohnDD.Value <> ohnLC.Value Then
            Else
            End If
        Next ohnLC
    Next ohnDD

' cuts each matching DD row and pastes to LC
Set ohnDD = wsDD.Range("A2")
Set ohnLC = wsLC.Range("A2")
wsDD.Activate
Range("A2").Activate

    For Each ohnDD In wsDD.Range("Q2:Q" & lastRowDD)
        For Each ohnLC In wsLC.Range("X2:X" & lastRowLC)
            If ohnDD.Value = ohnLC.Value Then
                wsDD.Range("A" & ohnDD.Row & ":U" & ohnDD.Row).Cut wsLC.Range("H" & ohnLC.Row)
            Else
            End If
        Next ohnLC
    Next ohnDD  'only non-matching records should remain in DD

----------------- example 3 oldest attempt-------------------

'match returns a row number
'for each cell in DD column Q, match with a cell in LC col X and return row number
wsDD.Activate
    For Each ohnDD In wsDD.Range("Q2:Q" & lastRowDD) '5114 recs but only non blank
        If ohnDD.Value > 0 Then 'ONLY IF NOT BLANK
            For Each ohnLC In wsLC.Range("X2:X" & lastRowLC)
                If ohnDD.Value = ohnLC.Value Then
                wsDD.Range("A" & ohnDD.Row & ":U" & ohnDD.Row).Cut wsLC.Range("H" & ohnLC.Row)
                Else
                End If
            Next ohnLC
        Else
        End If
    Next ohnDD

This is has cost me days of getting nothing else done! I'm finally asking for help. I appreciate all help!

Input Value Out of Range

Wonder with the request. "If the score is out of Range, print an Error". How to get the condition out of range if the following variables are >= 0.9(A) and < 0.6(F).

Write a program to prompt for a score between 0.0 
and 1.0. If the score is out of range, print an 
error. If the score is between 0.0 and 1.0, print 
a grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
If the user enters a value out of range, print a 
suitable error message and exit. For the test, 
enter a score of 0.85.

Java evaluate if multiple boolean parameters are equal

I was implementing an N-nary tree (here N=4) and want to put in a logic to do something if the boolean property val of all four children of a node are equal, I tried with:

if (childOne.val == childTwo.val == childThree.val == childFour.val){
    doSomthing();
}

however this doesn't work for my test cases, so I have to change it to a more explicit and verbose:

if (childOne.val == childTwo.val && childTwo.val == childThree.val && childThree.val == childFour.val){
    doSomthing();
}

and this one works. However I cannot make sense why the first evaluation doesn't give me the correct answer.

Subtract one column from others based on successive conditions

I have a df as follows. I would like to subtract col y from the other columns using the following rules:

  • No result can be negative
  • If y can be divided equally and subtracted across from a:c without generating a negative, then subtract an equal amount across cols
  • else, if y can be divided and subtracted equally from b:c and the remainder from a without generating a negative, then subtract from cols
  • else, if y can be subtracted from c, the remainder from b, and the subsequent remainder from a without generating a negative, then subtract from cols
  • else, if y can be subtracted from from b and the remainder from a without generating a negative, then subtract from cols
  • else, subtract from a

df:

structure(list(a = c(0, 6.22, 1.2, 0.22, 0.24), b = c(8.88, 1.08, 
0.25, 0, 0), c = c(13.76, 0, 19.61, 0, 0), d = c(-2.64, -0.3, 
-11.06, -0.22, -0.24)), .Names = c("a", "b", "c", "d"), row.names = c(NA, 
-5L), class = c("tbl_df", "tbl", "data.frame"), spec = structure(list(
    cols = structure(list(a = structure(list(), class = c("collector_double", 
    "collector")), b = structure(list(), class = c("collector_double", 
    "collector")), c = structure(list(), class = c("collector_double", 
    "collector")), d = structure(list(), class = c("collector_double", 
    "collector"))), .Names = c("a", "b", "c", "d")), default = structure(list(), class = c("collector_guess", 
    "collector"))), .Names = c("cols", "default"), class = "col_spec"))

starting table:

a     b     c      d
0     8.88  13.76  -2.64
6.22  1.08  0      -0.3
1.2   0.25  19.61  -11.06
0.22  0     0      -0.22
0.24  0     0      -0.24

desired result:

a     b     c      d
0     6.24  11.12  -2.64
6.22  0.78  0      -0.3
1.2   0.25  8.55   -11.06
0     0     0      -0.22
0     0     0      -0.24

VBA For loop + if statement error

I am trying to create a loop that finds the value of my input box, select the cell that has the matching value of my input box and delete its the entire row. For some reason It seems like my if condition is not working at all.

*Totalrow= my double variable for the total number of rows on my sheet *tenroxcode = my string variable for the inputbox

For i = 1 To totalrows
    If tenroxcode = Range("E" & i).Value Then
        Range("E" & i).Select
        ActiveCell.EntireRow.Delete
    End If
Next

Could someone PLEASE help me?

Compare the present value with the previous value in R while in ifelse()

I was working on a project in which if I want to compare the present value with the previous value and return an output 1 if true and 0 if false.

I tried

brv_trx1$'first' <- ifelse(brv_trx1$`Total TRx` != lag(brv_trx1$`Total TRx`),1,0)

This code did not work as expected. There was few errors in the

If statement executing when it shouldn't

Hello experienced programmers, here's the question for a non-experienced programmer.

Here's my code and some images explaining my issue.

void initialiseSystem(int status)
{
    if (status != '1' || status != '2')
    {
        std::cout << "Restart me, my wires got mixed up!" << std::endl;
        return;
    }
    std::cout << "I'm fully ready, I will wait until you will be ready.\nWhen you will be, please feel free to start chatting" << std::endl;
}

Here are the images, (full HD) https://imgur.com/a/3u6LI20.

I spent an hour starting at this if statement, and nothing. I rewritten it more than 50 times and nothing. This is a dumb problem, most likely... The if loop clearly states that if it's not equal to 1 OR not 2 then don't go there, it still goes ;(

Thank you for your help and time ;)

C# Referring to for-loop variable in if-statement

Can I refer to the variable I assigned to in the for-loop in an if-statement that is embedded in the loop? My plan was to iterate through the numberFactorList with the loop variable, but I am getting very strange output. With this input: 1,2,1,3,1,2,4,1,2,3,6,1,2,3,4,6,12 I am getting 2 and 4. With 1,2,1,5,1,2,5,10 I am getting 2 and 10 and so on. However, I want to only filter those numbers that are between two ones. What am I doing wrong?

for (int a = 0; a < numberFactorLength - 2; a++)
        {
        if (numberFactorList[a] + numberFactorList[a+1] + numberFactorList[a+2] == numberFactorList[a+1] + 2)
            {
                primeNumberList.Add(factorList[a + 1]);
            }
        }

I am still a beginner. Thank you!

PHP Laravel | Testing Polymorphic Many To Many | If Statement not working correctly

So I'm not having a huge problem but I did notice something that did not work and I can't explain why. The issue is within the route as I'm just learning and messing around with Polymorphic Relations and what not.

Keep in mind all data is seeded and I have verified there is proper data in the fields by manually inserting comments and making sure the show up.

Here's my web.php file.

Route::get('/get/{id}/post', function($id) {
  $user = User::findOrFail($id);
  foreach($user->posts as $post) {
    echo "<hr /><h2>" . $post->title . "</h2>";
    echo "<p>By: ". $post->users->name ." | Date:" . $post->created_at->format('n-j-Y');
    echo "<br />" . $post->content . "</p><hr />";
    echo "<h3>Comments</h3>";
    if(!empty($post->comments)) {
      foreach($post->comments as $comment) {
        echo "<u>" . $comment->users->name . "</u><br />" . $comment->content . "<br /><br />";
      }
    } else {
      echo "Sorry there are no comments yet.";
    }
  }
});

The Problem I'm having is within the if statement at the bottom it does in fact pull all the comments and the Users name when comments exist. The real problem is that when there are no comments its not showing the else statement echo.

I find this really weird become I come to find it works if I'm just outputting one single post but not if I pull multiple post for that user.

Any Ideas why this would do this I'm really confused. Thanks!

If username is in the list, do this else do that. [Wordpress]

I'm trying to display some content only for the following usernames: Admin, Jake, Shadow, Kid.

My current code is something like this:

add_action( 'wp_enqueue_scripts', 'load_script' );
function load_script(){
if( is_user_logged_in() ){
    // Display content only for the following usernames: Admin, Jake, Shadow, Kid.
} else { 
    // User is not logged in or is logged in but not in the list.
}
}

Thanks in advance!

Excel VLOOKUP/ INDEX multiple times based on value

Pic1ReferenceTable

Pic2InOut

So I want to be able to change the values from Pic2 in rows "ZERO" and "LINE-IN" and have it reference the table to output the value from the even number of rows. In Pic2 if I enter "AA","CC","BB" into row "ZERO" and "3","2","1" into row "LINE-IN" then it would take "AA" from "ZERO" on Pic2 go to column A on Pic1 and find the match, then Look within row 1 Pic1 to find "3", then output "Z" from row 2 into the "LINE-OUT" row. So, the value "CC" in row "ZERO" with value of "2" in row "LINE-IN" will output the value of "X".

I have came across a few possible ways to accomplish this using VLOOKUP, INDEX, MATCH, and IF. All solutions and the ways I can think to do what I asking requires to build multiple tables and that doesn't seem very practical the way I am imagining.

I am really looking for one or two formulas that I can reference instead of making several different tables to accomplish the same thing.

Thanks for any help or guidance towards a solution and sorry about having to follow the links for the pics.

How to Return Text with IF Function in an Array

First time poster. Thanks for all the great help!

In Google Sheets, I'm trying to query a column and look for a state abbreviation, and if that abbreviation is a match, then "East" if not then "West"

Wanting to return text values in my column based on state abbreviation. We have territory manager split into two domains--East and West. So, trying to easily sort my data by East/West.

Here's what I have:

=IF(M:M={"AL", "CA", "DE","FL","GA","IA","KY","ME","MD","MA","MN","MS","NH","NJ","NY","ND","RI","SD","TN","VT","VA","WV","WI"},"East","West")

But, when I fill down, it just fills down East, and does not seem to actually query M:M

Thoughts?

Thanks so much!

Conditional If with REGEX

I'm working on a function to try some regex. Let me explain.

function traitement
{
    if ($Matches.NAME -match "^A_(?<test1>[\w{1,6}]{1,7})")
    {
        [void]($memberOfCollection.add($Matches.test1))
    }
    elseif ($Matches.NAME -match "^A_(?<test2>[]*)")
    {
         [void]($memberOfCollection.add($Matches.test2))
    }
    else
    {
        [void]($memberOfCollection.add($Matches.NAME))
    }
}

I have $Matches.NAME return string like "A_UserINTEL", "A_UserINTELASUS" or "A_UserINTEL_Adobe"

I need to differentiate 2 strings coming from $Matches.NAME and therefore write several tests.

  • "A_UserINTEL" and "A_UserINTELASUS" must return "UserINTEL".

  • "A_UserINTEL_Adobe" must return "UserINTEL_Adobe"

Test1 allows me to retrieve "UserINTEL" but I didn't succeed test2 to bring me "UserINTEL_Adobe".

Any idea? Thank you.

permission denied md5sum after if else comparison

i wrote a script, which finds all files in a directory and prints its phaths aswell as the md5 sum of a snippet of their head and tail to a txt file.

this works fine.

now i added an if-statement, so that if the filesize is less than 150000 bytes, it shall just calculate the md5sum of the whole file, without the head tail stuff.

this doesn't work and i dont know why. It gives me the error message:

/Users/Tobias/Desktop/Festplatten_indizieren_schleife.sh: line 16: ./.DS_Store: Permission denied

Here is the whole code:

echo Wie heißt die Festplatte? read varname echo Los gehts! 

before=$(date +%s)

IFS=$'\n' minimum=150000 for i in $( find . -type f ); do 
filsize=$( stat -f%z "$i" )     
if  ((filesize < minimum)); then
    both=$("$i" | md5)
else            
    h=$(head -c +51000 "$i" | tail -c 1000)
    t=$(tail -c 51000 "$i" | head -c 1000)

    both=$("$h$t" | md5)    
fi  
echo "$varname $i ; $both" >> /Users/Tobias/Desktop/$varname.txt;    

done

after=$(date +%s)

echo Das hat: $(((after - $before)/60)) Minuten bzw $(((after - $before))) Sekunden gedauert

I'm using Mac os 10.13.6

Note: I am doing this, because i collect all these data of 30 different external harddrives, so i can compare them and find dupikates. I am well aware that i am reinventing the wheel. BUT I can't use a program that finds duplikates etc... since these are 30 external harddrives

Anyway, if someone knows a better solution to find duplikates in 30 external harddrives, i will be the happiest person!

any help is appreciated

Retrieve the value of the cell from the same row and opposite column if the conditions match in VBA

I'm currently working on an extract from a code for implementing a series of workbooks, that looks something like this:

Sub CopyData()
NewBook = ""
Path = ThisWorkbook.Path
Sheets("Staff").Select
For i = 2 To 100000
If Cells(i, 1).value = "" Then
    i = 100000
Exit For
End If
Name_file = Path & "\" & Sheets("Staff").Cells(i, 1).value & ".xls"
Sheets("TEMPLATE_TARGET").Select 

 Range("Vnt").value = Sheets("Staff").Cells(i, 5).value
If Range("Vnt").value = Worksheets("Sheet1").Range("G4:ED4").value And 
Worksheets("Sheet1").Range("G5:ED57").value <> 0 Then
 Range("Vtti").value = ????
Cells.Select
Selection.Copy

I need some help with defining the Vtti cell: If the cell defined Vnt is sharing any value from the range G4:ED4 in worksheet Sheet1 and if any of the cells under the matched cell in Sheet1 is not empty, then the value of the cell Vtti is equal to a data stored in a Sheet 1's column B cell, that is located on the same row as the filled cell.

Could you recommend a way how to define a logically proper IF..THEN..END IF statement for my case? Thanks in advance.

Task complete excel function

I have a 2 tables one is the DB and other is the UI; My EmployeeDB table is something like this:

Name:           Task 1  Task 2 Task 3
John Smith        X       X      X
Alexandra Kole    X       X             
Jane Austin               X

And in my UI table I have employee names in the first column, and I want to show the status of whether all the tasks are completed or not. So it has to be something like this.

Name:            Status 
John Smith       Complete
Alexandra Kole   Incomplete
Jane Austin      Incomplete

I have this formula that I have pasted to the Status column of this table:

=IF(EmployeeDB[Name]=B4;IF(OR(EmployeeDB[Task 1]=""; EmployeeDB[Task 2]="";  EmployeeDB[Task 3]="");  "Incomplete"; "Complete"); "n.a"). 

But it only works for the first employee in the status table, for the others, the result is n.a, even though the employee is on the DB.

Could you please state what is the problem, and how it can be fixed?

how to avoid multile if statements

I have next code:

  private static final List<String> VALUES =
  ImmutableList.of("15", "545", "856", "5", "4558"); 

  public int getAmountOfUnits(String value, int duration) {


if (VALUES.contains(value)) {


  if (duration >= 1 && duration <= 7) return 0;


  if (duration >= 8 && duration <= 82) {
    return getUnitAmount(duration, 22, 15, 1);
  }


  if (duration >= 83 && duration <= 90) return 7;


  if (duration >= 91) {
    return getUnitAmount(duration, 114, 24, 7);
  }
}



if (value.equalsIgnoreCase("3") && duration >= 0) {
  return getUnitAmount(duration, 15, 16, 1);
}


if (value.equalsIgnoreCase("4") && duration >= 0) {
  return getUnitAmount(duration, 59, 60, 0);
}

return 1;
  }

List item

private int getUnitAmount(int input, int startRange, int increment, int startUnit) {
  while (startRange < input) {
    startUnit++;
    startRange += increment;
  }
  return startUnit;
}

How I can avoid this multile line if statments?

Perl return if statment vriable

How can i do something like that: I want return IP server from if statment, where i sign if to variable. It is possible?

#!/usr/bin/env perl
#

use warnings;
use strict;

my $variable1 = "10.12.1.1";
my $variable2 = "10.12.1.2";

my $string = $ARGV[0];

my $serveris=>(if ($string =~ m/^[abcdefghijklm]/) {
            print " $variable1 \n"
} else {
            print " $variable2 \n"
})


print $serveris

Multiple value checks with if condition python3

How to excecute mutiple value with if condition like below, i tried it but not working

if 'mydj-lb-foxdc01' or 'tsdj-lb-foxdc02' or 'mydj-lb-noivm01' or 'mydj-lb-noivm02' not in line:

Below is working while tried ..

if 'mydj-lb-foxdc01' not in line:

dimanche 29 juillet 2018

How to search for a name from a text file

// how do I make the scanner find a name case insensitive? For example if Emily is in the text file.

import java.util.; import java.io.;

public class BabyNames {

public static void main(String[] args) throws FileNotFoundException {
    Scanner console = new Scanner(System.in);
    System.out.println("** Popularity of a baby name since year 1920 **");
    System.out.print("name? ");
    String name = console.next();

    Scanner input = new Scanner(new File("names.txt"));
    while (input.hasNext()) {
        String search = input.next();
        if (search = name) { // need help here

        }
    }
}

}

elif statement without else in list comprehension

I'm doing some string parsing and want to return 1 if the character is a letter, 2 if the character is a number, and pass if the character is anything else.

Normally I would just use a for loop and append to it like this

string = 'hello123...'
values = []
for char in string:
    if char.isalpha():
        values.append(1)
    elif char.isdigit():
        values.append(2)

which returns

[1, 1, 1, 1, 1, 2, 2, 2]

as expected. According to https://stackoverflow.com/a/30245465/10029403 using list comprehensions can be much faster. So I tried:

values = [1 if char.isalpha else 2 if char.isdigit for char in string]

However, this is giving me a syntax error as an 'else' is expected.

File "C:/Users/test3.py", line 12
values = [1 if char.isalpha else 2 if char.isdigit for char in string]
                                                     ^
SyntaxError: invalid syntax

I want it to add nothing if the character is anything but alphanumeric. What is wrong with my code?

I will have to execute this function possibly billions of times so if there is a better way to do this, any increase in efficiency is welcome.

How is this IF statement working?

I have the following code which is working, but I don't understand why it works. It is an IF statement, and what happens is if $VAR has a value it displays the DIV, but if it doesn't, it wont display the DIV. I am new to programming, and I would think that the way I have the code, the DIV should not show up if $VAR has a value. Please help me understand. Thanks!

<?php
    if (!empty($VAR)) { ?>
    <div class='543'>
        <H1>Complete.</h1>
    </div>
<?php } ?>

How can I write this else if statement more efficiently?

I have a page with some css custom buttons and I want the selected button to stay highlighted when a user clicks elsewhere on the page. I can get what I want writing an if/else statement to assign a class when a button is selected and a different class if it's not selected but it's long winded, how can I write it to be more efficient?

<input class="btn" id="moveIt_overall2" type="button" value="Overall" onclick="changeImpactState('impact_overall');"/>
    <input class="btn" id="moveIt_customer" type="button" value="Customer" onclick="changeImpactState('impact_customer');" />
    <input class="btn" id="moveIt_staff" type="button" value="Staff" onclick="changeImpactState('impact_staff');" />
    <input class="btn" id="moveIt_strategic" type="button" value="Strategic" onclick="changeImpactState('impact_strategic');" />

var moveItOverall = document.getElementById('moveIt_overall2');
var moveItCustomer = document.getElementById('moveIt_customer');
var moveItStaff = document.getElementById('moveIt_staff');
var moveItStrategic = document.getElementById('moveIt_strategic');

if(currentImpactState == 'impact_overall'){
        moveItOverall.className = 'btn-on';
        moveItCustomer.className = 'btn';
        moveItStaff.className = 'btn';
        moveItStrategic.className = 'btn';
    }else if(currentImpactState == 'impact_customer'){
        moveItOverall.className = 'btn';
        moveItCustomer.className = 'btn-on';
        moveItStaff.className = 'btn';
        moveItStrategic.className = 'btn';
    }else if(currentImpactState == 'impact_staff'){
        moveItOverall.className = 'btn';
        moveItCustomer.className = 'btn';
        moveItStaff.className = 'btn-on';
        moveItStrategic.className = 'btn';
    }else if(currentImpactState == 'impact_strategic'){
        moveItOverall.className = 'btn';
        moveItCustomer.className = 'btn';
        moveItStaff.className = 'btn';
        moveItStrategic.className = 'btn-on';
    }

How can I get a right order of data from previous sheets with VBA

Could someone help me out with the following code, I thought i figured it out but keep on stranding with the same problem:

Sub history()
nsheets = ActiveWorkbook.Worksheets.Count 'count sheets in workbook
nas_index = ActiveSheet.Index 'index of the activated sheet
nas_LR = Sheets(nas_index).Cells(Sheets(nas_index).Rows.Count, "A").End(xlUp).Row 'count rows of activesheet

For d = 1 To nsheets
    If d < nas_index Then
        pre_index = Sheets(nas_index - d).Index
        pre_LR = Sheets(pre_index).Cells(Sheets(pre_index).Rows.Count, "A").End(xlUp).Row

        oldtime = Sheets(d).Cells(1, 6).Value
        newwknr = Sheets(nas_index).Cells(1, 7).Value
        oldwknr = Sheets(pre_index).Cells(1, 7).Value
        StrOldTime = Format(oldtime, "hh:mm:ss")

        For n = 3 To nas_LR
         prid_new = Sheets(nas_index).Cells(n, 1).Value

         For o = 3 To pre_LR
            prid_old = Sheets(pre_index).Cells(o, 1).Value
            pre_am = Sheets(pre_index).Cells(o, 6).Value
            pre_amw = CStr(pre_am) & "(" & StrOldTime & ")" & "(wk: " & oldwknr & ")"
            If prid_new = prid_old Then
             'Below is not working properly
             '------------------------------
                re = re & " " & pre_amw 
                Sheets(nas_index).Cells(n, 10).Value = re
             '------------------------------
            End If

         Next o
        Next n
    Else
        'MsgBox exit loop
        Exit For
    End If

Next d



'------------------nevermind below
Dim ntime As Date, nStrTime As String
If Not ThisWorkbook.ActiveSheet.Cells(1, 10).Value = "" Then
'-new time
ThisWorkbook.ActiveSheet.Cells(1, 12).Value = Time()
ntime = ThisWorkbook.ActiveSheet.Cells(1, 12).Value
mstrtime = Format(ntime, "hh:mm:ss:ms")
ThisWorkbook.ActiveSheet.Cells(1, 12).Value = mstrtime

'-old time
gettime = ThisWorkbook.ActiveSheet.Cells(1, 10).Value
ThisWorkbook.ActiveSheet.Cells(1, 11).Value = gettime
myStrTime = Format(gettime, "hh:mm:ss:ms")
ThisWorkbook.ActiveSheet.Cells(1, 11).Value = myStrTime
End If

End Sub

The image below is so far what I got (the text in red, is what i wish to have). enter image description here

My goal is to have the following Check if I bought the same item before (ID). Collect data of this ID and store it in the column History. So that I can see if the product has been price changed over the previous weeks. I can't get the data properly of previous sheets. Instead of getting the following:
item: A B C D or
item: D C B A
I get something like this:
item: A A A A A A B B B B B B C C C C C C D D D D D D or
item: A B C D A B C D A B C D

I think I am failing here:

If prid_new = prid_old Then
                 'Below is not working properly
                 '------------------------------
                    re = re & " " & pre_amw 
                    Sheets(nas_index).Cells(n, 10).Value = re
                 '------------------------------
                End If

Can someone lent me a hand.

Warning while running ensemble code in R

I am trying to run an ensemble model using the majority vote method. this is the code for it.

pred_majority<-as.factor(ifelse(pred_rf_new=='TRUE' & 
model_1_epoch_predict$predict=='TRUE','TRUE',ifelse(pred_rf_new=='TRUE' & ksvm_predict=='TRUE','TRUE',ifelse(model_1_epoch_predict$predict=='TRUE' & ksvm_predict=='TRUE','TRUE','FALSE'))))

Executing the line reverts the following warning.

Warning messages:
1: In pred_rf_new == "TRUE" & model_1_epoch_predict$predict == "TRUE" :
longer object length is not a multiple of shorter object length
2: In model_1_epoch_predict$predict == "TRUE" & ksvm_predict == "TRUE" :
longer object length is not a multiple of shorter object length

Please help me out.

Hide DIV if function is empty

let's say I have the following code, how can I hide the DIV if the function is empty?

Similarly, how can I show another DIV if the function is empty?

<div class='box12'>
<h1>text<h1/>
<p><?php echo name5(); ?><p/>
</div>

Skipping lines of code in Python?

So as my first project on python I am trying to make a dichotomous key like program where it guesses what animal you are thinking of after asking questions, I'm really new to this so try to explain it kind of simple :). Also sorry if this question has been asked somewhere else, I didn't really know how to ask it.

think=input ("Think of an animal. Type ready when you want to begin")
think=think
#FUR
if think=="READY" :
   fur=input ("Does it have fur?") 
else :
   print ("I'll be waiting")
if fur=="YES" :
   legs=input ("Does it walk on four legs?") :
elif fur=="NO" :
   reptile=input ("Is it a reptile?")
#REPTILE
if reptile=="YES" :
   shell=input ("Does it have a shell?") 
if reptile=="NO" :
   fly=input ("Can it fly?") 
#LEGS
if legs=="YES" :
   pet=input ("Do people own it as a pet?")
if legs=="NO" :
   marsupial=input("Is it a marsupial?")

I can't get it to skip to "Do people own it as a pet" if you answer yes on legs. also, the "I'll be waiting" (else) doesn't work. Oh, and this is python 3.x btw.

Edited for formatting

Edit 2: Got rid of the parentheses in my comparisons :)

python To efficiently use the result of function in if statement

Is there any other code form, that one can both use a function in if statement and get the value of function without executing the function twice?

For example,

There exists a function, fun1(arg), which takes an hour to return its result (The result value can be either None or some int)

and I want to do some further calculation(for example get its squared value) only if the result from fun1 is not None.

This will be done by:

result = fun1(arg) 
if result: 
    result = result * result

Is there any shorter form such as

if (result = fun1(arg)):
    result = result * result

in python?

isinstance function in if statement python

As part of a lcm program I'm creating, I want a condition to determine whether the result of an expression is integer or float. After looking online, I found the isinstance function, which outputs a boolean. I want to be able to use that in the statement, and execute the respective . How exactly do I code it? This is an example:

num=input("Enter a number: ")
if isinstance(num,int):
  print("Float")
else:
  print("Integer")

Python: Luhn's algorithm / if statement never executes

I am trying to implement the Luhn's algorithm to check for credit card number validity. To do this every second digit needs to be multiplied by 2 and if the result is >9 it then is replaced by the sum of the digits.

def luhn_check(creditcardnr):
"""
check if credit card number is valid using the Luhn's algorithm
"""

som = 0
for i, digit in enumerate([int(x) for x in str(creditcardnr)]):
    if i in range(1, len(str(creditcardnr))-1,2):
        digit *= 2
        if digit > 9:
            digit -= digitsum(digit)
    som += digit
    print('digit :',digit,'    sum :',som)

return som % 10 == 0

When I run this code I get as result

digit : 5    sum : 5
digit : 2    sum : 7
digit : 2    sum : 9
digit : 9    sum : 18
digit : 7    sum : 25
digit : 2    sum : 27
digit : 0    sum : 27
digit : 9    sum : 36
digit : 3    sum : 39
digit : 9    sum : 48
digit : 6    sum : 54
False

the second sum should be 9 not 7

Python 27. how to stick data to correct tuple list in list

First of all see this code. Now i use python 27 on Psychopy 2(1.85.4)

before explain my problem introduce my list and datatype

1. oneman = 252 of [a,b,c,d]
2. bincan = [(0, []), (1, []), (2, []), (3, []), (4, []), (5, []), (6, [])]

The problem was identified at last function, oneman[0][0] = 'a' so i want use the 'a' for indexing bincan number. and stick the data 'd' to each list. but the result was correct result of logic is go to all bincan list like

fucking result [(0, [(d)]), (1, [d]), (2, [d]), (3, [d]), (4, [d]), (5, [d]), (6, [d])]

please where is the problem in this logic. def clear (datum) : Cdata = [] for i in datum: Cdata.append(i[0]) Cdata.append(i[1]) Cdata.append(i[3]) Cdata.append(i[4]) return Cdata

def reline(data):
    alpha = np.array(data)
    postC = alpha.reshape((252, 4))
    return postC.tolist()
oneman = reline(clear(fp[1]))

def bincan(listnum):
    alpha, beta = [] ,[]
    ceta = range(listnum)
    for i in range(listnum) :
        alpha.append(beta)
    return zip(ceta, alpha)
pillcan = bincan(7)


def sieve(datum):
    for i in datum:
        if i[0] == 0:
            pillcan[0][1].append(i[3])
    return pillcan

samedi 28 juillet 2018

How do I get input from user and call a function based on the input?

I'm new to Python and while practicing I made this program, It asks the user to choose one of the two shapes among circle and triangle. But every time I enter an input, no matter if it's a 'c', 't', 'r' or anything else, the function to calculate triangle area gets executed.

'''
This is a Calculator program
which asks the user to select a shape
and then calculate its area based on given dimensions
'''
print ('Shape Area Calculator is now running')

def triangleCalc():
    base = float(input('Enter Base of triangle: '))
    height = float(input('Enter Height of triangle: '))
    areaT = 0.5 * base * height
    print ('The area of triangle is: ' + str(areaT))

def circleCalc():
     radius = float(input('Enter radius of Circle: '))
     areaC = 3.14159 * radius * radius
     print ('The area of Circle is ' + str(areaC))



print('Which shape would you like to calculate the Area of?')
print('Enter C for Circle or T for Triangle')
option = input()
if option == 't' or 'T':
    triangleCalc()
elif option == 'c'or 'C':
    circleCalc()
else:
    print ('Invalid Choice')

if - else - Bash

Input file "temp.txt" has multiple lines. Script will parse temp.txt and search for these strings on different files. If result is "True", don't check other files and continue with next object. Is there any way to accomplish this?

temp.txt

abc
abd
abe
abf
abg

xyz

f1
f2
f3
f4
f5

Script:

function command() {
    if [ "$a -ne 0 ]; then
            echo "$i" 'True';
            else
            echo "$i" 'false';
    fi
}     


for x in (xyz)
    do
    cd $x;
    for i in `cat "temp.txt"`; do 
    command $i
    done

How to use if condition to hide element in Smarty template (TYPO3)?

TYPO3 website is using Smarty template engine. In one existing template called header.tpl I have this code:

<div class="header">
...
</div>
<div class="nav">
...
</div>

Is there some way to hide div element with the class "nav" using if condition? This header.tpl is used on every page, but I want to achieve that only on page with id=3 (in TYPO3) the navigation part will be hidden.

For example:

<div class="header">
...
</div>
{if (???) }
<div class="nav">
...
</div>
{/if}

Thank you very much for your help.

swift - if statement for random string and int

i have this if statement worked well but the code: DqJUXRcx may changed so, how to make it == random code ?

    @IBAction func btnPlusPressed(_ sender: UIButton)
{
        var strURLl = url.text!

        if (url.text == "DqJUXRcx" as String ){
                strURLl = "https://pastebin.com/raw/\(url.text!)"
            } else {
                strURLl = "\(url.text!)"
            }
}

Pokemon game in python: classes/objects, battle and deepcopy

I'm new on python and I'm trying to do a Pokemon game (like the gameboy and nds games). I've created the pokemon and trainer classes and I want to implement the battle mechanics. I thought it was working fine, but then I found that if I loose the battle the program enters in an infinite loop. I tried a lot to found the error and I discovered that when it exits the while alive(pokemon1) and alive(pokemon2) loop, the pokemon1 hp returns to full hp but the pokemon2 remains with the current hp. It makes non sense for me because the code is identical for both. Anyone knows why is it happening? I want it to return the current hp of both pokemon.

Here is a sample of my code showing the error:

import copy
import random

class Pokemon(object):
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp
    def ataque(self, oponent):
        oponent.hp = oponent.hp - 150 #just for a test

class Trainer(object):
    def __init__(self, name, *pokemon):
        self.name = name
        self.pokemon, self.pokemonname = [], []
        for pkmn in pokemon:
            self.pokemon.append(copy.deepcopy(pkmn))
            self.pokemonname.append(pkmn.name)

weavile = Pokemon ('Weavile', 150) #change the hp to more than 150 if you want to win
garchomp = Pokemon ('Garchomp', 250)
roserade = Pokemon ('Roserade', 160)
ambipom = Pokemon ('Ambipom', 160) 

eu = Trainer('You', weavile) #or choose ambipom to win
cynthia = Trainer('Cynthia', garchomp)

def alive(pokemon): #check if the pokemon is alive
    if pokemon.hp>0:
        return True
    if pokemon.hp<=0:
        pokemon.hp=0
        return False

def battle(trainer1, trainer2): #battle between two trainers
    fight1, fight2 = True, True
    while fight1 and fight2:
        print ('Choose a pokemon:', trainer1.pokemonname)
        pokemon1 = eval(input())
        while not alive(pokemon1):
            print (pokemon1.name, 'is out of batlle. Choose another pokemon')
            pokemon1 = eval(input())
        pokemon2 = random.choice(trainer2.pokemon)
        while not alive(pokemon2):
            pokemon2 = random.choice(trainer2.pokemon)
        print (trainer1.name, 'chose', pokemon1.name, '\n', trainer2.name, 'chose', pokemon2.name)
        while alive(pokemon1) and alive(pokemon2):
            pokemon1.ataque(pokemon2)
            if alive(pokemon2):
                pokemon2.ataque(pokemon1)
            print (pokemon1.name, pokemon1.hp)
            print (pokemon2.name, pokemon2.hp)
        print (trainer1.pokemon[0].name, trainer1.pokemon[0].hp) #here its returning the original hp
        print (trainer2.pokemon[0].name, trainer2.pokemon[0].hp) #here its returning the current hp, as it should
        if not any(alive(pokemon) for pokemon in trainer1.pokemon):
            fight1 = False
        if not any(alive(pokemon) for pokemon in trainer2.pokemon):
            fight2 = False

battle(eu, cynthia)

Creating an IF statement in Python that looks at previous IF statement output

I am having difficulty creating an IF statement that does the following:

  • If C1 = Buy, then Buy
  • If C2 = Sell, then Sell
  • If C1 & C2 = nan, then current cell = previous cell

Please see example below. I am hoping to create a column like 'C3'.

Sample Dataset:

index  C1    C2
0      Buy   nan
1      nan   nan
2      nan   Sell
3      nan   nan
4      Buy   nan
5      nan   Sell
6      nan   Sell
7      nan   nan
8      nan   nan
9      Buy   nan
10     nan   Sell

Output:

index  C1    C2    C3
0      Buy   nan   Buy
1      nan   nan   Buy
2      nan   Sell  Sell
3      nan   nan   Sell
4      Buy   nan   Buy
5      nan   Sell  Sell
6      nan   Sell  Sell
7      nan   nan   Sell
8      nan   nan   Sell
9      Buy   nan   Buy
10     nan   Sell  Sell

If/else statement in jQuery not working

I'm working on a wordpress website where I'm trying to create a table with real-time cryptocurrency prices and price changes. I am using the coinmarketcap v2 api (https://coinmarketcap.com/api/) to fetch the real time values. Im using a Wordpress plugin (shortcoder) that I can use to shortcode pieces of script.

What I want to do is to style the 24h change percentage value based on whether its value is negative or positive. I have tried both ways of styling seperately and they work.

However, what I cant get to work is the if/else statement in the jQuery to determine whether the 24h change percentage is negative. The jquery script I've tried to create is:

(function($){
$.getJSON('https://api.coinmarketcap.com/v2/ticker/1/', function( data ){
    if(data['data']['quotes']['USD']['percent_change_24h']>=0){
        $('#btc_24h').html('<span style="color:green;"> '+data['data']['quotes']['USD']['percent_change_24h']+'%</span>');    
    }else{
        $('#btc_24h').html('<span style="color:red;"> '+data['data']['quotes']['USD']['percent_change_24h']+'%</span>');
});

Unfortunately I am not that much of a jQuery hero and I've been trying to figure the problem out all morning. Does anyone know what I might be doing wrong?...

When I delete the if/else statement and just try both types of styling seperately they both work fine...

Error in javascript if expression

I am developing a vue application and I am using webpack for building my project. When I was running my application in development mode, I got an error as shown in the image.

enter image description here

As you can see seqNo variable has value 3 and it should not go inside the if condition. But it is going inside if condition. I was debugging using Google Chrome browser and then I switched to Firefox. I tried even using triple equations (===). But still the same problem occurs. Is there any way to overcome this issue ?

Thanks

vendredi 27 juillet 2018

How to get same data in different column with conditions

I want to replace same data in column B and column D from column A and column C respectively whenever the text “First and current year” presents.I have tried using IF loop but somehow it doesnt workingenter image description here Please help.

How to make a loop that loops 25 times, waits 5 minutes and then starts the next batch of 25? java

I know that i'll have a for loop that looks something like this. But other than that I have no idea for it to then start back up again.

for (int i = 0; i < 25; i++) {
// my code here

}

PySpark: Create New Column And Fill In Based on Conditions of Two Other Columns

I have the following data frame:

id  ts  days_r
123 T   32
342 I   3
349 L   10

I want to create a new column and fill in the values depending on if certain conditions are met on the "ts" column and "days_r" columns.

This is my desired data frame:

id  ts  days_r  0to2_count
123 T   32      1
342 I   3       0
349 L   10      0

I tried the following code in pyspark:

 df = df.withColumn('0to2_count', F.when((F.col("ts") == 'I') & (F.col('days_r') >=0) & (F.col('days_r') <= 2), 1) \
    .otherwise(F.when((F.col("ts") == 'T') & (F.col('days_r') >=0) & (F.col('days_r') <= 48), 1) \
    .otherwise(F.when((F.col("ts") == 'L') & (F.col('days_r') >=0 & F.col('days_r') <= 7), 1) \
    .otherwise(0))))

I get the error below:

Traceback (most recent call last):
  File "perc_0to2", line 1, in <module>
  File "perc_0to2", line 9, in perc_0to2
  File "/tmp/conda-4df0bea5-3a72-444c-b3c5-f1562d678953/real/envs/conda-env/lib/python2.7/site-packages/pyspark/sql/column.py", line 115, in _
    njc = getattr(self._jc, name)(jc)
  File "/tmp/conda-4df0bea5-3a72-444c-b3c5-f1562d678953/real/envs/conda-env/lib/python2.7/site-packages/py4j/java_gateway.py", line 1257, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "/tmp/conda-4df0bea5-3a72-444c-b3c5-f1562d678953/real/envs/conda-env/lib/python2.7/site-packages/pyspark/sql/utils.py", line 63, in deco
    return f(*a, **kw)
  File "/tmp/conda-4df0bea5-3a72-444c-b3c5-f1562d678953/real/envs/conda-env/lib/python2.7/site-packages/py4j/protocol.py", line 332, in get_return_value
    format(target_id, ".", name, value))
Py4JError: An error occurred while calling o826.and. Trace:
py4j.Py4JException: Method and([class java.lang.Integer]) does not exist
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:326)
    at py4j.Gateway.invoke(Gateway.java:274)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.ClientServerConnection.sendCommand(ClientServerConnection.java:244)
    at py4j.CallbackClient.sendCommand(CallbackClient.java:384)
    at py4j.CallbackClient.sendCommand(CallbackClient.java:356)
    at py4j.reflection.PythonProxyHandler.invoke(PythonProxyHandler.java:106)
    at com.sun.proxy.$Proxy94.execute(Unknown Source)
    at com.palantir.arrow.module.compute.DelegatedComputeService.lambda$execute$0(DelegatedComputeService.java:63)
    at com.palantir.foundry.spark.api.SparkAuthorization.runAsUserInternal(SparkAuthorization.java:164)
    at com.palantir.foundry.spark.api.SparkAuthorization.runAsUser(SparkAuthorization.java:105)
    at com.palantir.arrow.module.compute.DelegatedComputeService.execute(DelegatedComputeService.java:62)
    at com.palantir.arrow.module.ArrowSparkModuleResource.lambda$executeAsync$0(ArrowSparkModuleResource.java:106)
    at com.palantir.remoting3.tracing.DeferredTracer.withTrace(DeferredTracer.java:43)
    at com.palantir.remoting3.tracing.Tracers$TracingAwareCallable.call(Tracers.java:219)
    at com.codahale.metrics.InstrumentedExecutorService$InstrumentedCallable.call(InstrumentedExecutorService.java:197)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

If statement: test delayedexpansion !counter! variable inside if condition

I can't reference !count! inside the for loop, and if I reference it as %count%, then it simply is set to 1 (what it was before entering the loop).

setlocal enableextensions enabledelayedexpansion
FOR /F "tokens=*" %%a in ('returnNumLines.bat apiKey.txt') do SET numKeys=%%a
FOR /F "tokens=*" %%a in ('returnLine.bat %numKeys% apiKey.txt') do SET APIKEY=%%a

set dbName=somedb
set tableName=ur_table
set PGPASSWORD=1234
REM counter
set /a count = 1

echo CREATE TABLE temp_table (symbol varchar(8), timestamp date, open real, high real,low real,close real,adjusted_close real,volume real,dividend_amount real,split_coefficient real,CONSTRAINT temp_pkey PRIMARY KEY (timestamp,symbol)) WITH (OIDS=FALSE) TABLESPACE pg_default;ALTER TABLE temp_table OWNER to postgres; | psql -U postgres %dbName%

for /F "delims=;" %%a in (c:\test\nasdaqSymbolsNoHeader.csv) do (

    set /a count +=1

    ...

    IF "!count!"=="%numKeys%" (SET /a count=1)


)

echo drop table temp_table;| psql -U postgres somedb
endlocal

Set the digits to the appropriate place

Task: set the digits in the number in their place so in the end you get the highest number. (ex. 58734 - to become 87543).

In this case, I took a 3-digit number,but what if I want a number with many digits (as 58734 in example), do I have to write those if conditions every time, or I can do that some easier and better way?

Here's my code:

    Scanner sc = new Scanner(System.in);

    System.out.print("Enter 3-digit number: ");
    int num = sc.nextInt();
    while (num < 100 || num > 999) {
        System.out.print("Number isn't 3-digit! Enter it again: ");
        num = sc.nextInt();
    }
    int j = num % 10;
    int d = (num / 10);
    d = d % 10;
    int s = num / 100;

    if (j > d) {
        int t = j;
        j = d;
        d = t;
    }
    if (j > s) {
        int t = j;
        j = s;
        s = t;
    }
    if (d > s) {
        int t = d;
        d = s;
        s = t;
    }

    int res = s * 100 + d * 10 + j;
    System.out.println("Result: " + res);

Output:

Enter 3-digit number: 453
Result: 543

How to create a data frame from a nested for loop

I have a data frame which contains 341785 observations, imported as a .csv. I am running one column of my data through a nested for/if statement. I want to create an output in the form of a data frame, at the moment it is just filling the console with the output, row by row.

`for (level1 in dim(st) {
  if (is.na(st$level1[i])){
    print("No Level 1")
  }else if(st$level1[i]=="A"){
     print("Woodland")
  }else if (st$level1[i]=="B") {
     print("Scrubland")
  }else if(st$level1[i]=="C") {
     print("Semi-Natural Grassland/Marsh")
  }else if (stb$level1[i]=="D") {
     print("Unknown")
  }else if (st$level1[i]=="E") {
    print("Farmland")
  }else if(st$level1[i]=="F") {
    print("Human Sites")
  }else if (st$level1[i]=="G") {
    print("Water Bodies (Freshwater)")
  }else print("Other")
 }`

Goal would be

Level 1 1 Woodland 2 Farmland 3 Unknown 4 No Level 1 5 ...

I have tried to do it lots of different ways suggested online but none of them have worked, they have only created data frames with 0 Levels and 0 Observations. I am new to R and need help, especially as I am going to need to reproduce this for at least 6 more columns...

logical error : my program won't enter the if statment [duplicate]

This question already has an answer here:

So I wrote a code to convert standard time to 24hour format but for some reason my program can't enter the if statement.

Code:

public class Solution {
static BufferedReader br;
public static void main(String args[]) throws IOException
{
    br = new BufferedReader( new InputStreamReader(System.in));
    String str = br.readLine();
    String strt = str.substring(8);
    Solution.Time(str,strt); 
}
public static void Time(String str,String Strt) throws IOException
{
    String temp = str.substring(0,8);
    String pureNo[] = temp.split(":");        
    int a[]= new int[3];
    for(int i=0; i<3; i++)
    {
        int Temp = Integer.parseInt(pureNo[i]); 
        a[i] = Temp;
    }
    if(Strt=="AM") 
    {
        if(a[0]==12)
        {
           System.out.println("00"+str.substring(2,8)); 
        }
        else{
            System.out.println(a[0]+str.substring(2,8));
        }
    }
    else
    {
        if(a[0]==12)
        {
            System.out.println("12"+str.substring(2,8));
        }
        else
        {
            System.out.println(a[0]+12+str.substring(2,8));
        }
    }
}

}

so consider the input 01:00:00AM now it gives the ans as 13:00:00, which is wrong. please help.

swift - cannot make my if statement work is well as i need

i have a problem when i typed my code as is bellow but i got error ?!

i want user if typed code = 4234 on textFields and tap on "ADD" = "https://pastebin.com/raw/4234"

else = any url "http://www.example.com/"

@IBAction func btnPlusPressed(_ sender: UIButton)
{

    let alert = UIAlertController(title: "Provider M3U URL", message: "Add Provided URL to add you M3U Plailist", preferredStyle: .alert)
    let loginAction = UIAlertAction(title: "ADD", style: .default, handler: { (action) -> Void in

        var url = alert.textFields![0]

        if (url.text == "535" as String ){
            let strURLl : String = "https://pastebin.com/raw/\(url.text!)"

        }else{
            let strURLl : String = "\(url.text!)"
        }


        UserDefaults .standard .set(strURLl, forKey: "URL")

        let channelsVC = self.storyboard!.instantiateViewController(withIdentifier: "ChannelsViewController") as! ChannelsViewController
        channelsVC.strURL = strURLl!
        self.navigationController?.pushViewController(channelsVC, animated: true)

    })

why error appear like this : (Use of unresolved identifier 'strURLl')

For 70,000 rows, my macro is taking a lot of time to give output comment as per various conditions(if statement). Please help me improve my approach

For traversing 70,000 rows(using for loop), my macro is taking a lot of time to give output comment as per various conditions(if statement). Please help me improve my approach.I am working on around 70,000 rows and my code is taking a lot of time to run. Please see the attachment image that depicts how data looks. Can someone please guide me with a better approach here?enter image description here This code compares various columns and gives output on the basis of certain conditions.

Set wsa = ThisWorkbook.Sheets("Audit-NIMS vs Site Topology")

With wsa
AudLastCol = .Cells(1, Columns.Count).End(xlToLeft).Column
.Cells(1, AudLastCol + 1).Value = "Match;Issue Type;Actions"

For l = 2 To AudLastRow
    aPRTS = .Cells(l, AudLastCol).Value
    bNIMS = .Cells(l, NIMsLastCol).Value
    tempin = .Cells(l, 2).Value

    If aPRTS = bNIMS Then
        Deployed19 = Application.Match("Deployed(1.9)", .Rows(1), 0)
        If IsNumeric(Deployed19) Then
            d19 = .Cells(l, Deployed19).Value
        Else
            d19 = 0
        End If
        Deployed800 = Application.Match("Deployed (800)", .Rows(1), 0)
        If IsNumeric(Deployed800) Then
            d8 = .Cells(l, Deployed800).Value
        Else
            d8 = 0
        End If
        Deployed2500 = Application.Match("Deployed (2.5)", .Rows(1), 0)
        If IsNumeric(Deployed2500) Then
            d25 = .Cells(l, Deployed2500).Value
        Else
            d25 = 0
        End If

        PRTS800 = Application.Match("Total-800-PRTS", .Rows(1), 0)
        If IsNumeric(PRTS800) Then
            p8 = .Cells(l, PRTS800).Value
        Else
            p8 = 0
        End If

        PRTS1900 = Application.Match("Total-1900-PRTS", .Rows(1), 0)
        If IsNumeric(PRTS1900) Then
            p19 = .Cells(l, PRTS1900).Value
        Else
            p19 = 0
        End If

        PRTS2500 = Application.Match("Total-2500-PRTS", .Rows(1), 0)
        If IsNumeric(PRTS2500) Then
            p25 = .Cells(l, PRTS2500).Value
        Else
            p25 = 0
        End If
        If (p19 = d19) And (p8 = d8) And (p25 = d25) Then
            .Cells(l, AudLastCol + 1).Value = "TRUE;None;No Action Required."
        Else
            .Cells(l, AudLastCol + 1).Value = "FALSE;Both;Update NIMS and PRTS."
        End If
    ElseIf aPRTS = "NA" And bNIMS = "0" Then
        .Cells(l, AudLastCol + 1).Value = "TRUE;None;No Action Required."
    ElseIf aPRTS = "0" And bNIMS = "NA" Then
        .Cells(l, AudLastCol + 1).Value = "TRUE;None;No Action Required."
    ElseIf aPRTS > 0 And bNIMS = "NA" Then
        .Cells(l, AudLastCol + 1).Value = "N/A;NIMS;Update NIMS."
    ElseIf bNIMS > 0 And aPRTS = "NA" Then
        .Cells(l, AudLastCol + 1).Value = "N/A;PRTS;Check traffic from PRTS & Report to PRTS Team."
    ElseIf bNIMS > aPRTS Then
        .Cells(l, AudLastCol + 1).Value = "FALSE;PRTS;Check traffic from PRTS & Report to PRTS Team."
    ElseIf bNIMS < aPRTS Then
        .Cells(l, AudLastCol + 1).Value = "FALSE;NIMS;Update NIMS."
    End If
    'To compare certain category of Name and concatenate output accordingly.
    If InStr(1, .Cells(l, 1).Value, "52XC") > 0 Then
        .Cells(l, AudLastCol + 1).Value = .Cells(l, AudLastCol + 1).Value & "Clearwire Site."
    ElseIf InStr(1, .Cells(l, 1).Value, "82XC") > 0 Then
        .Cells(l, AudLastCol + 1).Value = .Cells(l, AudLastCol + 1).Value & "Clearwire Site."
    ElseIf InStr(1, .Cells(l, 1).Value, "XT") > 0 Then
        .Cells(l, AudLastCol + 1).Value = .Cells(l, AudLastCol + 1).Value & "COW Site."
    End If

    If bNIMS = "NA" And Application.CountIf(ThisWorkbook.Sheets("NIMS dump-SC level").Range("B1:B" & temprow), .Cells(l, 2).Value) Then
        .Cells(l, AudLastCol + 1).Value = Cells(l, AudLastCol + 1).Value & "Present in NIMS Dump."
    End If
Next l
End With