text
stringlengths
226
34.5k
Rounding logic in Python? Question: In my original code I was trying to compute some indices out of some float values and I faced the following problem: >>> print int((1.40-.3)/.05) 21 But: >>> print ((1.40-.3)/.05) 22.0 I am speechless about what is going on. Can somebody please explain? Answer: This is caused by floating point inaccuracy: >>> print repr((1.40-.3)/.05) 21.999999999999996 You could try using the `Decimal` type instead: >>> from decimal import Decimal >>> Decimal <class 'decimal.Decimal'> and then >>> (Decimal('1.40') - Decimal('.3')) / Decimal('.05') Decimal('22') The `fractions.Fraction` class would work too. Or, you could just round: >>> round((1.40-.3)/.05, 10) # round to 10 decimal places 22.0
How can I access a file in a completely different directory based on absolute path (Python) Question: import os test = os.path.exists("c:/conf.txt") if test == False: with open("c:/conf.txt", "w") as Inc: Inc.write("0") Inc.close() quit() if test == True: f = open("c:/conf.txt", 'r') b = int(f.readline()) b +=1 with open("c:/conf.txt", 'w') as writeinc: writeinc.write(str(b)) writeinc.close() using `open(c:/conf.txt)` doesn't work (also tried c:\\.) I get the following error message: IOError: [Errno 22] invalid mode ('w') or filename: 'c:/conf.txt' Is there a way to access a different directory using `open()` according to absolute path rather than relative? Answer: Sounds to me like you don't have permission to write to the root path of your drive. In Windows 7 and 8, you cannot create files in the root directory: > In Windows 7 or 8 (may be Vista), users (even administrators) are not > allowed to create files in the C drive root directory, otherwise, an error > message like “A required privilege is not held by the client” or “access is > denied” will be prompted. [Source](http://www.mkyong.com/computer-tips/cant-create-file-in-the-c-drive- root-directory-windows-8/) The article goes on how to modify the registry if you want to get around this restriction. > 1. Press keys “Windows Key + R”, type regedit > 2. Locate > HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA > 3. Update the EnableLUA value to 0 (turn if off) > 4. Restart Windows. >
StatementError: SQLite Date type only accepts Python date objects as input Question: I am using Flask-Security, the code seems fine, but when inserting a data from register view it gives the bellow error. Since I made SECURITY_TRACKABLE = True I added some extra fields in my models and the problem might be there :( sqlalchemy.exc.StatementError StatementError: SQLite Date type only accepts Python date objects as input. (original cause: TypeError: SQLite Date type only accepts Python date objects as input.) 'INSERT INTO user (name, surname, email, password, birth_date, active, confirmed_at, last_login_at, current_login_at, last_login_ip, current_login_ip, login_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' [{'surname': u'Example', 'name': u'Test', 'confirmed_at': None, 'login_count': None, 'last_login_ip': None, 'active': True, 'last_login_at': None, 'current_login_at': None, 'birth_date': u'1989-04-27', 'password': '$6$rounds=100000$yvVNKKdF5OFZY4Ur$bOpszUhnYVeMkY1fNwkjEcsA.BzOGCyelnPq9eKqmJFoTJ52Zd5cngYDqFQaPTZwSHoFq851IWGbl/gTqEUC1.', 'email': u'[email protected]', 'current_login_ip': None}] here is the form that I wrote to extend my RegisterForm: from wtforms.validators import Required from werkzeug.security import generate_password_hash, \ check_password_hash # to override the default RegisterForm from flask_security.forms import RegisterForm, ConfirmRegisterForm, Form,\ TextField, BooleanField, \ PasswordField, validators from flask.ext.security import Security, SQLAlchemyUserDatastore class LoginForm(Form): """this class is used for user access to the web application""" username = TextField('username', validators = [Required()]) password = PasswordField('password', validators = [Required()]) remember_me = BooleanField('remember_me', default = False) #unhash the password def password_unhash(self, hashed_passw, submited_passw): return check_password_hash(hashed_passw, submited_passw) class ExtendedConfirmRegisterForm(ConfirmRegisterForm): name = TextField('Name', [validators.Length(max=255), validators.Required()]) surname = TextField('Surname', [validators.Length(max=255)]) birth_date = TextField('Date of birth', [validators.Length(max=10)]) class ExtendedRegisterForm(RegisterForm): """RegisterForm class needed for retrieving data from user""" #returns false if the email exists def email_unique(self, email): if models.User.query.\ filter_by(email = email).\ first() != None: self.email.errors.\ append('This E-mail address is already in use. ' 'Please choose another one.') return False else: return True this is my models.py: from app import db from flask.ext.security import UserMixin, RoleMixin #association table that stores users and their roles roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) #orm table that stores information on roles class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin): """a class that used to create ORM Database and objects related to the class""" id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(255)) surname = db.Column(db.String(255)) email = db.Column(db.String(255), unique = True) password = db.Column(db.String(255)) birth_date = db.Column(db.Date) active = db.Column(db.Boolean()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) #SECURITY_CONFIRMABLE confirmed_at = db.Column(db.DateTime()) #SECURITY_TRACKABLE last_login_at = db.Column(db.DateTime()) current_login_at = db.Column(db.DateTime()) last_login_ip = db.Column(db.String(40)) current_login_ip = db.Column(db.DateTime()) login_count = db.Column(db.Integer(6)) Answer: You have a `birth_date` column but used a text field in the form. Flask- Security uses [WTForms](http://wtforms.readthedocs.org/en/latest/) for the form definitions; it has a dedicated [`DateField` type](http://wtforms.readthedocs.org/en/latest/fields.html#wtforms.fields.DateField) which I think should be used instead: from wtforms.fields import DateField class ExtendedConfirmRegisterForm(ConfirmRegisterForm): name = TextField('Name', [validators.Length(max=255), validators.Required()]) surname = TextField('Surname', [validators.Length(max=255)]) birth_date = DateField('Date of birth')
Why is requests.get() retrieving different HTML using Python than browser? Question: I am attempting to extract data from an HTML table, but it appears that the HTML isn't loading correctly when using `requests.get()`. Instead, a line in the source reads: > "JavaScript is not enabled and therefore this page may not function > correctly." When I navigate to the page in Google Chrome, the HTML appears as it should. How do I get a Python script to load the proper HTML? Answer: Welcome to the wonderful world of web-crawling. The problem you are experiencing is that `requests.get()` would just get you the initial page that the browser receives at the beginning of a page load. But, this is not the page you see in the browser since there could be so much involved in forming the web page: javascript function calls, AJAX calls etc. If you want to programmatically get the HTML you see when you click "Show source" in a web browser after the page was loaded - you would need a real browser. This is there [`selenium`](http://selenium-python.readthedocs.org/) could be a good option: from selenium import webdriver browser = webdriver.Firefox() browser.get(url) print browser.page_source Note that `selenium` itself is very powerful in terms of [locating elements](http://selenium-python.readthedocs.org/locating-elements.html) \- you don't need a separate HTML parser for extracting the data out of the page. Hope that helps.
Porting algorithm from Python to Go Question: I am trying to port this python code to Go but there is no **beta()** in math package. Where can i find beta and other functions required for this? from numpy import * from scipy.stats import beta class BetaBandit(object): def __init__(self, num_options=2, prior=(1.0,1.0)): self.trials = zeros(shape=(num_options,), dtype=int) self.successes = zeros(shape=(num_options,), dtype=int) self.num_options = num_options self.prior = prior def add_result(self, trial_id, success): self.trials[trial_id] = self.trials[trial_id] + 1 if (success): self.successes[trial_id] = self.successes[trial_id] + 1 def get_recommendation(self): sampled_theta = [] for i in range(self.num_options): #Construct beta distribution for posterior dist = beta(self.prior[0]+self.successes[i], self.prior[1]+self.trials[i]-self.successes[i]) #Draw sample from beta distribution sampled_theta += [ dist.rvs() ] # Return the index of the sample with the largest value return sampled_theta.index( max(sampled_theta) ) Answer: If you are talking about [`numpy.random.beta`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html), the Beta distribution which is a special case of the Dirichlet distribution, and is related to the Gamma distribution, you can check the project [**`gostat`**](https://code.google.com/p/gostat/). It has a [`beta.go` source code](https://code.google.com/p/gostat/source/browse/stat/beta.go) which implements that function.
Biopython SeqIO processing NNNNN in *.ab1 files Question: Thanks for your help. I apologize in advance if there is a function built into Biopython that handles this, I read the whole manual and couldn't find anything. **Goal:** Read in a raw sequencing file (*.ab1) and process using sequence.seq.translate(11) However, I get this error - "Bio.Data.CodonTable.TranslationError: Codon 'NNN' is invalid" **My Solution:** I added an additional table to the CodonTable and commented out the ambiguous checker in Bio.Data.CodonTable (had to do this to make it work) register_ncbi_table( name = 'bacteria sequencing table', alt_name = None, id = 24, table = { 'TTT': 'F', 'TTC': 'F', 'TTA': 'L', 'TTG': 'L', 'TCT': 'S', 'TCC': 'S', 'TCA': 'S', 'TCG': 'S', 'TAT': 'Y', 'TAC': 'Y', 'TGT': 'C', 'TGC': 'C', 'TGG': 'W', 'CTT': 'L', 'CTC': 'L', 'CTA': 'L', 'CTG': 'L', 'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P', 'CAT': 'H', 'CAC': 'H', 'CAA': 'Q', 'CAG': 'Q', 'CGT': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'ATT': 'I', 'ATC': 'I', 'ATA': 'I', 'ATG': 'M', 'ACT': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T', 'AAT': 'N', 'AAC': 'N', 'AAA': 'K', 'AAG': 'K', 'AGT': 'S', 'AGC': 'S', 'AGA': 'R', 'AGG': 'R', 'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V', 'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A', 'GAT': 'D', 'GAC': 'D', 'GAA': 'E', 'GAG': 'E', 'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G', 'AAN': 'X', 'TAN': 'X', 'GAN': 'X', 'CAN': 'X', 'ATN': 'X', 'TTN': 'X', 'GTN': 'X', 'CTN': 'X', 'ACN': 'X', 'TCN': 'X', 'GCN': 'X', 'CCN': 'X', 'AGN': 'X', 'TGN': 'X', 'GGN': 'X', 'CGN': 'X', 'ANA': 'X', 'TNA': 'X', 'GNA': 'X', 'CNA': 'X', 'ANT': 'X', 'TNT': 'X', 'GNT': 'X', 'CNT': 'X', 'ANC': 'X', 'TNC': 'X', 'GNC': 'X', 'CNC': 'X', 'ANG': 'X', 'TNG': 'X', 'GNG': 'X', 'CNG': 'X', 'NAA': 'X', 'NTA': 'X', 'NGA': 'X', 'NCA': 'X', 'NAT': 'X', 'NTT': 'X', 'NGT': 'X', 'NCT': 'X', 'NAC': 'X', 'NTC': 'X', 'NGC': 'X', 'NCC': 'X', 'NAG': 'X', 'NTG': 'X', 'NGG': 'X', 'NCG': 'X', 'NNN': 'X', 'ANN': 'X', 'TNN': 'X', 'GNN': 'X', 'CNN': 'X', 'NAN': 'X', 'NTN': 'X', 'NGN': 'X', 'NCN': 'X', 'NNA': 'X', 'NNT': 'X', 'NNG': 'X', 'NNC': 'X', 'NNN': 'X'}, stop_codons = ['TAA', 'TAG', 'TGA'], start_codons = ['TTG', 'CTG', 'ATT', 'ATC', 'ATA', 'ATG', 'GTG']) **ambiguous checker** for n in ambiguous_generic_by_id: assert ambiguous_rna_by_id[n].forward_table["GUU"] == "V" assert ambiguous_rna_by_id[n].forward_table["GUN"] == "V" if n != 23 : #For table 23, UUN = F, L or stop. assert ambiguous_rna_by_id[n].forward_table["UUN"] == "X" # F or L #R = A or G, so URR = UAA or UGA / TRA = TAA or TGA = stop codons if "UAA" in unambiguous_rna_by_id[n].stop_codons and\ "UGA" in unambiguous_rna_by_id[n].stop_codons: try: print(ambiguous_dna_by_id[n].forward_table["TRA"]) assert False, "Should be a stop only" except KeyError: pass assert "URA" in ambiguous_generic_by_id[n].stop_codons assert "URA" in ambiguous_rna_by_id[n].stop_codons assert "TRA" in ambiguous_generic_by_id[n].stop_codons assert "TRA" in ambiguous_dna_by_id[n].stop_codons del n **Question 1:** I would prefer not to edit the root `CodonTable.py` file. Any suggestions on how to avoid that? **Question 2:** I really don't want to comment out the ambiguous checker. Can someone help me write an exception to the ambiguous checker that will ignore my new codon table? Answer: When you load an ABI file, Biopython set the Seq alphabet as `IUPACUnambiguousDNA()`. My first approach is to set the alphabet to `SingleLetterAlphabet()`: from Bio import SeqIO from Bio.Alphabet import SingleLetterAlphabet for rec in SeqIO.parse("prots.ab1", "abi", alphabet=SingleLetterAlphabet()): print rec.seq.translate(11) Now the seq translates with "X" and "N".
Fast and efficient way to detect if two images are visually identical in Python Question: Given two images: image1.jpg image2.jpg What's a fast way to detect if they are visually identical in Python? For example, they may have different EXIF data which would yield different checksums, even though the image data is the same). Imagemagick has an excellent tool, "identify," that produces a visual hash of an image, but it's very processor intensive. Answer: Using PIL/Pillow: from PIL import Image im1 = Image.open('image1.jpg') im2 = Image.open('image2.jpg') if list(im1.getdata()) == list(im2.getdata()): print "Identical" else: print "Different"
drmaa error with sun grid engine - No active session Question: Hi I've installed gridengine on a 4-node cluster using the following command: sudo apt-get install gridengine-client gridengine-qmon gridengine-exec gridengine-master sudo apt-get install gridengine-exec gridengine-client And it returned: SGE_ROOT: /var/lib/gridengine SGE_CELL: bms I've therefore done all the necessary step to configure the gridengine and it works. However I want to run my job using python drmaa library and I've installed on the master node: sudo apt-get install libdrmaa-dev pip install drmaa So if i query the system with following script: #!/usr/bin/env python import drmaa def main(): """Query the system.""" s = drmaa.Session() s.initialize() print 'A DRMAA object was created' print 'Supported contact strings: ' + s.contact print 'Supported DRM systems: ' + str(s.drmsInfo) print 'Supported DRMAA implementations: ' + str(s.drmaaImplementation) print 'Version ' + str(s.version) print 'Exiting' s.exit() if __name__=='__main__': main() It returns: A DRMAA object was created Supported contact strings: session=NGS-1.9217.1679116461 Supported DRM systems: GE 6.2u5 Supported DRMAA implementations: GE 6.2u5 Version 1.0 Exiting But if I try to run a job with the script suggested by the link: <http://code.google.com/p/drmaa-python/wiki/Tutorial#Running_a_Job> It returns drmaa.errors.NoActiveSessionException: code 5: No active session Could anyone help me? What's wrong. The drmaa library looks like is able to communicate with gridengine but it cannot run a job. Why it raise this error? I would really appreciate any kind of help. Answer: you will find that the example of running job using DRMAA does not initialize the session so just add s.initialize() after creating new session s = drmaa.Session() as following: #!/usr/bin/env python import drmaa import os def main(): """Submit a job. Note, need file called sleeper.sh in current directory. """ s = drmaa.Session() s.initialize() print 'Creating job template' jt = s.createJobTemplate() jt.remoteCommand = os.getcwd() + '/sleeper.sh' jt.args = ['42','Simon says:'] jt.joinFiles=True jobid = s.runJob(jt) print 'Your job has been submitted with id ' + jobid print 'Cleaning up' s.deleteJobTemplate(jt) s.exit() if __name__=='__main__': main()
How can I log a functions arguments in a reusable way in Python? Question: I've found myself writing code like this several times: def my_func(a, b, *args, **kwargs): saved_args = locals() # Learned about this from http://stackoverflow.com/a/3137022/2829764 local_var = "This is some other local var that I don't want to log" try: a/b except Exception as e: logging.exception("Oh no! My args were: " + str(saved_args)) raise Running `my_func(1, 0, "spam", "ham", my_kwarg="eggs")` gives this output on stderr: ERROR:root:Oh no! My args were: {'a': 1, 'args': (u'spam', u'ham'), 'b': 0, 'kwargs': {'my_kwarg': u'eggs'}} Traceback (most recent call last): File "/Users/kuzzooroo/Desktop/question.py", line 17, in my_func a/b ZeroDivisionError: division by zero My question is, can I write something reusable so that I don't have to save locals() at the top of the function? And can it be done in a nice Pythonic way? EDIT: one more request in response to @mtik00: ideally I'd like some way to access saved_args or the like from within my_func so that I can do something other than log uncaught exceptions (maybe I want to catch the exception in my_func, log an error, and keep going). Answer: **Decorators** are what you are looking for. Here's an example: import logging from functools import wraps def arg_logger(func): @wraps(func) def new_func(*args, **kwargs): saved_args = locals() try: return func(*args, **kwargs) except: logging.exception("Oh no! My args were: " + str(saved_args)) raise return new_func @arg_logger def func(arg1, arg2): return 1 / 0 if __name__ == '__main__': func(1, 2) Here, I'm using arg_logger() as a _decorator_. Apply the decorator to any function you want to have this new behavior. There's a good discussion about decorators [here](http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Decorators).
python button does not work when image is added Question: When I try to add and image to the button, the program will run, but the button will be blank and you cannot click on it. If I change `image=Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif")` to `text='Open Directory` it works fine and you are able to click the button. I have no idea why when I change it to an img, it does not work. Any help will be appreciated. Here is my code: import Tkinter, Tkconstants, tkFileDialog class TkFileDialogExample(Tkinter.Frame): def __init__(self, root): Tkinter.Frame.__init__(self, root) # options for buttons button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5} # define buttons Tkinter.Button(self, image=Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif"), command=self.askdirectory).pack(**button_opt) # defining options for opening a directory self.dir_opt = options = {} options['initialdir'] = 'C:\\' options['mustexist'] = False options['parent'] = root options['title'] = 'This is a title' def askdirectory(self): #Returns a selected directoryname. return tkFileDialog.askdirectory(**self.dir_opt) if __name__=='__main__': root = Tkinter.Tk() TkFileDialogExample(root).pack() root.mainloop() Answer: First you have to define your image, using the self.image. So try: self.image = Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif") Then under your button, put: Tkinter.Button(self, image=self.image, command=self.askdirectory).pack(**button_opt)
Continuing code after executing a File - Python Question: I have made a Simple GUI that launches when i run my Twitch TV IRC Bot. But, the main bot doesn't continue until after i close the GUI. How would i make it so the Script runs at the same time as the GUI? This is the GUI: ##--GUI--## def whitelist_wipe(): execfile('command_whitelist_wipe.py') def modpack(): modpack = modpack_input.get() return root = Tk() modpack_input = StringVar() root.title('Geekster_Bot') root.geometry('450x450+500+300') WhitelistButton = Button(root, text = 'Clear Whitelist!', command + whitelist_wipe).pack() SubmitButton = Button(root, text = 'Change Modpack', command = modpack).pack() ModpackName = Entry(root, textvariable=modpack_input).pack() root.mainloop() This is the part where it launches the GUI from the main Bot scrpit: try: execfile('GUI.py') except: print('Error loading GUI') How would i continue the code with the GUI open? EDIT GUI.py; ##--GUI--## def whitelist_wipe(): execfile('command_whitelist_wipe.py') def modpack_var(): modpack_input = modpack_user.get() root = Tk() modpack_user = StringVar() root.title('Geekster_Bot') root.geometry('350x100+500+300') Label1 = Label(root, text = 'Geekster_Bot Controls!').pack() WhitelistButton = Button(root, text = 'Clear Whitelist!', command =whitelist_wipe).pack(side = LEFT) SubmitButton = Button(root, text = 'Change Modpack', command = modpack_var).pack() ModpackName = Entry(root, textvariable=modpack_user).pack() root.mainloop() Main Bot; try: #Create thread gui_thread = threading.Thread( target = execfile, args = ('GUI.py',) ) #Start thread gui_thread.start() #Code to run in the main thread except: print('Error loading GUI') def message(msg): #function for sending messages to the IRC chat global queue queue = queue + 1 print queue if queue < 20: #ensures does not send >20 msgs per 30 seconds. twitch = ('OUTPUT ON ' + channel + ' :' + msg + '\r\n') irc.send('PRIVMSG ' + channel + ' :' + msg + '\r\n') print (twitch) else: print 'Message deleted' def socialtimer(): #function for announcing social every 3 minutes global ntimer z = open(r'E:\Geekster_Bot\Twitter.txt') SOCIAL = z.read() message (SOCIAL) print 'Social Timers Started!' ntimer = threading.Timer(1200,socialtimer) ntimer.start() def queuetimer(): #function for resetting the queue every 30 seconds global queue print 'queue reset' queue = 0 threading.Timer(30,queuetimer).start() def modpack_var(): modpack_input = modpack_user.get() ##--Main Bot--## #General variables newsmsg = 'whitelist' modpack = modpack_input Answer: Since the gui itself runs in a loop it blocks the thread you start it in until you stop the loop (close the gui). You need to start the gui in a different thread from the main one. You can do this using the threading module: import threading try: #Create thread gui_thread = threading.Thread( target = execfile, args = ('GUI.py',) ) #Start thread gui_thread.start() #Code to run in the main thread except: print('Error loading GUI') In this code the `gui_thread` object is a thread, which runs the `execfile` callable (a function in this case) with the parameter `'GUI.py'` on start. Check the threading module documentation for further info: <https://docs.python.org/3.3/library/threading.html>
psutil - getting process name is blank Question: I'm trying to run this code and I'm not getting the list of processes by name: import psutil PROCNAME = "python.exe" for proc in psutil.process_iter(): if proc.name == PROCNAME: print proc What I get is nothing even though the process is running. Answer: I was experiencing the same problem. Changing `proc.name` to `proc.name()` solved it for me if anyone else was having similar issues.
Create a Student-Age graph in Python-Matplotlib Question: import matplotlib.pyplot as plt x = ['Eric','Jhon','bill','Daniel'] y = [10, 17, 12.5, 20] plt.plot(x,y) plt.show() When I run this code, I get this error `ValueError: could not convert string to float:` I want all names in list `x` at x-axis and corresponding ages are in second list `y` which will be used in bar graph. So here I have 1 more question Is it a good way to do in my case(I mean if we can create a list of tuples(name,age)) and that would be easy?? or something else. Answer: The error occurs because matplotlib is expecting numerical data but you're providing strings (the names). What you can do instead is plot your data using some numerical data and then replace the ticks on the x-axis using [`plt.xticks`](http://matplotlib.org/1.3.1/api/pyplot_api.html#matplotlib.pyplot.xticks) as below. import matplotlib.pyplot as plt names = ['Eric','John','Bill','Daniel'] x = range(len(names)) y = [10, 17, 12.5, 20] plt.plot(x, y) plt.xticks(x, names) plt.show() ![Plot example](http://i.stack.imgur.com/JHqwV.png)
Comparing two strings in Python - depends on string source...? Question: I have the following python script: import sys import io str1 = 'asd' str2 - 'asd' if (str2.find(str1)==-1): print('FALSE') else: print('TRUE') #Prints "TRUE" It works fine. No problem. The problem starts if I take the string, put it in a file (save it) and then read the content of the file to str1 and str2, like so: import sys import io fHandler = open(r'C:\dev\1.pub','r') str1 = fHandler.read() str2 = fHandler.read() if (str2.find(str1)==-1): print('FALSE') else: print('TRUE') #Prints "FALSE" Why is the behaviour different? Thanks! Answer: If you try to call `fHandler.read()` twice, then the second one will return n empty string (or empty bytes if you read binary). `fHandler.read()` reads everything until the end and the second call will start reading at the end until the end, so it returns an empty string. Try adding `fHandler.seek(0)` beetween your function calls and it should work.
How to execute sql Python script in Windows command Prompt? Question: I have a simple script that uses sqlite3 in Python. However, when I run this from cmd.exe in Windows I get an "Open With" window. If I click 'cancel' it says "Access is denied." in cmd.exe. import sqlite3 connection = sqlite3.connect("test_database.db") c = connection.cursor() c.execute("CREATE TABLE People(FirstName TEXT, LastName TEXT, Age INT)") c.execute("INSERT INTO People VALUES('Ron','Obvious',42)") connection.commit() connection.close() I can run Python scripts fine from cmd.exe. I just have this problem because I'm using sqlite? (Also, I have the sqlite path in PATH) How can I stop this "Open with" window appearing, and actually get my script to run correctly from cmd.exe? Answer: Running myscript.py in cmd does not work if I use import sqlite. Instead, I ran "python myscript.py" and the script runs fine. Thanks to @nerdwaller.
Check whether an entry present in python list and add the elements Question: I have two python list of the form list1 = [('TGFB1', 'TGFB1', 1), ('TGFB1', 'CRP', 0.4),('BRCA2', 'TP53', 0.3)] list2 = [('BRCA1', 'TP53', 2), ('TGFB1', 'CRP', 0.4),('BRCA2', 'TP53', 0.3)] I need to check whether each entry in list2 is present in list1 . If present add the integer part and store in a new list. If not present just append that entry to the newly created list. So here my newly created list3 should look like list3 = [('TGFB1', 'TGFB1', 1), ('TGFB1', 'CRP', 0.8),('BRCA2', 'TP53', 0.6),('BRCA1', 'TP53', 2) ] Answer: Following my above comment, this is what you might want: from copy import copy d3 = copy(dict(((x, y), z) for x, y, z in list1)) d2 = dict(((x, y), z) for x, y, z in list2) for key, value in d2.iteritems(): d3[key] = (d3[key] if key in d3 else 0.0) + value If you do really want to turn `d3` then back to a list of the same structure use: list3 = [key + (value,) for key, value in d3.iteritems()]
What is the canonical way to check if a function has been called in Python unittest without use of a mock? Question: If I have a class similar to the 1 below and I want to test the various cases for the bar function, how can I accomplish this without mocking the private functions? In other words, how in Python's unittest library could I achieve something similar to this: def test_bar(): f = Foo() f.bar(3) expect(self._is_positive_number).toBeCalled() **foo.py** class Foo(): def bar(self, x): if type(x) is not int: print('Please enter a valid integer') return False if x > 0: self._is_positive_number() elif x == 0: self._is_zero() else self._is_negative() def _is_positive_number(self): print('Positive') return True def _is_zero(self): print('Zero') return True def _is_negative_number(self): print('Negative') return True Answer: As far as I know, there's no way to do this without mocking out the private methods. However, the `mock` library (available as `unittest.mock` in the standard library as of 3.3, a separate installation otherwise) makes this relatively painless: try: # Python 3.3 or later import unittest.mock as mock except ImportError: # Make sure you install it first import mock class TestFoo(unittest.TestCase): def setUp(self): self.f = Foo() def test_bar(self): with mock.patch.object(self.f, '_is_positive_number') as is_pos: self.f.bar(3) self.assertTrue(is_pos.called)
Create a matrix of tf-idf values Question: I have a set of `documents` like: D1 = "The sky is blue." D2 = "The sun is bright." D3 = "The sun in the sky is bright." and a set of `words` like: "sky","land","sea","water","sun","moon" I want to create a matrix like this: x D1 D2 D3 sky tf-idf 0 tf-idf land 0 0 0 sea 0 0 0 water 0 0 0 sun 0 tf-idf tf-idf moon 0 0 0 Something like the example table given here: <http://www.cs.duke.edu/courses/spring14/compsci290/assignments/lab02.html>. In the given link, it uses the same words from the document but I need to use the set of `words` that I have mentioned. If the particular word is present in the document then I put the `tf-idf` values, else I put a `0` in the matrix. Any idea how I might build some sort of matrix like this? Python will be best but R also appreciated. I am using the following code but am not sure whether I am doing the right thing or not. My code is: from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from nltk.corpus import stopwords train_set = "The sky is blue.", "The sun is bright.", "The sun in the sky is bright." #Documents test_set = ["sky","land","sea","water","sun","moon"] #Query stopWords = stopwords.words('english') vectorizer = CountVectorizer(stop_words = stopWords) #print vectorizer transformer = TfidfTransformer() #print transformer trainVectorizerArray = vectorizer.fit_transform(train_set).toarray() testVectorizerArray = vectorizer.transform(test_set).toarray() #print 'Fit Vectorizer to train set', trainVectorizerArray #print 'Transform Vectorizer to test set', testVectorizerArray transformer.fit(trainVectorizerArray) #print #print transformer.transform(trainVectorizerArray).toarray() transformer.fit(testVectorizerArray) #print tfidf = transformer.transform(testVectorizerArray) print tfidf.todense() I am getting very absurd results like this (values are only `0` and `1` while I am expecting values between 0 and 1). [[ 0. 0. 1. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 1.] [ 0. 0. 0. 0.] [ 1. 0. 0. 0.]] I am also open to other libraries for calculating `tf-idf`. I just want a correct matrix which I mentioned above. Answer: A R solution could look like this: library(tm) docs <- c(D1 = "The sky is blue.", D2 = "The sun is bright.", D3 = "The sun in the sky is bright.") dict <- c("sky","land","sea","water","sun","moon") mat <- TermDocumentMatrix(Corpus(VectorSource(docs)), control=list(weighting = weightTfIdf, dictionary = dict)) as.matrix(mat)[dict, ] # Docs # Terms D1 D2 D3 # sky 0.5849625 0.0000000 0.2924813 # land 0.0000000 0.0000000 0.0000000 # sea 0.0000000 0.0000000 0.0000000 # water 0.0000000 0.0000000 0.0000000 # sun 0.0000000 0.5849625 0.2924813 # moon 0.0000000 0.0000000 0.0000000
Asserting execution order in python unittest Question: I have a function that creates a temporary directory, switches to that temporary directory, performs some work, and then switches back to the original directory. I am trying to write a unit test that tests this. I don't have a problem verifying that the current directory was changed to the temp dir and changed back again, but I'm having a problem verifying that the important stuff took place in between those calls. My original idea was to abstract the function into three sub functions so that I could test the call order. I can replace each of the three sub functions with mocks to verify that they are called -- however, I am still presented with the issue of verifying the order. On a mock I can use assert_has_calls, but upon what object do I call that function? Here is the class I'm trying to test: import shutil import os import subprocess import tempfile import pkg_resources class Converter: def __init__(self, encoded_file_path): self.encoded_file_path = encoded_file_path self.unencoded_file_path = None self.original_path = None self.temp_dir = None def change_to_temp_dir(self): self.original_path = os.getcwd() self.temp_dir = tempfile.mkdtemp() os.chdir(self.temp_dir) def change_to_original_dir(self): os.chdir(self.original_path) shutil.rmtree(self.temp_dir) def do_stuff(self): pass def run(self): self.change_to_temp_dir() self.do_stuff() self.change_to_original_dir() This is as far as I got writing the test case: def test_converter(self, pkg_resources, tempfile, subprocess, os, shutil): encoded_file_path = Mock() converter = Converter(encoded_file_path) converter.change_to_temp_dir = Mock() converter.do_stuff= Mock() converter.change_to_original_dir = Mock() assert converter.encoded_file_path == encoded_file_path assert converter.unencoded_file_path is None converter.run() Now that I have each function mocked, I can verify THAT they were called, but not in what ORDER. How do I go about doing this? Answer: One workaround would to be to create a separate mock object, attach methods to it and use [`assert_has_calls()`](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.assert_has_calls) to check the call order: converter = Converter(encoded_file_path) converter.change_to_temp_dir = Mock() converter.do_stuff = Mock() converter.change_to_original_dir = Mock() m = Mock() m.configure_mock(first=converter.change_to_temp_dir, second=converter.do_stuff, third=converter.change_to_original_dir) converter.run() m.assert_has_calls([call.first(), call.second(), call.third()])
How do I keep the focus on the command prompt when calling pylab.show? Question: I am calling a python script from the comandline (bash under Ubuntu): > python myScript.py within this script, I create a figure, show it (nonblocking) with PyLab and wait for a user entry: import matplotlib as mpl mpl.use('TkAgg') import pylab as pl fig = pylab.figure() # Figure gets some content here pl.show(block=False) inp = raw_input('Please enter your choice: ') # Prompt window has no focus Now my problem is, that the figure window, that is poping up, has the focus. But I want the focus to stay at or return to the command line window for interaction with the raw_input... Any suggestions how to achieve this? Thanks in advance! Answer: Some other lower level backends tend not to do it, try: import matplotlib as mpl mpl.use('Agg')
Spyder SymPy Wont Print Symbolic Math Question: I setup Anaconda 2.0.0 (Win 64). It has SymPy 0.7.5. I configured Spyder (2.3.0rc that came with Anaconda) to use symbolic math: _Tools > Preferences > iPython console > Advanced Settings > Symbolic Mathematics_ I create a new project and a new file: # -*- coding: utf-8 -*- from sympy import * init_printing(use_unicode=False, wrap_line=False, no_global=True) x = Symbol('x') integrate(x, x) print("Completed.") When I run this (Python or iPython console) it does not print the integral -- it only prints _Completed._ But what is weird is that while in the console that just did the run if I then re-type: integrate(x, x) It does print the integral. So running from a file never prints any symbolic math but typing in the console manually does? Can anyone help with this issue -- maybe it some sort of configuration? Thank you! Answer: Running a script is not the same as executing code in IPython. When you run the code in a cell or prompt in IPython, it captures the output of the last command and displays it to you. When you run a script, the script is just run, and the only thing that is displayed is what is printed to the screen. I don't think there is a way to send the IPython display object (which would be needed to get pretty latex output) from a script, but I may be misunderstanding how spyder executes the code in IPython, or missing some hooks that it has. You can try from IPython.display import display display(integrate(x, x))
Merging two Excel files by ID and combining columns with same name (python, pandas) Question: I am new to stackoverflow and pandas for python. I found part of my answer in the post [Looking to merge two Excel files by ID into one Excel file using Python 2.7](http://stackoverflow.com/questions/17661836/looking-to-merge-two- excel-files-by-id-into-one-excel-file-using-python-2-7) However, I also want to merge or combine columns from the two excel files with the same name. I thought the following post would have my answer but I guess it's not titled correctly: [Merging Pandas DataFrames with the same column name](http://stackoverflow.com/questions/20862068/merging-pandas-dataframes- with-the-same-column-name) Right now I have the code: import pandas as pd file1 = pd.read_excel("file1.xlsx") file2 = pd.read_excel("file2.xlsx") file3 = file1.merge(file2, on="ID", how="outer") file3.to_excel("merged.xlsx") file1.xlsx ID,JanSales,FebSales,test 1,100,200,cars 2,200,500, 3,300,400,boats file2.xlsx ID,CreditScore,EMMAScore,test 2,good,Watson,planes 3,okay,Thompson, 4,not-so-good,NA, what I get is merged.xlsx ID,JanSales,FebSales,**test_x** ,CreditScore,EMMAScore,**test_y** 1,100,200,cars,NaN,NaN, 2,200,500,,good,Watson,planes 3,300,400,boats,okay,Thompson, 4,NaN,NaN,,not-so-good,NaN, what I want is merged.xlsx ID,JanSales,FebSales,CreditScore,EMMAScore,**test** 1,100,200,NaN,NaN,cars 2,200,500,good,Watson,planes 3,300,400,okay,Thompson,boats 4,NaN,NaN,not-so-good,NaN,NaA In my real data, there are 200+ columns that correspond to the "test" column in my example. I want the program to find these columns with the same names in both file1.xlsx and file2.xlsx and combine them in the merged file. Answer: OK, here is a more dynamic way, after merging we assume that clashes will occur and result in 'column_name_x' or '_y'. So first figure out the common column names and remove 'ID' from this list In [51]: common_columns = list(set(list(df1.columns)) & set(list(df2.columns))) common_columns.remove('ID') common_columns Out[51]: ['test'] Now we can iterate over this list to create the new column and use `where` to conditionally assign the value dependent on which value is not null. In [59]: for col in common_columns: df3[col] = df3[col+'_x'].where(df3[col+'_x'].notnull(), df3[col+'_y']) df3 Out[59]: ID JanSales FebSales test_x CreditScore EMMAScore test_y test 0 1 100 200 cars NaN NaN NaN cars 1 2 200 500 NaN good Watson planes planes 2 3 300 400 boats okay Thompson NaN boats 3 4 NaN NaN NaN not-so-good NaN NaN NaN [4 rows x 8 columns] Then just to finish off drop all the extra columns: In [68]: clash_names = [elt+suffix for elt in common_columns for suffix in ('_x','_y') ] clash_names df3.drop(labels=clash_names, axis=1,inplace=True) df3 Out[68]: ID JanSales FebSales CreditScore EMMAScore test 0 1 100 200 NaN NaN cars 1 2 200 500 good Watson planes 2 3 300 400 okay Thompson boats 3 4 NaN NaN not-so-good NaN NaN [4 rows x 6 columns] The snippet above is from this :[Prepend prefix to list elements with list comprehension](http://stackoverflow.com/questions/3330880/prepend-prefix-to- list-elements-with-list-comprehension)
Dynamically assign values - python Question: looking to improve the efficiency of my code, as while my current method works, i feel it can be improved currently this is my code : if ouroraddrlen == (4,): ouropip = struct.unpack(">bbbb", payload[6:10]) # Need to change this to accept ipv6 as well print "Our I.P : ", ouropip notheirip = struct.unpack(">b", payload[10]) print "No. of their I.P's : ", notheirip theiroripv = struct.unpack(">b", payload[11]) print "Their I.P version:: ", theiroripv theiroraddrlen = struct.unpack(">b", payload[12]) print "Length of their Ip : ", theiroraddrlen theirfirstip = struct.unpack(">bbbb", payload[13:17]) print "First Ip : ", theirfirstip theirsecondip = struct.unpack(">bbbb", payload[18:22]) print "Second Ip : ", theirsecondip the output is : Time : (1401734263,) Our onion address : Ip version : (4,) Ip length : (4,) Our I.P : ( ) No. of their I.P's : (2,) Their I.P version:: (4,) Length of their Ip : (4,) First Ip : ( ) Second Ip : ( ) i have removed the real ip's but they are just ipv4 addresses however what i am wondering, is if it is possible to include an if statement after this section of code : notheirip = struct.unpack(">b", payload[10]) print "No. of their I.P's : ", notheirip where if the notheirip is greater than zero and depending on the length of : theiroraddrlen = struct.unpack(">b", payload[12]) print "Length of their Ip : ", theiroraddrlen which would be either 4 or 16 then it would set the payload values of the next section for example if notheirip = (2,) and theiroraddrlen = (4,) then i would want it to print out theirip = struct.unpack(">b << the number of b required so either 4 or 16 and then the range, this will always start at 13 and go up to either 4 or 16 in the future and loop until all the ip's are displayed not sure if that is clear but hopefully it is :) Thanks Answer: >>> from collections import namedtuple >>> Record = namedtuple("Record","IP NoIP IPV LenIP FirstIP SecondIP") >>> Record._asdict(Record._make(struct.unpack(">LbbbLL",payload[6:]))) {'FirstIP': 1145324612, 'NoIP': 17, 'SecondIP': 1431655765, 'IP': 3140690449L, IPV': 34, 'LenIP': 51} >>> I think would work (you might want different 4 byte type than L) (keep in mind i totally made up the payload so I would expect different results with a real one) if you want to get 4 digit tuples for the ips just unpack the new value new_record["IP"] = stuct.unpack("bbbb",new_record["IP"])
Python ginput not allowing new points to be plotted Question: This code asks the user to digitize three points (using ginput), then should plot those points to the screen atop the imshow plot. It does not. Any ideas why? from pylab import show, ginput, rand, imshow, plot from matplotlib.figure import Figure import numpy as np x1 = rand(103, 53) figure = Figure(figsize=(4, 4), dpi=100) axes = figure.add_subplot(111) imshow(x1) # Get user input x = ginput(3) x = np.array(x) # Plot the user's points to the screen plot(x[:, 0], x[:, 1], 'k*', ms=50) show() Answer: Not sure which way you are trying to plot, the star and the background or vice versa but you need to change the order of your calls. plot(10, 30, 'k*', ms=100) x = ginput(2) imshow(x1) show() This will show a star then when you click two points show your rand data. This is a nice example of using ginput taken from [here](http://matplotlib.org/examples/pylab_examples/ginput_manual_clabel.html): import time import numpy as np import matplotlib.pyplot as plt def tellme(s): print(s) plt.title(s,fontsize=16) plt.draw() ################################################## # Define a triangle by clicking three points ################################################## plt.clf() plt.axis([-1.,1.,-1.,1.]) plt.setp(plt.gca(),autoscale_on=False) tellme('You will define a triangle, click to begin') plt.waitforbuttonpress() happy = False while not happy: pts = [] while len(pts) < 3: tellme('Select 3 corners with mouse') pts = np.asarray( plt.ginput(3,timeout=-1) ) if len(pts) < 3: tellme('Too few points, starting over') time.sleep(1) # Wait a second ph = plt.fill( pts[:,0], pts[:,1], 'r', lw=2 ) tellme('Happy? Key click for yes, mouse click for no') happy = plt.waitforbuttonpress() # Get rid of fill if not happy: for p in ph: p.remove()
Skip subdirectory in python import Question: Ok, so I'm trying to change this: app/ - lib.py - models.py - blah.py Into this: app/ - __init__.py - lib.py - models/ - __init__.py - user.py - account.py - banana.py - blah.py And still be able to import my models using `from app.models import User` rather than having to change it to `from app.models.user import User` all over the place. Basically, I want everything to treat the package as a single module, but be able to navigate the code in separate files for development ease. The reason I can't do something like add `for file in __all__: from file import *` into **init**.py is I have circular references between the model files. A fix I don't want is to import those models from within the functions that use them. But that's super ugly. Let me give you an example: user.py ... from app.models import Banana ... banana.py ... from app.models import User ... I wrote a quick pre-processing script that grabs all the files, re-writes them to put imports at the top, and puts it into models.py, but that's hardly an improvement, since now my stack traces don't show the line number I actually need to change. Any ideas? I always though **init** was probably magical but now that I dig into it, I can't find anything that lets me provide myself this really simple convenience. Answer: It depends on what your circular references are for. If you have a class in user that inherits from Banana and a class in banana that inherits from User, you can't do this. You also can't do it if each class defines a decorator that gets used in the other or anything else that gets called during the actual import. You can, however, if you are just mutually referencing helper functions, or if your User object has a method to create new instances of Banana and your Banana object has a method that creates new instances of User. As long as the mutual reference doesn't actually get used until something in the module is called from outside it, then in your model folder, in `__init__.py`, you can just do something like: import user import banana #etc... user.banana = banana banana.user = user #etc... User = user.User Banana = banana.Banana Then for sake of clarity and not trying to figure out what's going on
How to extract the string values "Hello" and "World" from the XML using Python 2.6 Question: I need to extract the strings "Hello" and "World" using Python 2.6. Please advice. <Translate_Array_Request> <App_Id /> <From>language-code</From> <Options> <Category xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >string-value</Category> <Content Type xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">text/plain</ContentType> <Reserved Flags xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" /> <State xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >int-value</State> <Uri xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >string-value</Uri> <User xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" >string-value</User> </Options> <Texts> <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">**Hello**</string> <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">**World**</string> </Texts> <To>language-code</To> </Translate_Array_Request> Answer: There are multiple libraries in python that let you parse and extract data from XML. One way would be to use the [ElementTree XML python API](https://docs.python.org/2/library/xml.etree.elementtree.html). Assuming the input is saved as a string `xml_data`, this is what you do: >>> import xml.etree.ElementTree as ET >>> root = ET.fromstring(xml_data) >>> texts = root.find('Texts') >>> for data in texts: ... print data.text ... **Hello** **World**
How do I get the "biggest" path? Question: I need to write some Python code to get the latest version of Android from a path. For example: $ ls -l android_tools/sdk/platforms/ total 8 drwxrwxr-x 5 deqing deqing 4096 Mar 21 11:42 android-18 drwxrwxr-x 5 deqing deqing 4096 Mar 21 11:42 android-19 $ In this case I'd like to have `android_tools/sdk/platforms/android-19`. Answer: The [`max` function](https://docs.python.org/2.7/library/functions.html#max) can take a `key=myfunc` parameter to specify a function that will return a comparison value. So you could do something like: import os, re dirname = 'android_tools/sdk/platforms' files = os.listdir(my_dir) def mykeyfunc(fname): digits = re.search(r'\d+$', fname).group() return int(digits) print max(files, mykeyfunc) Adjust that regular expression as needed for the actual files you're dealing with, and that should get you started.
python error in get trending topic using tweepy Question: I am trying to get top 20 trending topic through twitter api based on the Tweepy library. Here is my python code: import tweepy import json import time today = time.strftime("%Y-%m-%d") CONSUMER_KEY = "" CONSUMER_SECRET = "" ACCESS_KEY = "" ACCESS_SECRET = "" auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth) trends = api.trends_daily(today) print trends I am using trends_daily function to get the top 20 trending topics for each day. The variable "today" is in **date format** : `today = time.strftime("%Y-%m-%d")`. And I tried string format as well. However, it keeps report error message: File "/Users/Ivy/PycharmProjects/TwitterTrend/trends.py", line 17, in <module> trends = api.trends_daily("2014-06-03") File "build/bdist.macosx-10.9-intel/egg/tweepy/binder.py", line 230, in _call File "build/bdist.macosx-10.9-intel/egg/tweepy/binder.py", line 203, in execute tweepy.error.TweepError: [{u'message': u'Sorry, that page does not exist', u'code': 34}] Answer: I believe that you're using tweepy version 1 which is [no longer supported](https://dev.twitter.com/docs/api/1/get/trends/daily): <https://api.twitter.com/1/trends/daily.json> Try to re-install (version 1.1), for example: <https://api.twitter.com/1.1/trends/available.json>
Argparse mutally exclusive by subgrouping Question: Currently the argparse of my code gives the following: usage: ir.py [-h] [-q | --json | -d ] Some text optional arguments: -h, --help show this help message and exit -q gene query terms (e.g. mcpip1) --json output in JSON format, use only with -q -d , --file_to_index file to index What I want it to do is the following: 1. `-q` should be mutually exclusive from `-d` 2. and `--json` should only go with `-q` What's the way go go about it? This is my argparse code: parser = argparse.ArgumentParser(description='''Some text''') group = parser.add_mutually_exclusive_group() group.add_argument("-q",help="gene query terms (e.g. mcpip1)",metavar="",type=str) group.add_argument("--json", help="output in JSON format, use only with -q", action="store_true") group.add_argument("-d","--file_to_index", help="file to index",metavar="",type=str) args = parser.parse_args() It currently rejects `-q` with `--json`: python ir.py --json -q mcpip1 usage: ir.py [-h] [-q | --json | -d ] ir.py: error: argument -q: not allowed with argument --json Answer: `-q` and `-d` aren't really options (presumably, one them is required); they're subcommands, so you should use the subparser feature of `argparse` to create two subcommands `query` and `index`, and associate `--json` only with the `query` subcommand. import argparse parser = argparse.ArgumentParser(description='''Some text''') subparsers = parser.add_subparsers() query_p = subparsers.add_parser("query", help="Query with a list of terms") query_p.add_argument("terms") query_p.add_argument("--json", help="output in JSON format, use only with -q", action="store_true") index_p = subparsers.add_parser("index", help="index a file") index_p.add_argument("indexfile", help="file to index") args = parser.parse_args() Help for the overall program is available with ir.py -h Help for each subcommand is displayed separately ir.py query -h ir.py index -h Usage would be something like ir.py query "list of terms" ir.py query --json "list of terms" ir.py index somefile.ext
ImportError: No module named ui_imagedialog Question: I am new to pyQt4. First I installed pyqt4 then installed QTDesigner. And tried to run the given program( From internet). The file is named as main.py import sys from PyQt4.QtGui import QApplication, QDialog from ui_imagedialog import Ui_ImageDialog app = QApplication(sys.argv) window = QDialog() ui = Ui_ImageDialog() ui.setupUi(window) window.show() sys.exit(app.exec_()) run the program using terminal python main.py I got the following error from ui_imagedialog import Ui_ImageDialog ImportError: No module named ui_imagedialog How to solve this?? Answer: You could try running this instead; import sys from PyQt4.QtGui import QApplication, QDialog app = QApplication(sys.argv) window = QDialog() window.show() sys.exit(app.exec_()) And if you are using PyQt5, use this; import sys from PyQt5.QtWidgets import QApplication, QDialog app = QApplication(sys.argv) window = QDialog() window.show() sys.exit(app.exec_()) This will produce an empty window. From the [documentation](http://pyqt.sourceforge.net/Docs/PyQt5/designer.html), the **ui_imagedialog** is an imaginary file.
Passing thread to threaded object Question: Quick question on the use of `QThread` in PyQt4 and Python 2.7. I am creating a process inherited from `QObject`, and assigning this to a `Qthread` I have created in a separate class (also inherited from `QObject`). Is it safe to pass the `QThread` object to the process object, so that I can call `thread.msleep(mseconds)` from within the process itself? I want to be able to make the thread wait or sleep, but I have read that time.sleep(seconds) is dodgy when used with PyQt multi-threading. I did try to send a signal from the process object to a slot in the main thread (attached to `thread.msleep(mseconds)` for that process object), but I found that this failed to work; the process object continued executing until complete, with the slot only being executed after this time. Even after adjusting priorities, this continued to happen. This is unacceptable since I want the process loop to run continuously. Any other recommendations? Answer: I eventually managed to alter my code to achieve the functionality that I required in my question: namely the ability to make a thread wait or sleep for a specified amount of time. Firstly, my research seems to show that one of the main reasons subclassing `QThread` became ill-advised in Qt was that a thread should not be able to manage itself. Though there is no official documentation on my question, I can only surmise that passing the thread object to the process object running on it would also be ill-advised, because the thread would again be able to control itself directly. The solution I have found is to dispense with `msleep()` altogether. Qt documentation on QThread recommends that `sleep()` and `wait()` functions are avoided because they do not fit well with the event driven nature of Qt. They recommend that `QTimer()` is used to call a function via a signal after it times out, in place of `msleep()`. By default `QTimer()` is used to send a repeating signal every time interval, but can also send a signal once using `QTimer.singleShot()`. It is also stated in the documentation that it is safe to call `QSleep()` from within a thread. I only use a repeating `QTimer` to call a single slot `foo()` multiple times, but to add a delay within `foo()`, `QTimer.singleShot()` could be used to call a second function `moo()` after a set number of milliseconds. EDIT: I have decided to include my threading code, which subclasses QObject and QThread to perform a task on a thread in a continual loop every given time interval. It is, as far as I can tell, fully functional, though could do with a little work. # -*- coding: utf-8 -*- import sys from PyQt4 import QtCore, QtGui # Class to be assigned to a thread. # This should be subclassed to provide new functionality. class GenericLoop(QtCore.QObject): def __init__(self): super(GenericLoop, self).__init__() # We use this signal to tell the main thread # when this thread is finished. finished_Sig = QtCore.pyqtSignal() # Default timeout is 0, i.e. do work on thread after # other events have been dealt with __timeout = 0 __processTimer = None __args = None __kwargs = None # We use this function to set the arguments used by run(), # if we want to change them mid-execution @QtCore.pyqtSlot(tuple, dict) def changeArgs(self, args, kwargs): self.__args = args self.__kwargs = kwargs # We can change the timeout used to make the thread run # at given intervals. Note that the timing is not exact, # since this is impossible with a real time operating system @QtCore.pyqtSlot(int) def setTimeout(self, mseconds): self.__timeout = int(mseconds) # Call either a singleShot QTimer (one execution), # or a normal QTimer (repeated), to start the loop @QtCore.pyqtSlot(bool, tuple, dict) def startTimer(self, singleShot, args, kwargs): self.__processTimer = QtCore.QTimer() # We can't pass args and kwargs directly because QTimer.timeout # emits a signal with allowing no contained variables # so we copy args and kwargs to local variables instead self.changeArgs(args, kwargs) if singleShot: self.__processTimer.singleShot(self.__timeout, self.callRun) else: self.__processTimer.timeout.connect(self.callRun) self.__processTimer.start(self.__timeout) # Call finish from within subclass using self.finish(), or # from another thread using signals. finish() will stop the # QTimer causing execution of the loop. The loop can be started again # by calling startTimer() or stopTimer() from another thread @QtCore.pyqtSlot() def stopTimer(self): if self.__processTimer.isActive(): self.__processTimer.stop() else: print "ERROR: stopTimer() has been called but no timer is running!" # We call this to delete the thread. @QtCore.pyqtSlot() def deleteThread(self): self.finished_Sig.emit() # This calls run(), in order to enable the passing of # command line arguments to the loop @QtCore.pyqtSlot() def callRun(self): self.run(self.__args, self.__kwargs) # run() can be called directly from another thread if required @QtCore.pyqtSlot(tuple, dict) def run(self, args, kwargs): print "ERROR: run() has not been defined! Stopping thread..." self.stopTimer() # Class for creating threads class GenericThread(QtCore.QObject): # Private variables include the thread. __sendArguments_Sig = QtCore.pyqtSignal(tuple, dict) __startTimer_Sig = QtCore.pyqtSignal(int, tuple, dict) __setTimeout_Sig = QtCore.pyqtSignal(int) __obj = None __finished_Sig = None __thread = QtCore.QThread() # Object to be threaded must be specified when # creating a GenericThread object def __init__(self, obj): super(GenericThread, self).__init__() self.__obj = obj self.moreInit() # Set up object on thread def moreInit(self): self.__thread = QtCore.QThread() self.__obj.moveToThread(self.__thread) # Allows thread to delete itself when done self.__obj.finished_Sig.connect(self.__thread.deleteLater) self.__sendArguments_Sig.connect(self.__obj.changeArgs) self.__startTimer_Sig.connect(self.__obj.startTimer) self.__setTimeout_Sig.connect(self.__obj.setTimeout) self.__thread.start() # Sets the QTimer timeout and does some checking # to make sure that types are as they should be def setTimeout(self, mseconds): if mseconds >= 0 and type(mseconds) is type(int()): self.__setTimeout_Sig.emit(mseconds) elif mseconds < 0 and type(mseconds) is type(int()): print "Error: timeout of below 0 ms specified." else: print "Error: timeout period is specified with a type other than int." # Starts a function in the thread via signals, and can pass # it arguments if required. Function executes until QTimer is stopped def startLoop(self, *args, **kwargs): if (self.__thread == None): print "ERROR: Thread has been deleted!" else: self.__startTimer_Sig.emit(False, args, kwargs) # Starts a function in the thread via signals, once def startOnce(self, *args, **kwargs): if (self.__thread == None): print "ERROR: Thread has been deleted!" else: self.__startTimer_Sig.emit(True, args, kwargs) # Calls a very simple GUI just to show that the program is responsive class GUIBox(QtGui.QWidget): def __init__(self): super(GUIBox, self).__init__() self.initUI() def initUI(self): self.resize(250, 150) self.setWindowTitle('Threading!') self.show() # Subclass GenericLoop to reimplement run and such. class SubClassedLoop(GenericLoop): def __init__(self): super(SubClassedLoop, self).__init__() __i = 0 @QtCore.pyqtSlot(tuple, dict) def run(self, args, kwargs): if self.__i>=50: self.stopTimer() return print self.__i, args self.__i += 1 app = QtGui.QApplication(sys.argv) ex = GUIBox() # Create 3 worker objects to do the actual calculation worker1 = SubClassedLoop() worker2 = SubClassedLoop() worker3 = SubClassedLoop() # Create 3 thread managing objects to do the thread control thread1 = GenericThread(worker1) thread2 = GenericThread(worker2) thread3 = GenericThread(worker3) # Set the threads to execute as soon as there is no work to do thread1.setTimeout(125) thread2.setTimeout(125) thread3.setTimeout(125) # Start threads thread1.startLoop(1) thread2.startLoop(2) thread3.startLoop(3) # Quit the program when the GUI window is closed sys.exit( app.exec_() )
Using owl:Class prefix with rdflib and xml serialization Question: I would like to use the `owl:` prefix in the XML serialization of my RDF ontology (using rdflib version 4.1.1); unfortunately I'm still getting the serialization as `rdf:Description` tags. I have looked at the answer about binding the namespace to the graph at [RDFLib: Namespace prefixes in XML serialization](http://stackoverflow.com/questions/4427607/rdflib-namespace- prefixes-in-xml-serialization) but this seems to only work when serializing using the `ns` format rather than `xml` format. Let's be more concrete. I'm attempting to get the following ontology (as taken from [Introducing RDFS and OWL](http://www.linkeddatatools.com/introducing- rdfs-owl)) in XML as follows: <!-- OWL Class Definition - Plant Type --> <owl:Class rdf:about="http://www.linkeddatatools.com/plants#planttype"> <rdfs:label>The plant type</rdfs:label> <rdfs:comment>The class of all plant types.</rdfs:comment> </owl:Class> Here is the python code for constructing such a thing, using `rdflib`: from rdflib.namespace import OWL, RDF, RDFS from rdflib import Graph, Literal, Namespace, URIRef # Construct the linked data tools namespace LDT = Namespace("http://www.linkeddatatools.com/plants#") # Create the graph graph = Graph() # Create the node to add to the Graph Plant = URIRef(LDT["planttype"]) # Add the OWL data to the graph graph.add((Plant, RDF.type, OWL.Class)) graph.add((Plant, RDFS.subClassOf, OWL.Thing)) graph.add((Plant, RDFS.label, Literal("The plant type"))) graph.add((Plant, RDFS.comment, Literal("The class of all plant types"))) # Bind the OWL and LDT name spaces graph.bind("owl", OWL) graph.bind("ldt", LDT) print graph.serialize(format='xml') Sadly, even with those bind statements, the following XML is printed: <?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" > <rdf:Description rdf:about="http://www.linkeddatatools.com/plants#planttype"> <rdfs:subClassOf rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> <rdfs:label>The plant type</rdfs:label> <rdfs:comment>The class of all plant types</rdfs:comment> <rdf:type rdf:resource="http://www.w3.org/2002/07/owl#Class"/> </rdf:Description> </rdf:RDF> Granted, this is still an Ontology, and usable - but since we have various editors, the much more compact and readable first version using the `owl` prefix would be far preferable. Is it possible to do this in `rdflib` without overriding the serialization method? **Update** In response to the comments, I'll rephrase my "bonus question" as simple clarification to my question at large. **Not a Bonus Question** The topic here involves the construction of the OWL namespace formatted ontology which is a shorthand for the more verbose RDF/XML specification. The issue here is larger though than the simple declaration of a namespace prefix for shorthand for only Classes or Properties, there are many shorthand notations that have to be dealt with in code; for example `owl:Ontology` descriptions should be added as good form to this notation. I am hoping that rdflib has support for the complete specification of the notation- rather than have to roll my own serialization. Answer: Instead of using the `xml` format, you need to use the `pretty-xml` format. It's listed in the documentation, [Plugin serializers](https://rdflib.readthedocs.org/en/4.1.0/plugin_serializers.html). That will give you the type of output that you're looking for. That is, you'd use a line like the following in order to use the [PrettyXMLSerializer](http://www.rdflib.net/rdflib-2.4.0/html/public/rdflib.syntax.serializers.PrettyXMLSerializer.PrettyXMLSerializer- class.html): print graph.serialize(format='pretty-xml') To address the "bonus question", you can add a line like the following to create the ontology header, and then serializing with `pretty-xml` will give you the following output. graph.add((URIRef('http://stackoverflow.com/q/24017320/1281433/ontology.owl'), RDF.type, OWL.Ontology )) <?xml version="1.0" encoding="utf-8"?> <rdf:RDF xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" > <owl:Ontology rdf:about="http://stackoverflow.com/q/24017320/1281433/ontology.owl"/> <owl:Class rdf:about="http://www.linkeddatatools.com/plants#planttype"> <rdfs:comment>The class of all plant types</rdfs:comment> <rdfs:subClassOf rdf:resource="http://www.w3.org/2002/07/owl#Thing"/> <rdfs:label>The plant type</rdfs:label> </owl:Class> </rdf:RDF> Adding the `x rdf:type owl:Ontology` triple isn't a very OWL-centric way of declaring the ontology though. It sounds like you're looking for something more like Jena's OntModel interface (which is just a convenience layer over Jena's RDF-centric Model), or the OWLAPI, but for RDFLib. I don't know whether such a thing exists (I'm not an RDFlib user), but you might have a look at: * [RDFLib/OWL-RL](https://github.com/RDFLib/OWL-RL): It looks like a reasoner, but it might have some of the methods that you need. * [Inspecting an ontology with RDFLib](http://www.michelepasin.org/blog/2011/07/18/inspecting-an-ontology-with-rdflib/): a blog article with links to source that might do some of what you want. * [Is there a Python library to handle OWL?](http://stackoverflow.com/q/1719812/1281433): A Stack Overflow question (now off-topic, because library/tool requests are off-topic, but it's an old question) where the accepted answer points out that rdflib is RDF-centric, not OWL-centric, but some of the other answers might be useful, particular [this one](http://stackoverflow.com/a/8379891/1281433), although most of those were outdated, even in 2011.
LED fade in python - implementing multithreading Question: I'm trying to build a program that controls an RGB LED through a RaspberryPi. I was able to build a simple fade program in python using [pi- blaster](https://github.com/sarfata/pi-blaster/), which works fine but doesn't let me do what I want. Here's my code: import time import sys import os blue = 21 green = 23 red = 22 def fade(color, direction, step): if direction == 'up': for i in range(0, 100, step): f=(i/float(100)) os.system('echo "%d=%f" > /dev/pi-blaster' % (color, f)) return fade(color, 'down', step) else: step=-step for i in range (100, 0, step): f=(i/float(100)) os.system('echo "%d=%f" > /dev/pi-blaster' % (color, f)) return fade(color, 'up', step) input = raw_input("Choose a color (r, g, b): ") if input == 'r': fade(red, 'up', 1) if input == 'g': fade(green, 'up', 1) if input == 'b': fade(blue, 'up', 1) The problem is that I want to be able to control the fade through an external script / program. My idea is to have a script which is always listening for user input, so when I type "red" it stops the ongoing fade and starts a new red one, by calling the function I posted before. I also want to be able to change the speed of the loop but this is already implemented into the "fade" function. I don't really understand how I could do this. I've read some things on here and I think I may have to use the Threading functions, but I don't really understand how those could work for my project. Thanks in advance for your help and sorry for my English which is not very good :) EDIT: I solved it using a loop checking continuously for keyboard inputs which then calls the fade function using multiprocessing. I can now kill the fade process using processName.terminate() Answer: to get much better performance (and as a clarification to the first answer) it is much better to write using python - but you must put a new line after each write with a '\n' Otherwise the code @daveydave400 gave is spot on I'm doing something like this: f = open('/dev/pi-blaster', 'w') f.write('0=120\n') #or f.write('0=%s\n'%amount) my actual code is in a function - in case you want to use that: def changer(pin, amount): f = open('/dev/pi-blaster', 'w') f.write('%d=%s\n'%(pin, str(amount))) if doing for loops using the the system command method you might find that python stops listening for keyboard input intermittently. This was certainly happening for me. I found that keyboardinterrupt was very hard to achieve with ctrl-c and had to repeatedly hit those keys to get the program to halt. Now i'm writing with python i'm not getting that issue.
Find edges in a cycle networkx python Question: I would like to make an algorithm to find if an edge belongs to a cycle, in an undirected graph, using networkx in Python. I am thinking to use `cycle_basis` and get all the cycles in the graph. My problem is that `cycle_basis` returns a list of nodes. How can I convert them to edges? Answer: You can construct the edges from the cycle by connecting adjacent nodes. In [1]: import networkx as nx In [2]: G = nx.Graph() In [3]: G.add_cycle([1,2,3,4]) In [4]: G.add_cycle([10,20,30]) In [5]: basis = nx.cycle_basis(G) In [6]: basis Out[6]: [[2, 3, 4, 1], [20, 30, 10]] In [7]: edges = [zip(nodes,(nodes[1:]+nodes[:1])) for nodes in basis] In [8]: edges Out[8]: [[(2, 3), (3, 4), (4, 1), (1, 2)], [(20, 30), (30, 10), (10, 20)]]
Clustering 500,000 geospatial points in python Question: I'm currently faced with the problem of finding a way to cluster around 500,000 latitude/longitude pairs in python. So far I've tried computing a distance matrix with numpy (to pass into the scikit-learn DBSCAN) but with such a large input it quickly spits out a Memory Error. The points are stored in tuples containing the latitude, longitude, and the data value at that point. In short, what is the most efficient way to spatially cluster a large number of latitude/longitude pairs in python? For this application, I'm willing to sacrifice some accuracy in the name of speed. Edit: The number of clusters for the algorithm to find is unknown ahead of time. Answer: I don't have your data so I just generated 500k random numbers into three columns. import numpy as np import matplotlib.pyplot as plt from scipy.cluster.vq import kmeans2, whiten arr = np.random.randn(500000*3).reshape((500000, 3)) x, y = kmeans2(whiten(arr), 7, iter = 20) #<--- I randomly picked 7 clusters plt.scatter(arr[:,0], arr[:,1], c=y, alpha=0.33333); out[1]: ![enter image description here](http://i.stack.imgur.com/EE6kn.png) I timed this and it took 1.96 seconds to run this Kmeans2 so I don't think it has to do with the size of your data. Put your data in a 500000 x 3 numpy array and try kmeans2.
When I run my fabfile, I am being asked for password although I specified a key. Why? Question: Good Day, I have a python script which runs a fabfile. My issue is that I am asked for a password whenever I run the fabfile from my script. However, the login works fine with the specified key when I run the fabfile manually from the command line even though I am using the same fab parameters. Here is the contents of my fabfile: [root@ip-10-10-20-82 bakery]# cat fabfile.py from fabric.api import run def deploy(): run('wget -P /tmp https://s3.amazonaws.com/LinuxBakery/httpd-2.2.26-1.1.amzn1.x86_64.rpm') run('sudo yum localinstall /tmp/httpd-2.2.26-1.1.amzn1.x86_64.rpm') Here is the syntax I use on the command line that works successfully: fab -u ec2-user -i id_rsa -H 10.10.15.185 deploy Here is the bit of python code which for some reason is prompting for a password instead of using the key: import subprocess subprocess.call(['fab', '-f', '/home/myhome/scripts/bakery/fabfile.py', '-u ec2-user', '-i', '/home/myhome/scripts/bakery/id_rsa', '-H', bakery_internalip, 'deploy']) Here is what happens when I run it: [10.10.15.185] Executing task 'deploy' [10.10.15.185] run: wget -P /tmp https://s3.amazonaws.com/LinuxBakery/httpd-2.2.26-1.1.amzn1.x86_64.rpm [10.10.15.185] Login password for ' ec2-user': Answer: I was being asked for a password even though I had specified a key because there was an extra space between the "u" and "ec2-user". Here is the snippet before: '-u ec2-user' And here it is after: '-uec2-user' The extra space meant that fab was trying to authenticate with " ec2-user" instead of "ec2-user".
Handling an image download popup Question: I'm trying to download an image using Python's Mechanize, and that's an easy thing to do with urlretrieve, however this image's 'src' attribute holds a url which initiates a download popup. There doesn't seem to be a url that points to the image. I'm using Python Mechanize, but my research tells me that there's no way to handle the pop up in Mechanize, and I would have to use something like Selenium. Is this the case? Answer: Yes Selenium seems to be the case for this. The following code shows how to deal with pop-up's. from selenium import webdriver from selenium.webdriver.common.alert import Alert driver = webdriver.Firefox() driver.get(url) try: alert = self.driver.switch_to_alert() # do something with alert, like download the content alert.dismiss() except: pass
Starting script using pyinotofy as daemon process Question: I have a number of questions regarding starting a script using pyinotify as a daemon. I have some code like this: #!/usr/bin/env python import sys import pyinotify import shutil import glob PACKAGES_DIR = '/var/my-packages' PACKAGES_TEMP_DIR = '/var/www-data/package_temp' wm = pyinotify.WatchManager() mask = pyinotify.IN_MOVED_TO class ProcessPackages(pyinotify.ProcessEvent): def process_IN_MOVED_TO(self, event): for directory in glob.glob(PACKAGES_TEMP_DIR + '/*'): shutil.move(directory, PACKAGES_DIR) handler = ProcessPackages() notifier = pyinotify.Notifier(wm, handler) wdd = wm.add_watch(PACKAGES_TEMP_DIR, mask) try: notifier.loop(daemonize=True, pid_file='/tmp/packages.pid', stdout='/tmp/stdout.txt') except pyinotify.NotifierError, err: print >> sys.stderr, err My question now is if I set to the daemonize parameter to True does this mean that the whole script is run as daemon or is it just pyinotify? If it is only pyinotify how would I go about running this entire script as a daemon process? If I run the script as daemon is it really necessary to make pyinotify a daemon as well? My last question is if pyinotify is daemonized would I definitely need a callback? In my case I just want the script to run forever and being killed only on system reboot/restart. The script should also run like any standard startup script without manual intervention. FYI, I am running an Ubuntu 12.04 server. Thanks in advance, nav Answer: I run an ipynotify-dependent process as a system service (which is what you want, by the sound of things), using Upstart - also on Ubuntu 12.04. Personally, I didn't modify the python script **at all**. I just made sure it ran fine at the terminal, then created an upstart config file like so: _/etc/init/myservice.conf_ : description "MyService" author "My Name" start on runlevel [2345] stop on runlevel [!2345] # Automatically restart process if crashed #respawn exec su myuser -c "/usr/bin/python /path/to/myscript.py > /tmp/myscript.log 2>&1" When your init file is in place, you'll want to try something like `sudo start myservice`, then inspect _/tmp/myscript.log_ for any errors. HTH!
How to extract all columns but one from an array (or matrix) in python? Question: Given a numpy 2d array (or a matrix), I would like to extract all the columns but the i-th. E. g. from 1 2 3 4 2 4 6 8 3 6 9 12 I would like to have, e.g. 1 2 3 2 4 6 3 6 9 or 1 2 4 2 4 8 3 6 12 I cannot find a pythonic way to do this. I now that you can extract given columns by simply a[:,n] or a[:,[n,n+1,n+5]] But what about extracting all of them but one? Answer: Take a look at numpy's [advanced slicing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean) >>> import numpy as np >>> a = np.array([[1,2,3,4], [2,4,6,8], [3,6,9,12]]) >>> a[:,np.array([True, True, False, True])] array([[ 1, 2, 4], [ 2, 4, 8], [ 3, 6, 12]])
Debug django tests Question: I see that [TestCase](https://docs.python.org/3/library/unittest.html) has a method [Debug()](https://docs.python.org/3/library/unittest.html#unittest.TestCase.debug), but I can't find any example on how to implement it. As far as I've tried, nothing works. Can anyone provide some code as to how to use it? Answer: ## debugunit.py from unittest import TestCase class MyTest(TestCase): def test1(self): print 'before' self.assertEquals(2+2, 5) print 'after' ## run > python -i debugunit.py To run a test interactively, create a `TestCase` instance, giving it the test name as a parameter. To run it, call the resulting object. >>> print MyTest('test1')() before None The "2+2!=5" exception is consumed by the unittest machinery. To get the set to run (with `setUp` and `tearDown`, etc), run the `debug()` method: >>> MyTest('test1').debug() before Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/unittest/case.py", line 400, in debug getattr(self, self._testMethodName)() File "debugunit.py", line 6, in test1 self.assertEquals(2+2, 5) File "/usr/lib/python2.7/unittest/case.py", line 515, in assertEqual assertion_func(first, second, msg=msg) File "/usr/lib/python2.7/unittest/case.py", line 508, in _baseAssertEqual raise self.failureException(msg) AssertionError: 4 != 5
python throwing an error HTTP 401 while accessing https://stream.twitter.com/1.1/statuses/filter.json Question: This is the Code I am running to get the stream of tweets using Streaming API by accessing the stream.twitter url mentioned in title. but it is throwing an error (HTTP error 401) In the code I am trying to track multiple terms import time import pycurl import urllib import json import oauth2 API_ENDPOINT_URL = 'https://stream.twitter.com/1.1/statuses/filter.json' USER_AGENT = 'TwitterStream 1.0' OAUTH_KEYS = {'consumer_key': 'ABC', 'consumer_secret': 'ABC', 'access_token_key': 'ABC', 'access_token_secret': 'ABC'} POST_PARAMS = {'include_entities': 0, 'stall_warning': 'true', 'track': 'iphone,ipad,ipod'} class TwitterStream(): def __init__(self, timeout=False): #self.oauth_token = Token(key=OAUTH_KEYS['access_token_key'], secret=OAUTH_KEYS['access_token_secret']) self.oauth_consumer = oauth2.Consumer(key=OAUTH_KEYS['consumer_key'], secret=OAUTH_KEYS['consumer_secret']) self.oauth_token = oauth2.Token(key=OAUTH_KEYS['access_token_key'], secret=OAUTH_KEYS['access_token_secret']) self.conn = None #pycurl.Curl() self.buffer = '' self.timeout = timeout self.setup_connection() def setup_connection(self): """ Create persistant HTTP connection to Streaming API endpoint using cURL. """ if self.conn: self.conn.close() self.buffer = '' self.conn = pycurl.Curl() # Restart connection if less than 1 byte/s is received during "timeout" seconds if isinstance(self.timeout, int): self.conn.setopt(pycurl.LOW_SPEED_LIMIT, 1) self.conn.setopt(pycurl.LOW_SPEED_TIME, self.timeout) self.conn.setopt(pycurl.URL, API_ENDPOINT_URL) self.conn.setopt(pycurl.USERAGENT, USER_AGENT) # Using gzip is optional but saves us bandwidth. self.conn.setopt(pycurl.ENCODING, 'deflate, gzip') self.conn.setopt(pycurl.POST, 1) self.conn.setopt(pycurl.POSTFIELDS, urllib.urlencode(POST_PARAMS)) self.conn.setopt(pycurl.HTTPHEADER, ['Host: stream.twitter.com', 'Authorization: %s' % self.get_oauth_header()]) # self.handle_tweet is the method that are called when new tweets arrive self.conn.setopt(pycurl.WRITEFUNCTION, self.handle_tweet) def get_oauth_header(self): """ Create and return OAuth header. """ params = {'oauth2_version': '1.0', 'oauth2_nonce': oauth2.generate_nonce(), 'oauth2_timestamp': int(time.time())} req = oauth2.Request(method='POST', parameters=params, url='%s?%s' % (API_ENDPOINT_URL, urllib.urlencode(POST_PARAMS))) req.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), self.oauth_consumer, self.oauth_token) return req.to_header()['Authorization'].encode('utf-8') def start(self): """ Start listening to Streaming endpoint. Handle exceptions according to Twitter's recommendations. """ backoff_network_error = 0.25 backoff_http_error = 5 backoff_rate_limit = 60 while True: self.setup_connection() try: self.conn.perform() except: # Network error, use linear back off up to 16 seconds print 'Network error: %s' % self.conn.errstr() print 'Waiting %s seconds before trying again' % backoff_network_error time.sleep(backoff_network_error) backoff_network_error = min(backoff_network_error + 1, 16) continue # HTTP Error sc = self.conn.getinfo(pycurl.HTTP_CODE) if sc == 420: # Rate limit, use exponential back off starting with 1 minute and double each attempt print 'Rate limit, waiting %s seconds' % backoff_rate_limit time.sleep(backoff_rate_limit) backoff_rate_limit *= 2 else: # HTTP error, use exponential back off up to 320 seconds print 'HTTP error %s, %s' % (sc, self.conn.errstr()) print 'Waiting %s seconds' % backoff_http_error time.sleep(backoff_http_error) backoff_http_error = min(backoff_http_error * 2, 320) def handle_tweet(self, data): """ This method is called when data is received through Streaming endpoint. """ self.buffer += data if data.endswith('\r\n') and self.buffer.strip(): # complete message received message = json.loads(self.buffer) self.buffer = '' msg = '' if message.get('limit'): print 'Rate limiting caused us to miss %s tweets' % (message['limit'].get('track')) elif message.get('disconnect'): raise Exception('Got disconnect: %s' % message['disconnect'].get('reason')) elif message.get('warning'): print 'Got warning: %s' % message['warning'].get('message') else: print 'Got tweet with text: %s' % message.get('text') if __name__ == '__main__': ts = TwitterStream() ts.setup_connection() ts.start() Please help me to resolve it. Answer: You could try updating your clock. sudo ntpdate ntp.ubuntu.com From: <http://lembra.wordpress.com/2012/03/08/twitter-stream- mysterious-401unauthorized-status-with-oauth-and-clock-issue/>
Hidden (missing) library dependency, when linking with cl.exe Question: I've just been exposed to a large non-trivial CMake/Eclipse based C++ project. One of the build targets is Windows/nmake based. In the final step of building an executable, the linker throws LNK1104: cannot open file 'python27.lib'. This is correct, because Python 2.7 hasn't been installed. Problem is, I cannot find any references to this library in cl.exe's command line. Also a grep on the whole project directory (including eclipses .metadata directory) won't find anything plausible. Deleting all the cmake generated build stuff didn't help too. The real question is, if MSVC-based libraries (import or static ones) have any mechanism to request additional libraries during the link step implicitely. There are a few pre-compiled ones in the mentioned project. I simply need the vocabulary, where to begin a more qualified search regarding the error cause. Answer: I found the answer here: [Puzzling dependency of Boost.Python 1.54 (debug build) to Python27.lib on Windows](http://stackoverflow.com/questions/19716859/puzzling-dependency-of- boost-python-1-54-debug-build-to-python27-lib-on-window) Basically, the culprit is a `#pragma comment()` directive inside the boost libraries.
flask-restless with mod_wsgi can't connect to MySQL server Question: I am trying to run a flask-restless app in apache using mod_wsgi. This works fine with the development server. I have read everything I can find and none of the answers I have seen seem to work for me. The app handles non-database requests properly but gives the following error when I try to access a url that requires a database access: `OperationalError: (OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 13] Permission denied)") None None` I have whittled down to basically the flask-restless quick-start with my `config` and my flask-sqlalchemy models imported (`from flask import models`). Here is my python code: import flask import flask.ext.sqlalchemy import flask.ext.restless import sys sys.path.insert(0, '/proper/path/to/application') application = flask.Flask(__name__, static_url_path = "") application.debug=True application.config.from_object('config') db = flask.ext.sqlalchemy.SQLAlchemy(application) from app import models # Create the Flask-Restless API manager. manager = flask.ext.restless.APIManager(application, flask_sqlalchemy_db=db) # Create API endpoints, which will be available at /api/<tablename> by # default. Allowed HTTP methods can be specified as well. manager.create_api(models.Asset, methods=['GET']) # start the flask loop if __name__ == '__main__': application.run() I assume that mod_wsgi isn't having a problem finding the `config` file which contains the database access details since I don't get an error when reading the config and I also don't get an error on `from app import models`. My research so far has led me to believe that this has something to do with the sql-alchemy db connection existing in the wrong scope or context and possibly complicated by the flask-restless API manager. I can't seem to wrap my head around it. Answer: Your code under Apache/mod_wsgi will run as a special Apache user. That user likely doesn't have the privileges required to connect to the database. Even though it says 'localhost' and you think that may imply a normal socket connection, some database clients will see 'localhost' and will automatically instead try and use the UNIX socket for the database. It may not have access to that UNIX socket connection. Alternatively, when going through a UNIX socket connection it is trying to validate whether the Apache user than has access, but if the database hasn't been setup to allow the Apache user access, it may then fail. Consider using daemon mode of mod_wsgi and configure daemon mode to run as a different user to the Apache user and one you know has access to the database.
Saving Image in a temporary file in django Question: I am very new in python and django.I have developed a project using django. Here all the images are watermarked.I have watermarked all the images using the following code... from PIL import Image def image_watermark(request,image_id): photo = Photo.objects.get(pk=image_id) watermark = Image.open('{0}/{1}'.format(settings.MEDIA_ROOT,'wmark.png')) img = Image.open(photo.photo.file) img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]- watermark.size[1]),watermark) img.save('{0}/{1}'.format(settings.MEDIA_ROOT,photo.photo.name), quality=80) wrapper = FileWrapper(open(photo.photo.url, 'rb')) response = StreamingHttpResponse(wrapper, 'image/jpeg') response['Content-Length'] = os.path.getsize(photo.photo.url) response['Content-Disposition'] = 'attachment; filename=photo.jpg' return response all of my images are watermarked now.But the problem is,as a user ,if i download these images,i found that the downloaded images are also watermarked,but i want to download the actual image,not the watermarked image,how can i solve the problem? Answer: You need to store the watermarked image into a different file. First you need to create another column to store the Watermarked image. class Photo(models.Model): ... watermarked_photo = ImageField() Then when you save the watermarked image into that column. from PIL import Image def image_watermark(request,image_id): photo = Photo.objects.get(pk=image_id) # Only need to watermark when there's no watermark if not photo.watermarked_photo.name: photo.watermarked_photo.name = 'watermarked_' + photo.photo.name watermark = Image.open('{0}/{1}'.format(settings.MEDIA_ROOT,'wmark.png')) img = Image.open(photo.photo.file) img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]- watermark.size[1]),watermark) img.save('{0}/{1}'.format(settings.MEDIA_ROOT, photo.watermarked_photo.name), quality=80) photo.save() wrapper = FileWrapper(open(photo.watermarked_photo.url, 'rb')) response = StreamingHttpResponse(wrapper, 'image/jpeg') response['Content-Disposition'] = 'attachment; filename=photo.jpg' return response My Django skill is a bit rusty, so this code might not work without some modification. But the idea should be solid. If you only want to use a temp file, then try this from PIL import Image import tempfile def image_watermark(request,image_id): photo = Photo.objects.get(pk=image_id) watermark = Image.open('{0}/{1}'.format(settings.MEDIA_ROOT,'wmark.png')) img = Image.open(photo.photo.file) img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]- watermark.size[1]),watermark) tmpfile = tempfile.TemporaryFile() img.save(tmpfile, img.format, quality=80) tmpfile.seek(0) wrapper = FileWrapper(tmpfile) response = StreamingHttpResponse(wrapper, 'image/jpeg') response['Content-Disposition'] = 'attachment; filename=photo.jpg' return response
How to read from QTextedit in python? Question: I created the GUI using QTDesigner and save the file as .ui extension. Then convert the file to .py file using the following code pyuic4 -x test.ui -o test.py Now I want to integrate my project code to this test.py file. Since I am new to pyqt4, I dont know how to read text from text edit and save to file and viceversa. Following is my code. from PyQt4 import QtCore, QtGui from final_ar_gui import * try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_AnaphoraResolution(object): def setupUi(self, AnaphoraResolution): AnaphoraResolution.setObjectName(_fromUtf8("AnaphoraResolution")) AnaphoraResolution.resize(608, 620) self.textEdit = QtGui.QTextEdit(AnaphoraResolution) self.textEdit.setGeometry(QtCore.QRect(0, 110, 271, 341)) self.textEdit.setObjectName(_fromUtf8("textEdit")) self.textEdit_2 = QtGui.QTextEdit(AnaphoraResolution) self.textEdit_2.setGeometry(QtCore.QRect(310, 110, 271, 341)) self.textEdit_2.setObjectName(_fromUtf8("textEdit_2")) self.pushButton = QtGui.QPushButton(AnaphoraResolution) self.pushButton.setGeometry(QtCore.QRect(40, 470, 91, 27)) self.pushButton.setObjectName(_fromUtf8("pushButton")) self.pushButton_2 = QtGui.QPushButton(AnaphoraResolution) self.pushButton_2.setGeometry(QtCore.QRect(170, 470, 171, 27)) self.pushButton_2.setObjectName(_fromUtf8("pushButton_2")) self.pushButton_3 = QtGui.QPushButton(AnaphoraResolution) self.pushButton_3.setGeometry(QtCore.QRect(370, 470, 81, 27)) self.pushButton_3.setObjectName(_fromUtf8("pushButton_3")) self.pushButton_4 = QtGui.QPushButton(AnaphoraResolution) self.pushButton_4.setGeometry(QtCore.QRect(480, 470, 98, 27)) self.pushButton_4.setObjectName(_fromUtf8("pushButton_4")) self.label = QtGui.QLabel(AnaphoraResolution) self.label.setGeometry(QtCore.QRect(180, 30, 241, 20)) self.label.setObjectName(_fromUtf8("label")) self.retranslateUi(AnaphoraResolution) self.connectActions() QtCore.QMetaObject.connectSlotsByName(AnaphoraResolution) def retranslateUi(self, AnaphoraResolution): AnaphoraResolution.setWindowTitle(QtGui.QApplication.translate("AnaphoraResolution", "Dialog", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton.setText(QtGui.QApplication.translate("AnaphoraResolution", "Enter", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton_2.setText(QtGui.QApplication.translate("AnaphoraResolution", "Pronominal Resolution", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton_3.setText(QtGui.QApplication.translate("AnaphoraResolution", "Clear", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton_4.setText(QtGui.QApplication.translate("AnaphoraResolution", "Quit", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("AnaphoraResolution", "Anaphora Resolution in Malayalam", None, QtGui.QApplication.UnicodeUTF8)) def connectActions(self): self.pushButton.clicked.connect(self.ent) def ent(self): %Dont know what code to write if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) AnaphoraResolution = QtGui.QDialog() ui = Ui_AnaphoraResolution() ui.setupUi(AnaphoraResolution) AnaphoraResolution.show() sys.exit(app.exec_()) When i click enter (push button) the input in the textEdit is read and save into a file named input.txt. When i click quit (pushbutton) the output in the outfile.txt is read and write into textEdit_2 . How to solve this ? Answer: If all you need is the displayed text in your QTextEdit widget, you can access that by using the [`toPlainText()`](http://pyqt.sourceforge.net/Docs/PyQt4/qtextedit.html#toPlainText) method on the widget you need the text from. Example: mytext = self.textEdit.toPlainText() At this point, you can do whatever you want with `mytext`. You can write it to a file, you can manipulated it, etc. If you need to (re)populate your `QTextEdit` with the modified value of `mytext`, you can do that by using [`setPlainText`](http://pyqt.sourceforge.net/Docs/PyQt4/qtextedit.html#setPlainText) self.textEdit.setPlainText(mytext) To write the string to a file, you'll do something like this: with open('somefile.txt', 'a') as f: f.write(mytext) This will append `mytext` to `somefile.txt`
Attribute error in python while trying to sign in Question: I am using python (with selenium webdriver) to sign into yahoo. Below is the code: import unittest from selenium import webdriver from selenium.common.exceptions import NoSuchElementException #Set Selenium firefox browser object browser = webdriver.Firefox() #Navigate to desired page browser.get( 'https://www.yahoo.com/' ) try: element = browser.find_element_by_title( 'Sign In' ) except NoSuchElementException: self.fail( "found: %s" % 'Sign In' ) Below is the error I see: element = browser.find_element_by_title( 'Sign In' ) AttributeError: 'WebDriver' object has no attribute 'find_element_by_title' Any suggestions how to fix this error? Answer: Use [`find_element_by_link_text()`](http://selenium- python.readthedocs.org/en/latest/api.html#selenium.webdriver.remote.webelement.WebElement.find_element_by_link_text) instead: element = browser.find_element_by_link_text('Sign In') Demo: >>> from selenium import webdriver >>> browser = webdriver.Firefox() >>> browser.get('https://www.yahoo.com/') >>> element = browser.find_element_by_link_text('Sign In') >>> element <selenium.webdriver.remote.webelement.WebElement object at 0x1087fc5d0>
python write files and maintain folder structure Question: I'm working on a script that will read files from one location, manipulate the data, and then write the output to a different location. At the command line the user will use a -p to specify a top-level folder and then the script will recurse through there and find all the files. I'm doing this using glob right now and the reading of the file is fine. But I also want the user to specify an output folder to write the files into and I want to maintain the folder structure of the input path. for eachFile in glob(args.path + "/*/*.json"): <- this seems dangerous. Better way? # do something to the json file # output the modified data to its new home #outfile = os.path.join(args.output, os.path.dirname(eachFile), eachFile) <- doesn't work outfile = os.path.join(args.putout, os.path.dirname(eachFile)[1:], eachFile) That last line is the best I've done but it has the problem of assuming this is being run on a posix machine when it strips off the "/" at the front of the directory. Also, let's say I pass in an input path of ~/Documents/2014 and an output of /tmp. The files will be written to /tmp/Users/myusername/Documents/2014/blah/whatever.json. This seems like a fairly common use case so I'm surprised that I haven't found someone else that needed to do this or a simple module that does it easily. Any suggestions? Answer: Here is a script that does close to what you need. The key thing here, is instead of glob, you needed os.walk because you want to drill down through the directory structure. You'll need to add sanity checks, but it's a good start. # Recurse and process files. import os import sys from fnmatch import fnmatch import shutil def process(src_dir, dst_dir, pattern='*'): """Iterate through src_dir, processing all files that match pattern and store them, including their parent directories in dst_dir. """ assert src_dir != dst_dir, 'Source and destination dir must differ.' for dirpath, dirnames, filenames in os.walk(src_dir): # Filter out files that match pattern only. filenames = filter(lambda fname: fnmatch(fname, pattern), filenames) if filenames: dir_ = os.path.join(dst_dir, dirpath) os.makedirs(dir_) for fname in filenames: in_fname = os.path.join(dirpath, fname) out_fname = os.path.join(dir_, fname) # At this point, the destination directory is created and you # have a valid input / output filename, so you'd call your # function to process these files. I just copy them :D shutil.copyfile(in_fname, out_fname) if __name__ == '__main__': process(sys.argv[1], sys.argv[2], '*.txt')
Running multiple stored procedures using pypyodbc giving incomplete results Question: I'm running a relatively simple python script that is meant to read a text file that has a series of stored procedures - one per line. The script should run the stored procedure on the first line, move to the second line, run the stored procedure on the second line, etc etc. Running these stored procedures should populate a particular table. So my problem is that these procedures aren't populating the table with all of the results that they should be. For example, if my file looks like exec myproc 'data1'; exec myproc 'data2'; Where myproc 'data1' should populate this other table with about ~100 records, and myproc 'data2' should populate this other table with an additional ~50 records. Instead, I end up with about 9 results total - 5 from the first proc, 4 from the second. I know the procedures work, because if I run the same sql file (with the procs) through OSQL and I get the correct ~150 records in the other table, so obviously it's something to do with my script. Here's the code I'm running to do this: import pypyodbc conn = pypyodbc.connect(CONN_STR.format("{SQL Server}",server,database,user,password)) conn.autoCommit = True procsFile = openFile('otherfile.txt','r+') #loop through each proc (line) in the file for proc in procsFile: #run the procedure curs = conn.cursor() curs.execute(proc) #commit results conn.commit() curs.close(); conn.close(); procsFile.close(); I'm thinking this has something to do with the procedures not committing...or something?? Frankly I don't really understand why only 5/100 records would be committed. I dont know. any help or advice would be much appreciated. Answer: There a couple things to check. One is that your data1 is actually a string 'data1', or if you want the value of data1? If you want the string 'data1', then you will have to add quotes around it. So your string to execute would look like this: exec_string = 'exec my_proc \'data1\';' * * * In your case you turn ON auto-commit and also you manually commit for the entire connection. I would comment out the auto-commit line: #conn.autoCommit = True And then change conn.commit() to the cursor instead curs.commit() As a one-liner: conn.cursor().execute('exec myproc \'data1\';').commit() * * * Also, your Python semi-colons (;) at the end of the python line are unnecessary, and may be doing something weird in your for-loop. (Keep the SQL ones though.)
Encoding with pandas.read_csv when file name has accents Question: I'm trying to load a CSV with pandas, but am running into a problem if the file name has accents. It's clearly an encoding problem, but although `read_csv` lets you set encoding for text within the file, I can't figure out how to encode the file name properly. input_file = r'C:\...\Datasets\%s\Provinces\Points\%s.csv' % (country, province) self.locs = pandas.read_csv(input_file,sep=',',skipinitialspace=True) The CSV file is Anzoátegui.csv. When I'm getting errors, input_file = 'C:\\...\Datasets\Venezuela\Provinces\Points\Anzoátegui.csv Error code: OSError: File b'C:\\PF2\\QGIS Valmiera\\Datasets\\Venezuela\\Provinces\\Points\\Anzo\xc3\xa1tegui.csv' does not exist So maybe it's converting my string to bytes? I tried using `io.StringIO(input_file)` as well, which puts the correct file name as a column header on an empty `DataFrame`: Empty DataFrame Columns: [C:\PF2\QGIS Valmiera\Datasets\Venezuela\Provinces\Points\Anzoátegui.csv] Index: [] Any ideas on how to get this file to load? Unfortunately I can't just strip out accents, as I have to interface with software that requires the proper name, and I have a ton of files to format (not just the one). Thanks! Edit: Full error Traceback (most recent call last): File "C:\PF2\eclipse-standard-kepler-SR2-win32-x86_64\eclipse\plugins\org.python.pydev_3.3.3.201401272249\pysrc\pydevd_comm.py", line 891, in doIt result = pydevd_vars.evaluateExpression(self.thread_id, self.frame_id, self.expression, self.doExec) File "C:\PF2\eclipse-standard-kepler-SR2-win32-x86_64\eclipse\plugins\org.python.pydev_3.3.3.201401272249\pysrc\pydevd_vars.py", line 486, in evaluateExpression result = eval(compiled, updated_globals, frame.f_locals) File "<string>", line 1, in <module> File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 404, in parser_f return _read(filepath_or_buffer, kwds) File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 205, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 486, in __init__ self._make_engine(self.engine) File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 594, in _make_engine self._engine = CParserWrapper(self.f, **self.options) File "C:\Python33\lib\site-packages\pandas\io\parsers.py", line 952, in __init__ self._reader = _parser.TextReader(src, **kwds) File "parser.pyx", line 330, in pandas.parser.TextReader.__cinit__ (pandas\parser.c:3040) File "parser.pyx", line 557, in pandas.parser.TextReader._setup_parser_source (pandas\parser.c:5387) OSError: File b'C:\\PF2\\QGIS Valmiera\\Datasets\\Venezuela\\Provinces\\Points\\Anzo\xc3\xa1tegui.csv' does not exist Answer: Ok folks, I got a little lost in dependency hell, but it turns out that this issue was fixed in pandas 0.14.0. Install the updated version to get files named with accents to import correctly. [Comments at github](https://github.com/pydata/pandas/issues/7345). Thanks for the input!
How do I load a modified python module? Question: I'm using the widely used module PySerial (<http://pyserial.sourceforge.net/index.html#>) for serial communication in Python. One of it's functions is readline() which reads a line until end of line '\n'. I created a new function readline_v2() similar to readline() in the same file serialutil.py. But each time I install the module using "python install setup.py", it seems as if none of the changes are reflected. The new function is not detected. What am I doing wrong? I'm using Windows 8 64 bit. I first downloaded pyserial's source, uncompressed it, and modified it when I found it didn't work the way I wanted it to. I tried it using pip also, using "pip install pyserial" but once again there is no change. I made sure I uninstalled the previous version before reinstalling. The files don't exist in the "C:/python27/lib/site-packages" folder after the uninstall. I also deleted all compiled/build files I saw in the serial package before reinstalling. Note: In "C:/python27/lib/site-packages", after installation, I can see the change reflected in the specific file serialutil.py. But I still am unable to call the function. Note2: serialutil.py consists of functions of the form- > > def readline() > def readline_v2() > This is the only place I added my function since the original function readline() is defined/used nowhere else. Final Note: I can't find a fix. But I used a workaround. I defined the new function in my file after doing an "import serial", instead of modifying the package itself. Not the ideal solution, but it works fine. Answer: You need to add the location of your new module to path with sys.path.append() or alternatively keep the new module in your project directory
Kivy Garden in PyInstaller - stuck trying to trace import Question: I have a Kivy-based Python project that I'm trying to build. It uses the NavigationDrawer component from Kivy Garden, through an import: > from kivy.garden.navigationdrawer import NavigationDrawer I have a PyInstaller spec file for it which builds a distributable version. This version works well on my machine, but unfortunately not on other machines. Running the interpreter in the 'dist' version with the -v switch, it appears that when I run the distributable on my machine, the navigationdrawer component is not actually coming from inside my build folder. All the other imports show something like: > import kivy.graphics.gl_instructions # dynamically loaded from > C:\Users\me\myapp\dist\RACECA~1\kivy.graphics.gl_instructions.pyd But the navigationdrawer import says: > import kivy.garden.navigationdrawer > > """directory C:\Users\me\\.kivy\garden\garden.navigationdrawer > C:\Users\me\\.kivy\garden\garden.navigationdrawer\\__init__.pyc matches > C:\Users\me\\.kivy\garden\garden.navigationdrawer\\__init__.py import > kivy.garden.navigationdrawer # precompiled from > C:\Users\me\\.kivy\garden\garden.navigationdrawer\\__init__.pyc""" But noo! I don't want you to import them from c:\users. I want them to get nicely copied into my dist folder like all the other imports. I've tried adding c:\users\me to PyInstaller's pathex, the system PATH and PYTHONPATH without any joy. Anyone have any ideas? Answer: Try installing your garden packages into your app. i.e. garden install --app navigationdrawer This will create a libs/garden folder inside the current directory and place the garden packages in there, which should make it easier to include.
Efficient way to aggregate and remove duplicates from very large (password) lists (SOLVED) Question: Context: * I am attempting to combine a large amount of separate password list text files into a single file for use in dictionary based password cracking. * Each text file is line delimited (a single password per line) and there are 82 separate files at the moment. Most (66) files are in the 1-100Mb filesize range, 12 are 100-700Mb, 3 are 2Gb, and 1 (the most problematic) is 11.2Gb. * In total I estimate 1.75 billion non-unique passwords need processing; of these I estimate ~450 million (%25) will be duplicates and ultimately need to be discarded. * I am attempting to do this on a device which has a little over 6Gb of RAM free to play with (i.e. 8Gb with 2Gb already consumed). Problem: I need a way to a) aggregate all of these passwords together and b) remove exact duplicates, within my RAM memory constrains and within a reasonable (~7 days, ideally much less but really I don't care if it takes weeks and then I never need to run it again) time window. I am a competent Python programmer and thus gave it a crack several times already. My most successful attempt used sqlite3 to store processed passwords on the hard disk as it progressed. However this meant that keeping track of which files had already been completed between processing instances (I cancelled and restarted several times to make changes) was tediously achieved by hashing each completed file and maintaining/comparing these each time a new file was opened. For the very large files however, any progress would be lost. I was processing the text files in blocks of ~1 billion (at most) lines at a time to prevent memory exhaustion without having no feedback for extended periods of time. I know that I could, given a lot of time populate my database fully as I achieved a DB filesize of ~4.5Gb in 24 hours of runtime so I estimate that left to run it would take about 4 days at most to get through everything, but I don't know if/how to most efficiently read/write to it nor do I have any good ideas on how to tackle the removing of duplicates (do it as I am populating the DB or make additional passes afterwards...? Is there a much faster means of doing lookups for uniqueness in a database configuration I don't know about?). * * * My request here today is for advice / solutions to a programming and optimisation approach on how to achieve my giant, unique password list (ideally with Python). I am totally open to taking a completely different tack if I am off the mark already. * * * Two nice to haves are: * A way to add more passwords in the future without having to rebuild the whole list; and * A database < 20Gb at the end of all this so that it isn't a huge pain to move around. * * * **Solution** Based on CL's solution which was ultimately a lot more elegant than what I was thinking I came up with a slightly modified method. Following CL's advice I setup a sqlite3 DB and fed the text files into a Python script which consumed them and then output a command to insert them into the DB. Straight off the bat this ~did~ work but was extremely (infeasibly) slow. I solved this by a few simple DB optimisations which was much easier to implement and frankly cleaner to just do all from the core Python script included below which builds upon CL's skeleton code. The fact that the original code was generating **sooooooo** many I/O operations was causing something funny on my (Win7) OS causing BSODs and lost data. I solved this by making the insertion of a whole password file one SQL transaction plus a couple of pragma changes. In the end the code runs at about 30,000 insertions / sec which is not the best but is certainly acceptable for my purposes. It may be the case that this will still fail on the largest of files but if/when that is the case, I will simply chunk the file down into smaller 1Gb portions and consume them individually. import sys import apsw i = 0 con = apsw.Connection("passwords_test.db") cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS Passwords(password TEXT PRIMARY KEY) WITHOUT ROWID;") cur.execute("PRAGMA journal_mode = MEMORY;") cur.execute("PRAGMA synchronous = OFF;") cur.execute("BEGIN TRANSACTION") for line in sys.stdin: escaped = line.rstrip().replace("'", "''") cur.execute("INSERT OR IGNORE INTO Passwords VALUES(?);", (escaped,)) i += 1 if i % 100000 == 0: # Simple line counter to show how far through a file we are print i cur.execute("COMMIT") con.close(True) This code is then run from command line: insert_passwords.py < passwordfile1.txt And automated by: for %%f in (*.txt) do ( insert_passwords.py < %%f ) All in all, the DB file itself is not growing too quickly, the insertion rate is sufficient, I can break/resume operations at the drop of a hat, duplicate values are being accurately discarded, and the current limiting factor is the lookup speed of the DB not the CPU or disk space. Answer: When storing the passwords in an SQL database, being able to detect duplicates requires an index. This implies that the passwords are stored twice, in the table and in the index. However, SQLite [3.8.2](http://www.sqlite.org/releaselog/3_8_2.html) or later supports [WITHOUT ROWID tables](http://www.sqlite.org/withoutrowid.html) (called "clustered index" or "index-organized tables" in other databases), which avoid the separate index for the primary key. There is no Python version that already has SQLite 3.8.2 included. If you are not using [APSW](http://code.google.com/p/apsw/), you can still use Python to create the SQL commands: 1. Install the newest `sqlite3` command-line shell ([download page](http://www.sqlite.org/download.html)). 2. Create a database table: $ sqlite3 passwords.db SQLite version 3.8.5 2014-06-02 21:00:34 Enter ".help" for usage hints. sqlite> CREATE TABLE MyTable(password TEXT PRIMARY KEY) WITHOUT ROWID; sqlite> .exit 3. Create a Python script to create the INSERT statements: import sys print "BEGIN;" for line in sys.stdin: escaped = line.rstrip().replace("'", "''") print "INSERT OR IGNORE INTO MyTable VALUES('%s');" % escaped print "COMMIT;" (The INSERT OR IGNORE statement will not insert a row if a duplicate would violate the primary key's unique constraint.) 4. Insert the passwords by piping the commands into the database shell: $ python insert_passwords.py < passwords.txt | sqlite3 passwords.db There is no need to split up input files; fewer transaction have less overhead.
Tkinter Ttk Python: limiting text entry widget values to numbers and limiting amount of characters Question: Probably an easy one here: in tkinter, ttk, how do you limit the amount of characters that can be input by the user into an entry field? For example, only allowing the user to insert one character and limiting the ability to insert any others? Additionally, how would I then make it so that only an intiger can be input into said text entry field, so that it doesn't allow the user to input any characters that aren't {0:9}? Thanks :) Btw i'm fairly new to programming so the simpler put, the better :) If it's any help to showing what to do, here's my program so far: from tkinter import * from tkinter import ttk def calculate(*args): try: valuex=int(x.get()) valuey=int(y.get()) valuez=int(z.get()) cappf.set(int(str(valuex)+str(valuey))*10**valuez) capnf.set(int(str(valuex)+str(valuey))*10**valuez*10**-3) capuf.set(int(str(valuex)+str(valuey))*10**valuez*10**-6) except ValueError: pass root=Tk() root.title('Capacitor Calculator') mainframe=ttk.Frame(root, padding='10 10 10 10') mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) x=StringVar() x_entry=ttk.Entry(mainframe, width=3, textvariable=x) x_entry.grid(column=1, row=2, sticky=(W,E)) y=StringVar() y_entry=ttk.Entry(mainframe, width=3, textvariable=y) y_entry.grid(column=1, row=3, sticky=(W,E)) z=StringVar() z_entry=ttk.Entry(mainframe, width=3, textvariable=z) z_entry.grid(column=1, row=4, sticky=(W,E)) cappf=StringVar() capnf=StringVar() capuf=StringVar() ttk.Button(mainframe, width=7, text='Calculate', command=calculate).grid(column=2, row=5, sticky=(N, E, S, W)) ttk.Label(mainframe, textvariable=cappf).grid(column=2, row=2, sticky=N) ttk.Label(mainframe, textvariable=capnf).grid(column=2, row=3, sticky=N) ttk.Label(mainframe, textvariable=capuf).grid(column=2, row=4, sticky=N) ttk.Label(mainframe, text='Input:').grid(column=1, row=1, sticky=N) ttk.Label(mainframe, text='Amount:').grid(column=2, row=1, sticky=N) ttk.Label(mainframe, text='Units:').grid(column=3, row=1, sticky=N) ttk.Label(mainframe, text='pf').grid(column=3, row=2, sticky=N) ttk.Label(mainframe, text='nf').grid(column=3, row=3, sticky=N) ttk.Label(mainframe, text='uf').grid(column=3, row=4, sticky=N) ttk.Button(mainframe, width=7, text='Quit', style='red.TButton', command=root.destroy).grid(column=2, row=6, sticky=(N, E, S, W)) ttk.Style().configure('red.TButton', foreground='red', padding=6, font='Corbel 18') ttk.Style().configure('TLabel', padding=6, font='Corbel 16', foreground='#0077AF') ttk.Style().configure("TButton", padding=6, relief="flat", font='Corbel 18', foreground='#00AA11') for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=3) x_entry.focus() y_entry.focus() z_entry.focus() root.bind('<Return>', calculate) root.mainloop() Answer: The entry widget supports a validation callback, specified by setting the validation mode (via the `validate` property) and providing the callback itself (via the `validatecommand` property). The Tkinter documentation for how to use it is very poor, unfortunately. The validation mode can be the strings `focusOut` (to apply the validation when the focus leaves the widget) and `key` (to apply it when the user presses a key). And `focus` and `focusIn` but I've not found them to be so useful. The validation callback should return a boolean that states whether the current (== new, in the case of `key` validation) contents are valid. If the validation fails, the change is rejected (the contents are reset) and the invalid contents callback is invoked (via the `invalidcommand` property) which can do things like sound the bell or make the screen flash. * * * A more elaborate validation mechanism is to always _officially_ claim that the edit is valid, but to change the background of the entry (or use some other indicator) to show that the edit _will be rejected_. Then, only do full validation/rejection on overall submission of the form (you were going to do that anyway, yes?). Like that, temporarily invalid states are permitted so long as the user goes back and fixes them before finishing their session. This is quite a lot more usable.
Best way to package a Python library that includes a C shared library? Question: I have written a library whose main functionality is implemented in C (speed is critical), with a thin Python layer around it to deal with the `ctypes` nastiness. I'm coming to package it and I'm wondering how I might best go about this. The code it must interface with is a shared library. I have a Makefile which builds the C code and creates the `.so` file, but I don't know how I compile this via distutils. Should I just call out to `make` with `subprocess` by overriding the `install` command (if so, is `install` the place for this, or is `build` more appropriate?) **Update** : I want to note that this is _not_ a Python extension. That is, the C library contains no code to itself interact with the Python runtime. Python is making foreign function calls to a straight C shared library. Answer: Given that you followed the instructions on how to [create Python extensions in C](https://docs.python.org/2/extending/extending.html), you should just enlist the extension modules like in [this documentation](https://docs.python.org/2/distutils/setupscript.html#describing- extension-modules). So the `setup.py` script of your library should look like this: from distutils.core import setup, Extension setup( name='your_python_library', version='1.0', ext_modules=[Extension('your_c_extension', ['your_c_extension.c'])], ) and `distutils` knows how to compile your extension to C shared library and moreover where to put it. _Of course I have no further information about your library, so you probably want to add more arguments to`setup(...)` call._
AttributeError: "'NoneType' object has no attribute 'path'" in <function _remove at 0x10c49a668> ignored Question: I'm trying to implement my coursera python project in flask environment. Also I'm using the <https://github.com/miguelgrinberg/flasky> (branch 7a) to understand how the blueprints work. Now, I define 2 blueprints: main_blueprint & rpsls_blueprint. And get the following error after running application: Traceback (most recent call last): File "manage.py", line 8, in <module> app = create_app(os.getenv('FLASK_CONFIG') or 'default') File "..../app/__init__.py", line 29, in create_app app.register_blueprint(rpsls_blueprint) File "/Library/Python/2.7/site-packages/flask/app.py", line 62, in wrapper_func return f(self, *args, **kwargs) File "/Library/Python/2.7/site-packages/flask/app.py", line 880, in register_blueprint if blueprint.name in self.blueprints: AttributeError: 'module' object has no attribute 'name' Exception AttributeError: "'NoneType' object has no attribute 'path'" in <function _remove at 0x10c49a668> ignored Does someone know where the problem is? Here is the related part of my `app/__init__.py` file: def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .rpsls import rpsls as rpsls_blueprint app.register_blueprint(rpsls_blueprint) return app Here is my app/rpsls/rpsls.py file: import random class RpslsGame(): def __init__(self): pass def name_to_number(self, name): if name == "rock": return 0 elif name == "Spock": return 1 elif name == "paper": return 2 elif name == "lizard": return 3 elif name == "scissors": return 4 else: return name + " does not match any\ of the five correct input strings" def number_to_name(self, number): if number == 0: return "rock" elif number == 1: return "Spock" elif number == 2: return "paper" elif number == 3: return "lizard" elif number == 4: return "scissors" else: return str(number) + \ " is not in the correct range" def rpslsMethod(self, player_choice): result = "" result += "Player chooses " + str(player_choice) + "\n" player_number = self.name_to_number(player_choice) comp_number = random.randrange(0, 5) comp_choice = self.number_to_name(comp_number) result += "Computer chooses " + comp_choice + "\n" differene = (comp_number - player_number) % 5 if (differene == 1 or differene == 2): result += "Computer wins\n" elif (differene == 3 or differene == 4): result += "Player wins\n" elif (differene == 0): result += "Try again, It's a tie\n" return result My app/rpsls/**init**.py file: from flask import Blueprint rpsls = Blueprint('rpsls', __name__) from . import views Answer: You imported the `rpls` module from the `rpls` package. That's a _module_ , not a blueprint object. You cannot register a module as a blueprint; you can only register [`flask.Blueprint()` instances](https://flask.readthedocs.org/en/latest/api/#flask.Blueprint). You may want to read up on how [Flask Blueprints work](https://flask.readthedocs.org/en/latest/blueprints/). You have both a `rpls` object in the `rpls` package, _and_ a submodule. When the `app.rpls.rpls` module is imported, it **replaced** the `rpls` `Blueprint` instance in your `__init__.py` file; the namespaces are not separate. Rename one or the other; the module or the `Blueprint` object.
Django Error: __init__() takes exactly 2 arguments (3 given) Question: Anyone can find what is causing the error in my code? I already searched, but didn't find an answer. I think the problem is with the function objects.get(param), but I'm not sure. What I wanted to do with my code was to retrieve the objects Genre, Country, Language and Directors if they were already added to the database. Here's the code: Models.py from django.db import models from numpy import unique class Director(models.Model): director = models.CharField(max_length=500, unique=True) def __unicode__(self): return self.director def __init__(self, director): super(Director, self).__init__() self.director = director class Language(models.Model): language = models.CharField(max_length=500, unique=True) def __unicode__(self): return self.language def __init__(self, language): super(Language, self).__init__() self.language = language class Genre(models.Model): genre = models.CharField(max_length=500, unique=True) def __unicode__(self): return self.genre def __init__(self, genre): super(Genre, self).__init__() self.genre = genre class Country(models.Model): country = models.CharField(max_length=500, unique=True) def __unicode__(self): return self.country def __init__(self, country): super(Country, self).__init__() self.country = country class Movie(models.Model): id_movie = models.CharField(max_length=200, unique=True) rating = models.CharField(max_length=200) votes = models.CharField(max_length=200) year = models.CharField(max_length=10) genre = models.ManyToManyField(Genre) country = models.ManyToManyField(Country) language = models.ManyToManyField(Language) directors = models.ManyToManyField(Director) def __init__(self, id_movie, rating, votes, year): super(Movie, self).__init__() self.id_movie = id_movie self.rating = rating self.votes = votes self.year = year def __unicode__(self): return self.id_movie crawler.py from movie_info.models import Movie, Genre, Director, Language, Country def get_movie_info(codigo_do_filme): import imdb ia = imdb.IMDb() movie = ia.get_movie(codigo_do_filme) return {'titulo': movie['title'], 'rating': movie['rating'], 'votes': movie['votes'], 'ano': movie['year'], 'genero': movie['genre'][0], 'pais': movie['countries'][0], 'idioma': movie['lang'][0], 'directors': movie['director']} def read_sheet(file_name, fieldnames=None, delimiter=",", quotechar="\n"): from csv import DictReader reader = DictReader(open(file_name,'rb'), fieldnames = fieldnames, delimiter = delimiter, quotechar=quotechar) return reader def fill_db_movie_info(the_sheet_file): file_csv = read_sheet(the_sheet_file) for movie in file_csv: id_filme = movie['id_move'] if not Movie.objects.filter(id_movie=id_filme).exists(): info = get_movie_info(id_filme) rating_imdb = info['rating'] movie_votes = info['votes'] movie_year = info['ano'] movie_genre = info['genero'] movie_country = info['pais'] movie_lang = info['idioma'] movie_directors = info['directors'] addToDB = Movie(id_filme, rating_imdb, movie_votes, movie_year) addToDB.save() if not Genre.objects.filter(genre=movie_genre).exists(): genreToDB = Genre(movie_genre) genreToDB.save() addToDB.genre.add(genreToDB) else: addToDB.genre.add(Genre.objects.get(genre=movie_genre)) if not Country.objects.filter(country=movie_country).exists(): countryToDB = Country(movie_country) countryToDB.save() addToDB.country.add(countryToDB) else: addToDB.country.add(Country.objects.get(country=movie_country)) if not Language.objects.filter(language=movie_lang).exists(): langToDB = Language(movie_lang) langToDB.save() addToDB.language.add(langToDB) else: addToDB.language.add(Language.objects.get(language=movie_lang)) for m_director in movie_directors: if not Director.objects.filter(director=m_director['name']).exists(): directorsToDB = Director(m_director['name']) directorsToDB.save() addToDB.directors.add(directorsToDB) else: addToDB.directors.add(Director.objects.get(director=m_director['name'])) print "salvou: " + id_filme, rating_imdb, movie_votes, movie_year, movie_genre, movie_country, movie_lang, movie_directors[0] The Traceback: pydev debugger: starting (pid: 1424) Traceback (most recent call last): File "/Applications/eclipse/plugins/org.python.pydev_3.5.0.201405201709/pysrc/pydevd.py", line 1845, in <module> debugger.run(setup['file'], None, None) File "/Applications/eclipse/plugins/org.python.pydev_3.5.0.201405201709/pysrc/pydevd.py", line 1373, in run pydev_imports.execfile(file, globals, locals) # execute the script File "/Users/rubenspessoa/Documents/Workspace/LearningDjango/main.py", line 7, in <module> fill_db_movie_info('/Users/rubenspessoa/Documents/Workspace/DATASET/test_subdataset.csv') File "/Users/rubenspessoa/Documents/Workspace/LearningDjango/crawler.py", line 49, in fill_db_movie_info addToDB.country.add(Country.objects.get(country=movie_country)) File "/Library/Python/2.7/site-packages/django/db/models/manager.py", line 151, in get return self.get_queryset().get(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 304, in get num = len(clone) File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 77, in __len__ self._fetch_all() File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 857, in _fetch_all self._result_cache = list(self.iterator()) File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 230, in iterator obj = model(*row_data) TypeError: __init__() takes exactly 2 arguments (3 given) Answer: You have defined `__init__` methods for all your models. You should not do that.
How is semaphore variable passed into the following object in python? Question: After tweaking with this piece of code a few times, I dropped sem.release() in the Server object WITHOUT actually passing the variable sem into it. But it works wonderfully... Can't seem to understand why a error wasn't throw for undeclared variable/reference import threading,time class Server(threading.Thread): def __init__(self, hostname): super(Server, self).__init__() self.__hostname = hostname def run(self): print self.__hostname+' left' time.sleep(5) print self.__hostname+' back' sem.release() #init sem = threading.BoundedSemaphore(2) for x in xrange(1,8): sem.acquire() Server('thread '+str(x)).start() Answer: There's nothing special about accessing a global variable inside a class. x = 3 class xprinter(object): def __init__(self): print(x) xprinter() output: 3
How can I use "include.yaml" in google appengine to share a library within two apps? Question: I have two different applications on GAE, but both have some code in common. I wanted to share that code but I can't find a way to import a .py file that's not in the same directory as the main app. I think that "includes" in the yaml file could be what I need (<https://developers.google.com/appengine/docs/python/config/appconfig#Python_app_yaml_Includes>) but I can't find any example on how to use it. I understand I need an include.yaml file, but what should I write in it!? Is there some more documentation I'm missing? I can't find a way to import that code in my main app... is there any? Answer: Thats not necessary. Make sure you include the path to the file with `sys.setpath()` pointing to the directory containing the other python code, and put an `__init__.py` in that directory. The best place to do this is in `appengine_config.py`
detect key press in python? Question: I am making a stopwatch type program in python and I would like to know how to detect if a key is pressed (such as p for pause and s for stop), and I would not like it to be something like raw_input that waits for the user's input before continuing execution. Anyone know how to do this in a while loop? Also, I would like to make this cross-platform, but if that is not possible, then my main development target is linux Answer: Use PyGame to have a window and then you can get the key events. **For the letter`p`:** import pygame, sys import pygame.locals() pygame.init() BLACK = (0,0,0) WIDTH = 1280 HEIGHT = 1024 windowSurface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) windowSurface.fill(BLACK) while True: events = pygame.event.get() for event in events: if event.key == pygame.K_p: #Do what you want to here pass if event.type == QUIT: pygame.quit() sys.exit()
python motor mongo cursor length or peek next Question: is there a way of determining the length of the motor mongo cursor or peeking ahead to see if there is a next ( instead of `fetch_next` perhaps `has_next` ) and not the `cursor.size()` that does not take into the provided limit() basically i desire to add the required json comma while (yield cursor.fetch_next): document = cursor.next_object() print document if cursor.has_next() # Sweeet print "," Answer: You can use the "alive" property. Try running this: from tornado import gen, ioloop import motor client = motor.MotorClient() @gen.coroutine def f(): collection = client.test.collection yield collection.drop() yield collection.insert([{'_id': i} for i in range(100)]) cursor = collection.find() while (yield cursor.fetch_next): print cursor.next_object(), cursor.alive ioloop.IOLoop.current().run_sync(f) It prints "True" until the final document, when alive is "False". A MotorCursor fetches data from the server in batches. ([The MongoDB documentation on batches](http://docs.mongodb.org/manual/core/cursors/#cursor- batches) explains how cursors and batches work for all MongoDB drivers, including Motor.) When "alive" is True it means either that there is more data available on the server, or data is buffered in the MotorCursor, or both. There is a race condition, however. Say that you fetch all but the final document, and before you fetch that last document another client deletes it, then you'll fail to find the last document even though "alive" was "True". Better to rearrange your loop: @gen.coroutine def f(): collection = client.test.collection yield collection.drop() yield collection.insert([{'_id': i} for i in range(100)]) cursor = collection.find() if (yield cursor.fetch_next): sys.stdout.write(str(cursor.next_object())) while (yield cursor.fetch_next): sys.stdout.write(", ") sys.stdout.write(str(cursor.next_object())) print
how to access global variable within __main__ scope? Question: I'm confused about the namespace and scope of variables in python Suppose I have a test.py: # -*- coding: utf-8 -*- """ @author: jason """ if __name__ == '__main__': global strName print strName and then, I define a variable named strName and try to access it in the test.py, but it throws an error: In [9]: strName = "Joe" In [10]: run test.py hello --------------------------------------------------------------------------- NameError Traceback (most recent call last) C:\Anaconda\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc) 195 else: 196 filename = fname --> 197 exec compile(scripttext, filename, 'exec') in glob, loc 198 else: 199 def execfile(fname, *where): d:\playground\test.py in <module>() 13 print "hello" 14 global strName ---> 15 print strName 16 NameError: global name 'strName' is not defined In [11]: I was wondering why this happens and is there any way to access strName in test.py? Answer: **test.py:** strName = "John Doe" print strName **Interactive Shell:** $ python >>> from test import strName >>> print strName John Doe
from qgis.core import QgsFeature, QgsGeometry. DLL load failed Question: I recently installed QGIS and I want to import qgis module of Python. I use Windows 7 x64 and QGIS 2.2 x64. I set the PATH to : C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\mapnik-v2.2.0\lib;C:\mapnik-v2.2.0\bin;C:\Program Files (x86)\QGIS Valmiera\apps\qgis\python;C:\OSGeo4W\bin;E:\Python\GeoDjango\myplanet;E:\Python\GeoDjango\myplanet;C:\Program Files (x86)\QGIS Valmiera\bin;C:\Program Files (x86)\QGIS Valmiera\apps\msys\bin;C:\Program Files (x86)\QGIS Valmiera\apps\Python27;C:\Program Files (x86)\QGIS Valmiera\bin;C:\Program Files (x86)\QGIS Valmiera\apps\qgis\python\qgis; and PYTHONPATH to: C:\mapnik-v2.2.0\python\2.7\site-packages;E:\Python\GeoDjango\myplanet;C:\Program Files\QGIS Valmiera\apps\qgis\python;C:\Program Files\QGIS Valmiera\apps\Python27\lib;C:\Program Files\QGIS Valmiera\apps\Python27\Lib\site-packages;C:\Program Files\QGIS Valmiera\apps\Python27\DLLs; I still get this error: import qgis File "C:\Program Files\QGIS Valmiera\apps\qgis\python\qgis\__init__.py", line 35, in <module> from qgis.core import QgsFeature, QgsGeometry ImportError: DLL load failed: The specified module could not be found. I used Dependency Walker to track the problems with the DLL load. this is the screenshot of Dependency Walker: ![enter image description here](http://i.stack.imgur.com/RO8o3.png) Error: At least one module has an unresolved import due to a missing export function in an implicitly dependent module. Error: Modules with different CPU types were found. Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module. How can I fix the errors? Answer: See here: [DLL load failed with PyQGIS](http://stackoverflow.com/questions/14334000/dll-load-failed-with- pyqgis/25269980#25269980) import sys sys.path.extend([r"C:\Program Files\QGIS Valmiera\apps",r"C:\Program Files\QGIS Valmiera\apps\qgis\bin",r"C:\Program Files\QGIS Valmiera\apps\Python27"]) import qgis.core
Python: Trouble with encoding on Windows (Bokeh plotting library) Question: I am trying to reproduce the simplest examples from the [Bokeh tutorial](http://bokeh.pydata.org/tutorial/basic.html), on a 64-bit Windows machine with Python 3.3.0. Here is the code in its entirety import pandas as pd import numpy as np import matplotlib.pyplot as mpl # NOTE need this import as output_file was not getting imported into the # global namespace import bokeh.plotting as bkp from bokeh.plotting import * # Skip the first point because it can be troublesome theta = np.linspace(0, 8*np.pi, 10000)[1:] # Compute the radial coordinates for some different spirals lituus = theta**(-1/2) # lituus golden = np.exp(0.306349*theta) # golden arch = theta # Archimedean fermat = theta**(1/2) # Fermat's # Now compute the X and Y coordinates (polar mappers planned for Bokeh later) golden_x = golden*np.cos(theta) golden_y = golden*np.sin(theta) lituus_x = lituus*np.cos(theta) lituus_y = lituus*np.sin(theta) arch_x = arch*np.cos(theta) arch_y = arch*np.sin(theta) fermat_x = fermat*np.cos(theta) fermat_y = fermat*np.sin(theta) # output to static HTML file bkp.output_file("lines.html") # Plot the Archimedean spiral using the `line` renderer. Note how we set the # color, line thickness, title, and legend value. line(arch_x, arch_y, color="red", line_width=2, title="Archimean", legend="Archimedean") This gives me the following error: Traceback (most recent call last): File "F:\programming\python\python64\python33\lib\site-packages\IPython\core\interactiveshell.py", line 2732, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-1-00be3b4eba05>", line 1, in <module> bkp.line(arch_x, arch_y, color="red", line_width=2, title="Archimean", legend="Archimedean") File "F:\programming\python\python64\python33\lib\site-packages\bokeh\plotting.py", line 318, in wrapper save() File "F:\programming\python\python64\python33\lib\site-packages\bokeh\plotting.py", line 284, in save f.write(html) File "F:\programming\python\python64\python33\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 1831286-1831289: character maps to <undefined> I understand that this has something to do with the encoding that Python is using to write to the output file, but don't know enough about setting the encoding of the output file or the encoding that is being used by Python to write out to fix this. Help appreciated. ## Edit: I tried to implement the advice given [here](http://www.macfreek.nl/memory/Encoding_of_Python_stdout), to always pass stdout output through a streamwriter: if sys.stdout.encoding != 'UTF-8': sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict') if sys.stderr.encoding != 'UTF-8': sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict') but some of the interface appears to have changed, and there is no `sys.stdout.encoding` variable. Traceback (most recent call last): File "F:\programming\python\python64\python33\lib\site-packages\IPython\core\interactiveshell.py", line 2732, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-1-e12310bc7a07>", line 1, in <module> if sys.stdout.encoding != 'UTF-8': File "F:\programming\python\python64\python33\lib\codecs.py", line 387, in __getattr__ return getattr(self.stream, name) AttributeError: '_io.FileIO' object has no attribute 'encoding' Answer: I have opened an issue to track this problem: <https://github.com/ContinuumIO/bokeh/issues/682> As you have discussed with eryksun, it seems easily fixable. I will keep you updated here, but if you want to participate in the issue, you are very welcome. Cheers
python 2.7 imaplib error Question: I tried to connect to my mail server via imaplib and got an error in constructor: My code: import imaplib imaplib.IMAP4_SSL('my_host.com', 1234) Error: Traceback (most recent call last) /home/username/www/site/<ipython console> in <module>() /usr/lib/python2.7/imaplib.py in __init__(self, host, port, keyfile, certfile) 1163 self.keyfile = keyfile 1164 self.certfile = certfile -> 1165 IMAP4.__init__(self, host, port) 1166 1167 /usr/lib/python2.7/imaplib.py in __init__(self, host, port) 197 self.state = 'NONAUTH' 198 else: --> 199 raise self.error(self.welcome) 200 201 typ, dat = self.capability() error: None Python recieved response from server and then raise an error, but it's a normal continuation response. Response from server: +OK my_host.com POP3 MDaemon 12.5.6 ready <MDAEMON-F201406061147.AA472534MD1387@my_host.com> What I should do to recieve my mails from my server? Answer: Demon point that he using protocol POP3. You are trying to communicate whit him using IMAP protocol. Change lib to poplib or change port to communicate via IMAP protocol(default is 143).
How to create graphic slider in Python that can be modified with mouse? Question: How can i create a graphic slider similar to a progress bar in PyQt that can be modified from 0 to 100 with mouse? ![enter image description here](http://i.stack.imgur.com/rUa9m.jpg) Answer: You have to set QSlider stylesheet appropriately. This solution is based on PyQt5 import sys from PyQt5 import QtGui, QtCore, QtWidgets class MyApp(object): def __init__(self): super(MyApp, self).__init__() self.mainWidget = QtWidgets.QWidget() self.mainLayout = QtWidgets.QVBoxLayout() self.mainWidget.setLayout(self.mainLayout) self.slider = QtWidgets.QSlider() self.slider.setOrientation(QtCore.Qt.Horizontal) self.slider.setStyleSheet(self.stylesheet()) self.mainLayout.addWidget(self.slider) self.mainWidget.show() sys.exit(app.exec_()) def stylesheet(self): return """ QSlider::groove:horizontal { background: white; height: 40px; } QSlider::sub-page:horizontal { background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #66e, stop: 1 #bbf); background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1, stop: 0 #bbf, stop: 1 #55f); height: 40px; } QSlider::add-page:horizontal { background: #fff; height: 40px; } QSlider::handle:horizontal { background: #bbf; border: 0px; width: 0px; margin-top: 0px; margin-bottom: 0px; border-radius: 0px; } """ if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) MyApp() and this is the output component ![enter image description here](http://i.stack.imgur.com/7NprK.png)
Python Searching and returning text inside parentheses Question: Okay, I have read many similar questions and tried them out but it's not working for some reason. I have a file with a bunch of lines that look like this: Here are some words: "<Hello> (silly girl) that isn't what she want(s)" I am trying to search for text of two or more characters within parentheses. Many combinations of `re.search` and `group()` returns something, but not exactly what I'm looking for. The value I want returned and printed in this case is: `"silly girl"`. Right now I have this: regex = re.compile("\((.+.+)\)") for line in lines: m = re.search(regex, line) if m: print(m.group()) The above prints: (silly girl) that isn't what she want(s) If I change the group index to `1`, as in `print(m.group(1))`, it prints the same thing just without the first parentheses: silly girl) that isn't what she want(s) What am I doing wrong? Answer: Regular expressions are _greedy_ by default, so capture from the first `'('` (before `'silly'`) to the last (after `'want(s'`). Instead: * Make it a _lazy_ match with `'?'`; * Use `'[^()]'` rather than `'.'` to exclude parentheses from the match (thanks to @thg435, and see their comment on the question for a potential drawback); * Use `'{2,}'` to indicate "two or more", rather than two separate "one or more" `'+'`s; and * Include a capturing group to exclude the parentheses themselves. Now you have: regex = re.compile(r"\(([^()]{2,}?)\)") This lets you switch to `findall` to get a list of results: >>> import re >>> regex = re.compile(r"\(([^()]{2,}?)\)") >>> s = "<Hello> (silly girl) that isn't what she want(s)" >>> m = re.findall(regex, s) >>> m ['silly girl'] See a demo of the regex [here](http://regex101.com/r/yI2iN6).
Create crontab with python-crontab in Python? Question: I am trying to add a line to my system user's crontab, from a Python script which uses the package python-crontab. My crontab file does not exist yet, and when I run this code, nothing happens (no errors, no results, no creation of crontab file): from crontab import CronTab cron = CronTab(user=True) # cron = CronTab(user='my_user') I tried this line too without any results job = cron.new(command='python3 /opt/my_script.py') job.minute.on(2) job.hour.on(12) True == job.is_valid() Am I missing anything? Answer: You need to save the cronjob, that's all that's missing: #!/bin/python from crontab import CronTab cron = CronTab(user=True) job = cron.new(command='python3 /opt/my_script.py') job.minute.on(2) job.hour.on(12) cron.write()
Auto running a script in python Question: I'm looking for a script that auto spams pictures of nicholas cage on the desktop I have this script right now but what I want to do is make it automatically run as soon as the USB is plugged in import shutil src = ('Kim.jpg') dst = ('H:/profile/desktop/Nic') count = 1 while count < 10: shutil.copyfile(src, dst + str(count) + ".jpg") count += 1 Answer: **Assumption** : You are using Windows. Almost on every new windows platform you need to approve an autorun of any executable so no leads here. But here is an alternative using some social/psychological engineering: Convert your program to a standalone executable using a tool like `py2exe`. I assume that after conversion your file is named `spammer.exe`. Then paste this file in the USB and super-hide it by opening Command Prompt inside your USB and typing: attrib +h +s +r spammer.exe Now create a shortcut with and icon of a typical folder of Windows and name it something attractive (if you know what I mean) and point it to `spammer.exe`. The user (in excitement) clicks at it and Kaboom!
trac ticketlog.web_ui error when browsing trac Question: I am receiving the following errors. i am using trac 0.12 on centos 5. I have plugins, advancedticketworkflow, ldaplugin, smtpldapemailsender, tracannouncer, tracwysiwg. i am trying to install commit ticket updater and similar plugins but they are not showing up. nor is it working. rac[paradox:loader] ERROR: Skipping "ticketlog = ticketlog.web_ui": Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/Trac-0.12.5-py2.4.egg/trac/loader.py", line 68, in _load_eggs entry.load(require=True) File "/usr/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg/pkg_resources.py", line 1954, in load entry = __import__(self.module_name, globals(),globals(), ['__name__']) File "/usr/lib/python2.4/site-packages/TracTicketChangelogPlugin-0.1-py2.4.egg/ticketlog/web_ui.py", line 45, in ? import json as simplejson ImportError: No module named json Trac[paradox:loader] ERROR: Skipping "tickettemplate = tickettemplate.ttadmin": Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/Trac-0.12.5-py2.4.egg/trac/loader.py", line 68, in _load_eggs entry.load(require=True) File "/usr/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg/pkg_resources.py", line 1954, in load entry = __import__(self.module_name, globals(),globals(), ['__name__']) File "/usr/lib/python2.4/site-packages/TracTicketTemplate-0.7-py2.4.egg/tickettemplate/ttadmin.py", line 213 with open(json_template_file) as f: ^ SyntaxError: invalid syntax (ttadmin.py, line 213) Trac[paradox:loader] ERROR: Skipping "tickettemplate = tickettemplate.ttadmin": Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/Trac-0.12.5-py2.4.egg/trac/loader.py", line 68, in _load_eggs entry.load(require=True) File "/usr/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg/pkg_resources.py", line 1954, in load entry = __import__(self.module_name, globals(),globals(), ['__name__']) File "/usr/lib/python2.4/site-packages/TracTicketTemplate-0.7-py2.4.egg/tickettemplate/ttadmin.py", line 213 with open(json_template_file) as f: ^ SyntaxError: invalid syntax (ttadmin.py, line 213) **UPDATE** I checked out latest version, when i run setup.py i get the following error python setup.py File "setup.py", line 55 install_requires=['simple_json' if sys.version_info < (2, 6) else ''], ^ SyntaxError: invalid syntax rpm -qa | grep -i python python-2.4.3-19.el5 dbus-python-0.70-7.el5 python-sqlite2-2.6.3-1.el5.rf python-iniparse-0.2.3-6.el5 libxml2-python-2.6.26-2.1.2 python-sqlite-1.1.7-1.2.1 python-elementtree-1.2.6-5 mod_python-3.2.8-3.1 MySQL-python-1.2.1-1 python-ldap-2.2.0-2.1 libselinux-python-1.33.4-2.el5 audit-libs-python-1.3.1-1.el5 rpm-python-4.4.2-37.el5 python-devel-2.4.3-19.el5 python-simplejson-2.0.9-8.el5 python-urlgrabber-3.1.0-2 postgresql-python-8.1.9-1.el5 python-json-3.4-3.el5 Answer: [TracTicketChangelogPlugin](http://trac- hacks.org/wiki/TracTicketChangelogPlugin) and [TracTicketTemplatePlugin](http://trac- hacks.org/wiki/TracTicketTemplatePlugin) do not support Python 2.4. TracTicketChangelogPlugin might support Python 2.4 if you install the `simplejson` package. TracTicketTemplatePlugin utilizes the `with_statement` so we'll need to add `from __future__ import with_statement` to get it to work with Python 2.5.
Why is `subprocess.call` not invoking the command Question: I'm trying to run a .wav file through ffmpeg using the `subprocess.call(shell=True)` in the following code and it doesn't seem to run. I know this because the `output_file` isn't created and I'm getting an exception in the `open()` method. What am I doing wrong? try: import pocketsphinx except: import pocketsphinx as ps import sphinxbase import subprocess import os hmmd = "../../Pocketsphinx_Files/en-us-8khz" lmdir = "../../Pocketsphinx_Files/cmusphinx-5.0-en-us.lm" dictp = "../../Pocketsphinx_Files/cmu07a.dic" output_filename = "../../temp/ps_output.wav" def recognize(filename="../../temp/temp_output.wav"): command = "ffmpeg -i "+filename+" -ac 1 -ab 16 -ar 16000 "+output_filename subprocess.call(command,shell=True) wavFile = open(output_filename,"rb") speechRec = ps.Decoder(hmm = hmmd, lm = lmdir, dict = dictp) wavFile.seek(44) speechRec.decode_raw(wavFile) result = speechRec.get_hyp() #os.remove(filename) #os.remove(output_filename) return result if __name__=="__main__": print(recognize()) edit: I've got ffmpeg installed. Furthermore, when I run the subprocess.call() command from the python interpreter it seems to work. This is why I'm stumped. Answer: I would recommend that you try using `subprocess.check_call()` or `check_output` instead of simply `call`. They will raise an exception if your program fails to execute correctly, instead of leaving you wondering why no output was generated. I'm going to guess that you may somehow be having path issues with your executable in a Python environment Try using this function with 'ffmpeg': def is_exe(prog): for path in os.environ["PATH"].split(os.pathsep): if os.path.isfile(os.path.join(path, prog)): if os.access(os.path.join(path, prog), os.X_OK): return os.path.join(path, prog) else: print "Program '%s' found in '%s', but lacks executable permissions." % (prog, path) return False If it returns `False`, you're having problems with Python running ffmpeg, otherwise it's ffmpeg which is having problems making sense of your arguments.
Prevent Python from showing entered input Question: In Python when I change the value of a variable through raw_input in the terminal it would write a new line stating its new value. I wanted to know if there is a way to avoid that because straight after user's input there is a print function which uses the value received before. In the end the user will get both values: original and modified while for the purpose of my program he only has to see the modified. I use IDLE to write my scripts and then execute them in terminal. **Update** A simple example would be the following. The input is string "Hello" and the output should be "Me: Hello". There should be no "Hello" before the final result. a = raw_input() print ("Me: " + a) And the output should be just Me: Hello rather than Hello Me: Hello Answer: if you want user to see the input, just mute `sys.stdout` (it's a bit hack tho): >>> from StringIO import StringIO >>> import sys >>> orig_out = sys.stdout >>> print 'give me input: ', give me input: >>> sys.stdout = StringIO() >>> a = raw_input('') string I type >>> sys.stdout = orig_out >>> a >>> 'string I type' ...and if you put this into a function then it's exactly what you want! a.py .... def foo(): orig_out = sys.stdout print 'give me input: ', sys.stdout = StringIO() a = raw_input() sys.stdout = orig_out if __name__ == '__main__': foo() running: yed@rublan $ ~ python a.py give me input: something I type!!!!! yed@rublan $ ~
Python scikit-learn (using grid_search.GridSearchCV) Question: I'm using grid search to fit machine learning model parameters. I typed in the following code (modified from the sklearn documentation page: <http://scikit- learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html>) from sklearn import svm, grid_search, datasets, cross_validation # getting data iris = datasets.load_iris() # grid of parameters parameters = {'kernel':('linear', 'poly'), 'C':[1, 10]} # predictive model (support vector machine) svr = svm.SVC() # cross validation procedure mycv = cross_validation.StratifiedKFold(iris.target, n_folds = 2) # grid search engine clf = grid_search.GridSearchCV(svr, parameters, mycv) # fitting engine clf.fit(iris.data, iris.target) However, when I look at `clf.estimator`, I get the following: SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) How did I end up with a 'rbf' kernel? I didn't specify it as an option in my parameters. What's going on? Thanks! P.S. I'm using '0.15-git' version for sklearn. **Addendum** : I noticed that `clf.best_estimator_` gives the right output. So what is `clf.estimator` doing? Answer: `clf.estimator` is simply a copy of the estimator passed as the first argument to the `GridSearchCV` object. Any parameters not grid searched over are determined by this estimator. Since you did not explicitly set any parameters for the SVC object `svr`, it was given all default values. Therefore, because `clf.estimator` is just a copy of `svr`, printing the value of `clf.estimator` returns an SVC object with default parameters. Had you instead written, e.g., svr = svm.SVC(C=4.3) then the value of `clf.estimator` would have been: SVC(C=4.3, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) There is no real value to the user in accessing `clf.estimator`, but then again it wasn't meant to be a public attribute anyways (since it doesn't end with a "_").
IOError: decoder jpeg not available when using Pillow Question: Before someone says `"sudo apt-get install libjpeg-dev"` or something along those lines, I do not have sudo access. I am on a slice of a server that does NOT allow me to have sudo access. So I've gotta do this entire thing in my local directory. That's the only way I can do it. I need a python script to resize an image. It works perfectly fine for png files, but it falls apart on jpeg files with the error listed in the title. Here are the steps I've taken so far: 1. Downloaded `libjpeg-dev` and installed it to `$HOME/jpegtest`, so inside the jpegtest/ folder is lib/, include/, and so on 2. I downloaded `Pillow` manually and extracted it out to `$HOME/Pillow` 3. I edited the `setup.py` fild so the `JPEG_ROOT` to a `libinclude(<absolute path to jpegtest>)` 4. I built and compiled `Pillow`, where it installed to `$HOME//.pythonbrew/pythons/Python-2.7.5/lib/python2.7/site-packages/Pillow-2.4.0-py2.7-linux-x86_64.egg` The important part of the output is as follows: *** TKINTER support not available --- JPEG support available *** OPENJPEG (JPEG2000) support not available --- ZLIB (PNG/ZIP) support available *** LIBTIFF support not available *** FREETYPE2 support not available *** LITTLECMS2 support not available *** WEBP support not available *** WEBPMUX support not available So I would assume that this means JPEG support will function, but when I run my program it says: > IOError: decoder jpeg not available While typing this I also noticed the question at [Pillow recognizes JPEG encoder on install, but not use](http://stackoverflow.com/questions/22409140/pillow-recognizes-jpeg- encoder-on-install-but-not-use), which sounded very close to mine, so I tried the solution there: ln -s /media/sdl1/home/midnight/jpegtest/lib/libjpeg.so /media/sdl1/home/midnight/.pythonbrew/pythons/Python-2.7.5/lib But I still have the same error. I've been working on this problem for about two days now, and I'm not entirely sure what to do. If anyone could offer some assistance, that would be very helpful. Answer: Instead of just downloading the libraries you need, try creating an entire Python environment in locally in your home folder: $ wget http://www.python.org/ftp/python/[desired version of Python].tgz $ tar xzf Python[version].tgz $ cd python-[version] $ ./configure $ make altinstall prefix=~ exec-prefix=~ Update your PATH variable so that your local Python is executed first: $ PATH = /home/user/[pathtopython]:$PATH Obtain pip, from which other packages can be installed: $ curl https://bootstrap.pypa.io/get-pip.py > get-pip.py $ ./get-pip.py $ pip install pillow URLs may vary. You might still have to modify setup.py - I haven't used this technique with C-like libraries so I'm not sure.
Shared library from Boost python build does not contain any functions Question: I'm having trouble building a shared library from my Boost Python project. For some reason, the final shared library is nearly empty and doesn't contain any of my wrapped functions. I've managed to get the "Hello World" example running on my machine, so I'm pretty sure I've got Boost installed and configured correctly. Here is the module definition (in the FM.h header file): /* Python Wrapper using Boost.python */ #include <boost/python.hpp> using namespace boost::python; BOOST_PYTHON_MODULE(fm_index) { class_<FM>("FM", init<>()) .def(init<uint8_t* , uint32_t, uint32_t>()) .def("save", &FM::save) .def("count", &FM::count) .def("locate", &FM::locate) .def("extract", &FM::extract) .def("load", &FM::load, return_value_policy<manage_new_object>()) .staticmethod("load") ; } And here is the build definition in my MakeFile: CCP=g++ CFLAGS=-W -Wall -O3 -fPIC INCCDS=./libcds/includes/ INCDIVSUF=./libdivsufsort/include/ BOOST_INC=/home/adevabhaktuni/boost_1_52_0/ BOOST_LIB=/home/adevabhaktuni/boost_1_52_0/stage/lib/ PYTHON_VERSION=2.6 PYTHON_INCLUDE=/usr/include/python$(PYTHON_VERSION) FM.o: FM.cpp FM.h $(CCP) -I $(INCCDS) -I $(INCDIVSUF) -I $(BOOST_INC) -I $(PYTHON_INCLUDE) -c $(CFLAGS) FM.cpp -o FM.o fm_index.so: FM.o ./libcds/lib/libcds.a ./libdivsufsort/lib/libdivsufsort.a $(CCP) -shared -W1,soname,fm_index.so -L $(BOOST_LIB) -lboost_python -lpython$(PYTHON_VERSION) FM.o ./libcds/lib/libcds.a ./libdivsufsort/lib/libdivsufsort.a -o fm_index.so The object file FM.o is about 206 kB, and when I run nm -u on it I see all of the functions I expect to see. However, the shared library fm_index.so is only 5 kB in size and is almost completely empty! nm -u fm_index.so fm_index.so: 0000000000200540 a _DYNAMIC 0000000000200728 a _GLOBAL_OFFSET_TABLE_ w _Jv_RegisterClasses 0000000000200518 d __CTOR_END__ 0000000000200510 d __CTOR_LIST__ 0000000000200528 d __DTOR_END__ 0000000000200520 d __DTOR_LIST__ 0000000000000508 r __FRAME_END__ 0000000000200530 d __JCR_END__ 0000000000200530 d __JCR_LIST__ 0000000000200748 A __bss_start w __cxa_finalize@@GLIBC_2.2.5 00000000000004c0 t __do_global_ctors_aux 0000000000000410 t __do_global_dtors_aux 0000000000200538 d __dso_handle w __gmon_start__ 0000000000200748 A _edata 0000000000200758 A _end 00000000000004f8 T _fini 00000000000003b8 T _init 00000000000003f0 t call_gmon_start 0000000000200750 b completed.6145 0000000000200748 b dtor_idx.6147 0000000000000490 t frame_dummy When I try to import the fm_index module in Python, I get the following error: ImportError: dynamic module does not define init function (initfm_index) Does anyone know what is going on here? I'm not using bjam because I couldn't figure out how to include the libcds.a and libdivsufsort.a libraries which the fm_index module depends on. However, I used a similar MakeFile to the one above on the "Hello World" project and it seemed to work fine. Any advice is very appreciated! Answer: You never define the functions you want to wrap with Boost.Python ? Maybe you should take a look on the first hello world example in the Boost.Python documentation: [Exposing Classes](http://www.boost.org/doc/libs/1_55_0/libs/python/doc/tutorial/doc/html/python/exposing.html)
Python: difficult in converting csv to list of list Question: I want to read a .csv file which has data format like -179.750 71.250 -26.7 -19.5 -22.5 -22.3 -8.0 -0.6 2.5 -179.750 68.750 -28.5 -21.3 -24.4 -24.4 -8.0 0.0 4.0 ..... and I want to convert to list of list as [[-179.750,71.250..2.5],[-179.750,68.750,..4.0] I use csv module to read csv file as: import csv csvfile= open('test.csv','rU') reader = csv.reader(csvfile,quotechar=" ") allRows = list(reader) print allRows The output is [['-179.750 68.750 ... -26.5'],['-179.750 68.250 ... 4.0']] please give me some idea so that i can modify and get my output. Thanks. Answer: The `quotechar` argument is for the character to be used to enclose a data entry containing delimiters, etc. You should use `delimiter`. If you want numbers out, not lists of strings, you'll want to also put the results through `float`. import csv csvfile= open('test.csv','rU') reader = csv.reader(csvfile,delimiter=" ") allRows = list(reader) print allRows numData=[ [float(i) for i in row] for row in allRows] print numData
SAWarning: Could not instantiate type <class 'sqlalchemy.sql.sqltypes.INTEGER'> when I use sqlalchemy and pd.io.sql.read_sql Question: I try to read pandas DataFrame from my SQLite table. When I run the code below import pandas as pd import sqlalchemy dbname = "sqlite:////Users/leda/home/Magnetic_stars/SQLite/Magnetic_stars.sqlite" engine = sqlalchemy.create_engine(dbname) res = pd.io.sql.read_sql("SELECT * FROM Resolved;", engine) I get SAWarning: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sqlalchemy/dialects/sqlite/base.py:860: SAWarning: Could not instantiate type <class 'sqlalchemy.sql.sqltypes.INTEGER'> with reflected arguments [u'4']; using no arguments. coltype = self._resolve_type_affinity(type_) /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sqlalchemy/dialects/sqlite/base.py:860: SAWarning: Could not instantiate type <class 'sqlalchemy.sql.sqltypes.INTEGER'> with reflected arguments [u'2']; using no arguments. coltype = self._resolve_type_affinity(type_) see my [issue on github](https://github.com/pydata/pandas/issues/7380) for more details. What am I doing wrong? Is this a bug? Answer: Ok, so looking at [github](https://github.com/pydata/pandas/issues/7380) it seems like your problem is solved. For the record, let me just shortly summarize what happend. As we know from [#7396](https://github.com/pydata/pandas/issues/7396), pandas is introspecting _all_ the tables per _every_ read_sql_table call. Another thing is that your database contains a table with a column of a type reported by sqlite as "INT(4)". SqlAlchemy (which is used by pandas under the hood) sqlite dialect [interprets the "(4)" part as an argument to be passed to its type constructor](https://github.com/zzzeek/sqlalchemy/blob/rel_0_9_4/lib/sqlalchemy/dialects/sqlite/base.py#L915). But constructor of [sqlalchemy.sql.sqltypes.INTEGER](https://github.com/zzzeek/sqlalchemy/blob/rel_0_9_4/lib/sqlalchemy/sql/sqltypes.py#L1445) doesn't take any arguments and that [causes a warning](https://github.com/zzzeek/sqlalchemy/blob/rel_0_9_4/lib/sqlalchemy/dialects/sqlite/base.py#L917) and effectively ignoring these arguments, treating INT(4) as INT.
Why does this Python 3 code fail to remove Unicode accented characters using str.translate()? Question: I am trying to normalise accented characters in a string in Python 3 like this: from bs4 import BeautifulSoup import os def process_markup(): #the file is utf-8 encoded fn = os.path.join(os.path.dirname(__file__), 'src.txt') # markup = BeautifulSoup(open(fn), from_encoding="utf-8") for player in markup.find_all("div", class_="glossary-player"): text = player.span.string print(format_filename(text)) # Python console shows mangled characters not in utf-8 player.span.string.replace_with(format_filename(text)) dest = open("dest.txt", "w", encoding="utf-8") dest.write(str(markup)) def format_filename(s): # prepare string s = s.strip().lower().replace(" ", "-").strip("'") # transliterate accented characters to non-accented versions chars_in = "àèìòùáéíóú" chars_out = "aeiouaeiou" no_accented_chars = str.maketrans(chars_in, chars_out) return s.translate(no_accented_chars) process_markup() The input src.txt file is utf-8 encoded: <div class="glossary-player"> <span class="gd"> Fàilte </span><span class="en"> Welcome </span> </div> <div class="glossary-player"> <span class="gd"> àèìòùáéíóú </span><span class="en"> aeiouaeiou </span> </div> The output file dest.txt looks like this: <div class="glossary-player"> <span class="gd">fã ilte</span><span class="en"> Welcome </span> </div> <div class="glossary-player"> <span class="gd">ã ã¨ã¬ã²ã¹ã¡ã©ã­ã³ãº</span><span class="en"> aeiouaeiou </span> </div> and I am trying to get it to look like this: <div class="glossary-player"> <span class="gd">failte</span><span class="en"> Welcome </span> </div> <div class="glossary-player"> <span class="gd">aeiouaeiou</span><span class="en"> aeiouaeiou </span> </div> I know there's solutions like unidecode but just wanted to find out what I'm doing wrong here. Answer: `chars.translate(no_accented_chars)` doesn't modify `chars`. It returns a new string with the translation applied. If you want to use the translated string, save it to a variable (perhaps the original `chars` variable): chars = chars.translate(no_accented_chars) or pass it directly to the `write` call: dest.write(chars.translate(no_accented_chars))
Can't sort into categories, values will increase indefinitely, can't remove enemies Question: import random from random import * import math from math import * from pygame import * import pygame, sys from pygame.locals import * import pygame.font from pygame.font import * bif= "grass.png" mif= "character front.png" mifB= "character back.png" mifL= "character left.png" mifR= "character right.png" mifRS= "character right still.png" mifLS= "character left still.png" skel= "skeleton front.png" skelB= "skeleton back.png" skelL= "skeleton left.png" skelR= "skeleton right.png" swordsky="sword_sky.png" sworddown="sword_down.png" swordleft="sword_left.png" swordright="sword_right.png" swordblank="sword_blank.png" healthpot="healthpot.png" levelup = 1 pygame.init() screen=pygame.display.set_mode((700,600),0,32) #background create r = 0 healthpotion=pygame.image.load(healthpot).convert_alpha() sword_blank=pygame.image.load(swordblank).convert_alpha() sword=pygame.image.load(sworddown).convert_alpha() sword_down=pygame.image.load(sworddown).convert_alpha() sword_sky=pygame.image.load(swordsky).convert_alpha() sword_right=pygame.image.load(swordright).convert_alpha() sword_left=pygame.image.load(swordleft).convert_alpha() background=pygame.image.load(bif).convert() character=pygame.image.load(mif).convert_alpha() character_back=pygame.image.load(mifB).convert_alpha() character_left=pygame.image.load(mifL).convert_alpha() character_right=pygame.image.load(mifR).convert_alpha() character_front=pygame.image.load(mif).convert_alpha() character_right_still=pygame.image.load(mifRS).convert_alpha() character_left_still=pygame.image.load(mifLS).convert_alpha() skeleton=pygame.image.load(skel).convert_alpha() skeleton_back=pygame.image.load(skelB).convert_alpha() skeleton_left=pygame.image.load(skelL).convert_alpha() skeleton_right=pygame.image.load(skelR).convert_alpha() skeleton_front=pygame.image.load(skel).convert_alpha() #convert image files to python useable files x,y = 300, 250 movex,movey = 0,0 Ai_x, Ai_y = 0, 500 moveAi_x, moveAi_y=0,0 movesx, movesy=0,0 ix, iy = -500, -500 experience = 0 aihp = 15 health = 100 sx,sy = x+10, y+20 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() #player movement if event.type==KEYDOWN: if event.key==K_a: if character==character_right: sx,sy= x+25, y+15 sword=sword_right elif character==character_right_still: sx,sy= x+25, y+15 sword=sword_right elif character==character_left_still: sx,sy= x-25, y+15 sword=sword_left elif character==character_left: sx,sy= x-25, y+15 sword=sword_left elif character==character_front: sx,sy= x, y+30 sword=sword_down elif character==character_back: sx,sy= x, y-20 sword=sword_sky if event.key==K_RIGHT: movex += .3 character=character_right elif event.key==K_LEFT: movex -= .3 character=character_left elif event.key==K_UP: movey -= .3 character=character_back elif event.key==K_DOWN: movey += .3 character=character_front if event.type==KEYUP: if event.key==K_RIGHT: movex = 0 character=character_right_still elif event.key==K_LEFT: movex = 0 character=character_left_still elif event.key==K_UP: movey = 0 character=character_back elif event.key==K_DOWN: movey = 0 character=character_front if event.key==K_a: if character==character_right: sx,sy= x+25, y+15 sword=sword_blank elif character==character_right_still: sx,sy= x+25, y+15 sword=sword_blank elif character==character_left_still: sx,sy= x-25, y+15 sword=sword_blank elif character==character_left: sx,sy= x-25, y+15 sword=sword_blank elif character==character_front: sx,sy= x, y+30 sword=sword_blank elif character==character_back: sx,sy= x, y-20 sword=sword_blank x+=movex y+=movey #Creep movement sdist = sqrt((sx - Ai_x)**2 + (sy - Ai_y)**2) #damage y2 = y - 20 if (sx, sy) != (x+40,y2): if x > sx: movesx = +.3 if x < sx: movesx = -.3 if y > sy: movesy = +.3 if y < sy: movesy = -.3 sx+=movesx sy+=movesy #sword movement if (Ai_x, Ai_y) != (x,y): if x > Ai_x: moveAi_x = .2 if x < Ai_x: moveAi_x = -.2 if y > Ai_y: moveAi_y = +.2 if y < Ai_y: moveAi_y = -.2 Ai_x+=moveAi_x Ai_y+=moveAi_y #creep movement #Controls for character newallocatedstr=0 newallocatedend=0 newallocatedagi=0 newallocatedchr=0 newallocatedwis=0 #stats if levelup == 2: newallocatedstr = eval(input("strength? (0-5):" )) newallocatedend = eval(input("endurance? (0-5):" )) newallocatedagi= eval(input(" agility? (0-5):" )) newallocatedchr = eval(input(" charisma? (0-5):" )) newallocatedwis = eval(input("wisdom? (0-5):" )) if ((newallocatedstr + newallocatedend) + (newallocatedagi + newallocatedchr) + newallocatedwis) > 5: print("You filthy cheater.") pygame.quit() sys.exit() levelup = 1 #levelup strn = newallocatedstr end = newallocatedend agi = newallocatedagi chra = newallocatedchr wis = newallocatedwis endurance= 5 + end strength=5 + strn wisdom=5 + wis charisma=5 + chra agility=5 + agi #stats # render health text maxhealth = health health = maxhealth if sdist<12: aihp = aihp - 1 dist = sqrt((Ai_x - x)**2 + (Ai_y - y)**2) #damage if dist<6: health = health - 1 font = pygame.font.Font(None, 25) mytext = font.render("Health:{0}".format(health), 1, (255,255,255)) exp = font.render("Experience:{0}".format(experience), 1, (255,255,255)) mytext = mytext.convert_alpha() if health == 0: print("Game over") pygame.quit() sys.exit() mana = 50 + wisdom font = pygame.font.Font(None, 25) mana = font.render("Mana:"+str(mana), 1, (255,255,255)) font = pygame.font.Font(None, 20) aihealth = font.render("Ai Health:{0}".format(aihp), 1, (255,255,255)) #create background screen.blit(background, (0,0)) if aihp >= 0: screen.blit(skeleton, (Ai_x, Ai_y)) screen.blit(aihealth, (Ai_x-25, Ai_y+40)) else: experience = experience + 10 screen.blit(exp, (15, 5)) screen.blit(mytext, (15, 25)) screen.blit(mana, (15, 50)) screen.blit(aihealth, (Ai_x-25, Ai_y+40)) screen.blit(sword, (sx, sy)) screen.blit(healthpotion, (ix, iy)) screen.blit(character, (x,y)) pygame.display.flip() pygame.display.update() This is my current code, ive been working on it for a while. Obviously the images won't work for anyone testing it, but my current problem is, when an enemy's `hp` goes below ``0, I don't know how to make the enemy completely get removed. I tried to do an if AIhp <= 0: Ai_x, Ai_y = -50, -50 But that only removes it from the screen, and since I also want to add drops it means when the Ai coordinates change so does the drop item coordinates since I only know how to make the drop coordinates equal to AI coordinates if I want it to appear in the place the AI died. Also the exp, and health both go down fine, but when I try to add exp from monster kill it goes up by about 10 a millisecond indefinitely, and when I tried to make the `maxhealth = health + endurance` it was same issue with growing indefinitely. I really need help, I have tried sorting my code into multiple functions but it only makes the entire thing stop working which pretty much exits out the option of just changing the sprites to objects... Answer: Your code does not take into account, that an enemy cannot be dead. I recommend to use a list of enemies, and then do all the operations for all the enemies. On enemy death, you will add the xp only once. It's better do make an Enemy class, that will do all the drawing, killing, etc, so you will not need to worry about it in your main code. Here are example calls: for enemy in enemies: if sdist<12: enemy.hit() if not enemy.isAlive(): enemies.remove(enemy) #add Drops enemy.move() enemy.draw(screen) Same goes for a player. If you divide this up, you will have a much easier time adding new functionality. The whole player movement could be a function in the class Player, since it does not interact with anything else. Do not use eval, a player would be able to execute any code. You want to cast the str to int. Like this: newallocatedwis = int(input("wisdom? (0-5):" )) If changing the code is too difficult, you can always start over. You already have the code written, so you will know what goes where.
Split a huge CSV in three random files in Python Question: I have a huge CSV and I want to split it in 3 random files with almost* equal size. *almost: the size cannot be divided by 3 I was thinking to create 3 blank lists, then in a for loop, I would randomly choose one number between `range(0,len(mycsv))` and append it in each list. Then, I will create a csv with the files from the first list and go on. But I think that this will be slow enough. Is there any build-in way or an easier than my own? Answer: For each line of your csv, randomly insert this line in one of three blank csv files. For 100.000 lines, it should not take long. import random with open("mycsv.csv") as fr: with open("1.csv", "w") as f1, open("2.csv", "w") as f2, open("3.csv", "w") as f3: for line in fr.readlines(): rd = random.randint(1, 3) f = f1 if rd == 1 else (f2 if rd == 2 else f3) f.write(line)
"self" as method attribute Question: I am attempting to teach myself Python at the moment and I am trying to work my way through a python program, which is essentially a pacman game. Whilst doing so, I discovered the following class call which contains 'self' as a method attribute. game = Game(agents, display, self, catchExceptions=catchExceptions) THE CONTEXT: This method call is part of the following function: class ClassicGameRules: """ These game rules manage the control flow of a game, deciding when and how the game starts and ends. """ def __init__(self, timeout=30): self.timeout = timeout def newGame( self, layout, pacmanAgent, ghostAgents, display, quiet = False, catchExceptions=False): [1] agents = [pacmanAgent] + ghostAgents[:layout.getNumGhosts()] [2] initState = GameState() [3] initState.initialize( layout, len(ghostAgents) ) [4] game = Game(agents, display, self, catchExceptions=catchExceptions) [5] game.state = initState [6] self.initialState = initState.deepCopy() [1] Just to make this a little more palatable, 'agents' contain the pacman and ghost agent objects combined into a list of lists, which when printed looks something like this: [<keyboardAgents.KeyboardAgent instance at 0x1004fe758>, <ghostAgents.RandomGhost instance at 0x1004fe518>, <ghostAgents.RandomGhost instance at 0x1004fe7a0>, <ghostAgents.RandomGhost instance at 0x1004fe950>, <ghostAgents.RandomGhost instance at 0x1004feb90>] [2] initState = GameState(): GameState() is a data object containing all sorts of information about the Game state [3] initState.initialize( layout, len(ghostAgents) ): initialises the very first game state from a layout array. This layout array lets the program know where the pacman and ghosts spawn, where the food and capsules are displayed and where walls can be found. [4] game = Game(agents, display, self, catchExceptions=catchExceptions): The Game class manages the control flow, soliciting actions from agents. Agents can be a keyboard agent (controlled by the player, who controls the pacman) and automated agents controlling the ghosts (see [1]). [5] game.state = initState: copies the content of [2] into the variable game.state. [6] self.initialState = initState.deepCopy(): deepCopy is a function which runs a copy operation on variables which define the game state of the game board, such as the layout or the position of the food. CLASS GAME: Here is the code of the class Game: class Game: """ The Game manages the control flow, soliciting actions from agents. """ def __init__( self, agents, display, rules, startingIndex=0, muteAgents=False, catchExceptions=False ): self.agentCrashed = False self.agents = agents ## agents contain the pacman and ghost agent objects combigned into a list of lists agents = [pacmanAgent] + ghostAgents[:layout.getNumGhosts()] self.display = display #print("This is the display object" + str(self.display)) self.rules = rules ## The rules are passed on as the self attribute of the ClassicGameRules class within the call of Game in newGame [REF 115]. self.startingIndex = startingIndex ## starting index is given as default attribute by the __init__ method. self.gameOver = False self.muteAgents = muteAgents self.catchExceptions = catchExceptions self.moveHistory = [] self.totalAgentTimes = [0 for agent in agents] ## This creates a list that replaces the list elements of the agents list, which contains the agent objects, with zeros. It looks something like this [0,0,0] ##print(self.totalAgentTimes) self.totalAgentTimeWarnings = [0 for agent in agents] self.agentTimeout = False import cStringIO self.agentOutput = [cStringIO.StringIO() for agent in agents] WHAT CONFUSES ME When game = Game(agents, display, self, catchExceptions=catchExceptions) is called, "self' is passed on to Game as an attribute. In Game the data contained within "self" takes is placed within the "rules" variable. But does does this variable contain? Intuitively I would suggest that it would be the "self" instance of the newGame object. But seeing how this method is called self.initialState = initState.deepCopy(), which doesn't seem to make sense... Or are we referencing the self - object of the ClassicGameRules class? I know this was a handful of text to read, but I wasn't quite sure how to shorten this question. Please let me know if more information is required. Any help would be highly appreciated. :) Z_101 Answer: In the method `newGame` of the class `ClassicGameRules`, `self` represents the current instance of the class: game = Game( agents, display, self, ...) v v v def __init__(self, agents, display, rules, ...) The first `self` of the `__init__` method here is to represents to the new object that will be created in the `Game` class. In your case, the `Game` class has in `rules` a reference to the instance of `ClassicGameRules` which called the constructor of the `Game` instance. The `deepCopy` after has nothing to do and is just to synchronized the initial state of both objects, by coping the state of the object just created (`game`) into the "parent" object (instance of `ClassicGameRules`).
How to get a list of axes for a figure in pyplot? Question: I am new to `python` and `pyplot`. I am trying to understand the documentation for the Matplotlib API related to the Figure [Figure API](http://matplotlib.org/api/figure_api.html). In the beginning it says there is a `class matplotlib.figure.AxesStack`, and then > The AxesStack is a callable, where ax_stack() returns the current axes When I try to use this in a program import numpy as np import matplotlib.pyplot as plt n=4 v=np.arange(n) X,Y = np.meshgrid(v,v) Z=np.random.rand(n-1,n-1) fig, ax = plt.subplots() plt.pcolormesh(X, Y, Z) plt.axis('tight') plt.colorbar() ast=fig.ax_stack() plt.show() I get error AttributeError: 'Figure' object has no attribute 'ax_stack' Answer: The property `axes` returns a list of the `Axes` objects in the `Figure` object: ax_list = fig.axes ([doc](http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.axes))
3D volume acrobatics in python.. selecting x/y/z rows/columns in 3D numpy arrays Question: I'm new to ndarrays in Numpy, so please be kind. I have a 3D raw volume imported into numpy as a dtype uint8 array with shape `(309L, 138L, 134L)` representing Z, Y, X dimensions. The Raw image dimensions are (x,y,z), 134 138 309 This array is called `ThreeD`. I can plot a Z 'section' of dimension XY of ThreeD with ThreeD[70] (selecting row 70) I can plot a Y 'section' of dimension XZ of ThreeD with ThreeD[:,70] (selecting column 70) but of course, there is the extra dimension! These first two are easy to reference, but I'm at a loss of how to select/reference the third dimension.. i.e. the X section of dimension YZ (i.e. slicing a face of the matrix). I should add that I'm not entirely sure of the XZ/YZ dimension here, so those references might be reversed. I got as far as I did using Sebastian Raschka's handy cheat sheet <http://sebastianraschka.com/Articles/2014_matrix_cheatsheet.html> thanks kindly for any help Answer: `ThreeD[70]` for `Z` `ThreeD[:, 70]` for `Y` `ThreeD[:, :, 70]` or `ThreeD[..., 70]` for `X` from Jaime. Thankyou.
Python Pandas calucate Z score of groupby means Question: I have a dataframe like this: df = pd.DataFrame({'Year' : ['2010', '2010', '2010', '2010', '2010', '2011', '2011', '2011', '2011', '2011', '2012', '2012', '2012', '2012', '2012'], 'Name' : ['Bob', 'Joe', 'Bill', 'Bob', 'Joe', 'Dave', 'Bob', 'Joe', 'Bill', 'Bill', 'Joe', 'Dave', 'Dave', 'Joe', 'Steve'], 'Score' : [95, 76, 77, 85, 82, 92, 67, 80, 77, 79, 82, 92, 64, 71, 83]}) I would like to get the Z Score for each _Name_ in each _Year_. I can do it if subset the Year column like this: (df[df.Year == '2010'].groupby(['Year', 'Name'])['Score'].mean() - df[df.Year == '2010'].groupby(['Year', 'Name'])['Score'].mean().mean()) / ( df[df.Year == '2010'].groupby(['Year', 'Name'])['Score'].mean().std()) Is there a cleaner way of doing it? Answer: There is a `zscore` functionality in `scipy`, but be careful the default delta-degree-of-freedom is 0 in `scipy.stats.zscore`: In [171]: import scipy.stats as ss S=(df[df.Year == '2010'].groupby(['Year', 'Name'])['Score'].mean()) pd.Series(ss.zscore(s, ddof=1), S.index) Out[171]: Year Name 2010 Bill -0.714286 Bob 1.142857 Joe -0.428571 dtype: float64
In PyGame, how to move an image every 3 seconds without using the sleep function? Question: Recently I've learned some basic Python, so I am writing a game using PyGame to enhance my programming skills. In my game, I want to move an image of a monster every 3 seconds, at the same time I can aim it with my mouse and click the mouse to shoot it. At the beginning I tried to use **time.sleep(3)** , but it turned out that it pause the whole program, and I can't click to shoot the monster during the 3 seconds. So do you have any solution for this? Thanks in advance! :) * * * Finally I solved the problem with the help of you guys. Thank you so much! Here is part of my code: import random, pygame, time x = 0 t = time.time() while True: screen = pygame.display.set_mode((1200,640)) screen.blit(bg,(0,0)) if time.time() > t + 3: x = random.randrange(0,1050) t = time.time() screen.blit(angel,(x,150)) pygame.display.flip() Answer: Pygame has a clock class that can be used instead of the python time module. Here is an example usage: clock = pygame.time.Clock() time_counter = 0 while True: time_counter = clock.tick() if time_counter > 3000: enemy.move() time_counter = 0
Python regex matching pattern not surrounded by double quotes Question: I'm not comfortable with regex, so I need your help with this one, which seems tricky to me. Let's say I've got the following string : string = 'keyword1 keyword2 title:hello title:world "title:quoted" keyword3' What would be the regex to get `title:hello`, `title:world`, remove these strings from the original one and leave `"title:quoted"` in it, because it's surrounded by double quotes ? I've already seen [this similar SO answer](http://stackoverflow.com/questions/11792258/python-regex-to-replace-a- string-if-not-surrounded-by-single-quotes), and here is what I ended up with : import re string = 'keyword1 keyword2 title:hello title:world "title:quoted" keyword3' def replace(m): if m.group(1) is None: return m.group() return m.group().replace(m.group(1), "") regex = r'\"[^\"]title:[^\s]+\"|([^\"]*)' cleaned_string = re.sub(regex, replace, string) assert cleaned_string == 'keyword1 keyword2 "title:quoted" keyword3' Of course, it does not work, and I'm not surprised, because regex are esoteric to me. Thank you for your help ! # Final solution Thanks to your answers, here is the final solution, working for my needs : import re matches = [] def replace(m): matches.append(m.group()) return "" string = 'keyword1 keyword2 title:hello title:world "title:quoted" keyword3' regex = '(?<!")title:[^\s]+(?!")' cleaned_string = re.sub(regex, replace, string) # remove extra withespaces cleaned_string = ' '.join(cleaned_string.split()) assert cleaned_string == 'keyword1 keyword2 "title:quoted" keyword3' assert matches[0] == "title:hello" assert matches[1] == "title:world" Answer: You can check for word boundaries (`\b`): >>> s = 'keyword1 keyword2 title:hello title:world "title:quoted" keyword3' >>> re.sub(r'\btitle:\w+\b', '', s, re.I) 'keyword1 keyword2 "title:quoted" keyword3' Or, alternatively, you can use [negative look behind and ahead assertions](https://docs.python.org/2/library/re.html#regular-expression- syntax) to check for not having quotes around `title:\w+`: >>> re.sub(r'(?<!")title:\w+(?!")', '', s) 'keyword1 keyword2 "title:quoted" keyword3'
Why does Python run a C++ function faster than C++ running its own function via its main() function? Question: I wrote an extremely brute force function to check if a number is a prime number. The loop goes up to 1,000,000. I compiled that C++ code into a shared library and ran that function with Python, then I ran the same function within C++'s main() function. Why does time show that python did it faster than C++? My C++ Code (cppcode.cpp): #include <iostream> #include <boost/python.hpp> using namespace boost::python; bool isPrime(long number) { if(number == 2) { return true; } for(int i = 3; i < number; i++) { if(number % i == 0) { return false; } } return true; } void runcpp(void) { for(int i = 2; i < 1000000; i++) { if(isPrime(i)) { std::cout << i << " is a prime number!" << std::endl; } } } BOOST_PYTHON_MODULE(cppcode) { def("runcpp", runcpp); } int main() { runcpp(); return 0; } My Python Code (main.py): import cppcode if __name__ == "__main__": cppcode.runcpp() Shell Output: $ g++ -Wall -shared -fPIC cppcode.cpp -o cppcode.so -lpython2.7 -lboost_python -I/usr/include/python2.7/ $ g++ -Wall cppcode.cpp -o main -lpython2.7 -lboost_python -I/usr/include/python2.7/ $ (time python main.py >> time.txt) && (time ./main >> time.txt) real 10m26.519s user 10m25.042s sys 0m0.737s real 10m48.754s user 10m47.796s sys 0m0.763s As you can see from the shell output above, when python ran the C++ "runcpp" function, it ran ~20 seconds faster than when C++'s main() function ran the same "runcpp" function. Does anyone have any idea as to why Python executed the same function faster than C++? Or am I reading it wrong? Answer: Remove all print statements - these cause the program to pause and you're benchmarking the time your system spends doing I/O which is highly variable and blankets any differences between your Python and your pure C++ runtime. Try doing some heavy mathematical computation like finding the first 1000 primes for a more fair comparison. Having said that, I don't expect your C++ program to outperform your Python program by much if at all. They should be neck-to-neck for the most part with the only possible disadvantage for Python being its interpreter's "boot-up" time.
Color image segmentation with Python Question: I have many pictures as below: ![target picture example](http://i.stack.imgur.com/C31sn.jpg) My objective is to identify those "beads", try to mark it with a circle, and count the detected numbers. I tried to use image segmentation algorithms via Python and the source codes are as below: from matplotlib import pyplot as plt from skimage import data from skimage.feature import blob_dog, blob_log, blob_doh from math import sqrt from skimage.color import rgb2gray from scipy import misc # try image = misc.imread('test.jpg') image_gray = rgb2gray(image) blobs_log = blob_log(image_gray, max_sigma=10, num_sigma=5, threshold=.1) # Compute radii in the 3rd column. blobs_log[:, 2] = blobs_log[:, 2] * sqrt(2) blobs_dog = blob_dog(image_gray, max_sigma=2, threshold=.051) blobs_dog[:, 2] = blobs_dog[:, 2] * sqrt(2) blobs_doh = blob_doh(image_gray, max_sigma=2, threshold=.01) blobs_list = [blobs_log, blobs_dog, blobs_doh] colors = ['yellow', 'lime', 'red'] titles = ['Laplacian of Gaussian', 'Difference of Gaussian', 'Determinant of Hessian'] sequence = zip(blobs_list, colors, titles) for blobs, color, title in sequence: fig, ax = plt.subplots(1, 1) ax.set_title(title) ax.imshow(image, interpolation='nearest') for blob in blobs: y, x, r = blob c = plt.Circle((x, y), r, color=color, linewidth=2, fill=False) ax.add_patch(c) plt.show() The best results obtained so far are still unsatisfactory: ![One of the results obtained](http://i.stack.imgur.com/bV6xD.png) How can I improve it ? Answer: You could use Gimp or Photoshop and test some filters and colors changes to differentiate the circles from the background. Brightness and Contrast adjustments may work. Then you can apply an Edge detector to detect the circles.
Running A Process In the Background In Flask Question: I am making a webapp in python and flask which will email & tweet to the webmaster when the moment his website goes down. I am thinking of running an infinite while loop which waits for 10 minutes and then send a request to the website to be checked and checks if the returned response is 200. The problem is that were in the script can I insert this loop? Any suggestions about how I can achieve this? Answer: # Soldier, tell me when you are dead Trying to report a problem from dying app is not the most reliable method. # Use external process to watch the app You shall have some external independent app, monitoring your app. If you live in pure Python environment, you may write a script, which will check if accessing some app url succeeds and if not, it would alert someone. For alerting, you may try e.g. `logbook` with log records being sent by e-mail (see [MailHandler](http://pythonhosted.org/Logbook/api/handlers.html#logbook.MailHandler) or [GMailHandler](http://pythonhosted.org/Logbook/api/handlers.html#logbook.GMailHandler)). In production environment it would be best to run some monitoring app like [Nagios](http://www.nagios.org/about) and simply check by [`check_http`](https://www.monitoring-plugins.org/doc/man/check_http.html) # Sample checking script using Logbook For better readibility, the content is split to more parts, real script is in one file called `monitor_url.py` ## `monitor_url.py`: Docstring, imports and MAIL_TEMPLATE Docstring explains usage and is finally used by command line parser `docopt` Imports are mostly `logbook` related """monitor_url.py - check GET access to a url, notify by GMail about problems Usage: monitor_url.py [options] <url> <from> <pswd> <to>... monitor_url.py -h Options: -L, --logfile <logfile> Name of logfile to write to [default: monitor_url.log]. -N, --archives <archives> Number of daily logs to keep, use 0 for unlimited [default: 0] The check is performed once a minute and does HTTP GET request to <url>. If there is a problem, it sends an e-mail using GMail account. There is a limit of 6 e-mails, which can be sent per hour. """ import time from logbook import Logger, GMailHandler, StderrHandler, NestedSetup, TimedRotatingFileHandler, Processor from logbook.more import JinjaFormatter from datetime import timedelta import requests from requests.exceptions import ConnectionError MAIL_TEMPL = """Subject: {{ record.level_name }} on {{ record.extra.url }} {{ record.message }} Url: {{ record.extra.url }} {% if record.exc_info %} Exception: {{ record.formatted_exception }} {% else %} Status: {{ record.extra.req.status_code }} Reason: {{ record.extra.req.reason }} {% endif %} """ ## `monitor_url.py`: `main` function performing the checks This script is looping in `while` and performs once a minute a check. If a problem is detected, or status code has changed, GMailHandler is configured to send e-mail. def main(url, e_from, pswd, e_to, logfile, archives): log = Logger("httpWatcher") def inject_req(record): record.extra.url = url record.extra.req = req processor = Processor(inject_req) gmail_handler = GMailHandler(e_from, pswd, e_to, level="WARNING", record_limit=6, record_delta=timedelta(hours=1), bubble=True) gmail_handler.formatter = JinjaFormatter(MAIL_TEMPL) setup = NestedSetup([StderrHandler(), TimedRotatingFileHandler(logfile, bubble=True), gmail_handler, processor]) with setup.applicationbound(): last_status = 200 while True: try: req = requests.get(url) if req.status_code != last_status: log.warn("url was reached, status has changed") if req.ok: log.info("url was reached, status OK") else: log.error("Problem to reach the url") last_status = req.status_code except ConnectionError: req = None log.exception("Unable to connect") last_status = 0 time.sleep(6) ## `montior_url.py` final `if __name__ ...` This part actually parses command line parameters and calls the `main` if __name__ == "__main__": from docopt import docopt args = docopt(__doc__) print args main(args["<url>"], args["<from>"], args["<pswd>"], args["<to>"], args["--logfile"], int(args["--archives"])) ## Call it Try to call it without parameters: $ python monitor_url.py Usage: monitor_url.py [options] ... monitor_url.py -h To get full help, use `-h` $ python monitor_url.py -h ...the help is the same as script docstring... Use it for real monitoring, here used for monitoring `http://localhost:8000` $ python monitor_url.py -L mylog.log -N 2 http://localhost:8000 <yourmail>@gmail.com xxxpasswordxxx [email protected] {'--archives': '2', '--logfile': 'mylog.log', '-h': False, '<from>': '[email protected]', '<pswd>': 'xxxxxxx', '<to>': ['[email protected]'], '<url>': 'http://localhost:8000'} [2014-06-09 19:41] INFO: httpWatcher: url was reached, status OK [2014-06-09 19:41] ERROR: httpWatcher: Unable to connect Traceback (most recent call last): ....(shortened)... raise ConnectionError(e, request=request) ConnectionError: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: / (Caused by <class 'socket.error'>: [Errno 111] Connection refused) [2014-06-09 19:41] WARNING: httpWatcher: url was reached, status has changed [2014-06-09 19:41] INFO: httpWatcher: url was reached, status OK Check logfile created in local folder. Check your gmail inbox (if there is nothing, you have to play with the password). # Conclusions Twitter notification is also possible with `logbook`, but is not shown here. To run the script, Python 2.7 is expected and you shall install some packages: $ pip install logbook jinja2 requests Managing notification from such a script is not easy. Consider this script of beta quality in this regard. Usage of solutions like `Nagios` seems to be more appropriate for this purpose.
How to automatically cluster my dataset images into different groups based on local features or global using python or OpenCV? Question: I have a dataset of images , and i want to group my images into different groups based on content. What i have tried till now is find median of images and thought to group them into different clusters based on median values , How can i do that? This is what i have tried till now. How can i do cluster my images into groups? I did Google out many things on clustering, But it showed results on clustering based on colors rather than clustering images into groups.Can anyone provide me with informative answers?Can i automatically cluster my dataset into groups based on median or some other technique? from PIL import Image import numpy as np import os Median=[] k=[] def get_imlist(path): return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')] path='D:/Images/dataset' imlist= get_imlist(path) for file in imlist: head,tail=os.path.split(file) im=np.array(Image.open(file).convert('L')) m=np.median(im) M=[m,tail] print '.' Median.append(M) Results=sorted(Median, key=lambda median: median[0]) print Results Answer: k-means is a common method for clustering and is in OpenCV <http://docs.opencv.org/modules/core/doc/clustering.html>. Before you cluster it is recommended that you use a representation that has a lower number of dimensions than the full n*m set of pixels. This is for two main reasons, robustness to noise, and the reduction of computational cost of the clustering process. The choice of representation may be critical to the perceived quality of the clusters, and will largely depend on your application. My current favorite is the GIST descriptor (c++: <http://lear.inrialpes.fr/software>, matlab: <http://people.csail.mit.edu/torralba/code/spatialenvelope/>). However that is not in OpenCV. So here i will use a gray level histogram, thus reducing the dimensions from m*n to b = no. of bins. Assuming a vector of gray level input images named frames. //set up histogram int histSize = 128; float range[] = { 0, histSize } ; const float* histRange = { range }; bool uniform = true; bool accumulate = false; Mat_<float> dataHists; cv::Mat grayImg; Mat hist_i; for(int i=0; i <frames.size(); i++) { grayImg =frames[i]; //histogram gray image calcHist( &grayImg, 1, 0, Mat(), hist_i, 1, &histSize, &histRange, uniform, accumulate ); normalize(hist_i, hist_i, 0, hist_i.rows, NORM_MINMAX, -1, Mat() ); //transpose for feature vector hist_i = hist_i.t(); //add to feature vectors for k-means dataHists.push_back(cv::Mat(hist_i)); } //k-means int k = 100; cv::Mat bestLabels; cv::kmeans(dataHists,k,bestLabels,TermCriteria(),3,KMEANS_PP_CENTERS); //have a look vector<cv::Mat> clusterViz(bestLabels.rows); for(int i=0;i<bestLabels.rows; i++) { clusterViz[bestLabels.at<int>(i)].push_back(cv::Mat(frames[bestLabels.at<int>(i)])); } namedWindow("clusters", WINDOW_NORMAL ); for(int i=0;i<clusterViz.size(); i++) { cv::imshow("clusters",clusterViz[i]); cv::waitKey(); } Hope this helps you.
Compare specific fields in two files -Python Question: I want to compare two files(file1 and file2) with different columns but have the first 4 columns in common, the output should be the lines of file2 existing in file1: **file 1:** 132.227.127.170 49163 173.194.40.110 443 132.227.127.170 49164 31.13.86.65 443 132.227.127.170 49165 193.51.224.40 443 132.227.127.170 49166 193.51.224.40 443 132.227.127.170 49167 193.51.224.40 443 ...... **file 2:** 132.227.127.170 49155 17.172.232.150 5223 3 4500.1587 106 132.227.127.170 49155 17.172.232.150 5223 3 8100.3275 106 132.227.127.170 49163 173.194.40.110 443 5 0.405 53 132.227.127.170 49164 31.13.86.65 443 7 0.018600000000000002 53 132.227.127.170 49165 193.51.224.40 443 417 42.5117 32362 132.227.127.170 49166 193.51.224.40 443 34 33.382 1236 132.227.127.170 49167 193.51.224.40 443 8 37.067099999999996 458 132.227.127.170 49168 193.51.224.40 443 5 0.0008 53 132.227.127.170 49169 193.51.224.40 443 5 0.0009 53 132.227.127.170 49170 31.13.86.65 443 937 30.7529 117540 ...... **Output:** 132.227.127.170 49163 173.194.40.110 443 5 0.405 53 132.227.127.170 49164 31.13.86.65 443 7 0.018600000000000002 53 132.227.127.170 49165 193.51.224.40 443 417 42.5117 32362 132.227.127.170 49166 193.51.224.40 443 34 33.382 1236 132.227.127.170 49167 193.51.224.40 443 8 37.067099999999996 458 .... So I tried this code, it normally HAS to work, I already tried it in other cases and worked very well, but I don t know what went wrong this time !! import string tstFile1=open("output","w+") with open('file1') as file1, open('file2') as file2: myf=[line.strip().split() for line in file1] f1=[line.strip() for line in filter(lambda x: x.strip().split()[0:3] in myf, file2)] for i in f1: tstFile1.write("%s\n" %i) tstFile1.close() So what do you suggest me to change in it? ANY help pleaase I tried to use an AWK command, but still the same problem Answer: The problem is that you are trying to be too fancy. There are too many steps in one, so you can easily miss small detail. The file1 contains 4 columns, but you are only extracting the first 3 columns from file2. Your problem will be fixed if you change the following row: f1=[line.strip() for line in filter(lambda x: x.strip().split()[0:4] in myf, file2)] and f2=[line.strip() for line in filter(lambda x: x.strip().split()[0:4] not in myf, file2)] Changing [0:3] to [0:4] (remember that python indexes are _between_ elements) But please split up this logic, it will make debugging **much** easier!
How to plot a density map in python? Question: I have a .txt file containing the x,y values of regularly spaced points in a 2D map, the 3rd coordinate being the density at that point. 4.882812500000000E-004 4.882812500000000E-004 0.9072267 1.464843750000000E-003 4.882812500000000E-004 1.405174 2.441406250000000E-003 4.882812500000000E-004 24.32851 3.417968750000000E-003 4.882812500000000E-004 101.4136 4.394531250000000E-003 4.882812500000000E-004 199.1388 5.371093750000000E-003 4.882812500000000E-004 1278.898 6.347656250000000E-003 4.882812500000000E-004 1636.955 7.324218750000000E-003 4.882812500000000E-004 1504.590 8.300781250000000E-003 4.882812500000000E-004 814.6337 9.277343750000000E-003 4.882812500000000E-004 273.8610 When I plot this density map in gnuplot, with the following commands: set palette rgbformulae 34,35,0 set size square set pm3d map splot "dens_map.map" u 1:2:(log10($3+10.)) title "Density map"` Which gives me this beautiful image: ![enter image description here](http://i.stack.imgur.com/AZsBO.jpg) Now I would like to have the same result with matplotlib. Answer: Here is my aim at a more complete answer including choosing the color map and a logarithmic normalization of the color axis. import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.colors import LogNorm import numpy as np x, y, z = np.loadtxt('data.txt', unpack=True) N = int(len(z)**.5) z = z.reshape(N, N) plt.imshow(z+10, extent=(np.amin(x), np.amax(x), np.amin(y), np.amax(y)), cmap=cm.hot, norm=LogNorm()) plt.colorbar() plt.show() I assume here that your data can be transformed into a 2d array by a simple reshape. If this is not the case than you need to work a bit harder on getting the data in this form. Using imshow and not pcolormesh is more efficient here if you data lies on a grid (as it seems to do). The above code snippet results in the following image, that comes pretty close to what you wanted: ![Resulting image](http://i.stack.imgur.com/XdRlN.png)
How to show webcam capture in Plone site using OpenCV? Question: I am using Plone 4.3. I am trying to create a face recognition system on the Plone site. I need to show webcam captures using a template page. My sample code is below. However, when I run this code, I can't get the captured image in the template file. sample.py: class video(BrowserView): video=ViewPageTemplateFile('video.pt') def chow(self): return self.video() def show_video(self): import cv2.cv as cv cv.NamedWindow("camera", 1) capture = cv.CaptureFromCAM(0) while True: img = cv.QueryFrame(capture) return img video.pt: <div id="res"> <!--Here face is url name--> <img id="draw" tal:attributes="src python:context.absolute_url() + '/face'"> <!--the above line refers to call a method of show_video()--> </div> Answer: This is a good starting point: <http://plone.org/products/collective.takeaportrait> (activate the optional OpenCV integration). Keep in mind that there's a **big** difference between showing the camera output on the screen (that is simply HTML 5) and performing face recognition server side.
Adding more than one list Question: I want to try the many ways the function of python So, I want to not use zip use other python function ,how can i do to? this is use zip and adding more than one list: but i want to other way not use zip: x = [12, 22, 32, 42, 52, 62, 72, 82, 29] y = [10, 11, 12, 13, 14, 15, 16, 17, 18] def add_list(i, j): l = [] for n, m in zip(x, y): l.append(n + m) return l i know this way, Answer: **without** using `zip`, you can use `map`: from operator import add x = [12, 22, 32, 42, 52, 62, 72, 82, 29] y = [10, 11, 12, 13, 14, 15, 16, 17, 18] res = map(add, x, y) # [22, 33, 44, 55, 66, 77, 88, 99, 47] Note that if the iterables are of different lengths, than the shortest will be padded with `None` which will cause a `TypeError` in the `add` instead of `zip` which will truncate to the shortest list. **On an aside** there's absolutely nothing wrong with using `zip` \- I'd probably re-write it as a list-comp though, eg: [sum(items) for items in zip(x, y)] This then scales easily to doing `zip(x, y, z, another_list)` etc...
pandas ValueError: numpy.dtype has the wrong size, try recompiling Question: I took a new clean install of OSX 10.9.3 and installed pip, and then did pip install pandas pip install numpy Both installs seemed to be perfectly happy, and ran without any errors (though there were a zillion warnings). When I tried to run a python script with import pandas, I got the following error: numpy.dtype has the wrong size, try recompiling Traceback (most recent call last): File "./moen.py", line 7, in import pandas File "/Library/Python/2.7/site-packages/pandas/__init__.py", line 6, in from . import hashtable, tslib, lib File "numpy.pxd", line 157, in init pandas.hashtable (pandas/hashtable.c:22331) ValueError: numpy.dtype has the wrong size, try recompiling How do I fix this error and get pandas to load properly? Answer: You can install previous version of pandas. pip uninstall numpy pip uninstall pandas pip install pandas==0.13.1 In my situation it solved problem...
how to merge file lines having the same first word in python? Question: I have written a program to merge lines in a file containing the same first word in python.However I am unable to get the desired output. Can anyone please suggest me the mistake in my program? **Note:- (line1,line 2)** and **(line4,line5,line6)** are merging since they have the same first element #input "file.txt" line1: a b c line2: a b1 c1 line3: d e f line4: i j k line5: i s t line6: i m n #output a b c a b1 c1 d e f i j k i s t i m n #my code for i in range(0,len(a)): j=i try: while True: if a[j][0] == a[j+1][0]: L.append(a[j]) L.append(a[j+1]) j=j+2 else: print a[i] print L break except: pass` Answer: Try this (give it the file as an argument). Produces a dictionary with the lines you expect. import sys if "__main__" == __name__: new_lines = dict() # start reading file with open(sys.argv[1]) as a: # iterate file by lines - removing newlines for a_line in a.read().splitlines(): # candidate is first word in every sentence candidate = a_line.split()[0] # split on whitespace by default # dictionary keys are previous candidates if candidate in new_lines.keys(): # word already included old_line = new_lines[candidate] new_lines[candidate] = "%s %s" % (old_line, a_line) else: # word not included new_lines[candidate] = a_line # now we have our dictionary. print it (or do what you want with it) for key in new_lines.keys(): print "%s -> %s" % (key, new_lines[key]) output: a -> a b c a b1 c1 i -> i j k i s t i m n d -> d e f
cx_Oracle - DLL load failed Question: I have a problem importing cx_Oracle with Python. I know a lot of issues with cx_Oracle have been discussed here, but it seems that I cannot find a solution to my problem after reading all the related topics. I have two machines, one is my computer and another one is a remote workstation, which have similar configs (Windows 7, 64-bits). I need to install cx_Oracle on the remote workstation but it does not work, whereas it works fine on my computer (I can import the module successfully and connect to my DB). On the remote workstation, I have the following error : Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import cx_Oracle ImportError: DLL load failed: The specified module could not be found. I have double-checked my environment variables, and I re-installed cx_Oracle a couple of times, but I cannot get it working... I did some research about this problem and I am kind of stuck here, I do not understand why it is working fine on my computer but not on this remote workstation (the only difference is that this remote workstation is a VM). Does anyone have an idea on what could be the issue? Running Dependancy Walker on both cx_oracle.pyd (on my computer where it works fine and on the remote workstation where cx_oracle does not work), the only difference are the dll MSVCR100 amd MSVCR90 which are not found on my remote workstation. I have the following environment variables setup: * `C:\Oracle as ORACLE_BASE` * `C:\Oracle\instantclient_12_1` as ORACLE_HOME * `C:\Oracle\instantclient_12_1` added to the "Path" variable Both machines are 64-bit, Windows 7 I am running Python 2.7.5 I unzipped instantclient-basic-nt-12.1.0.1.0 in `C:\Oracle\instantclient_12_1` I installed `cx_Oracle-5.1.2-11g.win32-py2.7s` On the remote workstation, `sys.path` gives me : > 'C:\Python27\Lib\idlelib', 'C:\Windows\system32\python27.zip', > 'C:\Python27\DLLs', 'C:\Python27\lib', 'C:\Python27\lib\plat-win', > 'C:\Python27\lib\lib-tk', 'C:\Python27', 'C:\Python27\lib\site-packages' * * * ## EDIT 1 In the previous post, all files (Python 2.7, cx_Oracle package, Oracle Instant client) were for 32 bit systems. I downloaded the same version of those files for 64 bit systems and everything is working fine on my remote workstation now. ## EDIT 2 Basically, the fix consisted for me in re-installing everything (Python, Oracle Instant Client and cx_Oracle) for 64-bit systems instead of 32-bit systems. To summarize, this was my problem and how it got fixed: 1) I installed Cx_Oracle (from 32-bit windows installation package) and Oracle Instant Client (32-bit) and it was working perfectly on my 64-bit system running python 2.7.5 for 32-bit systems 2) I did the same thing exactly on a Virtual Machine (running a 64-bit system as well) and it was not working 3) To get it working on the VM, I re-installed everything for 64-bit systems (python, Instant Client, Cx_Oracle) and it finally worked <http://www.oracle.com/technetwork/database/features/instant- client/index-097480.html> <http://sourceforge.net/projects/cx- oracle/files/5.1.2/> Also, Make sure to download the cx_Oracle and Instant client corresponding to your DB version (11g in my case). Hope this helps. Answer: I am running Oracle express on win 7 and python35(64 bit) . This is how I managed to get my django-1.9 connect to oracle. 1. Installed cx_Oracle using pip (`pip3 install cx_Oracle`) instead of downloading the msi from pypi website. 2. Downloaded Oracle instant client 64 bit version from (<http://www.oracle.com/technetwork/topics/winx64soft-089540.html>) and extracted to c:\oraclexe (just to keep all oracle stuff at one place) 3. Created below environment variables: `set ORACLE_BASE=C:\oraclexe set ORACLE_HOME=C:\oraniclexe\app\oracle\product\11.2.0\server set PATH=C:\oraclexe\instantclient_11_2;%PATH%` 4. Updated my django settings.py `DATABASES = { 'default':{ 'ENGINE':'django.db.backends.oracle' 'NAME':'XE', 'USER':'hr', 'PASSWORD':'hr', 'HOST':'localhost', 'PORT':'1521', }, } ` That's it. There after, my django migrations worked fine
Replace lowercase ASCII characters with X in Python Question: What is the cleanest, most Pythonic code for replacing lowercase characters with 'X' in a string? For example, `ABCDEFGhijklmnopQRSTUVwxyz` would become `ABCDEFGXXXXXXXXXQRSTUVXXXX`. Answer: I'd use [`str.translate()`](https://docs.python.org/2/library/stdtypes.html#str.translate) for that; easily the fastest method. A regular expression cannot touch this for speed. Python 2 version: import string map = string.maketrans(string.ascii_lowercase, 'X' * len(string.ascii_lowercase)) mapped = inputstring.translate(map) Python 3 version: import string map = str.maketrans(dict.fromkeys(string.ascii_lowercase, 'X')) mapped = inputstring.translate(map) Demo (Python 2): >>> import string >>> inputstring = 'ABCDEFGhijklmnopQRSTUVwxyz' >>> map = string.maketrans(string.ascii_lowercase, 'X' * len(string.ascii_lowercase)) >>> inputstring.translate(map) 'ABCDEFGXXXXXXXXXQRSTUVXXXX' `str.translate()` is _orders of magniture_ faster here: >>> import timeit >>> import re >>> def regex_replace(s, _sub=re.compile(r'[a-z]').sub): ... return _sub('X', s) ... >>> regex_replace(inputstring) 'ABCDEFGXXXXXXXXXQRSTUVXXXX' >>> timeit.timeit('f(s)', 'from __main__ import regex_replace as f, inputstring as s') 2.6076979637145996 >>> timeit.timeit('s.translate(m)', 'from __main__ import inputstring as s, map as m') 0.13378620147705078 The `str.translate()` version manages to do the task _20 times_ faster.
Using CouchDB Kit and Python; Trying to setup database without having to set DB inline Question: I am using `couchdbkit` to build a small Flask app and I am trying to write out some Python models so that interacting with the DB is easier (not inline). Here is my code so far: base.py from couchdbkit import * from api.config import settings class WorkflowsCloudant(Server): def __init__(self): uri = "https://{public_key}:{private_key}@{db_uri}".format( public_key=settings.COUCH_PUBLIC_KEY, private_key=settings.COUCH_PRIVATE_KEY, db_uri=settings.COUCH_DB_BASE_URL ) super(self.__class__, self).__init__(uri) class Base(Document): def __init__(self): server = WorkflowsCloudant.get_db(settings.COUCH_DB_NAME) self.set_db(server) super(self.__class__, self).__init__() workflows.py from couchdbkit import * from api.models.base import Base class Workflow(Base): workflow = DictProperty() account_id = IntegerProperty() created_at = DateTimeProperty() updated_at = DateTimeProperty() deleted_at = DateTimeProperty() status = StringProperty() Controller **init**.py from api.models import Workflow blueprint = Blueprint('workflows', __name__, url_prefix='/<int:account_id>/workflows') @blueprint.route('/<workflow_id>') def get_single_workflow(account_id, workflow_id): doc = Workflow.get(workflow_id) if doc['account_id'] != account_id: return error_helpers.forbidden('Invalid account') return Response(json.dumps(doc), mimetype='application/json') The error I keep getting is: `TypeError: doc database required to save document` I was trying to following the setup here (<http://couchdbkit.org/docs/gettingstarted.html>) but extrapolating their inline instructions to more of a dynamic context. Also, I am a Python newb, so my apologies for my ignorance Answer: This error happens if your model (Document) is not linked to the database (correctly). This is done by with `set_db` method. Also I think you should change your model: from couchdbkit import Document from couchdbkit import StringProperty, IntegerProperty from couchdbkit import DateTimeProperty, DictProperty class Workflow(Document): workflow = DictProperty() account_id = IntegerProperty() created_at = DateTimeProperty() updated_at = DateTimeProperty() deleted_at = DateTimeProperty() status = StringProperty() I changed the Base inheritance to Document class. Also avoid using `from some_module import *`! When you have your model set like this then you can link your model and couchdb like this: Workflow.set_db(server) NOTE: the code is not tested. I wrote it from my head so there could be some mistakes.
How to access MySQL from python Question: I've always used Xampp for db/ server purposes. I'm trying to use the same with my Python project but cannot seem to get it to work. Error from Python Shell import MySQLdb ImportError: No module named 'MySQLdb' I've been all around but nothing seems to work. I'm on windows 7, Python 3.3. Please someone advise. Links that would resolve this quick will be greatly appreciated. **Update:** Please note that it seems MySQL-python does not support python3 Answer: `pip install MySQL-python` Run this in your Windows console or Linux terminal, and this problem should disappear.
function names from config file in python Question: I have a JSON config file which tells me what kind of distribution to sample from. For example: { "parameter1" : { "distribution" : "exponential", "mean" = 5}, "parameter2" : { "distribution" : "poisson", "mean" = 3} } The list above can be exhaustive. I need have a function which will read this json file, and return the appropriate distribution to the calling code. I tried using string concatenation and `eval()`, but that gives me the sample values directly. I should be able to return the object/function to the calling function. Can some one help me do it? My attempt: import numpy.random as random def getDistribution(distribution, params): string= 'random.'+distribution return eval(string)(params["mean"]) This returns a value to me. Is there a way to return a handle to the actual distribution function like `random.exponential()` or `random.poisson()` which I can use in the function calling `getDistribution()`? Answer: You can use getattr to return the method (which is an attribute of `random`): def get_method(name): return getattr(random, name, None) def get_distribution(method, params): return method(params['mean']) method_name = 'exponential' method = get_method(method_name) if method: results = get_distribution(method, params) else: raise AttributeError('No such method in random: {}'.format(method_name)) `getattr` takes an optional third argument which is the value to return when the attribute cannot be found. I am using this to explicitly return `None`. You can change that to a default method that you want to use if the chosen method name is not available.