Re: [Tutor] working with c_byte?

2012-03-23 Thread Dave Angel

On 03/24/2012 01:10 AM, Alex Hall wrote:

Thanks, the&  (bitwise operator) trick seems to be promising. Should I
still mod by 256? If so, could you explain why, since the value cannot
exceed 127? Also, how does that work if a possible vlaue is 255,
according to the documentation?



You top-posted, which loses all earlier context.  Please put your 
response *after* whatever you're quoting.


I gave several possibilities;  you should use whichever seems to make 
the code clearest to you.  I think using a c_ubyte is the most 
straightforward.  That has values from 0 to 255, so it'd match the 
documentation.


But if you're sticking with c_byte, you have a signed value.  So the 
docs lie about the range being 0 to 255.  Or maybe they're written for 
some other language.  If you want to explicitly get the values 0 to 255, 
you can use the expression I provided, using modulo 256.


But the & operator doesn't care a bit.  (no pun intended).  You can use 
it on signed or on unsigned, or on unsigned modulo-ed data.  No change.


This all assumes you're running on a twos-complement processor, like the 
Intel Pentium.  If you're on ones-complement, half this stuff breaks, 
and the other half doesn't work very well.  Bit twiddling is quite 
processor specific.  Fortunately for us, the vast majority of machines 
these days use twos-complement.


One other thing:  these problems are not specific to Python.  I spent 
quite a while 15 years ago teaching a Java developer how to deal with 
similar issues.  At that time at least, Java didn't even have unsigned 
bytes.


--

DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with c_byte?

2012-03-23 Thread Alex Hall
Thanks, the & (bitwise operator) trick seems to be promising. Should I
still mod by 256? If so, could you explain why, since the value cannot
exceed 127? Also, how does that work if a possible vlaue is 255,
according to the documentation?

On 3/24/12, Dave Angel  wrote:
> On 03/23/2012 11:51 PM, Alex Hall wrote:
>> Hi all,
>> I am trying to read battery information. I found an example that sets
>> up a ctypes structure to get the information from a kernel call, and
>> it works... except that I just realized the values of some fields are
>> added. For instance, a value of 1 means that the battery is "high",
>> and 8 means it is charging. I didn't realize until just now that
>> Windows will give both of these to me as 9, so the dict I set up to
>> see what the value is won't work. Similarly, a value of 255 is always
>> seen in Python as -128, even if I multiply it by -1 to flip it.
>
> Don't multiply by -1, simply convert to an int, and use modulo 256 to
> get it to a positive value.
>  newval = int(cbyte) % 256
>
> Or perhaps use c_ubyte instead of c_byte to get unsigned values in the
> first place.
>
> A signed value uses the highest bit to indicate a negative value.  For
> an 8 bit signed value, the values range from -128 to 127.  There is no
> positive value above 127, so multiplying by -1 is the wrong answer.
> Besides if there are other bits in the byte, they'll get changed as
> well.  The modulo trick won't affect any of the 8 bits, only their
> interpretation.
>
>>   The
>> value I'm working with is a ctypes.c_byte. Here is the data structure:
>> class SYSTEM_POWER_STATUS(ctypes.Structure):
>>   _fields_=[
>>("ACLineStatus", ctypes.c_byte),
>>("BatteryFlag", ctypes.c_byte),
>>("BatteryLifePercent", ctypes.c_byte),
>>("Reserved1", ctypes.c_byte),
>>("BatteryLifeTime", ctypes.wintypes.DWORD),
>>("BatteryFullLiveTime", ctypes.wintypes.DWORD)
>>   ]
>>
>> and here is my dict to use when looking up the meaning of the BatteryFlag:
>> status_constants = {
>>   1:"high",
>>   2:"low",
>>   4:"critical",
>>   8:"charging",
>>   128:"no system battery",
>>   -128:"no system battery", #hack to get around odd negation of 128
>> flag... how to fix?
>>   255:"unknown"
>> }
>>
>
> cbyte & 1   will be nonzero (1) if that one "high" flag is set,
> regardless of the others.
> cbyte & 2will be nonzero (2) if  "low", and so on.
>
> for flag in 1,2,4,8,16,32,64,128:
>if cbyte & flag:
>   print  status_constants[cbyte & flag]
>
>
>> Of course, 9 means the battery is high and charging, but how do I
>> interpret an arbitrary integer as the sum of its flags? Is there a
>> binary trick I can use? I could record all the 1s in the binary number
>> and look up their positions... but is there a simpler way? If I do
>> that, where is the sign bit in c_byte? TIA.
>>
>>
>
> As I said earlier, the sign bit is 128, the highest bit in the byte.
> The number is 2's complement, which is why you must use modulo to
> convert it, not multiplication by -1.  The latter approach would work if
> the machine used ones complement.
>
> --
>
> DaveA
>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with c_byte?

2012-03-23 Thread Dave Angel

On 03/23/2012 11:51 PM, Alex Hall wrote:

Hi all,
I am trying to read battery information. I found an example that sets
up a ctypes structure to get the information from a kernel call, and
it works... except that I just realized the values of some fields are
added. For instance, a value of 1 means that the battery is "high",
and 8 means it is charging. I didn't realize until just now that
Windows will give both of these to me as 9, so the dict I set up to
see what the value is won't work. Similarly, a value of 255 is always
seen in Python as -128, even if I multiply it by -1 to flip it.


Don't multiply by -1, simply convert to an int, and use modulo 256 to 
get it to a positive value.

newval = int(cbyte) % 256

Or perhaps use c_ubyte instead of c_byte to get unsigned values in the 
first place.


A signed value uses the highest bit to indicate a negative value.  For 
an 8 bit signed value, the values range from -128 to 127.  There is no 
positive value above 127, so multiplying by -1 is the wrong answer.  
Besides if there are other bits in the byte, they'll get changed as 
well.  The modulo trick won't affect any of the 8 bits, only their 
interpretation.



  The
value I'm working with is a ctypes.c_byte. Here is the data structure:
class SYSTEM_POWER_STATUS(ctypes.Structure):
  _fields_=[
   ("ACLineStatus", ctypes.c_byte),
   ("BatteryFlag", ctypes.c_byte),
   ("BatteryLifePercent", ctypes.c_byte),
   ("Reserved1", ctypes.c_byte),
   ("BatteryLifeTime", ctypes.wintypes.DWORD),
   ("BatteryFullLiveTime", ctypes.wintypes.DWORD)
  ]

and here is my dict to use when looking up the meaning of the BatteryFlag:
status_constants = {
  1:"high",
  2:"low",
  4:"critical",
  8:"charging",
  128:"no system battery",
  -128:"no system battery", #hack to get around odd negation of 128
flag... how to fix?
  255:"unknown"
}



cbyte & 1   will be nonzero (1) if that one "high" flag is set, 
regardless of the others.

cbyte & 2will be nonzero (2) if  "low", and so on.

for flag in 1,2,4,8,16,32,64,128:
  if cbyte & flag:
 print  status_constants[cbyte & flag]



Of course, 9 means the battery is high and charging, but how do I
interpret an arbitrary integer as the sum of its flags? Is there a
binary trick I can use? I could record all the 1s in the binary number
and look up their positions... but is there a simpler way? If I do
that, where is the sign bit in c_byte? TIA.




As I said earlier, the sign bit is 128, the highest bit in the byte.  
The number is 2's complement, which is why you must use modulo to 
convert it, not multiplication by -1.  The latter approach would work if 
the machine used ones complement.


--

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] working with c_byte?

2012-03-23 Thread Alex Hall
Hi all,
I am trying to read battery information. I found an example that sets
up a ctypes structure to get the information from a kernel call, and
it works... except that I just realized the values of some fields are
added. For instance, a value of 1 means that the battery is "high",
and 8 means it is charging. I didn't realize until just now that
Windows will give both of these to me as 9, so the dict I set up to
see what the value is won't work. Similarly, a value of 255 is always
seen in Python as -128, even if I multiply it by -1 to flip it. The
value I'm working with is a ctypes.c_byte. Here is the data structure:
class SYSTEM_POWER_STATUS(ctypes.Structure):
 _fields_=[
  ("ACLineStatus", ctypes.c_byte),
  ("BatteryFlag", ctypes.c_byte),
  ("BatteryLifePercent", ctypes.c_byte),
  ("Reserved1", ctypes.c_byte),
  ("BatteryLifeTime", ctypes.wintypes.DWORD),
  ("BatteryFullLiveTime", ctypes.wintypes.DWORD)
 ]

and here is my dict to use when looking up the meaning of the BatteryFlag:
status_constants = {
 1:"high",
 2:"low",
 4:"critical",
 8:"charging",
 128:"no system battery",
 -128:"no system battery", #hack to get around odd negation of 128
flag... how to fix?
 255:"unknown"
}

Of course, 9 means the battery is high and charging, but how do I
interpret an arbitrary integer as the sum of its flags? Is there a
binary trick I can use? I could record all the 1s in the binary number
and look up their positions... but is there a simpler way? If I do
that, where is the sign bit in c_byte? TIA.


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Library of Module for Analyzing Answer Cards

2012-03-23 Thread Emile van Sebille

On 3/22/2012 11:45 AM Khalid Al-Ghamdi said...

Hi All,

I work in in academic testing environment and we employ expensive
machines to scan answer sheets (the ones where you blacken the letter of
the correct multiple choice answer). Anyway, I was thinking if there was
a way we could use regular old scanners to scan the sheets than analyze
the images to score the tests.

Do you know any modules or libraries in python that can be helpful in
that? Also, what approach if any would you employ to tackle this project?



For quick production deployment, I'd check out Bob's suggestion.

If I were going to write a python based solution I'd start with PIL (see 
http://www.pythonware.com/products/pil/)


I haven't tried doing something quite as detailed as what you're 
describing, but I do have PIL doing image analysis, cropping and 
resizing on an automated basis in a production environment.


I think I'd examine the scanned image for a location marker, then from 
that and an answer template that provides the answer box locations, 
locate the answer box area for each question in turn and identify the 
filled in multiple choice response.


HTH,

Emile



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python arthematics

2012-03-23 Thread Prasad, Ramit
Please reply to the list (or at least include it) and not just 
the person responding.

> i have tried upto two varibles but i want it to extend to mny more . I
> just need an idea. i have tried like this
> a=int(raw_input())
> b=int(raw_input())
> print "please enter operator"
> operator=raw_input()
> if operator == "+":
> c=a+b
> print c
> elif operator == "-":
> c=a-b
> print c
> elif operator == "/":
> c=a/b
> print c
> elif operator == "*":
> c=a*b
> print c

The easiest thing to do would be to put this in a loop and use 
the result as 'a'. This would not help with order of operations, 
but you can leave that to the user. Dumb, but much like a non-
scientific calculator.

Alan has already provided you with other options, but be warned
they are not beginner-level projects.

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python arthematics

2012-03-23 Thread Francesco Loffredo



Sukhpreet Sdhu wrote:

i want to write a program that reads simple arithematic epressions and 
calculates the result.
for example input "1*3+2" should generate "5'" as result

I'm happy to learn somebody else took the same path that I did to learn Python!

First of all, a disclaimer: I'm NOT pretending that my program is perfect or that it cannot be improved in many ways; feel free to 
show me all my mistakes!


I tried (and I think I succeeded) to build a "school calculator" that solves any arithmetic expression the same way that we were 
asked to at school.
If you use a calculator, it just gives you the final result, but it doesn't show all the intermediate steps, and I addressed just 
that problem.

I don't want to tell you exactly how I did it, but I'll give you some hints. 
First, the general look of the program:

 
transcript of a real session
Insert expression: {[(3+2)^2*2+5]:10}x3+1


 --- Normalizing Expression ---

from  {[(3+2)^2*2+5]:10}x3+1
to  (((3+2)^2*2+5)/10)*3+1


--- SOLUTION ---

(((3+2)^2*2+5)/10)*3+1 =

= ((5^2*2+5)/10)*3+1 =

= ((25*2+5)/10)*3+1 =

= ((50+5)/10)*3+1 =

= (55/10)*3+1 =

= 5.5*3+1 =

= 16.5+1 =

= 17.5 ... solved!

Press just Enter to finish, or
Insert expression:
end of 
transcript---

As you can see, it's very close to what you want, if not exactly that.

The main loop is really trivial, it just calls repeatedly the main expression solver function. It could be changed to include the 
input prompt, to let E() process strings from any source, but for now it just does

--
while E():
  print "Press just Enter to finish, or"
-

E()  is the interesting function, of course. After the input prompt:

-  it calls a function that "normalizes" the input string, to allow for some symbols Python cannot use in math expressions, but 
often used by little students. For example, you could enter "2 x 2 : 4" and Python must read "2*2/4". Or you could use graphically 
different parentheses: {} or [] instead of (), or you could enter any number of spaces to make the expression more human-readable 
This normalization seems just cosmetic, but it also solves a syntactical problem with raising to a power, as I'll explain later.


- it recognizes the innermost parenthesis (this can be tricky, but you'll have 
to discover yourself)

- it extracts the contents of that parenthesis in a string

- it repeats calling a function that
- extracts from the given string the highest-priority operation
- calculates the result of that operation (!)
- returns the string with the result substituted for the operation
- until the string just contains a number (!!)

- substitutes the number for the parenthesis in the expression

- records the simplified expression in a list

- starts over, until there are no more operations to calculate and the 
expression has become a single number (!!)

- prints out the list (this could be moved in the main loop with the input 
prompt, but again I'm too lazy for that ;-) )


I found some problems in the points with exclamation marks, and I'll give you 
some hints about those, too:

(!) - I use exec() to calculate the operation (after having thoroughly checked the input, so there's no security problem!), but I 
had to build special functions for division and for raising to a power. I wanted division to return an integer quotient whenever 
possible (both numbers a and b  are integer, and a%b == 0), and a float otherwise. So I wrote the divok() function. Raising to a 
power is written "a ** b" in Python, but my simple parser cannot tell this from a double multiplication symbol, a syntax error. 
That's why I used ^ as a power symbol, and I also changed ** into ^ in my normalization routine to allow for the correct syntax. 
Python, of course, still needs **, so I wrote the powok() function to calculate a**b when it receives a^b.


(!!) - The built-in s.isdigit() string method can be easily used to tell if a string is a number, but it fails recognizing negative 
and floating point numbers:

>>> a = "7876787564"
>>> a.isdigit()
True
>>> a = "7876787.564"
>>> a.isdigit()
False
>>> a = "-7876"
>>> a.isdigit()
False
That's why I wrote younumber() that returns True in the three above cases, and 
behaves like isdigit() otherwise.

Hope this can be a good starting point for your project.

Francesco



-
Nessun virus nel messaggio.
Controllato da AVG - www.avg.com
Versione: 2012.0.1913 / Database dei virus: 2114/4886 -  Data di rilascio: 
22/03/2012___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor