Jan Karel Schreuder | 1 Sep 20:14 2014

python launcher

Until now I have used IDLE to write and run programs. I decided it was time to do it the hard way and use only a
Terminal and a plain text editor, TextWrangler. I have Python 3.4.1 and OS 10.8.5. When I run the script by
calling for the interpreter in the terminal with the script as the parameter (e.g. python3 shares.py), it
runs fine. This is the output:

corrupt record.....removed
corrupt record.....removed
corrupt record.....removed
['description', 'symbol', 'current price', 'number of units']
			 List shares
			 Buy shares
			 Sell shares
			 Update prices
ridfx 21.98 833.592135342 18322.36
dodfx 46.99 390.964829507 18371.44
dfsvx 36.87 499.060771965 18400.37
pplix 15.42 1189.216568817 18337.72
total 73431.89

However, when I run it by using the Python Launcher, this is the result:

corrupt record.....removed
corrupt record.....removed
corrupt record.....removed
['description', 'symbol', 'current price', 'number of units']
('\t\t\t', 'List shares')
('\t\t\t', 'Buy shares')
('\t\t\t', 'Sell shares')
('\t\t\t', 'Update prices')
('ridfx', '21.98', '833.592135342', 18322.36)
(Continue reading)

Whees Northbee | 1 Sep 17:20 2014
Picon

How to count vehicle? I'm trying but my code don't increasing..

Hello, I'm trying to counting vehicle, but I can't increasing it, I use python 2.7.6 and opencv 2.4.9
Here the code:

import cv2

bgsMOG = cv2.BackgroundSubtractorMOG2(500,30,True)
cap         = cv2.VideoCapture("d:\MOV_5680.avi")
counter    =0
if cap:
    while True:
        ret, frame = cap.read()

        if ret:
            fgmask = bgsMOG.apply(frame, None, 0.01)           
            cv2.line(frame,(20,170),(320,170),(175,175,0),1)
            contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

            ax1=20     #coordinate of line where vehicle will be count if intersect
            ay1=170
            ax2=320
            ay2=170

            try: hierarchy = hierarchy[0]
            except: hierarchy = []
            for contour, hier in zip(contours, hierarchy):
                (x,y,w,h) = cv2.boundingRect(contour)
                
                if w > 10 and h > 15: 
                    cv2.rectangle(frame, (x,y), (x+w,y+h), (180, 0, 0), 1)
                      
                    x1=w/2      #to find centroid
                    y1=h/2
                    cx=x+x1
                    cy=y+y1
                    centroid=(cx,cy)
                    cv2.circle(frame,(int(cx),int(cy)),1,(0,255,0),-1)
                    

                    dy=cy-170   #my first try to increase counter, not work 
                    if dy==0:
                        if (cx<=320)and(cx>=70):
                            counter=counter+1

                    if cy==170:   #my second try to increasing, not work too
                         counter=counter+1

                            
            cv2.putText(frame, str(counter),(10,150), cv2.FONT_HERSHEY_SIMPLEX,2, (255, 0, 0), 1, True)                   
            cv2.imshow('Output', frame)
            cv2.imshow('FGMASK', fgmask)


            key = cv2.waitKey(100)
            if key == ord('q'):
                break
cap.release()
cv2.destroyAllWindows()



don't have error but I can't increasing the counter, please help me..
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Whees Northbee | 1 Sep 17:13 2014
Picon

How to count vehicle? I'm trying but my code don't increasing..

Hello, I'm trying to counting vehicle, but I can't increasing it, I use python 2.7.6 and opencv 2.4.9
Here the code:

import cv2

bgsMOG = cv2.BackgroundSubtractorMOG2(500,30,True)
cap         = cv2.VideoCapture("d:\MOV_5680.avi")
counter    =0
if cap:
    while True:
        ret, frame = cap.read()

        if ret:
            fgmask = bgsMOG.apply(frame, None, 0.01)           
            cv2.line(frame,(20,170),(320,170),(175,175,0),1)
            contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

            ax1=20     #coordinate of line where vehicle will be count if intersect
            ay1=170
            ax2=320
            ay2=170

            try: hierarchy = hierarchy[0]
            except: hierarchy = []
            for contour, hier in zip(contours, hierarchy):
                (x,y,w,h) = cv2.boundingRect(contour)
                
                if w > 10 and h > 15: 
                    cv2.rectangle(frame, (x,y), (x+w,y+h), (180, 0, 0), 1)
                      
                    x1=w/2      #to find centroid
                    y1=h/2
                    cx=x+x1
                    cy=y+y1
                    centroid=(cx,cy)
                    cv2.circle(frame,(int(cx),int(cy)),1,(0,255,0),-1)
                    

                    dy=cy-170   #my first code to increase counter 
                    if dy==0:
                        if (cx<=320)and(cx>=70):
                            counter=counter+1

                    if cy==170:

                            
            cv2.putText(frame, str(counter),(10,150), cv2.FONT_HERSHEY_SIMPLEX,2, (255, 0, 0), 1, True)                   
            #cv2.namedWindow('Output',cv2.cv.CV_WINDOW_NORMAL)
            #cv2.resizeWindow('Output',320,180)
            cv2.imshow('Output', frame)
            cv2.imshow('FGMASK', fgmask)


            key = cv2.waitKey(100)
            if key == ord('q'):
                break
cap.release()
cv2.destroyAllWindows()

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
jarod_v6@libero.it | 1 Sep 16:58 2014
Picon

python pipeline

Dear all,
I'll try to write a pipeline starting from a csv file where I write the name 
and the path of my files.
example.csv
Name,FASTQ1,FASTQ2,DIRECTORY
sampleA,A_R1_.fastq.gz,A_R2_.fastq.gz,108,~/FASTQ/
sampleB,B_R1_.fastq.gz,B_R2_.fastq.gz,112,~/FASTQ/


On that list I need to send each time 3 different script whic are depend one 
to the other. So I need to run1 and only whe it finisched start the second and 
then the 3.
One of the problems teach script write the output only in the same directory 
where I launch the program so I need to create. I set the output directory and 
the I want to obtain  this folder view
.
├── sampleA
│   ├── ref.txt
│   └── second
└── sampleB
    ├── ref.txt
    └── second
I have problems on how to move in different folder  and how can use subprocess 
for execute all.
Any idea in how can I do this?

def Staralign(file,pos):
		import subprocess

		global Path             
		global Read1
		global Read2    
		global Nome
		global label
		Read1 = []
		Read2 = []
		Nome = []
		Path = []
		label = []
		with open(file) as p:
			for i in p:
				lines = i.rstrip("\n").split(",")
				if lines[0] != "Name":
					Path.append(lines[10])
					Nome.append(lines[0])
					Read1.append(lines[7])
					Read2.append(lines[8])
		out = open("toRun.sh","w")
		out.write("#!/bin/bash\n")
		global pipe
		pipe =[]
		dizionario = {}
		for i in range(len(Nome)):
			dx =str("".join(Path[i])+ "/"+ "".join(Read1[i]))
			sn =str("".join(Path[i])+"/"+"".join(Read2[i]))
			if not os.path.exists(pos+"/"+i):
				os.makedirs(pos+"/"+i)
			print >>out, "cd " + pos +"\n"
			
			print  >>out,"~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --genomeDir 
/home/sbsuser/databases/Starhg19/GenomeDir/ --runMode alignReads --readFilesIn 
"+ dx  +" "+ ""+ sn +"   --runThreadN 12  --readFilesCommand zcat " +"\n"
			step_1_out =["~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --genomeDir 
/home/sbsuser/databases/Starhg19/GenomeDir/ --runMode alignReads --readFilesIn %
s   %s  --runThreadN 12  --readFilesCommand zcat "%(dx,dn)]
			print  >>out,"cd " +"  $PWD"+"/"+ "hg19_second/" +"\n"

			print  >>out,"~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --runMode 
genomeGenerate --genomeDir"+"  $PWD"+"/"+ "hg19_second/  --genomeFastaFiles 
~/databases/bowtie2Database/hg19.fa --sjdbFileChrStartEnd " +"$PWD"+"/"+ "SJ.
out.tab" +" --sjdbOverhang 49   --runThreadN 12" +"\n"
			pipe.append("~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --genomeDir 
/home/sbsuser/databases/Starhg19/GenomeDir/ --runMode alignReads --readFilesIn 
"+ dx  +" "+  ""+ sn +"   --runThreadN 12  --readFilesCommand zcat ")
			print  >>out,"cd  .." + "\n"
			print  >>out,"~/software/STAR_2.3.0e.Linux_x86_64_static/STAR --genomeDir"+ 
"  $PWD"+"/"+ "hg19_second/GenomeDir/  --runMode alignReads --readFilesIn "+ 
dx  +" "+ ""+ sn +"   --runThreadN 12  --readFilesCommand zcat " +"\n"
			dizionario.setdefault()
#	return Nome,Path,Read1,Read1

This isthe function I wrote but with this way I'm only able to write a bash 
script..

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Albert-Jan Roskam | 1 Sep 15:54 2014

abc module question

Hi,

I was playing with abc for the first time (never ever had any use for it). It works nicely with methods and properties.
But is there also a way to enforce that class Concrete has an attribute 'foo' of type 'list'? I could of course
write a 'foo' property, but I was hoping there was a direct way,

import sys
import abc

class Abstract(object):
    __metaclass__ = abc.ABCMeta

     <at> abc.abstractmethod    
    def __init__(self):
        pass
     <at> abc.abstractmethod
    def __getitem__(self, key):
        raise NotImplementedError("__getitem__ method required!")
     <at> abc.abstractproperty
    def encoding(self):
        raise NotImplementedError("encoding property required!")
     <at> abc.abstractproperty
    def foo(self):
        assert isinstance(self.foo, list)

class Concrete(Abstract):
    def __init__(self):
        self.foo = []  # it could be solved by making foo a property
    def __getitem__(self, key):
        pass
     <at> property
    def encoding(self):
        return "some encoding"

c = Concrete()

Traceback (most recent call last):
  File "C:\TEMP\abc_foo.py", line 46, in <module>
    c = Concrete()
TypeError: Can't instantiate abstract class Concrete with abstract methods foo

Regards,

Albert-Jan

PS: Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation,
roads, a 

fresh water system, and public health, what have the Romans ever done for us?

                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Juan Christian | 1 Sep 02:12 2014
Picon

Good Text Editor/IDE for Python

I've been using PyCharm to code in Python but it seems a bit "overpowered" for this task, and there are some annoying bugs. I used Sublime Text 2 in the past, but it seems to be dead now (last update was JUN/2013), so I don't really know any good options.

What do you guys use to code?
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Albert-Jan Roskam | 31 Aug 22:17 2014

how import a module upon instantiation of a class?

Hi,

I want to import a module upon instantiation (not definition) of a class. What is the best way to do this? In my
case, I need the "icu" module in only one place/class of the program. If that class won't be used, I don't
want to have an ImportError. Also, it might be nice to do the imports only when you actually need that
functionality. It's probably not really PEP-compliant to put the imports somewhere else than at the top
of the module, but I can live with that.

import some_nonbuiltin  # I don't want it here!

class KlassA(object):
    import some_nonbuiltin  # nope

    def __init__(self):
        some_nonbuiltin = __import__("some_nonbuiltin") # idem

        x = some_nonbuiltin.blah()

class KlassB(object):
    """some_nonbuiltin not needed here! """

    def __init__(self):
        pass

 
Regards,

Albert-Jan

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation,
roads, a 

fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Richard Dillon | 31 Aug 18:31 2014
Picon
Picon

This is driving my crazy! My file hasn't been corrupted

My text file has five numbers, 1-5
I don't what the problem is.
I've written the file using Word (saved as .txt ) as well as TextEdit
Python 3.4.1 on a Mac

Here's the code:

#   Richard Dillon

#   This program reads data from a .txt file and calculates a total
#   data in text file: 1,2,3,4 and 5 for a total of 15
#   error message: Non-numeric data found in the file

def main():

    
    total = 0.0

    try:

        infile = open('/Users/richarddillon/Desktop/numbers.txt', 'r')

        for line in infile:
            amount = float(line)
            total += amount

        infile.close()

        print(format(total, ',.2f'))

    except IOError:
        print('An error occured trying to read the file.')

    except ValueError:
        print('Non-numeric data found in the file.')

    except:
        print('An error occured.')

main()
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

LN A-go-go | 31 Aug 19:28 2014

calculate percents of items in a list


What would be a better way to calculate percentages of items in a list?
please....

CountList = [9221382, 10374466, 5192905, 1710238, 3359]
CL = [float(i) for i in CountList]
CL
sum = CL[0] + CL[1] + CL[2] + CL[3] + CL[4]
import math
perList = []
n = 0
def percentage(CL,sum):
 for i in CL:
     PER = "return 100 * float (CL[0])/float (sum)"
     perList.append(PER)
     n = n + 1
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Crush | 31 Aug 04:32 2014
Picon

Re: Tutor Digest, Vol 126, Issue 86

Thank you Allan for your criticism. Please see the below changes. As far as the embedded loops, I know no
other way to achieve the same out come. 

def kill_proc(process1, process2):
   i = psutil.Popen(["ps", "cax"], stdout=PIPE)
   out, err = i.communicate()
   for proc in psutil.process_iter():
       if proc.name == process1 and process2:
           proc.kill()

while True:
   while count < 15:
       count += 1
       kill_proc("bmdplay", "avconv")
       print "Starting the script", count
       time.sleep(2)
       p = subprocess.Popen("/Downloads/bmdtools/test_loop.sh",
shell=True, stderr=PIPE)
       for line in p.stderr:
           print line
           if "Segmentation" in line:
               kill_proc("bmdplay", "avconv")
               while restart < 3:
                   restart += 1
                   time.sleep(2)
                   q =
subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True,
stderr=PIPE)
                   for line in q.stderr:
                       print line
                       if restart == 3:
                       # send email saying so
                           sys.exit()
           if "storing 0x" in line:
               kill_proc("bmdplay", "avconv")
               while restart < 3:
                   restart += 1
                   sleep.time(2)
                   r =
subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True,
stderr=PIPE)
                   for line in r.stderr:
                       print line
                   if restart == 3:
                       # send email saying so
                       sys.exit()
       if count == 10:
           print "Going to sleep, will try again in..."
           #send email saying so
           time.sleep(2)
       if count == 15:
           # send email saying so
           print "Gave up"
           break
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Bo Morris | 31 Aug 00:31 2014
Picon

interacting with stderr

Here is my working code. It works great in the lab, but I still need to test it on a live system. I also need to add the email notifications to it, but I purposely left them out for now; I will also adjust the sleep time to a more appropriate amount. Anyone see any issues with it or ways to make it better?

  #!/usr/bin/env python

import subprocess
from subprocess import PIPE
import time
import psutil
import sys

count = 0
restart = 0

def kill_proc(process1, process2):
    i = psutil.Popen(["ps", "cax"], stdout=PIPE)
    out, err = i.communicate()
    for proc in psutil.process_iter():
        if proc.name == process1 and process2:
            proc.kill()

while True:
    while count < 15:
        count += 1
        kill_proc("bmdplay", "avconv")
        print "Starting the script", count
        time.sleep(2)
        p = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE)
        for line in p.stderr:
            print line
            if "Segmentation" in line:
                kill_proc("bmdplay", "avconv")
                while restart < 3:
                    restart += 1
                    time.sleep(2)
                    p = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE)
                    for line in p.stderr:
                        print line
                        if restart == 3:
                        # send email saying so
                            sys.exit() 
            if "storing 0x" in line:
                kill_proc("bmdplay", "avconv")
                while restart < 3:
                    restart += 1
                    sleep.time(2)
                    p = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE)
                    for line in p.stderr:
                        print line
                    if restart == 3:
                        # send email saying so
                        sys.exit()
        if count == 10:
            print "Going to sleep, will try again in..."
            #send email saying so
            time.sleep(2)
        if count == 15:
            # send email saying so
            print "Gave up"
            break
    break
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Gmane