mercredi 26 août 2015

If block get executed while condition is false

I am trying to copy a file from one directory to another, everything works perfect except when i try to run Copy.exe am getting an exception. What wrong with the code? why the code withing if statement is executed while the condition is false??

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class Ah {
    public static void main(String[] args){
        File from = new File("."+"/original.exe");
        File to = new File("/home/denis/Run/Copy.exe");
        if(!to.exists()) {                
            to.getParentFile().mkdirs();
        }
        if(from.exists()){
            FileChannel is = null;
            try {
                is = new FileInputStream(from).getChannel();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            FileChannel os = null;
            try {
                os = new FileOutputStream(to).getChannel();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                os.transferFrom(is, 0, is.size());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                  // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            for(File ff: new File(".").listFiles()){

            //Why this code is not executed???
            //why the condition is false but if clouse get executed??
            //is the problem caused by something else???
            System.out.print("There is no such file in a current working      directory, except for "+ff+"\n");
        }
      }
    }
}

This is the exception am getting when i run "/home/denis/Run/Copy.exe" from terminal

 java.io.FileNotFoundException: /home/denis/Run/Copy.exe (Text file busy)
   at gnu.java.nio.channels.FileChannelImpl.open(libgcj.so.10)
   at gnu.java.nio.channels.FileChannelImpl.<init>(libgcj.so.10)
   at gnu.java.nio.channels.FileChannelImpl.create(libgcj.so.10)
   at java.io.FileOutputStream.<init>(libgcj.so.10)
   at java.io.FileOutputStream.<init>(libgcj.so.10)
   at Ah.main(Copy.exe)
Exception in thread "main" java.lang.NullPointerException
   at Ah.main(Copy.exe)

I use GCJ to create executable and i am running java 6 on ubuntu v-12

Liquid nested if statement

This statement should only return goals scored if the value is higher than zero, but it's returning it regardless:

{% for member in site.data.members %}
<div class="player">
    {% if member.goals > 0 %}
        <span class="goals">{{ member.goals }}</span/>
    {% endif %}
</div>
{% endfor %}

Where have I gone wrong?

keep getting return error in python. I can't find a guide to help me explain why I get the return error in various instances

Only been at this for 2 weeks so bare with me please, I'm also learning from codeacademy. Yes, I did research and cannot find out why it is telling me it is outside of the function

name=input(" input name ")
print("welcome, {}".format (name))

class player():

    def __init__(self, atk, hp,):
        self.atk=atk
        self.hp=hp

    def __str__(self):
        return "{}, {}".format (self.atk, self.hp)

input("Time for a questionnaire to define your stats")
input("press enter to continue....")
print("in an intense battle when both you and your enemy are on the edge of consciousness and you have a chance to flee do you finish off the opponent taking a chance on being struck down or do you flee with your life?")
statq1=input("fight or flee")
if statq1 == "fight":
    return 5+self
elif statq1 == "flee":
    return 5+hp

Psychopy: Key response lagging, causing problems within script

I have a component of an experiment that asks participants to choose between earning 10 immediate points or a larger point amount in two weeks (points are later converted to dollar amount to provide incentive to the "larger later" choice). The later amount offered varies based on previous choices. The participant is given feedback on the choice he/she just made in the next routine. To set this up, I generated this in the code component in builder:

if key_resp_4.keys == 'left':
    feedback = 'You chose 10 points immediately'
    TotalNow = TotalNow + 10
    add = (amount - 10)/2 
    amount = add + amount
elif key_resp_4.keys == 'right':
    feedback = 'You chose more points in two weeks'
    TotalLater = TotalLater + amount
    amount = (amount + 10)/2 
elif key_resp_4.keys in ['', [], None]:
    feedback = 'You did not make a choice. No reward given.'
    amount = amount

The "amount" variable generates a numeric value, which is updated based on a left or right response. "TotalNow" and "TotalLater" keep track of the total points earned for each condition and are displayed in the next screen. These variables are working just fine.

My problem lies within the feedback variable. I've run through the script quite a few times to better understand what is happening. For most of the trials (though not all)--regardless of whether or not I make a key press--the feedback screen prints the message designated for a non response: "You did not make a choice..." Here's the strange part, though. On the feedback screen, the "TotalNow"/"TotalLater" variables display point values indicating that I DID make a key response, even though the "feedback" text variable reports that I didn't. Further, the next trial shows the updated "amount" variable correctly.

Therefore, there seems to be some disconnect between the key response and the result shown by the "feedback" variable in the next routine. I suspect that the key response may be lagging. I suspect this because I have found that I am able to make two key responses in one trial (as evidenced by extra points appearing in the point total shown in the next routine). I have set the key response component to force the end of the routine, store only the first key, and discard any previous responses. Even with these settings, though, it is possible to make two responses.

Does anybody have ideas as to why these events are occurring? I'm puzzled by this myself. Any help is much appreciated.

-Ben

How to avoid an exception using the ternary conditional operator (or other) without a try/except?

Each of the Google review score elements (of which there are 20) on a page such as this:

enter image description here

is defined in XPath thus:

  //ol/div[2]/div/div/div[2]/div[i]/div/div[3]/div/a[1]/div/div/div[2]/div/span

For some reason, when I try fetch all 20 with the following XPath, only the review scores that are not 'No reviews' get returned:

In [20]: reviews = driver.find_elements_by_xpath("//ol/div[2]/div/div/div[2]/div[position() >= 1 and position() <= 20]/div/div[3]/div/a[1]/div/div/div[2]/div/span")

In [21]: [i.text for i in reviews]

Out[21]: 
[u'20 reviews',
 u'4 reviews',
 u'4 reviews',
 u'15 reviews',
 u'2 reviews',
 u'7 reviews',
 u'3 reviews',
 u'14 reviews',
 u'2 reviews',
 u'4 reviews',
 u'3 reviews',
 u'30 reviews',
 u'6 reviews',
 u'3 reviews',
 u'2 reviews']

If I try to fetch these 'No reviews' elements individually, I get:

NoSuchElementException: Message: Unable to locate element: {"method":"xpath","selector":"//ol/div[2]/div/div/div[2]/div[6]/div/div[3]/div/a[1]/div/div/div[2]/div/span"}
Stacktrace:
    at FirefoxDriver.prototype.findElementInternal_ (file:///var/folders/th/40phk7_13ng3_7zs1rg70plh0000gn/T/tmpoUEQvJ/extensions/fxdriver@googlecode.com/components/driver-component.js:10299)
    at FirefoxDriver.prototype.findElement (file:///var/folders/th/40phk7_13ng3_7zs1rg70plh0000gn/T/tmpoUEQvJ/extensions/fxdriver@googlecode.com/components/driver-component.js:10308)
    at DelayedCommand.prototype.executeInternal_/h (file:///var/folders/th/40phk7_13ng3_7zs1rg70plh0000gn/T/tmpoUEQvJ/extensions/fxdriver@googlecode.com/components/command-processor.js:12282)
    at DelayedCommand.prototype.executeInternal_ (file:///var/folders/th/40phk7_13ng3_7zs1rg70plh0000gn/T/tmpoUEQvJ/extensions/fxdriver@googlecode.com/components/command-processor.js:12287)
    at DelayedCommand.prototype.execute/< (file:///var/folders/th/40phk7_13ng3_7zs1rg70plh0000gn/T/tmpoUEQvJ/extensions/fxdriver@googlecode.com/components/command-processor.js:12229)

I need a way to populate a list or dict with all 20 review scores in one go, while keeping track of their position in the 20 results, and populating a value of 0 every time 'No Reviews' is encountered. I tried using the ternary conditional operator, but I obviously I will get the NoSuchElementException each time a review score is 'No Reviews', before the statement gets to say else 0:

In [30]: mydict[6] = driver.find_element_by_xpath("//ol/div[2]/div/div/div[2]/div[6]/div/div[3]/div/a[1]/div/div/div[2]/div/span").text if driver.find_element_by_xpath("//ol/div[2]/div/div/div[2]/div[6]/div/div[3]/div/a[1]/div/div/div[2]/div/span").text else 0

How can I check for the non-presence or presence of the element in question without triggering an exception?

foo(:bar) if foo(:bar) != 0 the rails-way?

I have this if-condition:

foo(:bar) if foo(:bar) != 0

and I asked myself if there is a better "rails-/ruby-way" to express this condition? (Without calling the foo(:bar) twice?)

Display else results in Out-Gridview for powershell

I am trying to get a list of servers and the last time they rebooted to show in a table. However if it doesn't respond to a ping, I just need it to show on the list. I can't seem to figure out how to get it to add to the table after else.

Import-CSV $Downtime | % {
if(Test-Connection $_.server -Quiet -count 1){
    Get-WmiObject Win32_OperatingSystem -ComputerName $_.server | `
    select @{LABEL="Name"; EXPRESSION = {$_.PSComputerName}}, @{LABEL="Last Bootup"; EXPRESSION = {$_.convertToDateTime($_.LastBootupTime)}}
    }
else{@{LABEL="Name"; EXPRESSION = {$_.server}}
    }
} | Out-GridView

I can always save the else results in a text file but this would be more convenient. Thank you!