text
stringlengths
226
34.5k
Python import dependencies Question: I am dynamically creating some python code that I want to run inside a wrapper. Here is an overly simplified example. [wrapper.py] import cv2 img = cv2.imread('pic.png',0) __import__("fragment") cv2.imshow('pic',img) [fragment.py] img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) I want the wrapper to set up any imports and variables, then import the fragment which will do stuff (i.e. make the image grayscale) and then do some standardized stuff afterwards (i.e. display image). The fragments will be changing (genetic algorithm) so I would prefer to keep them separate from the setup which will be constant and will just get make manipulating the fragments more complicated. When I run the program I get dependency errors on the fragment because cv2 and img are not defined (scope errors). Is there a way to achieve this either with a correction to the method I have used above or with another method? I expect I might be able to also create the composite of the files in ram and then exec it or write over the fragment with a version of itself that contains all of the needed wrapping, but I wanted to see if there was something cleaner first. Sincerely, Paul. Answer: > The fragments will be changing (genetic algorithm) so I would prefer to keep > them separate from the setup which will be constant and will just get make > manipulating the fragments more complicated. Whatever the complexity of the genetic algorithms you implemented in `fragment.py` is, I do not see how importing `cv2` (and eventually more modules) will impact it in a way or an other. However, I agree with the first part of your statement in that you want to respect the principle of _[separation of concerns](https://en.wikipedia.org/wiki/Separation_of_concerns)_ and make your code cleaner. The solution I see for your problem is to set a configuration file `config.py` in which you set all your imports. But importing `config.py` into other files is useless unless you succeed to make modules such as `cv2` available elsewhere once for all. You can achieve that by _[dynamically importing them](http://www.diveintopython.net/functional_programming/dynamic_import.html)_ within `config.py` file: cv2=__import__('cv2') in your main program, `fragment.py` file or whatever module, you can make use of `cv2` by simply running this: import config config.cv2.imread('pic.png') `import config` ↔ you do not need anymore to run: `import cv2`. This is because this trick renders `cv2` as a global variable available across multiple modules. The same idea is valid for your other variables such as `img` that you need to declare in your `config.py` file too. Given these facts, here is my solution for your problem. Note that I am not using classes and functions: I prefer to address your problem straightforwardly and keep things too simple and clear instead. **Organization of the code:** The `config.py` file corresponds to your `wrapper.py`: solution/ β”œβ”€β”€ application.py β”œβ”€β”€ cfg β”‚Β Β  β”œβ”€β”€ config.py β”‚Β Β  └── __init__.pyc β”œβ”€β”€ gallery β”‚Β Β  └── pic.png └── genalgos β”œβ”€β”€ fragment.py └── __init__.py **config.py:** # This will make cv2 global and thus you won't need to import it in ./genalgos/fragment.py # You can use the same idea for all your other imports cv2=__import__('cv2') imgc=cv2.imread('./gallery/pic.png') # imgc is global **fragment.py:** # The only import you can not avoid is this one import cfg.config # imgs is global # By importing cfg.config you do not need to import cv2 here imgf=cfg.config.cv2.cvtColor(cfg.config.imgc,cfg.config.cv2.COLOR_BGR2GRAY) **application.py:** import cfg.config import genalgos.fragment if __name__=="__main__": """ Display the image 'imgc' as it is in 'cfg/config' file """ cfg.config.cv2.imshow('Pic in BGR',cfg.config.imgc) cfg.config.cv2.waitKey(0) cfg.config.cv2.destroyAllWindows() """ Display the grascaled image 'imgf' as it is in 'genalgos/fragment' file which itself is obtained after transforming imgc of 'cfg/config' file. """ cfg.config.cv2.imshow('PIC Grayscaled',genalgos.fragment.imgf) cfg.config.cv2.waitKey(0) # Press any key to exit cfg.config.cv2.destroyAllWindows() # Unpaint windows and leave
GAE Python get default bucket fxn returns None Question: I'm a GCS newbie trying to write an app that uploads a file to a bucket I have created. I've followed the tutorial and created a bucket using the browser interface. However when I programmatically try to access my bucket, I get an error. Instead of printing my default bucket name, my app ouputs "None". My ENTIRE app code is as shown: import webapp2 from google.appengine.api import app_identity class MainHandler(webapp2.RequestHandler): def get(self): self.response.write(app_identity.get_default_gcs_bucket_name()) app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True) What am I doing wrong? Answer: **Update** : Seems you can now create a default bucket **in the new console** too by visiting your app engine's application settings in the cloud console <https://console.cloud.google.com/appengine/settings?project=> [![Create Default Bucket](http://i.stack.imgur.com/ltbDK.png)](http://i.stack.imgur.com/ltbDK.png) * * * **Original** : You're getting `NONE` because by default there's no longer a default bucket > About default Cloud Storage buckets > > Applications created using the old App Engine console could use a default > Cloud Storage bucket, which had free quota and didn't require billing to be > enabled for the app. These applications continue to work as before in the > Google Cloud Platform Console. > > However, new App Engine projects created in the Google Cloud Platform > Console don't have a default Cloud Storage bucket. Instead you must use a > standard Cloud Storage bucket as described above. But since you manually created the bucket, you will already have its name and so can probably skip `app_identity.get_default_gcs_bucket_name()` and hardcode the bucket name or call it from a config variable, etc, etc. You can then use the [gcloud- python](https://github.com/GoogleCloudPlatform/gcloud-python) lib to upload files to your bucket: from gcloud import storage client = storage.Client() bucket = client.get_bucket('<bucket-name>') my_file = bucket.blob('/path/to/be/saved/in/bucket') my_file.upload_from_filename(filename='/path/to/local/file') You'll have to [vendor](https://cloud.google.com/appengine/docs/python/tools/libraries27#vendoring) the gcloud lib if you're doing this on app engine. All that said and done if you still want the old behaviour of getting the default bucket which is in the format `<project-id.appspot.com>`, you can follow [GAEfan's answer](http://stackoverflow.com/a/24237328/2295256), in short: > Go to the old console, appengine.google.com > Application Settings > Cloud > Integration > Create
Run a executable by python at background and still running Question: High! I have a executable made by py2exe whitch test if my vpn is connect or not at infinit loop runinngi on Windows. I want to make run in background or hiden, i searched for several forums and i found 2 scripts worked partialy. 1. rename script to "scrypt.pyw" and run py2exe again, the .exe hide when i run it, but close or vanish. Doesnt continues running after the click. 2. I am made another exe to call the fist one: import os import subprocess os.chdir("C:\Users\dl\Documents\Log\Py") proc = subprocess.Popen('ipLog.exe', creationflags=subprocess.SW_HIDE, shell=True) proc.wait() or os.chdir("C:\Users\dl\Documents\Log\Py") proc = subprocess.Popen('ipLog.exe', creationflags=subprocess.SW_HIDE, shell=True) -Works but the first command still visible, and when i close it, the first exe call by it quit too. 3. I tried install a module call self.hide but i cant. I am newbie in python and try to change my hobbies vb, vba to python. Thanks for any help. Answer: I found a solution in this thread [How to start daemon process from python on windows?](http://stackoverflow.com/questions/12843903/how-to-start-daemon- process-from-python-on-windows). Thank you all people helped with this thread, help my script too.
Need to check if an answer in a quiz is correct (Python) Question: So I have a dictionary with legislators and the parties they belong to. Five questions are outputted with random names and parties and the input is either Y or N. I need to now figure out how to check if its true or not but I am stumped. The code: from random import * legislators = { "Tsang Yok-sing" : "DAB", "Albert Ho" : "Democratic", "Lee Cheuk-yan" : "Labour", "James To" : "Democratic", "Chan Kam-lam" : "DAB", "Lau Wong-fat" : "Economic Synergy", "Emily Lau" : "Democratic" } names = list(legislators.keys()) parties = list(legislators.values()) numberCorrect = 0 for i in range(0, 5): name = names[randrange(len(names))] party = parties[randrange(len(parties))] ans = input("Does "+name+" belong to "+party+" (Y/N)?\n") Just need to get any advice on where to start on this. Thanks a lot! Answer: from random import * legislators = { "Tsang Yok-sing" : "DAB", "Albert Ho" : "Democratic", "Lee Cheuk-yan" : "Labour", "James To" : "Democratic", "Chan Kam-lam" : "DAB", "Lau Wong-fat" : "Economic Synergy", "Emily Lau" : "Democratic" } names = list(legislators.keys()) parties = list(legislators.values()) numberCorrect = 0 for i in range(0, 5): name = names[randrange(len(names))] party = parties[randrange(len(parties))] ans = raw_input("Does "+name+" belong to "+party+ " Y/N?") if ans == 'Y': if legislators[name] == party: print 'correct' else: print 'error' elif ans == 'N': if legislators[name] == party: print 'error' else: print 'correct'
Wing IDE not stopping at break point for Google App Engine Question: I'm new to Python, Wing IDE and Google cloud apps but have done a lot of programming so hopefully the below question is not too stupid. I've been trying for a couple of days to get Wing IDE to stop at a break point on the local (Windows 7) Google App Engine. I'm using the canned guestbook demo app and it launches fine and responds as expected in the web browser. However breakpoints are not working. I'm not sure if this is important but I see the following status message when first starting the debugger: Debugger: Debug process running; pid=xxxx; Not listening (too many connections) ... My run arguments are as per the recommendation in the Wing IDE help file section "Using Wing IDE with Google App Engine", namely: C:\x\guestbook --max_module_instances=1 --threadsafe_override=false One problem I found when trying to follow these instructions. The instructions say go into Project Properties and the Debug/Execute tab and set the Debug Child Processes to Always Debug Child Process. I found this option doesn't exist. Note also that in the guestbook app, if I press the pause button, the code breaks, usually in the python threading.py file in the wait method (which makes sense). Further note also that if I create a generic console app in Wing IDE, breakpoints work fine. I'm running 5.1.9-1 of Wing IDE Personal. I've included the Google appengine directory and the guestbook directories in the python path. Perhaps unrelated but I also find that sys.stdout.write strings are not appearing in the Debug I/O window. Thanks in advance for any assistance. Regards Adam Answer: As often happens with these things, writing this question gave me a couple of ideas to try. I was using the Personal edition ... so I downloaded the professional edition ... and it all worked fine. Looks like I'm paying $95 instead of $45 when the 30 day trial runs out.
Return all tags and values of a given object within xml document in Python Question: I have xml which looks like this... <CONFIG2> <OBJECT id="{2D3474AA-9A0F-4696-979C-1BCE9350F3BD}" type="3" name="Test2" rev="1"> <RULEITEM> <ID>{BF7D00C5-57BC-4187-9B07-064BA5744A12}</ID> <PROPERTIES> <columnname/> <columnvalue/> <days>|</days> <enabled>1</enabled> <eventdate>0001-01-01</eventdate> <eventtime>00:00:00</eventtime> <function>average</function> <parameters/> <stattype>standard</stattype> </PROPERTIES> <ITEM> <ID>{61C82F62-8F31-4754-A705-7CCBB34C6FD4}</ID> <PROPERTIES> <actionindex>0</actionindex> <actiontype>eventlog</actiontype> <severity>error</severity> </PROPERTIES> </ITEM> </RULEITEM> <PROPERTIES> <groups>|</groups> </PROPERTIES> </OBJECT> I am trying to return everything within OBJECT and /OBJECT. For example, I would like to return all tags and values for the OBJECT where type="3" and name="test2". Here is my current python script... import xml.etree.ElementTree as ET tree = ET.parse(r'C:\Users\User\Desktop\xml\config.xml') root = tree.getroot() objectType = input("What object type are you looking for?: ") for item in root.findall('OBJECT'): if item.attrib['type'] == objectType: print(item.get('name')) objectName = input("What is the name of the object you are looking for?: ") for item in root.findall('OBJECT'): if item.attrib['type'] == objectType and item.get('name') == objectName: print(list(item)) This returns... <Element "RULEITEM' at 0x00064F3C0>, <Element 'PROPERTIES' at 0x0064FB40> I like it to return the entire object and all tags and values. Does anyone know how I could do this? Thanks! Answer: Consider adjusting second loop by using another `findall()` iteration on all of `OBJECT's` children and grandchildren and so forth using (`//*`). Also, consider appending to a pre-defined list instead of `list()` (which would have broken each character of the loops' text item) and condition it to remove `None` values (i.e., empty nodes). Finally, use the `tag` and `text` property of the node: ... same code as above... values = [] for item in root.findall('OBJECT'): if item.attrib['type'] == objectType and item.get('name') == objectName: for data in root.findall("OBJECT//*"): if data.text is not None: values.append(data.tag + ': ' + data.text) for v in values: print(v) #What object type are you looking for?: 3 #Test2 #What is the name of the object you are looking for?: Test2 #RULEITEM: # #ID: {BF7D00C5-57BC-4187-9B07-064BA5744A12} #PROPERTIES: # #days: | #enabled: 1 #eventdate: 0001-01-01 #eventtime: 00:00:00 #function: average #stattype: standard #ITEM: # #ID: {61C82F62-8F31-4754-A705-7CCBB34C6FD4} #PROPERTIES: # #actionindex: 0 #actiontype: eventlog #severity: error #PROPERTIES: # #groups: |
How to sort a list with duplicate items by the biggest number of duplicate occurrences - Python Question: I have a list1 = ["one", "two", "two", "three", "four" , "five", "five", "five", "six"] and the Output should be list2 = ["five" , "two", "one", "three" , "six"] * `"five"` is the first element because in list1 has the highest number of occurrences (3) * `"two`" is the second element because in list1 has the next highest number of occurrences (2) * `"one"`, `"three`" and `"six"` have the same lower number of occurrences (1) so they are the last in my `list2` \- It doesn't really matter what position they will be as long as they are after "five" and "two". On short, `list2 = ["five" , "two", "six", "three" , "one"]` or `list2 = ["five" , "two", "three", "one" , "six"]` or any other variations are accepted. I could solve this by creating a dictionary to store the number of occurances and then create a new list with my items ordered by the dict my_dict = {i:list1.count(i) for i in list1} but I need something cleaner Answer: You could use a list comprehension and [`Counter`](https://docs.python.org/3/library/collections.html#counter- objects): from collections import Counter print([element for element,count in Counter(list1).most_common()]) Outputs: ['five', 'two', 'three', 'six', 'four', 'one']
wx.TextCtrl is blank for very long strings Question: I'm trying to display the string representation of a list of many float items in a wx.TextCtrl using the SetValue() method. As soon as the length of the string to be displayed reaches 6151 characters the TextCtrl goes blank and does not display the string. I can still copy portions of the text control as normal and paste them somewhere (such as a text editor) but the characters in the text control itself don't appear on the screen. Why isn't the text control's value displayed in the text control? How do I make it display the string if it's longer than 6150 characters? This happens when setting the text control's value using the SetValue method and when typing in the text control. Changing the max length for the text control didn't help. Environment: * Windows 10 (64 bit) * Python 2.7.10 * wxPython 3.0 Example code: import wx import os class MainWindow(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(200,-1)) self.control = wx.TextCtrl(self) self.control.SetMaxLength(10000) #doesn't help self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.control, 1, wx.EXPAND) self.SetSizer(self.sizer) self.SetAutoLayout(1) self.sizer.Fit(self) self.Show(True) app = wx.App(False) frame = MainWindow(None, "Sample editor") app.MainLoop() Answer: It looks like a bug. According to the [this](https://groups.google.com/forum/#!topic/wxpython-users/m_6SYxkiI00), it should max out at 64K since Windows 98 unless the operating system you have has some kind of odd limit. You can actually increase the number of characters displayed by using one of the `wx.TE_RICH` style flags. I was able to replicate your issue on Windows 7 with Python 2.7 and wxPython 3.0.2 using the following code: import wx ######################################################################## class MyPanel(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" super(MyPanel, self).__init__(parent) self.text = wx.TextCtrl(self, value="y"*7000) btn = wx.Button(self, label='Line Length') btn.Bind(wx.EVT_BUTTON, self.onLength) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.text, 0, wx.EXPAND|wx.ALL, 5) sizer.Add(btn, 0, wx.CENTER|wx.ALL, 5) self.SetSizer(sizer) #---------------------------------------------------------------------- def onLength(self, event): """""" print len(self.text.GetValue()) ######################################################################## class MyFrame(wx.Frame): """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" super(MyFrame, self).__init__(parent=None, title='Test') panel = MyPanel(self) self.Show() if __name__ == '__main__': app = wx.App(False) frame = MyFrame() app.MainLoop() If I add the `wx.TE_RICH` flag and call `Layout()`, I can make it work though: import wx ######################################################################## class MyPanel(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" super(MyPanel, self).__init__(parent) self.text = wx.TextCtrl(self, value="y"*7000, style=wx.TE_RICH) btn = wx.Button(self, label='Line Length') btn.Bind(wx.EVT_BUTTON, self.onLength) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.text, 0, wx.EXPAND|wx.ALL, 5) sizer.Add(btn, 0, wx.CENTER|wx.ALL, 5) self.SetSizer(sizer) self.Layout() #---------------------------------------------------------------------- def onLength(self, event): """""" print len(self.text.GetValue()) ######################################################################## class MyFrame(wx.Frame): """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" super(MyFrame, self).__init__(parent=None, title='Test') panel = MyPanel(self) self.Show() if __name__ == '__main__': app = wx.App(False) frame = MyFrame() app.MainLoop() You should report this bug here: <http://trac.wxwidgets.org/>
What is the preferred way to import pylab at a function level in Python 2.7? Question: I have written a relatively simple function in python that can be used to plot the time domain history of a data set as well as the frequency domain response of a data set after a fast fourier transform. In this function I use the command `from pylab import *` to bring in all the necessary functionality. However, despite successfully creating the plot, I get a warning stating > import * only allowed at the module level. So if using the command `from pylab import *` is not the preferred methodology, how do I properly load all the necessary functionality from pylab. The code is attached below. Also, is there a way to close the figure after the function is exited, I have tried `plt.close()` which is not recognized for subplots? def Time_Domain_Plot(Directory,Title,X_Label,Y_Label,X_Data,Y_Data): # Directory: The path length to the directory where the output file is # to be stored # Title: The name of the output plot, which should end with .eps or .png # X_Label: The X axis label # Y_Label: The Y axis label # X_Data: X axis data points (usually time at which Yaxis data was acquired # Y_Data: Y axis data points, usually amplitude from pylab import * from matplotlib import rcParams rcParams.update({'figure.autolayout': True}) Output_Location = Directory.rstrip() + Title.rstrip() fig,plt = plt.subplots() matplotlib.rc('xtick',labelsize=18) matplotlib.rc('ytick',labelsize=18) plt.set_xlabel(X_Label,fontsize=18) plt.set_ylabel(Y_Label,fontsize=18) plt.plot(X_Data,Y_Data,color='red') fig.savefig(Output_Location) plt.clear() Answer: From the [matplotlib documentation](http://matplotlib.org/faq/usage_faq.html#matplotlib-pyplot-and- pylab-how-are-they-related): > `pylab` is a convenience module that bulk imports `matplotlib.pyplot` (for > plotting) and `numpy` (for mathematics and working with arrays) in a single > name space. Although many examples use `pylab`, it is no longer recommended. I would recommend not importing `pylab` at all, and instead try using import matplotlib import matplotlib.pyplot as plt And then prefixing all of your `pyplot` functions with `plt`. I also noticed that you assign the second return value from `plt.subplots()` to `plt`. You should rename that variable to something like `fft_plot` (for fast fourier transform) to avoid naming conflicts with `pyplot`. With regards to your other question (about `fig, save fig()`) you're going to need to drop that first `fig` because it's not necessary, and you'll call `savefig()` with `plt.savefig()` because it is a function in the `pyplot` module. So that line will look like plt.savefig(Output_Location) Try something like this: def Time_Domain_Plot(Directory,Title,X_Label,Y_Label,X_Data,Y_Data): # Directory: The path length to the directory where the output file is # to be stored # Title: The name of the output plot, which should end with .eps or .png # X_Label: The X axis label # Y_Label: The Y axis label # X_Data: X axis data points (usually time at which Yaxis data was acquired # Y_Data: Y axis data points, usually amplitude import matplotlib from matplotlib import rcParams, pyplot as plt rcParams.update({'figure.autolayout': True}) Output_Location = Directory.rstrip() + Title.rstrip() fig,fft_plot = plt.subplots() matplotlib.rc('xtick',labelsize=18) matplotlib.rc('ytick',labelsize=18) fft_plot.set_xlabel(X_Label,fontsize=18) fft_plot.set_ylabel(Y_Label,fontsize=18) plt.plot(X_Data,Y_Data,color='red') plt.savefig(Output_Location) plt.close()
How does the __future__ module work in Python 2.7? Question: In Python 2.7 using the `__future__` module and the `print_function` you can use the python 3.X print function. My question is, how did the developers of Python know what was coming in the future releases of Python? Or was this module added to Python 2.7 after it was released? Here is the code I am talking about: from __future__ import print_function print("Hello world!") Answer: The [`__future__`](https://docs.python.org/3.5/library/__future__.html) module was introduced in Python 2.1 in order to have access to upcoming features/functions which will lead to incompatibilities with the current implementation and is extended with each version if needed. So the module gives the possibility to use those incompatible functions of future versions in earlier versions. So you can make use of the upcoming advantages of those functions. There are three main reasons for that module as stated in the docs: > `__future__` is a real module, and serves three purposes: > > * To avoid confusing existing tools that analyze import statements and > expect to find the modules they’re importing. > * To ensure that future statements run under releases prior to 2.1 at > least yield runtime exceptions (the import of `__future__` will fail, > because there was no module of that name prior to 2.1). > * To document when incompatible changes were introduced, and when they > will be β€” or were β€” made mandatory. This is a form of executable > documentation, and can be inspected programmatically via importing > `__future__` and examining its contents. >
python-couchdb: How to check if database already exists Question: I am writing a small Python program that loads some documents into couchdb. It would be very convenient to check whether a database with a certain name already exists, so I can either create a new one or open the existing one. What I want to do is something like this: import couchdb def connect(url, dbName): server = couchdb.Server(url) if dbName exists: # how do I do this? return server[dbName] else: return server.create(dbName) I know a try-except block would do the trick, but isn't there a more elegant way? Answer: The easiest way I can think is: import couchdb server = couchdb.Server("http://localhost:5984") "dataBaseName" in server Return `True` if a database with the name exists, `False` otherwise <https://github.com/djc/couchdb-python/blob/master/couchdb/client.py#L88-L99>
validate email address with Python Question: I'm trying to validate emails using [validate_email 1.3 : Python Package Index](https://pypi.python.org/pypi/validate_email), like this: from validate_email import validate_email is_valid = validate_email('[email protected]',check_mx=True) How can I speed this up? My `for` loop isn't very effective with amount of emails I need to verify... Answer: Only use `check_mx=True` the first time you encounter a domain. After that, just use a regex to validate the address.
Loop through and compare spreadsheet cells in Python Question: Please excuse the crude code and I'm sure there are better ways to accomplish this but I am new to programming. Basically I have an excel file with 2 sheets, sheet 1 is populated in column A, sheet 2 is populated in A, B, and C. I want to run through all of the cells in sheet 1 column A searching for a match in sheet 2 column A and copy the info from B and C to sheet 1 if found. The code below kind of works, it copies some data and populates it but it doesn't really match up correctly and it seems to skip a lot of cells if they are the same value as the previous cell. Any help would be greatly appreciated. import openpyxl wb = openpyxl.load_workbook('spreadsheet.xlsx') sheet1 = wb.get_sheet_by_name('Sheet1') sheet2 = wb.get_sheet_by_name('Sheet2') for row in sheet1['A1':'A200']: for cell in row: obj1 = cell.value for row2 in sheet2['A1':'A2000']: for cell2 in row2: obj2 = cell2.value if obj1 == obj2: row = str(cell2.row) site = 'B' + row tic = 'C' + row sheet1[site] = sheet2[site].value sheet1[tic] = sheet2[tic].value wb.save('spreadsheet2.xlsx') Answer: Your question is a little unclear but if I understand you correctly this should help: import openpyxl wb = openpyxl.load_workbook('spreadsheet.xlsx') sheet1 = wb.get_sheet_by_name('Sheet1') sheet2 = wb.get_sheet_by_name('Sheet2') for i in range(1, 201): if sheet1.cell(row = i, column = 1).value == sheet2.cell(row = i, column = 1).value: sheet1.cell(row = i, column = 2).value = sheet2.cell(row = i, column = 2).value sheet1.cell(row = i, column = 3).value = sheet2.cell(row = i, column = 3).value wb.save('spreadsheet2.xlsx') I was able to clean up the code by the using the `.cell()` method. If this isn't what you need just comment and tell me what exactly you are trying to do. Hope this helps!
How can I add an integer variable to an openmdao driver? Question: I am confused by this openmdao error. Why is this being raised? Can I somehow tell openmdao that I don't have gradients and to use finite differences? Why is this raised for childWeight but not eta? I can get past this problem by initializing al my variables as floating point (eg. `root.add('childWeight', IndepVarComp('x',100))` -> `root.add('childWeight', IndepVarComp('x',100.0))`), but I would like to understand why this error was raised. from openmdao.api import Component, Group, Problem, ScipyOptimizer, IndepVarComp class gym(Component): def __init__(self): super(gym, self).__init__() self.add_param('eta', 0.01) self.add_param('childWeight', 240) self.add_output('acc', 1) def solve_nonlinear(self, params, unknowns, resids): <...... parameters are used to produce objective "acc" ...> unknowns["acc"] = .... top = Problem() root = top.root = Group() root.add('gym', gym()) top.driver = ScipyOptimizer() top.driver.options['optimizer'] = 'BFGS' root.add('eta',IndepVarComp('x', 0.01)) root.add('childWeight', IndepVarComp('x',100)) root.connect('eta.x', 'gym.eta') root.connect('childWeight.x', 'gym.childWeight') top.driver.add_desvar('eta.x', 0, 1.0) top.driver.add_desvar('childWeight.x', 0, 1000) top.driver.add_objective('gym.acc') top.setup() top.run() raises the error File "script.py", line 98, in <module> top.setup() File "/usr/local/lib/python2.7/site-packages/openmdao/core/problem.py", line 694, in setup self.driver._setup() File "/usr/local/lib/python2.7/site-packages/openmdao/drivers/scipy_optimizer.py", line 91, in _setup super(ScipyOptimizer, self)._setup() File "/usr/local/lib/python2.7/site-packages/openmdao/core/driver.py", line 115, in _setup (item_name, name, oname)) RuntimeError: Parameter 'childWeight.x' is a 'pass_by_obj' variable and can't be used with a gradient based driver of type 'BFGS'. Answer: The problem is this line root.add('childWeight', IndepVarComp('x',240)) You've created an integer variable. Try this instead: root.add('childWeight', IndepVarComp('x',240.)) If you want to use finite-differences you will also want: top.root.fd_options['force_fd'] = True
Solve for constants of 4-parameter (Rodbard Equation) using Python Question: I am new to python and what I am trying to do is write an algorithm to solve for the 4 unknown parameters in the Rodbard Equation where we are relating a grayscale value measured using ImageJ to optical density calibration discs. This equation is nonlinear and is written as y = c*((x-a)/(d-x))^(1/b) where a, b, c, and d are unknown. I have the values of x and y for four point (176.5, 0), (161.333, 0.1), (66.1667, 0.9), and (40.833, 2.5). Below, I have posted my attempt to solve for these 4 unknowns. Any help to point me in the right direction would be greatly appreciated! import scipy.optimize as opt def f(a, b, c, d): 0 == [c * ((176.5 - a)/(d - 176.5))**(1/b)] 0.1 == [c * ((161.333 - a)/(d - 161.333))**(1/b)] 0.9 == [c * ((66.1667 - a)/(d - 66.1667))**(1/b)] 2.5 == [c * ((40.833 - a)/(d - 40.833))**(1/b)] return f opt.curve_fit(a, b, c, d) print a print b print c print d Answer: If you want to use curve_fit, you should do the following: def f(x1, a1, b1, c1, d1): return c1 * (((x1 - a1)/(d1 - x1))**1/b1) x_data = np.array([176.5, 161.333, 66.1667, 40.833]) y_data = np.array([0., 0.1, 0.9, 2.5]) p0 = np.array([168., -0.01, -7.4, 35000.]) popt, pcov = opt.curve_fit(f, x_data, y_data, p0, None, False, True, ftol = 0.00001) p0 is the initial guess and if you do not inform it, an array of all ones will be assumed. With the provided data I have tried with different params but I've not been able to find a solution. I hope this helps. Good luck!
Twillio Restclient in python Question: I'm Using Twilio Rest API in python to send sms , Below is the code I'm using to send SMS SMS was being sent successfully by below code but I want body of text to be declared as a variable. For example if I declare `ABC = "Test message"` then body should be `Test message`. from twilio.rest import TwilioRestClient ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) message = client.messages.create( body="Hello World!", to="+12125551234", from_="+15105551234", ) print message.sid If I use body = "ABC" it's sending message as "ABC" by sms i want declare variable in this case ABC = "Test Message " i want Body as Testmessage message = client.messages.create( body="Hello Monkey!", # Message body, if any to="+12125551234", from_="+15105551234", ) print message.sid Is there any way to send declare variable as Message. Answer: Hi if you write anything in a "" (string) then it will be treated as a String. You should modify your code like below: text = "Test Message" message = client.messages.create( body= text, to="+12125551234", from_="+15105551234", ) print message.sid Basically you should assign the variable `text` to `body` so now body is "Test Message"
drone-kit Python is not connecting with Iris+ Question: I'm trying to build my first dronekit python program, and I'm doing some tests with some examples but I couldn't connect to my UAV(Iris+). I plugged the usb radio(3DR 915 MHz) and I put `vehicle = connect('/dev/ttyUSB0', wait_ready=True)`. Actually I have no idea which string I should put in. Thanks in advance guys, I need some help! My code: print "Start simulator (SITL)" from dronekit_sitl import SITL sitl = SITL() sitl.download('copter', '3.3', verbose=True) sitl_args = ['-I0', '--model', 'quad', '--home=-35.363261,149.165230,584,353'] sitl.launch(sitl_args, await_ready=True, restart=True) # Import DroneKit-Python from dronekit import connect, VehicleMode import time # Connect to the Vehicle. print "Connecting to vehicle on: '/dev/ttyUSB0'" vehicle = connect('/dev/ttyUSB0', wait_ready=True) # Get some vehicle attributes (state) print "Get some vehicle attribute values:" print " GPS: %s" % vehicle.gps_0 print " Battery: %s" % vehicle.battery print " Last Heartbeat: %s" % vehicle.last_heartbeat print " Is Armable?: %s" % vehicle.is_armable print " System status: %s" % vehicle.system_status.state print " Mode: %s" % vehicle.mode.name # settable # Close vehicle object before exiting script vehicle.close() # Shut down simulator sitl.stop() print("Completed") Answer: Best place for getting dk support now is probably here: <https://discuss.dronekit.io/c/python> In answer, I have not tried this on Linux. I suspect the connection string is correct, but you may have to also set the baud rate using baud=57600
Scraping using beautiful soup not working for a particular URL as expected Question: I was trying to scrape some data off from a site using beautifulsoup on python 3.5(i'm working on eclipse) and requests from the site '<http://www.transfermarkt.com/arsenal- fc/startseite/verein/11/saison_id/2015>' which has some stats for footballers. my code: from bs4 import BeautifulSoup import requests r=requests.get('http://www.transfermarkt.com/arsenalfc/startseite/verein/11/saison_id/2015') soup = BeautifulSoup(r.content, 'html.parser') print (soup.prettify()) I expect a neat and pretty looking html code but all i get as output is this: <html> <head> <title> 404 Not Found </title> </head> <body bgcolor="white"> <center> <h1> 404 Not Found </h1> </center> <hr> <center> nginx </center> </hr> </body> </html> For a different url it works. I have tried a couple of other url's and it worked. But not for this one. Am I doing something wrong. Any suggestion is appreciated. Thanks Answer: You should use a user-agent to make the website think the request comes from a browser. This worked for me: from bs4 import BeautifulSoup import requests headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'} r=requests.get('http://www.transfermarkt.com/arsenalfc/startseite/verein/11/saison_id/2015', headers=headers) soup = BeautifulSoup(r.content, 'html.parser') print(soup.prettify())
Get NS and MX web information python Question: Im trying to get information about two domain input with this code: #! usr/bin/python domainlist=[] #Ask for domain 1 domain = raw_input("------------------------------------------\nIntroduce el primer domino de la pagina web:\n") domainlist.append(domain) #Ask for domain 2 domain = raw_input("------------------------------------------\nIntroduce el segundo domino de la pagina web:\n") domainlist.append(domain) print "-------------------" #Declare Variable #Find dns def fundns(): import dns.resolver idns = dns.resolver.query(i,'NS') print "Los DNS de %s" % domain + " son:" for server in idns: print server #Find mx def funmx(): import dns.resolver mx = dns.resolver.query(i,'MX') print "Los MX de %s" % domain + " son:" for rdata in mx: print "Host", rdata.exchange for i in domainlist: fundns() print "----------------------------------------" funmx() but I received this error: > Traceback (most recent call last): File "ejercicio5.py", line 29, in funmx() > File "ejercicio5.py", line 22, in funmx I can see in the print all the information unless last `mx` registry, and I don't know what is wrong... Some one could help me? Answer: You need to actually pass the domain names to your functions import dns.resolver domainlist = ['google.com', 'yahoo.com'] #Declare Variable #Find dns def fundns(domain): idns = dns.resolver.query(domain,'NS') print "Los DNS de %s" % domain + " son:" for server in idns: print server #Find mx def funmx(domain): mx = dns.resolver.query(domain,'MX') print "Los MX de %s" % domain + " son:" for rdata in mx: print "Host", rdata.exchange for i in domainlist: fundns(i) print "----------------------------------------" funmx(i) Previously you were trying to use global variables, or so it seems. The Output: Los DNS de google.com son: ns3.google.com. ns2.google.com. ns4.google.com. ns1.google.com. ---------------------------------------- Los MX de google.com son: Host alt3.aspmx.l.google.com. Host alt2.aspmx.l.google.com. Host alt4.aspmx.l.google.com. Host alt1.aspmx.l.google.com. Host aspmx.l.google.com. Los DNS de yahoo.com son: ns6.yahoo.com. ns2.yahoo.com. ns5.yahoo.com. ns3.yahoo.com. ns1.yahoo.com. ns4.yahoo.com. ---------------------------------------- Los MX de yahoo.com son: Host mta5.am0.yahoodns.net. Host mta7.am0.yahoodns.net. Host mta6.am0.yahoodns.net.
Python Attribute Error: type object has no attribute Question: I am new to Python and programming in general (since December) and try to teach myself some Object-Oriented Python and got this error on my lattest project: AttributeError: type object 'Goblin' has no attribute 'color' I have a file to create "Monster" classes and a "Goblin" subclass that extends from the Monster class. When I import both classes the console returns no error >>>from monster import Goblin >>> Even creating an instance works without problems: >>>Azog = Goblin >>> But when I call an attribute of my Goblin class then the console returns the error on top and I don't figure out why. Here is the complete code: import random COLORS = ['yellow','red','blue','green'] class Monster: min_hit_points = 1 max_hit_points = 1 min_experience = 1 max_experience = 1 weapon = 'sword' sound = 'roar' def __init__(self, **kwargs): self.hit_points = random.randint(self.min_hitpoints, self.max_hit_points) self.experience = random.randint(self.min_experience, self.max_experience) self.color = random.choice(COLORS) for key,value in kwargs.items(): setattr(self, key, value) def battlecry(self): return self.sound.upper() class Goblin(Monster): max_hit_points = 3 max_experience = 2 sound = 'squiek' Answer: You are not creating an instance, but instead referencing the class `Goblin` itself as indicated by the error: > AttributeError: **type** object 'Goblin' has no attribute 'color' Change your line to `Azog = Goblin()`
Django command: How to insert newline in the help text? Question: I was looking to do something like this, but for a Django management command: [Python argparse: How to insert newline in the help text?](http://stackoverflow.com/questions/3853722/python-argparse-how-to- insert-newline-in-the-help-text) Answer: You can do the following to set the formatter_class on the ArgumentParser Django creates for you: from argparse import RawTextHelpFormatter from django.core.management.base import BaseCommand class Command(BaseCommand): def create_parser(self, *args, **kwargs): parser = super(Command, self).create_parser(*args, **kwargs) parser.formatter_class = RawTextHelpFormatter return parser
How to execute external Python script with a program coded in Haxe? Question: I have a Haxe program and I need to retrieve data from Wordnik API. Here are the list of supported platform in Wordnik: <http://developer.wordnik.com/#!/libraries> I have no experience in all of these languages supported by Wordnik. However, I think Python is the most feasible way to connect Wordnik API into my Haxe program because Python is a scripting language and can be executed from terminal command. Perhaps, something like Haxe program execute the Python WITH some parameters. Then the Python script retrieve data from Wordnik and then compile it into a JSON or .txt file. Finally return back to Haxe program to parse the JSON or .txt file. I am not sure how this thing can work, hence I am looking for guidance here :). Answer: One thing to look out for is using the [Python 3 version](https://github.com/wordnik/wordnik-python3) of the library, instead of the [Python 2.7 one](https://github.com/wordnik/wordnik-python) which is linked to on that overview page. Haxe's Python target [only supports version 3 or higher](https://github.com/HaxeFoundation/haxe/issues/4195). There shouldn't be a need for a Python program serving as an interface between Haxe and the Wordnik API - you could write [externs](http://haxe.org/manual/lf-externs.html) describing the interface to just use it directly from Haxe. An `extern` for a very simple class, [`wordnik.models.Label`](https://github.com/wordnik/wordnik- python3/blob/master/wordnik/models/Label.py), could look like this: package wordnik.models; @:pythonImport("wordnik.models.Label", "Label") extern class Label { public var text:String; public var type:String; public function new() { } } With that, you can then use the API from Haxe: package; import python.Lib; import wordnik.models.Label; class Main { static function main() { var label = new Label(); label.text = "Test"; trace(label.text); } } You can find a lot of examples of Python externs in [the Haxe standard library](https://github.com/HaxeFoundation/haxe/tree/development/std/python/lib). It also has wrappers for things that are a bit more complex to express, like [`KwArgs`](https://github.com/HaxeFoundation/haxe/blob/development/std/python/KwArgs.hx).
Python - How to call the main fuction of a module in another module? Question: I am trying to write a python module that calls the main function of another module in its main function. The module I am writing is called Trial.py and the module that contains the function to be called is called `print_all.py` . print_all.py is a module is a library called mrtparse. The library can be found [here](https://github.com/YoshiyukiYamauchi/mrtparse). Note that when I run `print_all.py` in the Linux shell it requires a file (.gz) as argument as follows $ python print_all.py updates.gz `Trial.py` looks something like this: from mrtparse import * import gzip import print_all import os from urllib2 import urlopen, URLError, HTTPError def fn1(): Bla Bla def fn2(): Bla Bla def main(): mrtparse.print_all.main(updates.gz) //I want to do something like this if __name__ == '__main__': main() All the modules and the files to be passed as arguments are in the same directory. It seems like an easy to do thing but I am having such a hard time with it. Answer: you could in the script you want to run the main function from place main() in the else statement instead of if **name** then import it in your script and just run. if __name__=='__main__': pass else: main()
Python: import all submodules' method? Question: I organized my helper method into this way: [![enter image description here](http://i.stack.imgur.com/Tz9jc.png)](http://i.stack.imgur.com/Tz9jc.png) All the methods are used in the current file, so I need to import them like this: from helpers.utility_helper import * from helpers.app_helper import * from helpers.gmm_helper import * from helpers.plot_helper import * So I can directly use methods in each of the submodule. For example, use `my_helper()` instead of `helpers.utility_helper.my_helper()`. But this looks quite verbose, is it possible to combine them into one line? Something may look like `import * from helpers/*` Answer: I would advise to use explicit imports instead of importing whole: from helpers.utility_helper import my_helper, your_helper This will help to avoid mistakes. For short names you can use _as_ : import helpers.utility_helper as util import helpers.app_helper as app import helpers.gmm_helper as gmm import helpers.plot_helper as plot It is quite normal practice.
HSV2BGR conversion fails in Python OpenCV script Question: My script is supposed to take a greyscale image and map the values to hues. #!/usr/bin/env python import cv2 import numpy infile = cv2.imread('Lenna.png') infile = infile[:,:,0] hues = (numpy.array(infile)/255.)*179 outimageHSV = numpy.array([[[b,255,255] for b in a] for a in hues]).astype(int) outimageBGR = cv2.cvtColor(outimageHSV, cv2.COLOR_HSV2BGR) cv2.imshow('dst_rt', outimageBGR) cv2.waitKey(0) cv2.destroyAllWindows() It fails on the line with cvtColor and I get this error: OpenCV Error: Assertion failed (depth == CV_8U || depth == CV_16U || depth == CV_32F) in cvtColor, file /tmp/opencv20150506-38415-u2kidu/opencv-2.4.11/modules/imgproc/src/color.cpp, line 3644 Traceback (most recent call last): File "luma2hue.py", line 16, in <module> outimageBGR = cv2.cvtColor(outimageHSV, cv2.COLOR_HSV2BGR) cv2.error: /tmp/opencv20150506-38415-u2kidu/opencv-2.4.11/modules/imgproc/src/color.cpp:3644: error: (-215) depth == CV_8U || depth == CV_16U || depth == CV_32F in function cvtColor Do I need to do something else to my outimageHSV array to make it ready for cvtColor? Answer: The error message implies that cv2.cvtColor expects an image with a (color) depth of 8 or 16 bit unsigned int (8U, 16U) or 32 bit float (32F). Try changing `astype(int)` to `astype(numpy.uint8)`
Python Deep Learning Keras: Wrong number of dimensions: expected 3, got 2 with shape Question: I am new to Keras, a deep learning library and need your help. The model is built without errors, but has the following issue when calling model.fit(X, y): TypeError: ('Bad input argument to theano function with name "~/machine_learning2/lib/python2.7/site-packages/keras/backend/theano_backend.py:380" at index 0(0-based)', 'Wrong number of dimensions: expected 3, got 2 with shape (16, 40).') This is similar as this one <https://github.com/fchollet/keras/issues/815> My y train matrix is a matrix with multiple rows and one column. One solution mentioned about converting y to 3d tensor with binary one-hot coding. Is there an example of this? Answer: You can use: from keras.utils import np_utils np_utils.to_categorical(y_train, n_classes) for one hot encoding, where y_train is a train class vector and n_classes - total number of a classes, However, based on that the error description mentions (16, 40), rather than a (Nx1), I suspect you might have an issue with your X as well.
Resolving ValidationError: [u"'' value has an invalid date format. It must be in YYYY-MM-DD format."] in Django 1.9.2? Question: Earlier I created two fields & migrated everything. after that I tried to add three fields `title`,`about`,`birthdate` into the model. I created a model like this : from __future__ import unicode_literals from django.utils import timezone from django.db import models # Create your models here. class APP1Model(models.Model): name = models.CharField(max_length=120) percentage = models.CharField(max_length=120) title = models.CharField(max_length=100,default='Title') birth_date = models.DateTimeField(blank=True, null=True) about = models.TextField(max_length=100,null=True,default='About Yourself') def __unicode__(self): return self.name But when I try to migrate in python shell, it is showing a validation error like this: Operations to perform: Apply all migrations: admin, contenttypes, auth, app1, sessions Running migrations: Applying app1.0005_auto_20160217_1346...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards field, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 221, in add_field self._remake_table(model, create_fields=[field]) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 103, in _remake_table self.effective_default(field) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 210, in effective_default default = field.get_db_prep_save(default, self.connection) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 728, in get_db_prep_save prepared=False) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1301, in get_db_prep_value value = self.get_prep_value(value) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1296, in get_prep_value return self.to_python(value) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 1273, in to_python params={'value': value}, django.core.exceptions.ValidationError: [u"'' value has an invalid date format. It must be in YYYY-MM-DD format."] How to rectify this? I tried all solution i read here but it doesn't work? I am using Django: 1.9.2 My migration File from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app1', '0004_auto_20160217_0427'), ] operations = [ migrations.AddField( model_name='app1model', name='about', field=models.TextField(default='About Yourself', max_length=100, null=True), ), migrations.AddField( model_name='app1model', name='birth_date', field=models.DateField(blank=True, default='', null=True), ), migrations.AddField( model_name='app1model', name='title', field=models.CharField(default='', max_length=100), ), ] Answer: I went through the same problem some months back.I Just deleted the birthdate field changes in all the migration Files inside migration folder. Then I replaced the birthdate with this code:- birthdate = models.DateTimeField(blank=True, null=True) Then after applying migration ,it works fine...
Python - Limiting Number of Threads while Multithreading Question: Code below. import sys import urllib2 import threading import time urls = ["http://www.google.com", "http://www.apple.com"] def fetch_url(url): html = urllib2.urlopen(url).read() print html f = open("Output.txt", "w") e = open("ErrorUsers.txt", "w") threads = [threading.Thread(target=fetch_url, args=(url,)) for url in urls] for thread in threads: try: thread.daemon = True thread.start() except urllib2.HTTPError, e: e.write(url + "\n") except urllib2.URLError, e: e.write(url + "\n") for thread in threads: thread.join() Essentially I need to grab data from a large number of sites (we're talking in the tens of thousands). I'm using the above code as a base, which works great, however, the code freezes after the creation of 750 threads of so. I'm wondering how to limit the number of active threads, or to like close a thread once it finishes. Answer: You can use a thread pool like the one implemented in multiprocessing.In the following snippet, a maximum of 100 threads will be active any time. from multiprocessing.pool import ThreadPool urls = ["http://www.google.com", "http://www.apple.com"] def fetch_url(url): html = urllib2.urlopen(url).read() print html pool = ThreadPool(100) pool.map(fetch_url, urls) pool.close() pool.join()
TestSuite vs "test discover" Question: Is there any difference between creating a TestSuite and add to it all the TestCases, or just running `python -m unittest discover` in the TestCases directory? For example, for a directory with two TestCases: `test_case_1.py` and `test_case_2.py`: import unittest from test_case_1 import TestCaseClass as test1 from test_case_2 import TestCaseClass as test2 suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(test1)) suite.addTest(unittest.makeSuite(test2)) unittest.TextTestRunner().run(suite) Or just `cd` into that directory and run `python -m unittest discover`. I'm getting the same result with either way, but I'm interesting in knowing whether one way is preferred over the other, and why. Answer: I think an obvious benefit in favor of `discover` is maintenance. * After a month, you get rid of `test_case_2` \- some of your code above will fail (the `import`) and you'll have to correct your above script. That's annoying, but not the end of the world. * After two months, someone on your team made `test_case_3`, but was unaware that they need to add it to the script above. No tests fail, and everyone is happy - the problem is, nothing from `test_case_3` actually runs. However, you might counter that it's unreasonable to write new tests, and not notice that they're not running. This brings to the next scenario. * Even worse - after three months, someone merges two versions of your above script, and `test_case_3` gets squeezed out again. This might go unnoticed. Until it's corrected, people can work all they want on the stuff that `test_case_3` is supposed to check, but it's just untested.
aws server : paramiko issue Question: while i can normally connect to a server with ssh command : >[ec2-user@dsi_valid_env:~/scripts]$ssh [email protected] >[email protected]'s password: but i am struggling to connect with paramiko for a python script : >>> import paramiko >>> ssh = paramiko.SSHClient() >>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) >>> ssh.connect("172.XX.YY.ZZ",username="test",password="test") paramiko.ssh_exception.SSHException: could not get keys from ssh-agent do you have any idea of what i am doing wrong ? below the debug stacktrace of my ssh.connect : ssh.connect("172.XX.YY.ZZ",username="test",password="test") DEBUG:paramiko.transport:starting thread (client mode): 0x24532d0L INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_5.3) DEBUG:paramiko.transport:kex algos:[u'diffie-hellman-group-exchange-sha256', u'diffie-hellman-group-exchange-sha1', u'diffie-hellman-group14-sha1', u'diffie-hellman-group1-sha1'] server key:[u'ssh-rsa', u'ssh-dss'] client encrypt:[u'aes128-ctr', u'aes192-ctr', u'aes256-ctr', u'arcfour256', u'arcfour128', u'aes128-cbc', u'3des-cbc', u'blowfish-cbc', u'cast128-cbc', u'aes192-cbc', u'aes256-cbc', u'arcfour', u'[email protected]'] server encrypt:[u'aes128-ctr', u'aes192-ctr', u'aes256-ctr', u'arcfour256', u'arcfour128', u'aes128-cbc', u'3des-cbc', u'blowfish-cbc', u'cast128-cbc', u'aes192-cbc', u'aes256-cbc', u'arcfour', u'[email protected]'] client mac:[u'hmac-md5', u'hmac-sha1', u'[email protected]', u'hmac-sha2-256', u'hmac-sha2-512', u'hmac-ripemd160', u'[email protected]', u'hmac-sha1-96', u'hmac-md5-96'] server mac:[u'hmac-md5', u'hmac-sha1', u'[email protected]', u'hmac-sha2-256', u'hmac-sha2-512', u'hmac-ripemd160', u'[email protected]', u'hmac-sha1-96', u'hmac-md5-96'] client compress:[u'none', u'[email protected]'] server compress:[u'none', u'[email protected]'] client lang:[u''] server lang:[u''] kex follows?False DEBUG:paramiko.transport:Ciphers agreed: local=aes128-ctr, remote=aes128-ctr DEBUG:paramiko.transport:using kex diffie-hellman-group14-sha1; server key type ssh-rsa; cipher: local aes128-ctr, remote aes128-ctr; mac: local hmac-sha1, remote hmac-sha1; compression: local none, remote none DEBUG:paramiko.transport:Switch to new keys ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/dist-packages/paramiko/client.py", line 307, in connect look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host) File "/usr/lib/python2.6/dist-packages/paramiko/client.py", line 456, in _auth self._agent = Agent() File "/usr/lib/python2.6/dist-packages/paramiko/agent.py", line 339, in __init__ self._connect(conn) File "/usr/lib/python2.6/dist-packages/paramiko/agent.py", line 68, in _connect raise SSHException('could not get keys from ssh-agent') paramiko.ssh_exception.SSHException: could not get keys from ssh-agent Answer: I found the issue, i changed : ssh.connect("172.XX.YY.ZZ",username="test",password="test") to: ssh.connect("172.XX.YY.ZZ",username="test",password="test", allow_agent=False) apparently the switch to "password authentification" is not fully automatic in some cases
OpenCV & Python : Face Detection using haarcascades is detecting many boxes as eyes. Question: I am using Haarcascades for detecting faces and eyes. My problem is, its bounding many boxes as eyes. My syntax is face_cascade = cv2.CascadeClassifier('haarcascades\haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascades\haarcascade_eye.xml') img = cv2.imread('SAM7.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray,1.2,6) I am currently using 1.2 and 6. What should be the value of the parameters in faces(5 line) like scaleFactor, minNeighbors ?? Answer: You really need to play with the parameters and find the ones works fine for you. Always there is a better way to do it but remember you'll never achieve 100% accuracy. You can learn about the parameters [here](http://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html#cascadeclassifier- detectmultiscale). An example of face and eyes detection in python that works for me: import cv2 face_cascade = cv2.CascadeClassifier("../haarcascades/haarcascade_frontalface_default.xml") eye_cascade = cv2.CascadeClassifier("../haarcascades/haarcascade_eye.xml") cap = cv2.VideoCapture(0) while cap.isOpened(): ret, frame = cap.read() if ret: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale( gray, scaleFactor=1.3, minNeighbors=5, minSize=(50, 50) ) for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0),2) roi_gray = gray[y:y + h, x:x + w] roi_color = frame[y:y + h, x:x + w] eyes = eye_cascade.detectMultiScale( roi_gray, scaleFactor=1.2, minNeighbors=5, minSize=(10, 10) ) for (ex, ey, ew, eh) in eyes: cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (255, 0, 0), 2) cv2.imshow("Faces found", frame) k = cv2.waitKey(10) & 0xff if k == 27: break cv2.destroyAllWindows() cap.release() I hope this helps you. If you need help with the code let me know.
Curl is working but urllib2 fails in python Question: I am working on Zomato API for my application, when I hit request using curl I get the correct response but when I try same using urllib2 I get different answer. **Curl Request** import os def callCurl(): os.popen('curl -X GET --header "Accept: application/json" --header "user_key: key" "https://developers.zomato.com/api/v2.1/geocode?lat=18.5363242&lon=73.8932641" > out.txt') f = open("out.txt") text = f.read() print text **Output** {"location":{"entity_type":"","entity_id":0,"title":"Koregaon Park","latitude":"18.5363242000","longitude":"73.8932641000","city_id":5,"city_name":"Pune","country_id":1,"country_name":"India"},"popularity":{"popularity":"4.88","nightlife_index":"4.92","nearby_res":["11135","6504409","10750","10987","11520","10143","10699","10213","10580"],"top_cuisines":["North Indian","Fast Food","Italian","Desserts","Chinese"],"popularity_res":"100","nightlife_res":"10","subzone":"Koregaon Park","subzone_id":3307,"city":"Pune"},"link":"https:\/\/www.zomato.com\/pune\/koregaon-park-restaurants?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","nearby_restaurants":{"1":{"restaurant":{"R":{"res_id":11135},"apikey":"key","id":"11135","name":"Uncle's Chinese","url":"https:\/\/www.zomato.com\/pune\/uncles-chinese-koregaon-park?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","location":{"address":"3 & 5, A\/10, Meera Garden Society, Lane 7, Off North Main Road, Koregaon Park, Pune","locality":"Koregaon Park","city":"Pune","city_id":5,"latitude":"18.5374166667","longitude":"73.9000250000","zipcode":"0","country_id":1},"cuisines":"Chinese, Thai","average_cost_for_two":550,"price_range":2,"currency":"Rs.","offers":[],"thumb":"https:\/\/b.zmtcdn.com\/data\/pictures\/chains\/5\/11135\/3450ffa45030801aa2f4934fe77b280e_featured_thumb.jpg","user_rating":{"aggregate_rating":"3.7","rating_text":"Very Good","rating_color":"5BA829","votes":638},"photos_url":"https:\/\/www.zomato.com\/pune\/uncles-chinese-koregaon-park\/photos#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","menu_url":"https:\/\/www.zomato.com\/pune\/uncles-chinese-koregaon-park\/menu#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","featured_image":"https:\/\/b.zmtcdn.com\/data\/pictures\/5\/11135\/db4bce431acbbe60afba5a6e8b39719e_featured_v2.jpg","has_online_delivery":1,"is_delivering_now":1,"deeplink":"zomato:\/\/r\/11135","order_url":"https:\/\/www.zomato.com\/pune\/uncles-chinese-koregaon-park\/order?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","order_deeplink":"","events_url":"https:\/\/www.zomato.com\/pune\/uncles-chinese-koregaon-park\/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1"}},"2":{"restaurant":{"R":{"res_id":6504409},"apikey":"key","id":"6504409","name":"Effingut Brewerkz","url":"https:\/\/www.zomato.com\/pune\/effingut-brewerkz-koregaon-park?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","location":{"address":"21\/A , Plot 389, Lane Number 6, Serene Bay, Koregaon Park, Pune 411001","locality":"Koregaon Park","city":"Pune","city_id":5,"latitude":"18.5342194444","longitude":"73.8984916667","zipcode":"411001","country_id":1},"cuisines":"Continental, North Indian, Mughlai, Burmese","average_cost_for_two":2000,"price_range":4,"currency":"Rs.","offers":[],"zomato_events":[{"event":{"event_id":46679,"start_date":"2016-02-18","end_date":"2016-02-18","end_time":"23:00:00","start_time":"20:00:00","is_active":1,"date_added":"2015-09-10 15:58:04","photos":[{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/1af\/d672fcb7f03e257ad51006d2a38781af_1441880884.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/1af\/d672fcb7f03e257ad51006d2a38781af_1441880884_thumb.jpg","order":0,"md5sum":"d672fcb7f03e257ad51006d2a38781af","photo_id":88657,"uuid":1441880565992433,"type":"NORMAL"}}],"restaurants":[],"is_valid":1,"share_url":"http:\/\/www.zoma.to\/r\/6504409","title":"Pub Quiz - Every Thursday","description":"#ThirstyThursday is back! Answer simple questions and win Effingut beer! Questions on Sports, sitcoms, movies, food, drinks and a lot more! \r\nHow thirsty are you this Thursday? ;)","display_time":"08:00 pm - 11:00 pm","display_date":"18 February","is_end_time_set":1,"disclaimer":"Restaurants are solely responsible for the service; availability and quality of the events including all or any cancellations\/ modifications\/ complaints.","event_category":0,"event_category_name":"","book_link":""}}],"thumb":"https:\/\/b.zmtcdn.com\/data\/pictures\/9\/6504409\/ab9ffd804fa06c820ee0aba93161e9b9_res_featured_thumb.jpg","user_rating":{"aggregate_rating":"4.4","rating_text":"Excellent","rating_color":"3F7E00","votes":829},"photos_url":"https:\/\/www.zomato.com\/pune\/effingut-brewerkz-koregaon-park\/photos#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","menu_url":"https:\/\/www.zomato.com\/pune\/effingut-brewerkz-koregaon-park\/menu#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","featured_image":"https:\/\/b.zmtcdn.com\/data\/pictures\/9\/6504409\/ab9ffd804fa06c820ee0aba93161e9b9_featured_v2.jpg","has_online_delivery":1,"is_delivering_now":0,"deeplink":"zomato:\/\/r\/6504409","events_url":"https:\/\/www.zomato.com\/pune\/effingut-brewerkz-koregaon-park\/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1"}},"3":{"restaurant":{"R":{"res_id":10750},"apikey":"key","id":"10750","name":"Dario's","url":"https:\/\/www.zomato.com\/pune\/darios-koregaon-park?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","location":{"address":"Sundarban Hotel, Lane 1, Off North Main Road, Koregaon Park, Pune","locality":"Koregaon Park","city":"Pune","city_id":5,"latitude":"18.5375833333","longitude":"73.8885194444","zipcode":"0","country_id":1},"cuisines":"Italian, Cafe, Salad, Healthy Food","average_cost_for_two":1800,"price_range":3,"currency":"Rs.","offers":[],"thumb":"https:\/\/b.zmtcdn.com\/data\/pictures\/0\/10750\/05965fda1b86a06071c8312b33466ca0_res_featured_thumb.jpg","user_rating":{"aggregate_rating":"4.3","rating_text":"Excellent","rating_color":"3F7E00","votes":1761},"photos_url":"https:\/\/www.zomato.com\/pune\/darios-koregaon-park\/photos#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","menu_url":"https:\/\/www.zomato.com\/pune\/darios-koregaon-park\/menu#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","featured_image":"https:\/\/b.zmtcdn.com\/data\/pictures\/0\/10750\/05965fda1b86a06071c8312b33466ca0_featured_v2.jpg","has_online_delivery":1,"is_delivering_now":1,"deeplink":"zomato:\/\/r\/10750","order_url":"https:\/\/www.zomato.com\/pune\/darios-koregaon-park\/order?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","order_deeplink":"","events_url":"https:\/\/www.zomato.com\/pune\/darios-koregaon-park\/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1"}},"4":{"restaurant":{"R":{"res_id":10987},"apikey":"key","id":"10987","name":"Cafe 1730","url":"https:\/\/www.zomato.com\/pune\/cafe-1730-koregaon-park?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","location":{"address":"21\/1, Serene Bay, Lane 6, Off North Main Road, Koregaon Park, Pune","locality":"Koregaon Park","city":"Pune","city_id":5,"latitude":"18.5341833333","longitude":"73.8982777778","zipcode":"0","country_id":1},"cuisines":"European, Continental, North Indian, Goan, Cafe","average_cost_for_two":2000,"price_range":4,"currency":"Rs.","offers":[],"zomato_events":[{"event":{"event_id":55453,"start_date":"2016-01-02","end_date":"2016-02-29","end_time":"21:00:00","start_time":"11:00:00","is_active":1,"date_added":"2016-01-02 13:14:33","photos":[{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/9e2\/e210d91c583b9aeafa90930e7134b9e2_1455112161.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/9e2\/e210d91c583b9aeafa90930e7134b9e2_1455112161_thumb.jpg","order":0,"md5sum":"e210d91c583b9aeafa90930e7134b9e2","photo_id":107008,"uuid":14551121586638,"type":"FEATURED"}},{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/404\/7500c47cc5571bf24c115a8a64273404_1448960204.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/404\/7500c47cc5571bf24c115a8a64273404_1448960204_thumb.jpg","order":1,"md5sum":"7500c47cc5571bf24c115a8a64273404","photo_id":102274,"uuid":14517206735387,"type":"NORMAL"}}],"restaurants":[],"is_valid":1,"share_url":"http:\/\/www.zoma.to\/r\/10987","title":"Steal The Bar","description":"-PITCHERS-\r\n*Its Not A Beer 999\/-\r\n*Lemon Tarika 999\/-\r\n*Sweet Lime & Jalapeno 999\/-\r\n*Pink Panthers 1399\/-\r\n*The Idol Eyes 1399\/-\r\n*1730 Jubilee 1199\/-\r\n*Long Island Iced Tea 1399\/-\r\n*Cosmopolitan 1099\/-\r\n*Mojito 1199\/-\r\n*Apple Sangria 1099\/-\r\n*Fresh Lime Martini 1099\/-\r\n\r\n-BAR DEALS-\r\n*Beer glass 79\/-\r\n*Beer Tower 669\/-\r\n*Kingfisher beer bucket 599\/-\r\n*K.f. ultra bucket 749\/-\r\n*Domestic whisky 675\/-\r\n(Blenders pride\/antiquity blue\/signature premium 3.60ml)\r\n*Bacardi \/vodka 699\/-\r\n(3.60ml)\r\n*Dark rum 399\/-\r\n(3.60ml)\r\n*Regular scotch 999\/-\r\n(Teachers highland cream\/teachers50\/vat69\/ballantines)\r\n(3.60ml)\r\n*Premium vodka 1399\/-\r\n(Absolut flavors \/ absolut \/ketelone)3.60ml","display_time":"11:00 am - 09:00 pm","display_date":"02 January - 29 February","is_end_time_set":1,"disclaimer":"Restaurants are solely responsible for the service; availability and quality of the events including all or any cancellations\/ modifications\/ complaints.","event_category":0,"event_category_name":"","book_link":""}},{"event":{"event_id":57508,"start_date":"2016-01-28","end_date":"2016-02-29","end_time":"15:30:59","start_time":"11:00:59","is_active":1,"date_added":"2016-01-28 14:42:18","photos":[{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/6e7\/69ad1cdd77bd8ca27542ccd41198b6e7_1453972338.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/6e7\/69ad1cdd77bd8ca27542ccd41198b6e7_1453972338_thumb.jpg","order":0,"md5sum":"69ad1cdd77bd8ca27542ccd41198b6e7","photo_id":105186,"uuid":14539722884108,"type":"FEATURED"}},{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/b41\/a9f64768cd738199608dac752f666b41_1453972338.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/b41\/a9f64768cd738199608dac752f666b41_1453972338_thumb.jpg","order":1,"md5sum":"a9f64768cd738199608dac752f666b41","photo_id":105187,"uuid":14539722884067,"type":"NORMAL"}},{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/4a7\/992edf24f98a656d79d95e4d2ddd24a7_1453972339.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/4a7\/992edf24f98a656d79d95e4d2ddd24a7_1453972339_thumb.jpg","order":2,"md5sum":"992edf24f98a656d79d95e4d2ddd24a7","photo_id":105188,"uuid":14539722885523,"type":"NORMAL"}}],"restaurants":[],"is_valid":1,"share_url":"http:\/\/www.zoma.to\/r\/10987","title":"The LunchPad Menu","description":"With Modesty of melting meat and the gratitude of the smoky fire,the best of all times.\nFor ultimate experience.To make the memorable lunch.\nWe bring you The LunchPad Menu !!!\n\nMonday To Friday \n\"A 5 course Meal\"\nFor Herbivores - 449\/-\nFor Carnivores - 499\/-\n(Taxes as applicable)\n\n","display_time":"11:00 am - 03:30 pm","display_date":"28 January - 29 February","is_end_time_set":1,"disclaimer":"Restaurants are solely responsible for the service; availability and quality of the events including all or any cancellations\/ modifications\/ complaints.","event_category":1,"event_category_name":"","book_link":""}},{"event":{"event_id":59367,"start_date":"2016-02-20","end_date":"2016-02-20","end_time":"23:00:31","start_time":"19:00:31","is_active":1,"date_added":"2016-02-14 19:49:44","photos":[{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/fdd\/b8c3b540f657231cb9d847075e87dfdd_1448447011.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/fdd\/b8c3b540f657231cb9d847075e87dfdd_1448447011_thumb.jpg","order":0,"md5sum":"b8c3b540f657231cb9d847075e87dfdd","photo_id":107705,"uuid":14554595836638,"type":"FEATURED"}}],"restaurants":[],"is_valid":1,"share_url":"http:\/\/www.zoma.to\/r\/10987","title":"Saturday night live with \"Mike\"","description":"So what could your weekend look like?\nFrom the moment you arrive you can sit back and relax,\nWe have thought of everything,\nThere is something for everyone.\nFor all those music lovers we have got a live act by \"Mike\"\nFor foodies treat yourself with our scrumptious continental and Goan cuisine and for our beers lovers we have offer all night.\nIsn't this a perfect weekend for you all?","display_time":"07:00 pm - 11:00 pm","display_date":"20 February","is_end_time_set":1,"disclaimer":"Restaurants are solely responsible for the service; availability and quality of the events including all or any cancellations\/ modifications\/ complaints.","event_category":1,"event_category_name":"","book_link":""}},{"event":{"event_id":59368,"start_date":"2016-02-21","end_date":"2016-02-21","end_time":"16:00:57","start_time":"11:00:57","is_active":1,"date_added":"2016-02-14 19:50:12","photos":[{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/57e\/d4a8cbcea29b6ae31f786ae62fa8557e_1448446788.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/57e\/d4a8cbcea29b6ae31f786ae62fa8557e_1448446788_thumb.jpg","order":0,"md5sum":"d4a8cbcea29b6ae31f786ae62fa8557e","photo_id":107706,"uuid":14554596124108,"type":"FEATURED"}}],"restaurants":[],"is_valid":1,"share_url":"http:\/\/www.zoma.to\/r\/10987","title":"Cafe1730 Sunday Brunch","description":"unlimited food only @699 \/-\nunlimited food, beer and wine @959 \/- \nUnlimited food, beer and imfl @1599 \/-\n(Taxes as applicable)\n\nThe perfect Sunday awaits you at cafe1730.Meet up with family and friends in a relaxed ambiance, enjoying the most delicious brunch dishes and best wines in town.\n\n \nThe feast opens with a spectacular brunch of fresh salads, home made pastries and the best local fishes and cheeses. But there is more, The al a carte brunch menu offers a definite selection of seasonally inspired brunch dishes. The Sunday is completed with the delightful dessert table full of treats no one should miss the Pure indulgence.\nAnd not to forget we have live act by Austin Fernandes just to keep your feet tapping... \n\n","display_time":"11:00 am - 04:00 pm","display_date":"21 February","is_end_time_set":1,"disclaimer":"Restaurants are solely responsible for the service; availability and quality of the events including all or any cancellations\/ modifications\/ complaints.","event_category":1,"event_category_name":"","book_link":""}}],"thumb":"https:\/\/b.zmtcdn.com\/data\/pictures\/7\/10987\/92a13cb47c42ff9f7b9717cb7fedba2a_res_featured_thumb.jpg","user_rating":{"aggregate_rating":"4.0","rating_text":"Very Good","rating_color":"5BA829","votes":925},"photos_url":"https:\/\/www.zomato.com\/pune\/cafe-1730-koregaon-park\/photos#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","menu_url":"https:\/\/www.zomato.com\/pune\/cafe-1730-koregaon-park\/menu#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","featured_image":"https:\/\/b.zmtcdn.com\/data\/pictures\/7\/10987\/92a13cb47c42ff9f7b9717cb7fedba2a_featured_v2.jpg","has_online_delivery":1,"is_delivering_now":1,"deeplink":"zomato:\/\/r\/10987","order_url":"https:\/\/www.zomato.com\/pune\/cafe-1730-koregaon-park\/order?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","order_deeplink":"","events_url":"https:\/\/www.zomato.com\/pune\/cafe-1730-koregaon-park\/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1"}},"5":{"restaurant":{"R":{"res_id":11520},"apikey":"key","id":"11520","name":"The Burger House","url":"https:\/\/www.zomato.com\/pune\/the-burger-house-koregaon-park?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","location":{"address":"A\/1, Rahul Terrace, Ground Floor, Lane 7, Meera Nagar, Koregaon Park, Pune","locality":"Koregaon Park","city":"Pune","city_id":5,"latitude":"18.5366388889","longitude":"73.9000638889","zipcode":"0","country_id":1},"cuisines":"American, Fast Food, Burger","average_cost_for_two":400,"price_range":1,"currency":"Rs.","offers":[],"thumb":"https:\/\/b.zmtcdn.com\/data\/pictures\/0\/11520\/6f486dcc6e8877b408f942896322882e_res_featured_thumb.JPG","user_rating":{"aggregate_rating":"3.6","rating_text":"Very Good","rating_color":"5BA829","votes":788},"photos_url":"https:\/\/www.zomato.com\/pune\/the-burger-house-koregaon-park\/photos#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","menu_url":"https:\/\/www.zomato.com\/pune\/the-burger-house-koregaon-park\/menu#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","featured_image":"https:\/\/b.zmtcdn.com\/data\/pictures\/0\/11520\/6f486dcc6e8877b408f942896322882e_featured_v2.JPG","has_online_delivery":1,"is_delivering_now":1,"deeplink":"zomato:\/\/r\/11520","order_url":"https:\/\/www.zomato.com\/pune\/the-burger-house-koregaon-park\/order?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","order_deeplink":"","events_url":"https:\/\/www.zomato.com\/pune\/the-burger-house-koregaon-park\/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1"}},"6":{"restaurant":{"R":{"res_id":10143},"apikey":"key","id":"10143","name":"Arthur's Theme","url":"https:\/\/www.zomato.com\/pune\/arthurs-theme-koregaon-park?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","location":{"address":"2, Vrindavan Apartment, Lane 6, Off North Main Road, Koregaon Park, Pune","locality":"Koregaon Park","city":"Pune","city_id":5,"latitude":"18.5385388889","longitude":"73.8986805556","zipcode":"0","country_id":1},"cuisines":"European, Italian","average_cost_for_two":1300,"price_range":3,"currency":"Rs.","offers":[],"thumb":"https:\/\/b.zmtcdn.com\/data\/pictures\/3\/10143\/2ca672418c2a9d664c5bc2ced4ab7cb7_res_featured_thumb.jpg","user_rating":{"aggregate_rating":"4.3","rating_text":"Excellent","rating_color":"3F7E00","votes":1553},"photos_url":"https:\/\/www.zomato.com\/pune\/arthurs-theme-koregaon-park\/photos#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","menu_url":"https:\/\/www.zomato.com\/pune\/arthurs-theme-koregaon-park\/menu#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","featured_image":"https:\/\/b.zmtcdn.com\/data\/pictures\/3\/10143\/2ca672418c2a9d664c5bc2ced4ab7cb7_featured_v2.jpg","has_online_delivery":1,"is_delivering_now":1,"deeplink":"zomato:\/\/r\/10143","order_url":"https:\/\/www.zomato.com\/pune\/arthurs-theme-koregaon-park\/order?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","order_deeplink":"","events_url":"https:\/\/www.zomato.com\/pune\/arthurs-theme-koregaon-park\/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1"}},"7":{"restaurant":{"R":{"res_id":10699},"apikey":"key","id":"10699","name":"Prem's","url":"https:\/\/www.zomato.com\/pune\/prems-koregaon-park?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","location":{"address":"28\/2, SBI Training Centre, North Main Road, Koregaon Park, Pune 411001","locality":"Koregaon Park","city":"Pune","city_id":5,"latitude":"18.5396583333","longitude":"73.8934388889","zipcode":"411001","country_id":1},"cuisines":"North Indian, Chinese, Continental","average_cost_for_two":1200,"price_range":3,"currency":"Rs.","offers":[],"thumb":"https:\/\/b.zmtcdn.com\/data\/pictures\/9\/10699\/1154483951e226d02d7746e349cf65a5_res_featured_thumb.jpg","user_rating":{"aggregate_rating":"3.9","rating_text":"Very Good","rating_color":"5BA829","votes":1299},"photos_url":"https:\/\/www.zomato.com\/pune\/prems-koregaon-park\/photos#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","menu_url":"https:\/\/www.zomato.com\/pune\/prems-koregaon-park\/menu#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","featured_image":"https:\/\/b.zmtcdn.com\/data\/pictures\/9\/10699\/1154483951e226d02d7746e349cf65a5_featured_v2.jpg","has_online_delivery":1,"is_delivering_now":0,"deeplink":"zomato:\/\/r\/10699","events_url":"https:\/\/www.zomato.com\/pune\/prems-koregaon-park\/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1"}},"8":{"restaurant":{"R":{"res_id":10213},"apikey":"key","id":"10213","name":"Malaka Spice","url":"https:\/\/www.zomato.com\/pune\/malaka-spice-koregaon-park?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","location":{"address":"Lane 5, Opposite Oxford Properties, North Main Road, Koregaon Park, Pune","locality":"Koregaon Park","city":"Pune","city_id":5,"latitude":"18.5374333333","longitude":"73.8974833333","zipcode":"","country_id":1},"cuisines":"Malaysian, Thai, Vietnamese, Japanese, Korean, Asian","average_cost_for_two":2000,"price_range":4,"currency":"Rs.","offers":[],"thumb":"https:\/\/b.zmtcdn.com\/data\/pictures\/chains\/3\/10213\/6a645a5fa205af3ece1512c9c38b923e_featured_thumb.jpg","user_rating":{"aggregate_rating":"4.4","rating_text":"Excellent","rating_color":"3F7E00","votes":2568},"photos_url":"https:\/\/www.zomato.com\/pune\/malaka-spice-koregaon-park\/photos#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","menu_url":"https:\/\/www.zomato.com\/pune\/malaka-spice-koregaon-park\/menu#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","featured_image":"https:\/\/b.zmtcdn.com\/data\/pictures\/3\/10213\/5e3195141eb36f299e217f6e2e477d61_featured_v2.jpg","has_online_delivery":1,"is_delivering_now":1,"deeplink":"zomato:\/\/r\/10213","order_url":"https:\/\/www.zomato.com\/pune\/malaka-spice-koregaon-park\/order?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","order_deeplink":"","events_url":"https:\/\/www.zomato.com\/pune\/malaka-spice-koregaon-park\/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1"}},"9":{"restaurant":{"R":{"res_id":10580},"apikey":"key","id":"10580","name":"Hidden Place - The Hangout","url":"https:\/\/www.zomato.com\/pune\/hidden-place-the-hangout-koregaon-park?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","location":{"address":"2 & 3, Upper Ground Floor, Gera Legend, North Main Road, Koregaon Park, Pune","locality":"Koregaon Park","city":"Pune","city_id":5,"latitude":"18.5396694444","longitude":"73.8871611111","zipcode":"0","country_id":1},"cuisines":"Finger Food, North Indian, Continental","average_cost_for_two":1000,"price_range":3,"currency":"Rs.","offers":[],"zomato_events":[{"event":{"event_id":48384,"start_date":"2016-02-02","end_date":"2016-02-29","end_time":"20:00:00","start_time":"12:00:00","is_active":1,"date_added":"2015-10-06 19:16:54","photos":[{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/c26\/920f6523684454ea62d88911b03f0c26_1446448276.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/c26\/920f6523684454ea62d88911b03f0c26_1446448276_thumb.jpg","order":0,"md5sum":"920f6523684454ea62d88911b03f0c26","photo_id":93464,"uuid":1446448240937387,"type":"NORMAL"}},{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/5b8\/5485e985778bff879cb4617f43dcf5b8_1446448276.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/5b8\/5485e985778bff879cb4617f43dcf5b8_1446448276_thumb.jpg","order":1,"md5sum":"5485e985778bff879cb4617f43dcf5b8","photo_id":93465,"uuid":1446448241675278,"type":"NORMAL"}},{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/bde\/ef0075476a283bbd14c1b8fa4c976bde_1448867798.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/bde\/ef0075476a283bbd14c1b8fa4c976bde_1448867798_thumb.jpg","order":2,"md5sum":"ef0075476a283bbd14c1b8fa4c976bde","photo_id":96026,"uuid":1448867064602104,"type":"NORMAL"}},{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/d1b\/3ebbfdee1673aa337f4fdaed3fd08d1b_1448867799.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/d1b\/3ebbfdee1673aa337f4fdaed3fd08d1b_1448867799_thumb.jpg","order":3,"md5sum":"3ebbfdee1673aa337f4fdaed3fd08d1b","photo_id":96027,"uuid":1448867203422890,"type":"NORMAL"}},{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/bd6\/4e773de66328c7d01405c6edb8d5abd6_1448867799.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/bd6\/4e773de66328c7d01405c6edb8d5abd6_1448867799_thumb.jpg","order":4,"md5sum":"4e773de66328c7d01405c6edb8d5abd6","photo_id":96028,"uuid":1448867203988532,"type":"NORMAL"}},{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/c75\/01c952e8c4e7c595136c96bcba27dc75_1452491019.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/c75\/01c952e8c4e7c595136c96bcba27dc75_1452491019_thumb.jpg","order":5,"md5sum":"01c952e8c4e7c595136c96bcba27dc75","photo_id":103147,"uuid":1452490989772374,"type":"NORMAL"}},{"photo":{"url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/f97\/52f544fa43b2ca7428274f453c82af97_1448867800.jpg","thumb_url":"https:\/\/b.zmtcdn.com\/data\/zomato_events\/photos\/f97\/52f544fa43b2ca7428274f453c82af97_1448867800_thumb.jpg","order":6,"md5sum":"52f544fa43b2ca7428274f453c82af97","photo_id":96030,"uuid":1448867725107894,"type":"NORMAL"}}],"restaurants":[],"is_valid":1,"share_url":"http:\/\/www.zoma.to\/r\/13011","title":"An OFFER UNHEARD OF - A Pint for Rs.92*\/Pint or A Litre for Rs.166*\/Litre","description":"Get a Pint for Rs.92*\/Pint (On a Bucket of 6 Pints) or a Litre for Rs. 166*\/Litre (6L Towers) at The Crazy Frog (DP Road) and The Hangout (Kothrud)! Offer available up to 8pm EVERYDAY at both the outlets! Crazy offer isn't it? \r\n\r\nAlso, whether is your Birthday or NOT, we're giving you an offer you can't refuse! :P Here's what we have to offer in our Birthday Bonker Bash for INR 5999*\/- - 2 Kingfisher Towers - 1 Bottle Smirnoff Vodka OR Smirnoff Vodka Flavor - 1 Bottle Signature OR Royal Challenge OR Caribbean Legend Rum - 1 Bottle Champagne Prosecco OR 2 Bottle RIO Sparking (375ML X 2) - Mixers. Need we say more? ;)\r\n\r\n*T&C Apply! Legal age is mandatory.","display_time":"12:00 pm - 08:00 pm","display_date":"02 February - 29 February","is_end_time_set":1,"disclaimer":"Restaurants are solely responsible for the service; availability and quality of the events including all or any cancellations\/ modifications\/ complaints.","event_category":0,"event_category_name":"","book_link":""}}],"thumb":"https:\/\/b.zmtcdn.com\/data\/pictures\/0\/10580\/70f30d18d32c58e2a9307d6f79419b6e_res_featured_thumb.jpg","user_rating":{"aggregate_rating":"3.9","rating_text":"Very Good","rating_color":"5BA829","votes":2297},"photos_url":"https:\/\/www.zomato.com\/pune\/hidden-place-the-hangout-koregaon-park\/photos#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","menu_url":"https:\/\/www.zomato.com\/pune\/hidden-place-the-hangout-koregaon-park\/menu#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","featured_image":"https:\/\/b.zmtcdn.com\/data\/pictures\/0\/10580\/70f30d18d32c58e2a9307d6f79419b6e_featured_v2.jpg","has_online_delivery":1,"is_delivering_now":1,"deeplink":"zomato:\/\/r\/10580","order_url":"https:\/\/www.zomato.com\/pune\/hidden-place-the-hangout-koregaon-park\/order?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","order_deeplink":"","events_url":"https:\/\/www.zomato.com\/pune\/hidden-place-the-hangout-koregaon-park\/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1"}}}} **urllib2 Request** import urllib import urllib2 import json def callUrllib(): values = {"lat" : "18.5363242", "lon":"73.8932641"} headers = {'Accept': 'application/json', 'user_key' : "key"} data = urllib.urlencode(values) req = urllib2.Request("https://developers.zomato.com/api/v2.1/geocode", data, headers) response = urllib2.urlopen(req) the_page = response.read() print json.loads(the_page) **Output** {"location":{"entity_type":"","entity_id":0,"title":"Koregaon Park","latitude":"18.5363242000","longitude":"73.8932641000","city_id":5,"city_name":"Pune","country_id":1,"country_name":"India"},"popularity":{"status":"failed","message":"Coordinates missing","nightlife_index":0,"popularity":0},"link":"https:\/\/www.zomato.com\/pune\/koregaon-park-restaurants?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1","nearby_restaurants":[]} Using urllib2 I am not getting value for key **nearby_restaurants**. Why both are giving different output? Am I doing it correctly? Please Help :) Answer: You are actually doing here `POST` request with python. That's why your latitude longitude is not accepted by the server as they were sending as `POST`. If you use NULL value for the `data` it would return same I believe. To achieve `GET` use following. Here I am adding the data with the url as GET and sending empty value for second parameter. req = urllib2.Request("https://developers.zomato.com/api/v2.1/geocode?"+data, '', headers)
Pass a file list from PowerShell to Python script via stdin Question: I'd like to create a Python script that I can pipe file names into, so it can be used like this: ls *.csv | python .\myscript.py I know I can read the standard input using `fileinput` or `sys.stdin`, but since the output is in a formatted table: Directory: C:\path\to\csv Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 15.02.2016 10:18 4755 data_1.csv -a---- 15.02.2016 10:18 522 data_2.csv I'd have to parse it. Since this seems to be a common pattern, I expect there's a standard solution. I'd like to avoid writing my own if I can, but I haven't been able to find any. (In case it's important, I'm running it in PowerShell on Windows 10.) **Edit:** I'm asking whether there's some library or pattern I'm missing, for this specific (and seemingly quite common) scenario of piping file paths to a script. I'd like to avoid writing parsing code if it isn't necessary. Answer: Based on googling and your kind comments, it seems it would be best to just do the filtering _before_ passing it to the actual Python script. I'll stick with that, then.
What is the name for the Maya Python library(ies)? Question: I want to distinguish between the [Python libraries available in Maya](http://help.autodesk.com/view/MAYAUL/2016/ENU/?guid=GUID-C0F27A50-3DD6-454C-A4D1-9E3C44B3C990): 1. _MEL_ (the embedded Maya language) 2. _Maya Python libraries_ (`maya.cmds`, but also `maya.standalone` and `maya.mel.eval`) 3. _PyMEL_ [[*]](https://github.com/LumaPictures/pymel) (`pymel.core` and others) 4. _Maya Python API 1.0_ (`maya.OpenMaya`) 5. _Maya Python API 2.0_ (`maya.api.OpenMaya`) Do the Maya Python libraries (item 2) have a name? A name that covers 2, 4 and 5 would be sufficient. Answer: Not really. `import Maya` will give you all of them, though most people start one level down with, for example, `import maya.cmds as cmds` There are a few more that you missed in your list: `OpenMaya` , the old api, has siblings `OpenMayaRender`, `OpenMayaUI`, and `OpenMayaAnimation` and there's also `maya.util` You can list the full roster of top-level maya modules like this: import maya import inspect maya_modules = {name:mod for name, mod in inspect.getmembers(maya) if inspect.ismodule(mod) } the full list in Maya 2016 is: 'OpenMaya': <module 'maya.OpenMaya' from 'c:\program files\autodesk\maya2016\Python\lib\site-packages\maya\OpenMaya.pyc'>, 'OpenMayaAnim': <module 'maya.OpenMayaAnim' from 'c:\program files\autodesk\maya2016\Python\lib\site-packages\maya\OpenMayaAnim.pyc'>, 'OpenMayaFX': <module 'maya.OpenMayaFX' from 'c:\program files\autodesk\maya2016\Python\lib\site-packages\maya\OpenMayaFX.pyc'>, 'OpenMayaMPx': <module 'maya.OpenMayaMPx' from 'c:\program files\autodesk\maya2016\Python\lib\site-packages\maya\OpenMayaMPx.pyc'>, 'OpenMayaRender': <module 'maya.OpenMayaRender' from 'c:\program files\autodesk\maya2016\Python\lib\site-packages\maya\OpenMayaRender.pyc'>, 'OpenMayaUI': <module 'maya.OpenMayaUI' from 'c:\program files\autodesk\maya2016\Python\lib\site-packages\maya\OpenMayaUI.pyc'>, 'app': <module 'maya.app' from 'c:\program files\autodesk\maya2016\Python\lib\site-packages\maya\app\__init__.py'>, 'cmds': <module 'maya.cmds' from 'c:\program files\autodesk\maya2016\Python\lib\site-packages\maya\cmds\__init__.py'>, 'debug': <module 'maya.debug' from 'c:\program files\autodesk\maya2016\Python\lib\site-packages\maya\debug\__init__.py'>, 'mel': <module 'maya.mel' from 'c:\program files\autodesk\maya2016\Python\lib\site-packages\maya\mel\__init__.py'>, 'standalone': <module 'maya.standalone' (built-in)>, 'utils': <module 'maya.utils' from 'c:\program files\autodesk\maya2016\Python\lib\site-packages\maya\utils.py'> It would of course be trivial to make your own module which imported a subset of those.
Python - How to get the filename in tkinter file dialog Question: I am trying to get just the file name of the selected file in tkinter file dialog Here's my code: def browseFile(self): root = tk.Tk() root.withdraw() file_path = askopenfilename(filetypes=(("Video files", "*.mp4;*.flv;*.avi;*.mkv"), ("All files", "*.*") )) print file_path What I am getting with this code is the whole path of the selected file, where I only need the file name. How can I do it? results with my code: C:/Users/Guest/vid1.mp4 what I want: vid1.mp4 Answer: >>> import os >>> s = "C:/Users/Guest/vid1.mp4" >>> os.path.split(s) ('C:/Users/Guest', 'vid1.mp4') >>> os.path.split(s)[1] 'vid1.mp4' Alternatively, >>> os.path.basename(s) 'vid1.mp4'
Python if, elif, else chain alternitive Question: I am using a speech recognition library to create a Siri like program. I hope that in the future I can use the code with an Arduino to control things around my room. Here is my problem: I have the basic speech recognition code worked out but for the program to understand certain commands I would have to run the speech through a very long list of if-elif-elif-elif-else commands and that might be slow. As most of the time it will be resulting at else as the command will not be recognized I need a faster alternative to a long chain of if-elif-else statements. I am also using a tts engine to talk back to you. here is my code so far import pyttsx import time engine = pyttsx.init() voices = engine.getProperty("voices") spch = "There is nothing for me to say" userSaid = "NULL" engine.setProperty("rate", 130) engine.setProperty("voice", voices[0].id) def speak(): engine.say(spch) engine.runAndWait() def command(): **IF STATEMENT HERE** r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) print("CaSPAR is calibrated") audio = r.listen(source) try: userSaid = r.recognize_google(audio) except sr.UnknownValueError: spch = "Sorry, I did'nt hear that properly" except sr.RequestError as e: spch = "I cannot reach the speech recognition service" speak() print "Done" Answer: Try using a dictionary setting in which the key is the value that you are testing for and the entry for that key is a function to process. Some of the text books on Python point out that this is a more elegant solution than a series of if ... elif statements and picks up the entry immediately instead of having to test each possibility. Note that since each key can be of any type, this is better than something like the switch statement in C which requires the switch argument and the cases to be integer values. For example. def default(command) print command, ' is an invalid entry' mydict = {'create':mycreate, 'delete':mydelete, 'update':myupdate} action = mydict.get(command, default) # set up args from the dictionary or as command for the default. action(*args) An interesting point is that [Most efficient way of making an if-elif-elif- else statement when the else is done the most?](http://stackoverflow.com/questions/17166074/most-efficient-way-of- making-an-if-elif-elif-else-statement-when-the-else-is-don) states that while the get is more "elegant" it may actually be slower than the code below. However, that may be because the post deals with direct operations and not function calls. YMMV def default(command) print command, ' is an invalid entry' mydict = {'create':mycreate, 'delete':mydelete, 'update':myupdate} if command in mydict: action = mydict.[command] # set up args from the dictionary . action(*args) else: default(command)
Python Domain Name Regular Expression Pattern Question: I would like to be able to match a domain by following the below rules: * The domain name should be a-z | A-Z | 0-9 and hyphen(-) * The domain name should between 1 and 63 characters long * Last Tld must be at least two characters, and a maximum of 6 characters * The domain name should not start or end with hyphen (-) (e.g. -google.com or google-.com) * The domain name can be a subdomain (e.g. mkyong.blogspot.com) I already have the java flavored regex I just need this python flavored ^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$ I couldn't find any python regex for this matter as everyone expects the use of urlparse. I don't need to split a url by domain, port, tlds and so on, I only need to do a simple domain replace so regex should be the solution for me What I have done: expectedstring = re.sub(r"^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$" , "XXX" , string) Example strings: string = "This is why this domain example.com will never be the same after some years, it might just be example.co.uk but will never get to example.-com. Documents could be located in this specific location http://en.example.com/documents/print.doc as you probably already know." expectedstring = "This is why this domain XXX will never be the same after some years, it might just be XXX but will never get to example.-com. Documents could be located in this specific location http://XXX/documents/print.doc as you probably already know." List of valid domain names * www.google.com * google.com * mkyong123.com * mkyong-info.com * sub.mkyong.com * sub.mkyong-info.com * mkyong.com.au * g.co * mkyong.t.t.co List of invalid domain names, and why. * mkyong.t.t.c - Tld must between 2 and 6 long * mkyong,com - Comma is not allow * mkyong - No Tld * mkyong.123 , Tld not allow digit * .com - Must start with [A-Za-z0-9] * mkyong.com/users - No Tld * mkyong.com - Cannot begin with a hyphen - * mkyong-.com - Cannot end with a hyphen - * sub.-mkyong.com - Cannot begin with a hyphen - * sub.mkyong-.com - Cannot end with a hyphen - Answer: I run a test based on the list of given domain names (python 2.7x): import re valid_domains = """ www.google.com google.com mkyong123.com mkyong-info.com sub.mkyong.com sub.mkyong-info.com mkyong.com.au g.co mkyong.t.t.co """ invalid_domains = """ mkyong.t.t.c mkyong,com mkyong mkyong.123 .com mkyong.com/users -mkyong.com mkyong-.com sub.-mkyong.com sub.mkyong-.com """ valid_names = valid_domains.split() invalid_names = invalid_domains.split() # match 1 character domain name or 2+ domain name pattern = '^([A-Za-z0-9]\.|[A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9]\.){1,3}[A-Za-z]{2,6}$' print 'checking valid domain names ============' for name in valid_names: print name.ljust(50), ('True' if re.match(pattern, name) else 'False').rjust(5) print '\nchecking invalid domain names ============' for name in invalid_names: print name.ljust(50), ('True' if re.match(pattern, name) else 'False').rjust(5) Output: checking valid domain names ============ www.google.com True google.com True mkyong123.com True mkyong-info.com True sub.mkyong.com True sub.mkyong-info.com True mkyong.com.au True g.co True mkyong.t.t.co True checking invalid domain names ============ mkyong.t.t.c False mkyong,com False mkyong False mkyong.123 False .com False mkyong.com/users False -mkyong.com False mkyong-.com False sub.-mkyong.com False sub.mkyong-.com False [Edit] To achieve the same result as the expectedstring provided, I come up with the following approach (without checking "http(s)"): import re # match 1 character domain name or 2+ domain name pattern = '(//|\s+|^)(\w\.|\w[A-Za-z0-9-]{0,61}\w\.){1,3}[A-Za-z]{2,6}' string = "This is why this domain example.com will never be the same after some years, it might just be example.co.uk but will never get to example.-com. Documents could be located in this specific location http://en.example.com/documents/print.doc as you probably already know." expectedstring = "This is why this domain XXX will never be the same after some years, it might just be XXX but will never get to example.-com. Documents could be located in this specific location http://XXX/documents/print.doc as you probably already know." resultstring = ''.join([re.sub(pattern , "\g<1>XXX" , string)]) print 'resultstring: \n', resultstring print '\nare they equal? ', expectedstring == resultstring Output is: resultstring: This is why this domain XXX will never be the same after some years, it might just be XXX but will never get to example.-com. Documents could be located in this specific location http://XXX/documents/print.doc as you probably already know. are they equal? True
How to obtain a math function as an output in python Question: I want to do something like this def gaussian(x, amp): return amp * exp(-(x-cen)**2 /wid) I want to substitute just amp and x and obtain an equation as output for example: gaussian(1,3) `3 * exp(-(1-cen)**2 /wid)` as output. Can I do this for a couple of lists, in one several values of amplitude an in the other their respective x's Answer: I am not sure what you mean by "I need an equation". Do you need something you can evaluate? Then probably you can return a lambda object, and then you can evaluate that. Or you can use closure something like: import math def gaussian(x, amp): def _gauss( cen,wid): return amp * math.exp(-(x-cen)**2 /wid) return _gauss g = gaussian(10,1) print g(2,4) g now is a callable function where x and amp has been replaced so you need to pass only cen and wid The reason why this work is because the internal function, _gauss, gets evaluated every time you call the wrapper function, doing so the function will be evaluated using the argument passed by the parent function and be used there as "static". Since then you return a function you can evaluate that and pass all the params left, this is a common technique for when a library forces you to have parameterlles callbacks. Only draw back is more expensive then a simple function call, that is to generate the child function, not to evaluate it.
Logging not working in a separate thread Question: I've a `python 2.5` app that creates a separate thread to work. I want to log to a file, and I'm able to do it from the main thread, but when I log from the other threads it doesnt works. This happen on the main thread: log_filename = os.path.join(os.path.dirname(__file__), "log", args[1]+'.log') logging.basicConfig(filename=log_filename, level=logging.DEBUG) logging.debug("Hello world!") # this works, line got written to a file This is how the thread are getting initialized: worker_thread = threading.Thread(target = MY_worker.MY_worker, args = tuple([task_queue])) worker_thread.start() Now from a method that runs on the thread I'm doing: logging.debug("testing") # this doesnt got printed in the log file I even tried setting up the log again (inside the thread, just before writting to log): log_filename = os.path.join(os.path.dirname(__file__), "log", 'sandbox.log') logging.basicConfig(filename=log_filename, level=logging.DEBUG) logging.debug("testing") # doesn't works neither. I tried writting directly to a file, and it worked: f = open(log_filename,'a') f.write('some testing message \n') f.close() Why is this happening and how to make it work? Answer: Are you quite sure it's not some problem unrelated to the logging? The following trivial script behaves as expected, under both Python 2.x and 3.x. import logging import threading import time def worker(arg): while not arg['stop']: logging.debug('Hi from myfunc') time.sleep(0.5) def main(): logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s') info = {'stop': False} thread = threading.Thread(target=worker, args=(info,)) thread.start() while True: try: logging.debug('Hello from main') time.sleep(0.75) except KeyboardInterrupt: info['stop'] = True break thread.join() if __name__ == '__main__': main() When run, it produces 0 Thread-1 Hi from myfunc 1 MainThread Hello from main 502 Thread-1 Hi from myfunc 753 MainThread Hello from main 1003 Thread-1 Hi from myfunc 1504 Thread-1 Hi from myfunc 1505 MainThread Hello from main 2006 Thread-1 Hi from myfunc 2255 MainThread Hello from main 2507 Thread-1 Hi from myfunc 3007 MainThread Hello from main 3009 Thread-1 Hi from myfunc 3510 Thread-1 Hi from myfunc 3759 MainThread Hello from main 4012 Thread-1 Hi from myfunc until I stop it with Ctrl-C.
Python bindings for VLC Question: I am on Windows, and I wish to use Python Bindings for VLC. I've already downloaded the module from <https://github.com/geoffsalmon/vlc-python> , and did as per the read me. But, still I'm stuck at importing the module. The error looks like this : Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> import vlc File "c:\python27\python-vlc-1.1.2\vlc.py", line 173, in <module> dll, plugin_path = find_lib() File "c:\python27\python-vlc-1.1.2\vlc.py", line 150, in find_lib dll = ctypes.CDLL('libvlc.dll') File "C:\Python27\lib\ctypes\__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] The specified module could not be found Any Solution on where to place the module ? My main aim is to play MP3 audio files through vlc, which would be part of some other activity. Answer: I had same problem. It turns out for me if you have 64bit python, you need 64bit vlc player. If you have 32bit python, you need 32bit vlc player. Hope that works for you too.
'application not registered on db instance' after user table truncation Question: I deleted all the info in my users table during testing. Now when I try to run a `manage.py` command to recreate the admin user, I get `RuntimeError: application not registered on db instance and no application bound to current context`. I've been reading about Flask contexts, especially [What is the purpose of Flask's context stacks?](http://stackoverflow.com/questions/20036520/what-is-the-purpose-of- flasks-context-stacks), but it's not clear to me how to fix this. How do I fix this error? $ python manage.py db create_admin Traceback (most recent call last): File "manage.py", line 58, in <module> manager.add_command("create_admin", create_admin()) File "manage.py", line 47, in create_admin confirmed_on=datetime.datetime.now() File "c:\envs\virtalenvs\flask_mini\lib\site-packages\sqlalchemy\orm\scoping.py", line 150, in do return getattr(self.registry(), name)(*args, **kwargs) File "c:\envs\virtalenvs\flask_mini\lib\site-packages\sqlalchemy\util\_collections.py", line 878, in __call__ return self.registry.setdefault(key, self.createfunc()) File "c:\envs\virtalenvs\flask_mini\lib\site-packages\flask_sqlalchemy\__init__.py", line 704, in create_session return SignallingSession(self, **options) File "c:\envs\virtalenvs\flask_mini\lib\site-packages\flask_sqlalchemy\__init__.py", line 149, in __init__ self.app = db.get_app() File "c:\envs\virtalenvs\flask_mini\lib\site-packages\flask_sqlalchemy\__init__.py", line 845, in get_app raise RuntimeError('application not registered on db ' RuntimeError: application not registered on db instance and no application bound to current context `manage.py`: import os from flask_script import Manager from myflaskapp.app import create_app from myflaskapp.models.user import User from myflaskapp.database import db manager = Manager(app) @manager.command def create_admin(): db.session.add(User( username="admin1", email="[email protected]", password="admin", admin=True, confirmed=True, confirmed_on=datetime.datetime.now() )) db.session.commit() manager.add_command("create_admin", create_admin()) manager.run() Answer: You're using `@manager.command`, so you shouldn't also use `manager.add_command`. Completely remove the line `manager.add_command('create_admin', create_admin())`. If you want to use `add_command`, then remove `@manager.command` and use `manager.add_command('create_admin', Command(create_admin))`. You get the error because the app context is only active when the manager is running, but you're calling the function prematurely.
return index for rows in csv module python Question: I'm trying to return a specific string that reads out "RowX: [sum of row]" for each row of a tsv table where X = the row number (index +1). So far I can get everything to work except for the row number. My code: #!/usr/bin/env python from __future__ import division, print_function import sys import csv def my_sum(row): a = 0 for i in row: a = a + float(i) return a def main(): tsvfile_input = sys.argv[1] data = csv.reader(open(tsvfile_input), delimiter = '\t') for row in data: RowSum = my_sum(row) print('Row' + 'X' + ': ' + str(RowSum)) if __name__ == '__main__': main() So far in place of 'X' I've tried data.index(), which returned: AttributeError: '_csv.reader' object has no attribute 'index' Sorry if obvious. I'm extremely new to coding and am doing this as part of an exercise. Also, if you're wondering why I didn't just use sum(), it's part of the exercise to not use sum(). Thanks! Answer: How about [enumerating](https://docs.python.org/2/library/functions.html#enumerate) the data? for index, row in enumerate(data): RowSum = my_sum(row) print('Row %d: %f' % (index + 1, rowSum)) Python also has sum function already, so you can do: for index, row in enumerate(data): print('Row %d: %f' % (index + 1, sum(float(num) for num in row))) Edit (full example of the main function): def main(): tsvfile_input = sys.argv[1] data = csv.reader(open(tsvfile_input), delimiter = '\t') for index, row in enumerate(data): print('Row %d: %f' % (index + 1, sum(float(num) for num in row)))
NxN python arrays subsets Question: I need to carry out some operation on a subset of an `NxN array`. I have the center of the sub-array, `x` and `y`, and its size. So I can easily do: `subset = data[y-size:y+size,x-size:x+size]` And this is fine. What I ask is if there is the possibility to do the same without writing an explicit loop if `x` and `y` are both 1D arrays of positions. Thanks! Answer: Using a simple example of a 5x5 array and setting _size=1_ we can get: import numpy as np data = np.arange(25).reshape((5,5)) size = 1 x = np.array([1,4]) y = np.array([1,4]) subsets = [data[j-size:j+size,i-size:i+size] for i in x for j in y] print(subsets) Which returns a list of numpy arrays: [array([[0, 1],[5, 6]]), array([[15, 16],[20, 21]]), array([[3, 4],[8, 9]]), array([[18, 19],[23, 24]])] Which I hope is what you are looking for.
Opening a sheet in excel file in Python Question: I am an absolute beginner in Python programming. I have a bunch of excel files (with extension .xls) which I would like to be able to read in python. I have to extract 2 columns from a given sheet from each file and write them into a CSV file. This is data coming from some measurement results so the format of each excel file is the same. I have to create n CSV files from a given number of n excel files. From my general search I figured I could use module xlrd. I tried downloading the module as described [here](http://stackoverflow.com/questions/20461790/im- having-a-lot-of-trouble-installing-xlrd-0-9-2-for-python). I am working on windows with python 2 and using Python GUI IDLE. When I go to the command line in windows, browse to the folder where I saved the module files and type python setup.py build I get an error message saying "`python is not recognized as an internal or external command, operable program or batch file`." I also setup the system variable as described [here](http://stackoverflow.com/questions/19407469/xlrd-import-issue-with- python-2-7) but that does not help. As I read somewhere else, I use import sys print sys.path which displays ['', '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'] Does that mean my environment variable is correctly set up? Please help me getting started with using .xls files in Python. Thanks. Answer: Solution [here](http://stackoverflow.com/questions/20461790/im-having-a-lot- of-trouble-installing-xlrd-0-9-2-for-python) proposed by M4rtini worked for me. Posting here again If windows this should work. Browser to "folder with python"\scripts Open cmd here (shift + right click and and it should be an option in the context menu.) type inn: easy_install.exe xlrd It should download and install if for you
Sort Python DataFrame by Day of the Week Question: I'm trying to sort my dataframe by the day of the week in the index. I was able to create a workaround where I created an additional column that I manually assigned the correct order value to and then sorted. But there has to be a better way, especially when I'm dealing with potentially more date values. dict = {'Monday': Monday/MonCount, 'Tuesday': Tuesday/TueCount, 'Wednesday': Wednesday/WedCount, 'Thursday': Thursday/ThuCount, 'Friday': Friday/FriCount} df = pd.Series(dict, name='DailyValue') dff = DataFrame(df) dff['Day'] = dff.index dff['Sorter'] = [5,1,4,2,3] dff.sort_values(by = ['Sorter'], inplace = True) #dff.sort(['Day'], ascending = True) dff.plot(kind='bar', grid = True, y = ['DailyValue']) plt.show() Answer: You can use a list comprehension to generate the weekdays (i.e. 0-6) in your index, and then create a series from these values. You sort this series by these weekday values and take the index. You then use `ix` to index your original series based on this sorted index. import numpy as np import pandas as pd s = pd.Series(np.random.randn(14), index=pd.date_range('2016-1-1', periods=14)) s Out[34]: 2016-01-01 0.915488 2016-01-02 -1.053409 2016-01-03 -1.826033 2016-01-04 0.559250 2016-01-05 -0.278086 2016-01-06 0.041113 2016-01-07 1.076463 2016-01-08 0.942720 2016-01-09 -0.850388 2016-01-10 -0.649713 2016-01-11 2.769957 2016-01-12 0.498103 2016-01-13 1.098085 2016-01-14 0.699077 Freq: D, dtype: float64 idx = pd.Series([d.weekday() for d in s.index]).sort_values().index s.ix[idx] Out[36]: 2016-01-04 0.559250 2016-01-11 2.769957 2016-01-05 -0.278086 2016-01-12 0.498103 2016-01-06 0.041113 2016-01-13 1.098085 2016-01-07 1.076463 2016-01-14 0.699077 2016-01-01 0.915488 2016-01-08 0.942720 2016-01-02 -1.053409 2016-01-09 -0.850388 2016-01-03 -1.826033 2016-01-10 -0.649713 dtype: float64 As a one liner... s_new = s.ix[pd.Series([d.weekday() for d in s.index]).sort_values().index] Exactly the same for a dataframe. df_new = df.ix[pd.Series([d.weekday() for d in df.index]).sort_values().index]
Redirecting output of script called from within Flask, into its own log file Question: One of the user options in my Flask application is to trigger a web-scrape. The output of this process (and indeed _any_ external process, and the output of the main Flask app itself) is stdout which is the terminal in which I've started my main Flask app. I wish to maintain the overall Flask log in the terminal, while forcing the log from the scraping process into its own file (for downloading). So given: @app.route("/download-log", methods=["GET"]) def downloadlog(): # Check for valid file and assign it to `inbound_file` with open('log.txt', 'r') as log: contents = log.read() response = make_response(contents) response.headers["Content-Disposition"] = "attachment; filename=log.txt" return response .. which is working well, I need **log.txt** (currently just a `touch`ed file for proof-of-concept) to be the log from the scraping process, which I call thus: @app.route('/scrape', methods=['GET', 'POST']) @login_required # Use of @login_required decorator def scrape(): scraper.scrape('/path/to/URLs.csv', ['manager']) where `scraper` is a standalone python script that can and does run off its own bat normally, but is being called from within the Flask app here. I know how to redirect stdout into a file when calling a script itself, but how can I get the stdout of scraper.py into a file when it has been invoked from the Flask app? Answer: edit scraper.py and add a redirect to a log file: import sys sys.stdout = sys.stderr = open('log.txt','wt')
google-api-python-client broken because of OAuth2? Question: I am trying to check if a certain dataset exists in bigquery using the Google Api Client in Python. It always worked untill the last update where I got this strange error I don't know how to fix: Traceback (most recent call last): File "/root/miniconda/lib/python2.7/site-packages/dsUtils/bq_utils.py", line 106, in _get resp = bq_service.datasets().get(projectId=self.project_id, datasetId=self.id).execute(num_retries=2) File "/root/miniconda/lib/python2.7/site-packages/oauth2client/util.py", line 140, in positional_wrapper return wrapped(*args, **kwargs) File "/root/miniconda/lib/python2.7/site-packages/googleapiclient/http.py", line 755, in execute method=str(self.method), body=self.body, headers=self.headers) File "/root/miniconda/lib/python2.7/site-packages/googleapiclient/http.py", line 93, in _retry_request resp, content = http.request(uri, method, *args, **kwargs) File "/root/miniconda/lib/python2.7/site-packages/oauth2client/client.py", line 598, in new_request self._refresh(request_orig) File "/root/miniconda/lib/python2.7/site-packages/oauth2client/client.py", line 864, in _refresh self._do_refresh_request(http_request) File "/root/miniconda/lib/python2.7/site-packages/oauth2client/client.py", line 891, in _do_refresh_request body = self._generate_refresh_request_body() File "/root/miniconda/lib/python2.7/site-packages/oauth2client/client.py", line 1597, in _generate_refresh_req uest_body assertion = self._generate_assertion() File "/root/miniconda/lib/python2.7/site-packages/oauth2client/service_account.py", line 263, in _generate_ass ertion key_id=self._private_key_id) File "/root/miniconda/lib/python2.7/site-packages/oauth2client/crypt.py", line 97, in make_signed_jwt signature = signer.sign(signing_input) File "/root/miniconda/lib/python2.7/site-packages/oauth2client/_pycrypto_crypt.py", line 101, in sign return PKCS1_v1_5.new(self._key).sign(SHA256.new(message)) File "/root/miniconda/lib/python2.7/site-packages/Crypto/Signature/PKCS1_v1_5.py", line 112, in sign m = self._key.decrypt(em) File "/root/miniconda/lib/python2.7/site-packages/Crypto/PublicKey/RSA.py", line 174, in decrypt return pubkey.pubkey.decrypt(self, ciphertext) File "/root/miniconda/lib/python2.7/site-packages/Crypto/PublicKey/pubkey.py", line 93, in decrypt plaintext=self._decrypt(ciphertext) File "/root/miniconda/lib/python2.7/site-packages/Crypto/PublicKey/RSA.py", line 235, in _decrypt r = getRandomRange(1, self.key.n-1, randfunc=self._randfunc) File "/root/miniconda/lib/python2.7/site-packages/Crypto/Util/number.py", line 123, in getRandomRange value = getRandomInteger(bits, randfunc) File "/root/miniconda/lib/python2.7/site-packages/Crypto/Util/number.py", line 104, in getRandomInteger S = randfunc(N>>3) File "/root/miniconda/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 202, in read return self._singleton.read(bytes) File "/root/miniconda/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 178, in read return _UserFriendlyRNG.read(self, bytes) File "/root/miniconda/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 137, in read self._check_pid() File "/root/miniconda/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 153, in _check_pid raise AssertionError("PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()") AssertionError: PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork() Is someone understanding what is hapening? Note that I also get this error with other bricks like GCStorage. Note also that I use the following command to load my Google credentials: from oauth2client.client import GoogleCredentials def get_credentials(credentials_path): #my json credentials path logger.info('Getting credentials...') try: os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_path credentials = GoogleCredentials.get_application_default() return credentials except Exception as e: raise e So if anyone know a better way to load my google credentials using my json service account file, and which would avoid the error, please tell me. Answer: It looks like the error is in the PyCrypto module, which appears to be used under the hood by Google's OAuth2 implementation. If your code is calling `os.fork()` at some point, you may need to call `Crypto.Random.atfork()` afterward in both the parent and child process in order to update the module's internal state. See here for PyCrypto docs; search for "atfork" for more info: <https://github.com/dlitz/pycrypto> This question and answer might also be relevant: [PyCrypto : AssertionError("PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()")](http://stackoverflow.com/questions/16981503/pycrypto- assertionerrorpid-check-failed-rng-must-be-re-initialized-after-fo)
python threading with sync queue Question: I have a script that follows the same logic in this sample. Basically I insert items into a global queue and spawn threads with a while loop that gets and item from the queue and the calls task_done. I can get the threads to join if my while loop is checking that the queue is not empty, but I wanted to try and incorporate a flag that I could set myself to exit the loop. When I try to do this, joining the thread blocks forever. Here is the non-working sample that doesnt join the threads: import threading import queue class Mythread(threading.Thread): def __init__(self): super().__init__() self.signal = False def run(self): global queue while not self.signal: item = q.get() print(item) q.task_done() def stop(self): self.signal = True q = queue.Queue for i in range(5000): q.put(i) threads = [] for i in range(2): t = Mythread() threads.append(t) for t in threads: t.start() q.join() for t in threads: print(t.signal) <---- False t.stop() print(t.signal) <---- True t.join() <---- Blocks forever Here is the one that works using queue empty import threading import queue class Mythread(threading.Thread): def __init__(self): super().__init__() def run(self): global queue while not q.empty(): item = q.get() print(item) q.task_done() q = queue.Queue for i in range(5000): q.put(i) threads = [] for i in range(2): t = Mythread() threads.append(t) for t in threads: t.start() q.join() for t in threads: t.join() <---- Works fine print(t.is_alive()) <--- returns False Any ideas? Answer: q.get blocks so it won't reach your while condition
How can I find out what package that a python module belongs to? Question: You are given some python source code with some import statements for modules that you don't recognize. You are curious and would like to know what packages these modules belong to. 2 scenarios. **Scenario #1:** Some of the imports fail because you don't have the correct packages installed. You need figure out which package to install. Is there a way to do this without leaving the command line? **Scenario #2:** It seems that you do have the modules installed already, but you are curious about which package they belong to. Is there a way to discover this quickly and efficiently on the command line? Answer: Normally a module from a package should be imported as: import a.b where **a** is the package and **b** is the module. So the import statement should tell you what you need.
Removing points stored in a dictionary in a matplotlib basemap animation Question: I am trying to do the following: Plot points and store a reference in a dictionary. While animating remove points. A minimal example looks as follows: %matplotlib qt import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.animation as animation fig = plt.figure() m = Basemap(projection='aeqd',lat_0=72,lon_0=29, resolution='l', llcrnrlon=15, llcrnrlat=69, urcrnrlon=41, urcrnrlat=75.6,area_thresh = 100) pointDict=dict() pointDict[1]=m.plot (0, 0,marker='.',label='first')[0] pointDict[2]=m.plot (0, 0,marker='.',label='second')[0] def init(): print ("Init") x,y = m(30, 73) pointDict[1].set_data(x,y) x,y = m(31, 73) pointDict[2].set_data(x,y) return pointDict.values() def animate(i): print ("Frame {0}".format(i)) if i==2: l=pointDict.pop(1) print ("Removing {0}".format(l.get_label())) l.remove() del l return pointDict.values() anim = animation.FuncAnimation(plt.gcf(), animate, init_func=init, frames=10, interval=1000, blit=True) plt.show() Output: Init Init Frame 0 Frame 1 Frame 2 Removing first Frame 3 Interestingly, if I am plotting just the first point (that is, remove pointDict[2]=m.plot and pointDict[2].set_data in the init function), this works. But if both are plotted, neither removing the first, nor the second point works. Related questions brought me just as far as I am now: [Matplotlib Basemap animation](http://stackoverflow.com/questions/21207513/matplotlib-basemap- animation) [How to remove lines in a Matplotlib plot](http://stackoverflow.com/questions/4981815/how-to-remove-lines-in-a- matplotlib-plot) [Matplotlib animating multiple lines and text](http://stackoverflow.com/questions/20624408/matplotlib-animating- multiple-lines-and-text) [Python, Matplotlib, plot multi-lines (array) and animation](http://stackoverflow.com/questions/19519587/python-matplotlib-plot- multi-lines-array-and-animation) I am using Anaconda with Python-2.7 kernel. Answer: I found out what the problem is and want therefore to answer my question by myself: The problem with this is somewhat unexpected the blit=True. Obviously, blitting can be only used if the point is set within the animate function. Thus, setting the data in the init routine causes problems. So there are two options: set blit to False, but this is not very elegant. The other option is to set the points in the first frame. Then the init and animate functions that work are as follows: def init(): print ("Init") pointDict[1].set_data([],[]) pointDict[2].set_data([],[]) return pointDict.values() def animate(i): print ("Frame {0}".format(i)) if i==0: print ("Init") x,y = m(30, 73) pointDict[1].set_data(x,y) x,y = m(31, 73) pointDict[2].set_data(x,y) if i==2: l=pointDict.pop(1) print ("Removing {0}".format(l.get_label())) l.remove() del l return pointDict.values() anim = animation.FuncAnimation(plt.gcf(), animate, init_func=init, frames=10, interval=1000, blit=True) plt.show()
getMouse in python using graphics Question: I am very new to Python. I need to write a program to move my ball or circle when I click the mouse. How do I achieve this? I have the below code that I got started with. from graphics import * import time def MouseTracker(): win = GraphWin("MyWindow", 500, 500) win.setBackground("blue") cir = Circle(Point(250,250) ,20) cir.setFill("red") cir.draw(win) while(win.getMouse() != None): xincr = 0 yincr = 0 for i in range(7): cir.move(xincr, yincr) time.sleep(.2) win.getMouse() Answer: Assuming you are not bound to some specific tools or implementation, you may find matplotlib useful. You can plot a circle onto the drawing area using a circle patch (<http://matplotlib.org/api/patches_api.html>) and then move it around when there is mouse-click in the graph axes. You will need to connect to the event-click listener and define a callback function which handles the drawing update - see <http://matplotlib.org/users/event_handling.html> for examples of how to do this. You can get the coordinates of the mouse press using the xdata and ydata methods. This worked for me in python 2.7: import matplotlib.pyplot as plt from matplotlib.patches import Circle fig = plt.figure() ax = fig.add_subplot(111) circ = Circle((0.5,0.5), 0.1) ax.add_patch(circ) def update_circle(event): ax.cla() circ = Circle((event.xdata, event.ydata), 0.1) ax.add_patch(circ) fig.canvas.draw() fig.canvas.mpl_connect('button_press_event', update_circle) plt.show()
Retain top-N elements as we loop across all elements Question: Here is what I am trying to do. The output of a calculation on a dataframe gives a number. I use that number to rank the different dataframes and I need to retain the top-N (in the example below, the top 10 is chosen). The ranking is achieved by comparing the number to the last number of a reverse sorted list. If the current number is larger, the list is popped and the new entry added to the list followed by reverse sorting again. The following is structurally identical to what I have and it works, albeit slowly. I would appreciate any suggestions to improve its speed, efficiency or Pythonicness. import random import pandas as pd def gen_df(): return random.uniform(0.0, 1.0), pd.DataFrame() if __name__ == '__main__': mylist = [] for i in range(1000): val, df = gen_df() if len(mylist) < 10: mylist.append((val, df)) else: mylist.sort(reverse=True) if mylist[-1][0] < val: mylist.pop() mylist.append((val, df)) EDIT: Reduced one sort after suggestion by zondo. Answer: The way to speed it up is to replace your list with a min-heap of size 10. Put the first 10 frames into the heap. Then, for each item, if it's larger than the smallest item on the heap, pop the smallest item and push the new item. I'm not a Python programmer, so I'll present the pseudocode. heap = new min-heap for each item if (heap.length < 10) heap.push(item) else if (item > heap.peek()) heap.pop(); // remove smallest item heap.push(item); // add new item This assumes, of course, that there's a min-heap implementation that you can use. I suspect [heapq](https://docs.python.org/2/library/heapq.html) will do the trick. That's going to be significantly faster than sorting the list every time you insert a new item.
Django staticfiles not found on Heroku (with whitenoise) Question: This question seems to be asked several time but I can not fix it. I deployed a django app on production with `DEBUG = False`. I set my `allowed_host`. I used `{% load static from staticfiles %}` to load static files. I exactly write the settings sugested by Heroku doc : BASE_DIR = os.path.dirname(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' BUT I got an error 500. And got this traceback (by mail) ... `cache_name = self.clean_name(self.hashed_name(name)) File "/app/.heroku/python/lib/python3.5/site- packages/django/contrib/staticfiles/storage.py", line 94, in hashed_name (clean_name, self)) ... ValueError: The file β€˜app/css/font.css’ could not be found with <whitenoise.django.GzipManifestStaticFilesStorage object at 0x7febf600a7f0>.` When I run `heroku run python manage.py collectstatic --noinput` All seems ok : `276 static files copied to '/app/annuaire/staticfiles', 276 post-processed.` Does anyone have an idea to help me, please ? Thanks EDIT : annuaire |-- /annuaire |-- -- /settings.py |-- /app |-- -- /static/...` wsgi.py from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = get_wsgi_application() application = DjangoWhiteNoise(application) Answer: I got it. I needed to add python manage.py collectstatic --noinput; in my Procfile. Heroku doc said that `collecticstatic` is automatically triggered. <https://devcenter.heroku.com/articles/django-assets> Thanks
Is there a way in Python to exit the program if the line is blank? Question: My file is a .txt file and all comments have no spaces before them. I have a file with 10,000 lines that looks like this and I am reading every line of the file. ## something ## something ## something 12312312 123123 12312312 123123 123123 However, my code will fail if there is not a value in every line. Is there a way in Python to exit the program if the line is blank? I just need a simple If statement to fix my program. Something like if line == blank: quit Answer: If you want to completely exit the program and the line contains no whitespace(if it does replace `line` with `line.strip()`: if not line: sys.exit() assuming you have imported sys As pointed out by @zondo, you could just use a `continue` statement to skip that line if you do not want the program to fail: if not line.strip(): continue
malt parser gives assertion error when using it with nltk Question: I am using malt parser with python nltk. I have successfully downloaded the training data and updated the latest nltk. When I call the malt parser it gives me an asertion error. Below is the code from python which includes the traceback as well. mp = MaltParser("C:/Users/mustufain/Desktop/Python Files/maltparser-1.8.1","C:/Users/mustufain/Desktop/Python Files/maltparser-1.7.2",additional_java_args=['-Xmx512m']) Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> mp = MaltParser("C:/Users/mustufain/Desktop/Python Files/maltparser-1.8.1","C:/Users/mustufain/Desktop/Python Files/maltparser-1.7.2",additional_java_args=['-Xmx512m']) File "C:\Python34\lib\site-packages\nltk\parse\malt.py", line 131, in __init__ self.malt_jars = find_maltparser(parser_dirname) File "C:\Python34\lib\site-packages\nltk\parse\malt.py", line 72, in find_maltparser assert malt_dependencies.issubset(_jars) AssertionError >>> Answer: **`TL;DR`** (In **PYTHON3**!!): import urllib.request urllib.request.urlretrieve('http://www.maltparser.org/mco/english_parser/engmalt.poly-1.7.mco', 'C:\\Users\\mustufain\\Desktop\\engmalt.poly-1.7.mco') urllib.request.urlretrieve('http://maltparser.org/dist/maltparser-1.8.1.zip', 'C:\\Users\\mustufain\\Desktop\\maltparser-1.8.1.zip') zfile = zipfile.ZipFile('C:\\Users\\mustufain\\Desktop\\maltparser-1.8.1.zip') zfile.extractall('C:\\Users\\mustufain\\Desktop\\maltparser-1.8.1\\') Then: from nltk.parse import malt mp = malt.MaltParser('C:\\Users\\mustufain\\Desktop\\maltparser-1.8.1\\', "C:\\Users\\mustufain\\Desktop\\engmalt.poly-1.7.mco") mp.parse_one('I shot an elephant in my pajamas .'.split()).tree()
Python 2.7 imports module from wrong location Question: I'm on Python 2.7.6 un Ubuntu 14.04 and I'm trying to import openpyxl. I upraged to a recent version via `sudo pip install openpyxl --upgrade` and `pip show openpyxl` gives the following output: pip show openpyxl --- Name: openpyxl Version: 2.3.3 Location: /usr/local/lib/python2.7/dist-packages Requires: However, when inside python, after I `import openpyxl` It seems to load it from a different location: `/usr/lib` instead of `/usr/local/lib` openpyxl.__version__ '1.7.0' openpyxl.__file__ '/usr/lib/pymodules/python2.7/openpyxl/__init__.pyc' I have set the `$PYTHONPATH` to `/usr/local/lib/python2.7/dist-packages` And when looking at `sys.path` I get this output: ['', '/usr/local/lib/python2.7/dist-packages',... and 12 other locations] It seems to have my desired location in first. Nevertheless the wrong module gets loaded. **EDIT:** Contents of `$PATH`: /misc/software-lin/lmbsoft/build/x86_64-gcc4.8/release/bin:/misc/software-lin/lmbsoft/build/x86_64-gcc4.8/debug/bin:/misc/software-lin/lmbsoft/build/x86_64-gcc4.8/bin:/home/maid/phd/3rdpartySoft/art-2009-03-12/bin:/home/maid/phd/3rdpartySoft/ANTs-1.9.x-Linux/bin:/misc/software-lin/lmbsoft/build/x86_64-gcc4.8/release/bin:/misc/software-lin/lmbsoft/build/x86_64-gcc4.8/debug/bin:/misc/software-lin/lmbsoft/build/x86_64-gcc4.8/bin:/home/maid/phd/3rdpartySoft/art-2009-03-12/bin:/home/maid/phd/3rdpartySoft/ANTs-1.9.x-Linux/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:.:/home/maid/bin:/misc/software-lin/matlabR2015a/bin:/home/maid/phd/3rdpartySoft/nifty_reg-1.3/niftyreg_install/bin:/misc/software-lin/lmbsoft/cudatoolkit-3.2.16-x86_64/cuda/bin:/misc/database/cv2/local/bin:/misc/software-lin/vibez/bin:/usr/lib/jvm/java-6-openjdk/jre/bin:/misc/software-lin/vivi:/home/maid/localsoft/voreen/voreen-src-3.0.1-unix/bin/:/home/maid/tmp/ij146/ImageJ:.:/home/maid/bin:/misc/software-lin/matlabR2015a/bin:/home/maid/phd/3rdpartySoft/nifty_reg-1.3/niftyreg_install/bin:/misc/software-lin/lmbsoft/cudatoolkit-3.2.16-x86_64/cuda/bin:/misc/database/cv2/local/bin:/misc/software-lin/vibez/bin:/usr/lib/jvm/java-6-openjdk/jre/bin:/misc/software-lin/vivi:/home/maid/localsoft/voreen/voreen-src-3.0.1-unix/bin/:/home/maid/tmp/ij146/ImageJ Any help appreciated, thanks, Dominic Answer: I posit that if you `echo $PATH` you will find that `/usr/lib` is being searched before `/usr/local/lib`. Because it finds it in `/usr/lib` first, it will not go on to look in `/usr/local/lib`. `sys.path` only covers the `$PYTHONPATH` variable and doesn't show you the contents of `$PATH`.
Install h5py without sudo Question: I'm trying to install `h5py` package via `pip` for python 2.7, I can't use `sudo` and I have python 3.2 installed too. Here is my attemp: I have installed pip: curl -O https://bootstrap.pypa.io/get-pip.py python2.7 get-pip.py --user then I installed `wheel` `~/.local/bin/pip2.7 install --user wheel` Collecting wheel /home/myuser/.local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:315: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning. SNIMissingWarning /home/myuser/.local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:120: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Using cached wheel-0.29.0-py2.py3-none-any.whl Installing collected packages: wheel Successfully installed wheel-0.29.0 Then installed `h5py`, seems it failed. `~/.local/bin/pip2.7 install --user h5py` Collecting h5py Using cached h5py-2.5.0.tar.gz /usr/lib/python2.7/dist-packages/setuptools/command/install_scripts.py:3: UserWarning: Module pip was already imported from /home/myuser/.local/lib/python2.7/site-packages/pip/__init__.pyc, but /usr/lib/python2.7/dist-packages is being added to sys.path from pkg_resources import Distribution, PathMetadata, ensure_directory Requirement already satisfied (use --upgrade to upgrade): numpy>=1.6.1 in /usr/lib/python2.7/dist-packages (from h5py) Requirement already satisfied (use --upgrade to upgrade): Cython>=0.17 in /home/myuser/.local/lib/python2.7/site-packages (from h5py) Requirement already satisfied (use --upgrade to upgrade): six in /home/myuser/.local/lib/python2.7/site-packages (from h5py) Building wheels for collected packages: h5py Running setup.py bdist_wheel for h5py ... error Complete output from command /usr/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-7KTR1Y/h5py/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpE1KVSupip-wheel- --python-tag cp27: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- Failed building wheel for h5py Running setup.py clean for h5py Failed to build h5py Installing collected packages: h5py Running setup.py install for h5py ... done Successfully installed h5py-2.5.0 run python via `python2.7` Python 2.7.3 (default, Feb 27 2014, 19:58:35) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import h5py Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/myuser/.local/lib/python2.7/site-packages/h5py/__init__.py", line 23, in <module> from . import _conv File "h5py/h5r.pxd", line 21, in init h5py._conv (/tmp/pip-build-7KTR1Y/h5py/h5py/_conv.c:7356) File "h5py/_objects.pxd", line 12, in init h5py.h5r (/tmp/pip-build-7KTR1Y/h5py/h5py/h5r.c:2941) File "h5py/_objects.pyx", line 1, in init h5py._objects (/tmp/pip-build-7KTR1Y/h5py/h5py/_objects.c:7226) ImportError: /home/myuser/.local/lib/python2.7/site-packages/h5py/defs.so: undefined symbol: H5Oexists_by_name What I'm doing wrong? **Update:** `~/.local/bin/pip2.7 show h5py` --- Metadata-Version: 1.1 Name: h5py Version: 2.5.0 Summary: Read and write HDF5 files from Python Home-page: http://www.h5py.org Author: Andrew Collette Author-email: andrew dot collette at gmail dot com License: UNKNOWN Location: /home/myuser/.local/lib/python2.7/site-packages Requires: numpy, Cython, six My OS is Ubuntu 12.04.1 LTS. Answer: So there's a few things happening here: 1. Missing SSL certificate problems (see the `urllib3` link) 2. `setuptools` not finding `wheel`, meaning a wheel isn't built, so `pip` calls `python setup.py install` directly 3. `h5py` is trying to use a function in HDF5 which does not exist in the version of HDF5 that's on your system. 1 and 2 are worth fixing (as they may be symptoms of other problems with the system), but 3 is the reason `h5py` isn't working for you. `h5py` is trying to access `H5Oexists_by_name`. According to <https://www.hdfgroup.org/HDF5/doc/RM/RM_H5O.html#Object-ExistsByName>, this first appeared in version 1.8.5 of HDF5. According to <http://packages.ubuntu.com/source/precise/hdf5>, the version of HDF5 on your system is 1.8.4 (but you need to check this!). Somehow `h5py` thinks the HDF5 library on you system is 1.8.5 or higher (see <https://github.com/h5py/h5py/blob/4ee8f89b6dc658fdea5dc62d0f29058121928cfe/h5py/h5o.pyx#L172>) It looks like someone else has run into a similar problem, and filed <https://bugs.launchpad.net/ubuntu/+source/hdf5/+bug/1418220>. You probably want to inform them of your problem, so that they can produce a bug fix.
Split Strings to change them Question: I'm new with python,I'm trying to learn I hope you can help me. What I'm trying to to is to change week day, something like this. Today is {Mon|Tue|Wed|Thu|Fri} the best day. **It suppose to change randonly those week days**. Do you have any idea? Thank you! Answer: This should work: import random days = ["Mon", "Tue", "Wed", "Thur", "Fri"] random_choice = random.choice(days) print("Today is " + random_choice + " the best day.")
'utf-8' decode error in tensorflow tutorial Question: I'm running into this bizarre problem where when I run from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('/home/fqiao/development/MNIST_data/', one_hot=True) I get: File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.5/dist-packages/tensorflow/examples/tutorials/mnist/input_data.py", line 199, in read_data_sets train_images = extract_images(local_file) File "/usr/local/lib/python3.5/dist-packages/tensorflow/examples/tutorials/mnist/input_data.py", line 58, in extract_images magic = _read32(bytestream) File "/usr/local/lib/python3.5/dist-packages/tensorflow/examples/tutorials/mnist/input_data.py", line 51, in _read32 return numpy.frombuffer(bytestream.read(4), dtype=dt)[0] File "/usr/lib/python3.5/gzip.py", line 274, in read return self._buffer.read(size) File "/usr/lib/python3.5/_compression.py", line 68, in readinto data = self.read(len(byte_view)) File "/usr/lib/python3.5/gzip.py", line 461, in read if not self._read_gzip_header(): File "/usr/lib/python3.5/gzip.py", line 404, in _read_gzip_header magic = self._fp.read(2) File "/usr/lib/python3.5/gzip.py", line 91, in read self.file.read(size-self._length+read) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/default/_gfile.py", line 45, in sync return fn(self, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/default/_gfile.py", line 199, in read return self._fp.read(n) File "/usr/lib/python3.5/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte However, if I just run the code in input_data.py directly, everything appears to be fine: >>> dt = numpy.dtype(numpy.uint32).newbyteorder('>') >>> f = tf.gfile.Open('/home/fqiao/development/MNIST_data/train-images-idx3-ubyte.gz', 'rb') >>> bytestream = gzip.GzipFile(fileobj=f) >>> testbytes = numpy.frombuffer(bytestream.read(4), dtype=dt)[0] >>> testbytes 2051 Anyone has any idea what's going on? My system: Ubuntu 15.10 x64 python 3.5.0. Answer: The bug has been addressed by a recent change [555e73d](https://github.com/tensorflow/tensorflow/commit/555e73da8f171992085c68614f74b23b8180292c). MNIST files need to be opened with binary 'rb' mode instead of just text 'r'.
Python Sqlite3 Database Locked, QWidget Question: I'm getting a `sqlite3.OperationalError: database is locked` when I try to update the database from a pyqt widget. The main window shows a list of items in a database. When an item is double clicked a widget will pop up with options to modify a value in the same row of the database. I have 4 separate .py files; (I have removed most of the code) `DBmanager.py` that contains all the functions for interacting with the database. class DatabaseUtility: def __init__(self, databaseFile): self.db = databaseFile self.conn = sqlite3.connect(self.db) self.c = self.conn.cursor() def ChangeItemQuantity(self, itemName, incramentQuantity): try: # Change given item quantity in database self.c.execute(''' SELECT quantity FROM items WHERE itemName=? ''',(itemName,)) print(itemName) print(incramentQuantity) current_quantity = self.c.fetchone() print(current_quantity[0]) new_quantity = current_quantity[0] + incramentQuantity self.c.execute(''' UPDATE items SET quantity = ? WHERE itemName=? ''',(new_quantity, itemName)) self.conn.commit() except Exception as error: # Rollback any changes if something goes wrong. self.conn.rollback() raise error def __del__(self): """Commit and close database connection when the class is terminated.""" # pass self.conn.commit() self.c.close() self.conn.close() `StartGui.py` that contains the functions for the GUI. import sys from PyQt4 import QtCore, QtGui from guiFormat import Ui_MainWindow from itemWidget import Ui_itemWidget from DBmanager import DatabaseUtility class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.db = 'testdb.db' self.dbUtil = DatabaseUtility(self.db) self.ui.updateButton.clicked.connect(self.populateTable_default) self.ui.updateButton.clicked.connect(self.dbUtil.UpdateDatabase) self.ui.searchButton.clicked.connect(self.populateTable_search) self.ui.tableWidget.doubleClicked.connect(self.open_item_widget) self.ui.tableWidget.resizeRowsToContents() # Populate table on initial startup self.populateTable_default() def open_item_widget(self): self.item_widget = ItemWidget(self) # self.item_widget.show() column_count = self.ui.tableWidget.columnCount() self.item_widget.ui.tableWidget.setColumnCount(column_count) self.item_widget.ui.tableWidget.setRowCount(1) column_names = self.dbUtil.GetColumns('items') self.item_widget.ui.tableWidget.setHorizontalHeaderLabels(column_names) row = self.ui.tableWidget.currentRow() for column in range(column_count): x = self.ui.tableWidget.item(row, column).text() item_data = QtGui.QTableWidgetItem(str(x)) self.item_widget.ui.tableWidget.setItem(0, column, item_data) self.item_widget.show() class ItemWidget(QtGui.QWidget): def __init__(self, parent=None): self.db = 'testdb.db' self.dbUtil2 = DatabaseUtility(self.db) QtGui.QWidget.__init__(self, parent) self.ui = Ui_itemWidget() self.ui.setupUi(self) self.ui.cancelOkButtonBox.rejected.connect(self.close) self.ui.cancelOkButtonBox.accepted.connect(self.submit_changes) def submit_changes(self): # Get item Name. item_name = self.ui.tableWidget.item(0,0).text() # Get number from increment box. quant_increment = self.ui.QuantSpinBox.value() alert_incrament = self.ui.alertSpinBox.value() print('Changing quantity...', item_name, quant_increment) self.dbUtil2.ChangeItemQuantity(item_name, quant_increment) self.close() ##====================================================================================================================== ##====================================================================================================================== if __name__ == "__main__": dbUtil = DatabaseUtility('testdb.db') app = QtGui.QApplication(sys.argv) mainwindow = MainWindow() mainwindow.show() # itemwidget = ItemWidget() # itemwidget.show() sys.exit(app.exec_()) `Mainwindow.py` is an export from pyqt designer for the main window. `Itemwidget.py` is also an export from pyqt designer for the item widget. Thank you for all your help. Answer: The `sqlite3` documentation says: > When a database is accessed by multiple connections, and one of the > processes modifies the database, the SQLite database is locked until that > transaction is committed. Since you have two connections, one opened by `MainWindow` and the other by `ItemWidget`, one likely cause of your problem is just what the doc says. One connection tries to update the database when changes made by the other connection is not committed. This won't happen with the `ChangeItemQuantity` method you are showing as the change it makes is immediately committed, but obviously `DatabaseUtility` has other methods you are not showing, like `UpdateDatabase`. If they make changes that are not immediately committed, that could be the problem. Let `MainWindow` and `ItemWidget` share one connection and see if the problem goes away. You can do this by making `conn` a shared attribute of `DatabaseUtility` instances, with no change to callers: class DatabaseUtility: conn = None def __init__(self, databaseFile): self.db = databaseFile if self.__class__.conn is None: self.__class__.conn = sqlite3.connect(self.db) self.c = self.conn.cursor() Also, although this seems less likely to be the problem, if some other process has an open transaction on the same SQLite database, the database will be locked for as long as that transaction is active. Some apps have the bad habit of maintaining an active transaction it seems. Whenever I open a database with [SQLite Browser](http://sqlitebrowser.org/), I can't do anything to the database from other programs (maybe I can turn that off, but I never bothered to figure out how...)
Matplotlib not installing inside virtualenv mac Question: So I have Python 3 and `matplotlib` installed globally. If I run python outside of a virtual environment and import matplotlib to check the version it shows 1.5.1 . But I am facing problems installing matplotlib within a virtual environment. I created a virtual environment using the command `python3 -m venv ds` and activated `ds`. These are the contents of my `requirements.txt` `matplotlib==1.4.2 numpy==1.9.1` When I do `pip3 install -r requirements.txt` I get this Collecting matplotlib==1.4.2 (from -r requirements.txt (line 1)) Using cached matplotlib-1.4.2.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 20, in <module> File "/private/var/folders/ym/gfrm424x31j4vd944cdhn4hr0000gn/T/pip-build-pcfq8bhb/matplotlib/setup.py", line 155, in <module> result = package.check() File "/private/var/folders/ym/gfrm424x31j4vd944cdhn4hr0000gn/T/pip-build-pcfq8bhb/matplotlib/setupext.py", line 962, in check min_version='2.3', version=version) File "/private/var/folders/ym/gfrm424x31j4vd944cdhn4hr0000gn/T/pip-build-pcfq8bhb/matplotlib/setupext.py", line 446, in _check_for_pkg_config if (not is_min_version(version, min_version)): File "/private/var/folders/ym/gfrm424x31j4vd944cdhn4hr0000gn/T/pip-build-pcfq8bhb/matplotlib/setupext.py", line 174, in is_min_version return found_version >= expected_version File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/distutils/version.py", line 70, in __ge__ c = self._cmp(other) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/distutils/version.py", line 337, in _cmp if self.version < other.version: TypeError: unorderable types: str() < int() IMPORTANT WARNING: pkg-config is not installed. matplotlib may not be able to find some of its dependencies ============================================================================ Edit setup.cfg to change the build options BUILDING MATPLOTLIB matplotlib: yes [1.4.2] python: yes [3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]] platform: yes [darwin] REQUIRED DEPENDENCIES AND EXTENSIONS numpy: yes [version 1.10.4] six: yes [using six version 1.10.0] dateutil: yes [dateutil was not found. It is required for date axis support. pip/easy_install may attempt to install it after matplotlib.] pytz: yes [pytz was not found. pip will attempt to install it after matplotlib.] tornado: yes [tornado was not found. It is required for the WebAgg backend. pip/easy_install may attempt to install it after matplotlib.] pyparsing: yes [pyparsing was not found. It is required for mathtext support. pip/easy_install may attempt to install it after matplotlib.] pycxx: yes [Official versions of PyCXX are not compatible with matplotlib on Python 3.x, since they lack support for the buffer object. Using local copy] libagg: yes [pkg-config information for 'libagg' could not be found. Using local copy.] ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/ym/gfrm424x31j4vd944cdhn4hr0000gn/T/pip-build-pcfq8bhb/matplotlib You are using pip version 7.1.2, however version 8.0.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. How should I install matplotlib version 1.4.2 in virtual environment ? My question has been marked as duplicate but that link doesn't solve my question. The solution given is for Ubuntu Answer: You can use the system package in your virtualenv with [this](http://virtualenv.readthedocs.org/en/latest/userguide.html#the-system- site-packages-option) option. Otherwise, [this SO post](http://stackoverflow.com/questions/27024731/matplotlib-compilation- error-typeerror-unorderable-types-str-int) may help you.
Trying to python takes a variable in to Create Table Question: I'm trying to python takes a variable when it ask for the data base name but it does not work this is my code, I do not know whan I'm doing wrong. any idea ? #!/usr/bin/python # -*- encoding: utf-8 -*- import MySQLdb name_db = raw_input('Type Data Base Name : ') bd = MySQLdb.connect("localhost","root","9090i","clientes" ) cursor = bd.cursor() sql = "CREATE TABLE name_db (NOMBRE CHAR(20) NOT NULL, APELLIDO CHAR(20), EDAD INT, SEXO CHAR(1), SALARIO FLOAT )" cursor.execute(sql) bd.close() Answer: Change sql = "CREATE TABLE name_db (NOMBRE CHAR(20) NOT NULL, APELLIDO CHAR(20), EDAD INT, SEXO CHAR(1), SALARIO FLOAT )" to sql = "CREATE TABLE {name} (NOMBRE CHAR(20) NOT NULL, APELLIDO CHAR(20), EDAD INT, SEXO CHAR(1), SALARIO FLOAT )".format(name = name_db) The {name} is Python's syntax for string replacement so this should create a constant SQL String that has the value you typed in substituted for the table name. To check this it's a good idea to print out the SQL before you execute it. That makes it easier for you to see why the code isn't working.
Swift get user input with prompt Question: In Swift, I want to have a continous user-input loop, much like how the python interpreter works, where a prompt is made, you type a line, the result of the line is displayed, and then the user is prompted again. This is my code so far: import Foundation func input() -> String { var keyboard = NSFileHandle.fileHandleWithStandardInput() var inputData = keyboard.availableData return NSString(data: inputData, encoding: NSUTF8StringEncoding) as! String } while true { println("Obl>") var theInput = input() println("\(theInput)") } However, this results in a scheme like this: Obl> hello world hello world Obl> yo yo What I want it to look like is this: Obl> hello world hello world Obl> hello hello How can this be accomplished? Answer: Are you still using Swift 1? `println` has been deprecated in Swift 2. Swift 1: print("Obl> ") Swift 2: print("Obl>", terminator: " ") And instead of your `input()` function, you can just use `readLine`, which is a standard function in Swift: let theInput = readLine()
python logging performance comparison and options Question: I am researching high performance logging in Python and so far have been disappointed by the performance of the python standard logging module - but there seem to be no alternatives. Below is a piece of code to performance test 4 different ways of logging: import logging import timeit import time import datetime from logutils.queue import QueueListener, QueueHandler import Queue import threading tmpq = Queue.Queue() def std_manual_threading(): start = datetime.datetime.now() logger = logging.getLogger() hdlr = logging.FileHandler('std_manual.out', 'w') logger.addHandler(hdlr) logger.setLevel(logging.DEBUG) def logger_thread(f): while True: item = tmpq.get(0.1) if item == None: break logging.info(item) f = open('manual.out', 'w') lt = threading.Thread(target=logger_thread, args=(f,)) lt.start() for i in range(100000): tmpq.put("msg:%d" % i) tmpq.put(None) lt.join() print datetime.datetime.now() - start def nonstd_manual_threading(): start = datetime.datetime.now() def logger_thread(f): while True: item = tmpq.get(0.1) if item == None: break f.write(item+"\n") f = open('manual.out', 'w') lt = threading.Thread(target=logger_thread, args=(f,)) lt.start() for i in range(100000): tmpq.put("msg:%d" % i) tmpq.put(None) lt.join() print datetime.datetime.now() - start def std_logging_queue_handler(): start = datetime.datetime.now() q = Queue.Queue(-1) logger = logging.getLogger() hdlr = logging.FileHandler('qtest.out', 'w') ql = QueueListener(q, hdlr) # Create log and set handler to queue handle root = logging.getLogger() root.setLevel(logging.DEBUG) # Log level = DEBUG qh = QueueHandler(q) root.addHandler(qh) ql.start() for i in range(100000): logging.info("msg:%d" % i) ql.stop() print datetime.datetime.now() - start def std_logging_single_thread(): start = datetime.datetime.now() logger = logging.getLogger() hdlr = logging.FileHandler('test.out', 'w') logger.addHandler(hdlr) logger.setLevel(logging.DEBUG) for i in range(100000): logging.info("msg:%d" % i) print datetime.datetime.now() - start if __name__ == "__main__": """ Conclusion: std logging about 3 times slower so for 100K lines simple file write is ~1 sec while std logging ~3. If threads are introduced some overhead causes to go to ~4 and if QueueListener and events are used with enhancement for thread sleeping that goes to ~5 (probably because log records are being inserted into queue). """ print "Testing" #std_logging_single_thread() # 3.4 std_logging_queue_handler() # 7, 6, 7 (5 seconds with sleep optimization) #nonstd_manual_threading() # 1.08 #std_manual_threading() # 4.3 1. The nonstd_manual_threading option works best since there is no overhead of the logging module but obviously you miss out on a lot of features such as formatters, filters and the nice interface 2. The std_logging in a single thread is the next best thing but still about 3 times slower than nonstd manual threading. 3. The std_manual_threading option dumps messages into a threadsafe queue and in a separate thread uses the standard logging module. That comes out to be about 25% higher than option 2, probably due to context switching costs. 4. Finally, the option using "logutils"'s QueueHandler comes out to be the most expensive. I tweaked the code of logutils/queue.py's _monitor method to sleep for 10 millis after processing 500 messages as long as there are less than 100K messages in the queue. That brings the runtime down from 7 seconds to 5 seconds (probably due to avoiding context switching costs). My question is, why is there so much performance overhead with the logging module and are there any alternatives? Being a performance sensitive app does it even make sense to use the logging module? p.s.: I have profiled the different scenarios and seems like LogRecord creation is expensive. Answer: If you want a better answer try to describe your problem in more detail, why you need such a huge number of messages to log? Logging was designed to record important information, especially warnings and errors, not every line you execute. If logging takes more than 1% of your processing time, probably you are using it wrongly and that's not logging fault. Second, related to performance: do not build the message before sending it to logging module (replace format % params with format command params). This is because logging does this for you, but much faster.
Why subprocess.call () is showing error in linux? Question: Let us consider Linux platform where I need to execute a program called smart.exe which uses input.dat file. Both the files are placed in the same directory with each file having the same file permission 777. Now if I run the following command in the terminal window smart.exe is fully executed without any error. $./smart.exe input.dat On the other hand, if I use the following python script called my_script.py placed in the same directory, then I get an error. my_script.py has the following code: #!/usr/bin/python import os, subprocess exit_code = subprocess.call("./smart.exe input.dat", shell = False) The error is as follows: File "my_script.py", line 4, in <module> exit_code = subprocess.call("./smart.exe input.dat", shell = False) File "/usr/lib64/python2.6/subprocess.py", line 478, in call p = Popen(*popenargs, **kwargs) File "/usr/lib64/python2.6/subprocess.py", line 642, in __init__ errread, errwrite) File "/usr/lib64/python2.6/subprocess.py", line 1234, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory Can someone please tell me why this is happening. Please note that the smart.exe should take around 10 sec to fully complete. This may be a clue for the problem. Please also advise if there is any other way to run smart.exe from my_script.py. Your solution is much appreciated! Answer: You should decide if you want shell support or not. If you want the shell to be used (which is not necessary here), you should use `exit_code = subprocess.call("./smart.exe input.dat", shell=True)`. Then the shell interprets your command line. If you don't want it (as you don't need it and want to avoid unnecessary complexity), you should do `exit_code = subprocess.call(["./smart.exe", "input.dat"], shell=False)`. (And there is no point naming your binarys `.exe` under Linux.)
Python: how to create a submatrix discretizing a circle? Question: In a 2D square grid (matrix) full of `zeros`, I need to create a submatrix full of `ones`, with the shape of this submatrix being as close as possible to a circle. I know a circle cannot be precisely represented when you work with cells or pixels, therefore I aim at a discretized circle. The best thing I could come up with was this code, which produces **square submatrices** (the blue square in the image below): from __future__ import division import numpy import matplotlib.pyplot as plt import matplotlib.colors as mc import random import os import math n=101 #Grid size empty_lattice=numpy.zeros((n,n)) #The empty 2D grid x=int(numpy.random.uniform(0,n-1)) #X coord. top left corner y=int(numpy.random.uniform(0,n-1)) #Y coord. top left corner side=int(numpy.random.uniform(15,n)) #Side of the square approximating the circle max_y=n-y #Checks the distance between the y of the submatrix origin and the matrix vertical boundary max_x=n-x #Checks the distance between the x of the submatrix origin and the matrix horizontal boundary max_width=0 #Initializes a maximum width for the loading submatrix if max_y<max_x: #This assigns the minimum value between max_y and max_x to max_width, so that the submatrix is always a square max_width=max_y else: max_width=max_x if side>max_width: for i in range(0,max_width): for j in range(0, max_width): empty_lattice[x+i][y+j]=1 else: for i in range(0, side): for j in range(0, side): empty_lattice[x+i][y+j]=1 Now, visually this translates into the following image, but as you know there is a noticeable difference between the blue square and the inscribed circle in terms of area: [![enter image description here](http://i.stack.imgur.com/kmeWz.png)](http://i.stack.imgur.com/kmeWz.png) **My question:** how could I amend my code in order to be able to "smooth" the corners of my squares so that something which resembles a circle appears? **EDIT** The circles should be drawn even if they do not entirely reside within the grid boundaries (look at the image). Answer: This function fills in a circle of 1s that looks pretty good. def fill_cell(cell, corner, rad): m, n = cell.shape ctr = corner[0]+m/2, corner[1]+n/2 x = np.arange(m) - ctr[0] y = np.arange(n) - ctr[1] X,Y = np.meshgrid(x, y, order='ij') # could try order='xy' Z = ((X**2 + Y**2)<= rad**2).astype(cell.dtype) return Z empty_lattice[:] = fill_cell(empty_lattice, (x,y),side/2) Position in `empty_lattice` is not right - because of a difference in how you are defining the `x,y` coordinates and my assumptions, but I think you can sort that out. Radius looks good, though it might be off by an integer. To fill in multiple circles, you could iterate over the `x,y` values, and assign lattice values for a slice (view) xyslice = slice(x,15), slice(y,15) empty_lattice[xyslice] = fill_cell(empty_lattice[xyslice],...) For overlapping circles I'd look into some sort of logical assignment empty_lattice[xyslice] |= fill_cell(...)
Python using classmethod for multiple constructors Question: I have been struggling trying to create multiple constructors with the classmethod decorator. There is an example in SO - [What is a clean, pythonic way to have multiple constructors in Python?](http://stackoverflow.com/questions/682504/what-is-a-clean-pythonic- way-to-have-multiple-constructors-in-python) (second answer) class Cheese(object): def __init__(self, num_holes=0): "defaults to a solid cheese" self.number_of_holes = num_holes @classmethod def random(cls): return cls(random(100)) @classmethod def slightly_holey(cls): return cls(random(33)) @classmethod def very_holey(cls): return cls(random(66, 100)) However this example is not very clear and the code does not work for me in python 3 when typing the commands given: gouda = Cheese() emmentaler = Cheese.random() leerdammer = Cheese.slightly_holey() giving - AttributeError: type object 'Cheese' has no attribute 'random' as this is one of the only examples I can find. Answer: `randint` should work: from random import randint class Cheese(object): def __init__(self, num_holes=0): "defaults to a solid cheese" self.number_of_holes = num_holes @classmethod def random(cls): return cls(randint(0, 100)) @classmethod def slightly_holey(cls): return cls(randint(0, 33)) @classmethod def very_holey(cls): return cls(randint(66, 100)) gouda = Cheese() emmentaler = Cheese.random() leerdammer = Cheese.slightly_holey() Now: >>> leerdammer.number_of_holes 11 >>> gouda.number_of_holes 0 >>> emmentaler.number_of_holes 95
Calling Popen in Python on a MAC - Error can not find file Question: When I try to shell out of my Python 3.51 program to run the Popen command I get the following errors. Yet when I copy the exact string I'm passing to Popen to the Terminal command line it works fine and opens the file in Adobe Reader which is my default app for the .pdf files. Here is the Code: > > finalCall = r'open /Users/gbarnabic/Documents/1111/combined.pdf' > print(finalCall) > pid_id = subprocess.Popen(finalCall).pid > Here is the error: > open /Users/gbarnabic/Documents/1111/combined.pdf Exception in Tkinter > callback Traceback (most recent call last): File > "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/**init**.py", > line 1549, in **call** return self.func(*args) File "pdfcomb2.py", line 212, > in change_dir self.openPDF(outFileName, pageNum) File "pdfcomb2.py", line > 426, in openPDF subprocess.run(finalCall) File > "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", > line 696, in run with Popen(*popenargs, **kwargs) as process: File > "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", > line 950, in **init** restore_signals, start_new_session) File > "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", > line 1544, in _execute_child raise child_exception_type(errno_num, err_msg) > FileNotFoundError: [Errno 2] No such file or directory: 'open > /Users/gb/Documents/1111/combined.pdf' Georges-MBP:filepicktest gb$ open > /Users/gb/Documents/1111/combined.pdf Georges-MBP:filepicktest gb$ Answer: With Popen you need to set `shell=True` to pass command as a string or split command in a list of arguments. Could be done with `shlex` import shlex import subprocess subprocess.Popen(shlex.split('open ....')) You could check example in documentation: <https://docs.python.org/2/library/subprocess.html#subprocess.Popen> So the error here means that Python try to run file with name `open /Users/gb/Documents/1111/combined.pdf`. Obviously it doesn't exist
Python 3.4 - Installing Kivy Error Question: I'm trying to install Kivy on Python 3.4 using the instructions here: <https://kivy.org/docs/installation/installation-windows.html> I'm on the installing dependencies step, where it gives me this error: <http://prntscr.com/a5rk5k> Initially I tried just going ahead to the last step (python -m pip install kivy) and it looked like it worked fine, but then I tried import kivy in a Visual Studio project and it said "Unable to resolve "kivy"" Any ideas anyone? Keep in mind, I had Python 3.5 installed (which kivy does not work with) before now and set to default, but I changed the path in the command prompt. Answer: Something is not right with your kivy installation, use `python -m pip list` to check what packages are missing and (re)install them, one-by-one would be the best for debugging. And also you've pasted it wrong, so the `kivy.deps.gstreamer` was read as a separate comand and not a package for `pip` For simple installing of kivy just follow the install docs or if you don't mind having another folder or reinstalling python for new kivy&python try [KivyInstaller](https://github.com/KeyWeeUsr/KivyInstaller) which hopefully makes the whole process beginnerproof. You enter what you need in the beginning and then wait.
How to catch Python3 SocketIO error Question: I'm making a simple app that uses [socketIO_client](https://pypi.python.org/pypi/socketIO-client). I can't figure out how to "catch" the error when the connection fails. from socketIO_client import SocketIO, LoggingNamespace sock = SocketIO("localhost", 3000, LoggingNamespace) When the server is offline the following is printed in the console: WARNING:root:localhost:3000/socket.io [waiting for connection] HTTPConnectionPool(host='localhost', port=3000): Max retries exceeded with url: /socket.io/?EIO=3&transport=polling&t=1455989769325-0 (Caused by <class 'ConnectionRefusedError'>: [Errno 111] Connection refused) But an exception isn't raised that I can catch and I tried creating my own namespace class with `on_error`, `on_disconnect`, and `on_event`functions defined but none of them were executed. [This answer](http://stackoverflow.com/questions/29714822/python3-catch-errors-when- from-self-connectbadhost-6667) didn't work either. How can I "catch" this error so I can handle it properly? Alternatively, where can I find more detailed documentation? Thanks! Answer: The `LoggingMixin` of `socketIO_client` very explicitly turns the exception into a string and logs it; you'll have to subclass `SocketIO` and customise the loop that implements retrying things for a number of seconds. If you simply want to let the exception bubble up the first time it occurs (independent of the time-out): from socketIO_client import SocketIO, LoggingNamespace import socketIO_client.logs class MySocketIO(SocketIO): def _yield_warning_screen(self, seconds=None): yield from socketIO_client.logs._yield_elapsed_time(seconds) sock = MySocketIO("localhost", 3000, LoggingNamespace) For more complex behaviour like raising only after timing out, a more complex loop implementation in place of the transparent `yield from` is needed.
Python3: Popen communication Question: I'm a gamer, and a coder. In one of my game, minecraft, I need a server, so, with a friend, I bought one. But, this friend doesn't understand anything of coding and, in particular, of the Linux' bash, so he can't switch on/off our server, and he can't work on it. So I decied to make a program that help him with our server. The point is that the server is coded in java (it is a jar) and I can't acces to it without external commands. So, I reed lots of docs, and all of these docs said to me: Β«You must use subprocess!Β»!! So I used it, but I have a BIG problem in this Popen object Note before the problem: my program doesn't just switch on/off the server, it is a server with the relatives clients that allow to interract with the minecraft server and it uses some socket and threading libreries. So, the problem is: class getOutput(Thread): def __init__(self,outProc,connection): self.proc = outProc #My Popen object self.connection = connection #a socket object (my server biding) self.stop = False #A way to stop this thread is to put getOutput.stop = True Thread.__init__(self) def run(self): proc = self.proc conn = self.connection while True: if self.stop: #if getOutput.stop = True, stop the thread break out = proc.stdout.readlines() #My problem... for lines in out: print(out) #My output where the server is started conn.send(line) #send to client the output of the server def StartMcServ(): global proc, conn, outputManager, McServStarted #Because it's a server and I must launch the minecraft server more than once print('[Server/Info] Started McServ!') #Info is always useful logfile.log('[Server/Info] Started McServ!') #a librery that I created that log in a file, ignore this line proc = sh.Popen(JavaServ(),stdin=PIPE,stdout=PIPE,stderr=PIPE) #sh=subprocess, I did a from subprocess import PIPE,STDOUT ; import subprocess as sh because of the functions of subprocess have the same name that my libreries outputManager = getOutput(proc,conn) #My thread, that have the process and the connection outputManager.start() def PutInput(*,Input=None): #A function that put input in my server if Input and type(Input) == type(b'') and Input.endswith(b'\n'): proc.stdin.write(Input) so, **I really don't know** what is the problem, but the communication with the server doesn't work, I'm sooooo sad of it _P.S.: I dont put all the program or the main of it because of its lengh :D P.S. (2): I'm sorry if I did english mistakes, but I'm 13 and I'm learning it at school_ Answer: Sorry if I didnt anwer before, I just had a LOT of work, but I found where my problem comes. I want to have output of an Popen class in real time, so I do some while True: a = proc.stdout.readlines() #proc is my Popen class, my problem... for line in a: srv.send(bytes(a)) #srv is a socket class that I configure, I prefer to dont add all of this shit here if self.stop == True: break What I wanna do is that my readlines function blocks while proc gives an output, but it just sucks up my CPU, and I cry
How to run external Python script in Golang? Question: I would like to run an external Python script that gets 4 arguments. If I would like to run the Python script in cmd it would look like this: python Required\Python\screenshot.py-master\screenshot.py --nojs -thumb <http://google.com/> Required\Images\Screenshots\google.jpg So, I would like to run this command from Go. How could I implement this? Thanks. Answer: If examples from doc are not helpful, maybe this will make it easier for you. test.go: package main import ( "log" "os" "os/exec" ) func main() { log.Println(os.Args) if len(os.Args) == 1 { return } cmd := exec.Command(os.Args[1], os.Args[2:]...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr log.Println(cmd.Run()) } test.py: import sys print sys.argv usage: $ go run test.go python test.py 1 two 3 four 2016/02/20 21:45:42 [/tmp/go-build772613382/command-line-arguments/_obj/exe/test python test.py 1 two 3 four] ['test.py', '1', 'two', '3', 'four'] 2016/02/20 21:45:42 <nil>
Tuple looping (I think) Question: I have this code for a quiz but only the first question appears. I can answer the first question and the score will adjust accordingly however the next question never appears. I have tried researching looping through tuples and have played around with my code but to no avail. I am a Python newbie and would appreciate some help please. I have spent hours on it believe me. from tkinter import * root = Tk() root.title("End of year exam") score = 0 def submit_button_clicked(): global score global questions score = 0 if answer.get() == questions[0][1]: score+=1 else: score = score scoretxt.config(text = "Your score is: {}".format(str(score))) questions =[("What does 13 + 5 = ?","18"),("What does 12 + 8 = ?","20"),("What does 19 + 6 = ?","25"),("What does 17 + 15 = ?","32")] Label(root,text = "Question : ",bg ="light grey").grid(row = 0,column = 0, sticky = W) question=Label(root,bg = "light green",text= questions[1][0], width = 38) question.grid(row =1,column=0) Label(root,text = "Answer: ",bg = "light grey").grid(row = 2, column = 0, sticky = W) answer = Entry(root,bg ="white",width = 45, justify = CENTER) answer.grid(row = 3,column=0) scoretxt = Label(root,text ="Your score is:",bg = "light green", width = 38) scoretxt.grid(row = 10,column = 0, sticky = W) ### make a submit button Button(root,text= "Submit",bg = "light grey",command = submit_button_clicked).grid(row = 4,column = 0, sticky = W) root.mainloop() Answer: This should work. I added a `try` statement in the function `submit_button_clicked()` so if the question was the last one it would still update the score. If you read through the code you should see what I changed. Let me no if you don't understand it. Have a great day! from tkinter import * root = Tk() root.title("End of year exam") score = 0 questions =[("What does 13 + 5 = ?","18"),("What does 12 + 8 = ?","20"),("What does 19 + 6 = ?","25"),("What does 17 + 15 = ?","32")] current_question = 0 def submit_button_clicked(): global score global questions global current_question if answer.get() == questions[current_question][1]: score += 1 current_question += 1 try: question.config(text=questions[current_question][0]) except: pass answer.delete(0, 'end') scoretxt.config(text = "Your score is: {}".format(str(score))) Label(root,text = "Question : ",bg ="light grey").grid(row = 0,column = 0, sticky = W) question=Label(root,bg = "light green",text=questions[current_question][0], width = 38) question.grid(row =1,column=0) Label(root,text = "Answer: ",bg = "light grey").grid(row = 2, column = 0, sticky = W) answer = Entry(root,bg ="white",width = 45, justify = CENTER) answer.grid(row = 3,column=0) scoretxt = Label(root,text ="Your score is:",bg = "light green", width = 38) scoretxt.grid(row = 10,column = 0, sticky = W) ### make a submit button Button(root,text= "Submit",bg = "light grey",command = submit_button_clicked).grid(row = 4,column = 0, sticky = W) root.mainloop()
Make array from Requests.get in python Question: I Do the following : @app.route('/api/test/', methods=['GET']) def catalogue1(): cache = [] r = requests.get("http://192.168.198.140:5000/api/listdir") cache = r.content cache = ["vagrant.txt", "Securite_sociale.jpg"] ; when i try to print cache[0] i get "[" . How can i transform this result to an array . Answer: I know nothing about Flask but it looks like `r.content` is a string, yet to be de-serialized into a Python list. e.g. rather than cache = ["vagrant.txt", "Securite_sociale.jpg"] you have: cache = '["vagrant.txt", "Securite_sociale.jpg"]' I'm presuming it's JSON, in which case you could fix this with import json cache = json.loads(r.content) But I'm also presuming there's a built-in way to do this in Flask
How to convert a wav file -> bytes-like object? Question: I'm trying to programmatically analyse wav files with the audioop module of Python 3.5.1 to get channel, duration, sample rate, volumes etc. however I can find no documentation to describe how to convert a wav file to the 'fragment' parameter which must be a bytes-like object. Can anybody help? Answer: [file.read()](https://docs.python.org/3/library/functions.html#open) returns a `bytes` object, so if you're just trying to get the contents of a file as `bytes`, something like the following would suffice: with open(filename, 'rb') as fd: contents = fd.read() However, since you're working with [audioop](https://docs.python.org/3/library/audioop.html), what you need is raw _audio data_ , not raw file contents. Although uncompressed WAVs contain raw audio data, they also contain headers which tell you important parameters about the raw audio. Also, these headers must not be treated as raw audio. You probably want to use the [wave](https://docs.python.org/3/library/wave.html) module to parse WAV files and get to their raw audio data. A complete example that reverses the audio in a WAV file looks like this: import wave import audioop with wave.open('intput.wav') as fd: params = fd.getparams() frames = fd.readframes(1000000) # 1 million frames max print(params) frames = audioop.reverse(frames, params.sampwidth) with wave.open('output.wav', 'wb') as fd: fd.setparams(params) fd.writeframes(frames)
python kivy i don't see just an empty window Question: I made my first kivy program. When I run this app, then it appears empty window. This is the whole program. Python code: #!/usr/bin/env python3 # -*- coding: utf-8 -*- # from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty, StringProperty class Myfirstwidget(BoxLayout): def text(self, val): print('text input text is: {txt}'.format(txt=val)) class MainAPP(App): def build(self): return Myfirstwidget() if __name__ == '__main__': MainAPP().run() Kivy code `myfirstwidget.kv` : #:kivy 1.9.1 <Myfirstwidget>: Button: on_press: self.text(txt_inpt.text) TextInput: id: txt_inpt Answer: Change name of the kv file to `main.kv`. Its name must be like the name of the App class, but lower case, and without 'app'. More info here [docs](https://kivy.org/docs/guide/lang.html#how-to- load-kv).
Django, python syntax error while running makemigrations (DecimalField choices) Question: In my application, I'm calling API to create choices for DecimalField in models.py. # -*- coding: utf-8 -*- from django.db import models import re from suds.client import Client from datetime import datetime from django.utils import timezone class Allegro: def __init__(self): self.webapi_key = 'hidden key' self.country = 1 self.client = Client('https://webapi.allegro.pl/service.php?wsdl') self.client.options.cache.setduration(hours=1) self.starting_time = '24h' def get_categories(self): category_list = self.client.service.doGetCatsData( countryId=self.country, webapiKey=self.webapi_key ).catsList.item categories = [] for item in category_list: categories.append({'id': item.catId, 'name': item.catName, 'parent': item.catParent}) return categories # search for free only, with time fixed at 24h. User can set phrase and category only. def search(self, category, phrase): params = [{ 'item': ({'filterId': 'category', 'filterValueId': {'item': category}}, {'filterId': 'startingTime', 'filterValueId': {'item': self.starting_time}}, {'filterId': 'search', 'filterValueId': {'item': phrase}}) }] search_raw_result = self.client.service.doGetItemsList( countryId=self.country, webapiKey=self.webapi_key, filterOptions=params, ).itemsList.item search = [] for item in search_raw_result: search.append({'id': item.itemId, 'name': item.itemTitle, 'type': item.priceInfo.item[0].priceType, 'price': item.priceInfo.item[0].priceValue}) return search def choices(): choice_prep = Allegro() choice = choice_prep.get_categories() choice_list = [] add = "'" for item in choice: if item['parent'] == 0: item_name = add + item['name'] + add choice_list.append([item['id'], item_name]) return choice_list class FreeSearch(models.Model): a = choices() mail = models.CharField(verbose_name='mail', max_length=100) phrase = models.CharField(verbose_name='phrase', max_length=150) category = models.DecimalField(verbose_name='category', max_digits=6, decimal_places=0, choices=a) end_date = models.DateTimeField(verbose_name="Data koΕ„cowa", blank=True) activation_key = models.CharField(max_length=40, blank=True) key_expires = models.DateTimeField(default=timezone.now) def __str__(self): return '%s, %s, %s' % (self.mail, self.phrase, self.category) class Meta: verbose_name = "Wyszukanie" verbose_name = "Wyszukania" Choices should be list of lists where are only two values, id which is decimal max 5 digits and name which contains category names in Allegro auction service. After calling python manage.py makemigrations in cmd following problem occurs: C:\Users\Dom\allewatcher>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python35\lib\site-packages\django\core\management\__init__.py", line 351, in execute_from_command_line utility.execute() File "C:\Python35\lib\site-packages\django\core\management\__init__.py", line 343, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python35\lib\site-packages\django\core\management\base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python35\lib\site-packages\django\core\management\base.py", line 445, in execute output = self.handle(*args, **options) File "C:\Python35\lib\site-packages\django\core\management\commands\makemigrat ions.py", line 63, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "C:\Python35\lib\site-packages\django\db\migrations\loader.py", line 47, in __init__ self.build_graph() File "C:\Python35\lib\site-packages\django\db\migrations\loader.py", line 176, in build_graph self.load_disk() File "C:\Python35\lib\site-packages\django\db\migrations\loader.py", line 102, in load_disk migration_module = import_module("%s.%s" % (module_name, migration_name)) File "C:\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 658, in exec_module File "<frozen importlib._bootstrap_external>", line 764, in get_code File "<frozen importlib._bootstrap_external>", line 724, in source_to_code File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "C:\Users\Dom\allewatcher\search\migrations\0001_initial.py", line 20 ('category', models.DecimalField(decimal_places=0, max_digits=6, verbose_nam e='category', choices=[[26013, Antyki i Sztuka], [98553, Bilety], [64477, Biuro i Reklama], [19732, BiΕΌuteria i Zegarki], [73973, Delikatesy], [11763, Dla Dziec i], [5, Dom i OgrΓ³d], [63757, Erotyka], [20585, Filmy], [8845, Fotografia], [9, Gry], [122640, Instrumenty], [6, Kolekcje], [2, Komputery], [122233, Konsole i a utomaty], [7, KsiΔ…ΕΌki i Komiksy], [3, Motoryzacja], [1, Muzyka], [20782, Nieruch omoΕ›ci], [1454, OdzieΕΌ, Obuwie, Dodatki], [16696, PrzemysΕ‚], [76593, RΔ™kodzieΕ‚o] , [10, RTV i AGD], [3919, Sport i Turystyka], [122332, SprzΔ™t estradowy, studyjn y i DJ-ski], [4, Telefony i Akcesoria], [1429, Uroda], [55067, Wakacje], [121882 , Zdrowie]])), ^ SyntaxError: invalid syntax I also don't know why in error description there's no quotation marks added by add variable in choices function. # -*- coding: utf-8 -*- from **future** import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='FreeSearch', fields=[ ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)), ('mail', models.CharField(max_length=100, verbose_name='mail')), ('phrase', models.CharField(max_length=150, verbose_name='phrase')), ('category', models.DecimalField(decimal_places=0, max_digits=6, verbose_name='category', choices=[[26013, Antyki i Sztuka], [98553, Bilety], [64477, Biuro i Reklama], [19732, BiΕΌuteria i Zegarki], [73973, Delikatesy], [11763, Dla Dzieci], [5, Dom i OgrΓ³d], [63757, Erotyka], [20585, Filmy], [8845, Fotografia], [9, Gry], [122640, Instrumenty], [6, Kolekcje], [2, Komputery], [122233, Konsole i automaty], [7, KsiΔ…ΕΌki i Komiksy], [3, Motoryzacja], [1, Muzyka], [20782, NieruchomoΕ›ci], [1454, OdzieΕΌ, Obuwie, Dodatki], [16696, PrzemysΕ‚], [76593, RΔ™kodzieΕ‚o], [10, RTV i AGD], [3919, Sport i Turystyka], [122332, SprzΔ™t estradowy, studyjny i DJ-ski], [4, Telefony i Akcesoria], [1429, Uroda], [55067, Wakacje], [121882, Zdrowie]])), ('end_date', models.DateTimeField(blank=True, verbose_name='Data koΕ„cowa')), ('activation_key', models.CharField(max_length=40, blank=True)), ('key_expires', models.DateTimeField(default=django.utils.timezone.now)), ], options={ 'verbose_name': 'Wyszukania', }, ), ] Answer: The problems seems to be in this item: OdzieΕΌ, Obuwie, Dodatki You have a '**,** ' sign there which causes syntax error - this value is put directly into `0001_initial.py` file and then makes impression that list item has 4 items instead of two. To fix it just remove comma from it's value or just escape it somehow (for example by using HTML entity `&#44;` \- but it depends on how you are using it further) * * * **EDIT** Although commas cause problem directly it seems that issue lays deeper. You migration's code's strings were generated without aphostrophes what causes the problem. I have checked your code - I have created app, copied your code and run python manage.py makemigrations stack _stack is name of my application BTW_ String have been generated with aphostrophes ('category', models.DecimalField(choices=[[26013, "'Antyki i Sztuka'"], [98553, "'Bilety'"], [64477, "'Biuro i Reklama'"], [19732, "'Bi\u017cuteria i Zegarki'"], [73973, "'Delikatesy'"], [11763, "'Dla Dzieci'"], [5, "'Dom i Ogr\xf3d'"], [63757, "'Erotyka'"], [20585, "'Filmy'"], [8845, "'Fotografia'"], [9, "'Gry'"], [122640, "'Instrumenty'"], [6, "'Kolekcje'"], [2, "'Komputery'"], [122233, "'Konsole i automaty'"], [7, "'Ksi\u0105\u017cki i Komiksy'"], [3, "'Motoryzacja'"], [1, "'Muzyka'"], [20782, "'Nieruchomo\u015bci'"], [1454, "'Odzie\u017c, Obuwie, Dodatki'"], [16696, "'Przemys\u0142'"], [76593, "'R\u0119kodzie\u0142o'"], [10, "'RTV i AGD'"], [3919, "'Sport i Turystyka'"], [122332, "'Sprz\u0119t estradowy, studyjny i DJ-ski'"], [4, "'Telefony i Akcesoria'"], [1429, "'Uroda'"], [55067, "'Wakacje'"], [121882, "'Zdrowie'"]], decimal_places=0, max_digits=6, verbose_name=b'category')), If it is possible I recommend you to delete all files in **your_application/migrations** (avoiding delete `__init__.py`!) and then try to recreate migration by using standard `makemigrations` command. I have been using Django in 1.9.2 version, suds 0.4 and Python 2.7
Django M2MFields 'through' widgets Question: Are there exists any examples of Django widgets which can be useful for ManyToManyFields with 'through' attributes? For example, i have these models (got the source from django documentation): from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): # __unicode__ on Python 2 return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): # __unicode__ on Python 2 return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) Obvisously, standart ModelMultipleChoiceField won't work here. I need to populate 'date_joined' , and 'invite_reason' while adding. Which is the simpliest way to achieve this? Answer: This is a bit too complex for a simple widget. I can't even imagine how it would look like. You will have to use [inline formsets](https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#inline- formsets) for that purpose. This should give something like this: from django.forms import inlineformset_factory MembershipFormSet = inlineformset_factory(Group, Membership, fields=( 'person', 'date_joined', 'invite_reason')) group = Group.objects.get(pk=group_id) formset = MembershipFormSet(instance=group) Within `django.contrib.admin`, you can use inlines with [InlineModelAdmin](https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin).
ImportError: Could not import the Python Imaging Library (PIL) required to load image files Question: I am trying to run the average.py program in the facemorpher 1.0.1 python package. I have created a virtual environment that has openCV installed with homebrew, python 2.7 installed in homebrew, and executable `frameworkpython` that makes a framework build of python inside the virtual environment `cv`. running the average program currently gives me this output. (cv) Francess-MacBook-Pro-2:face_morpher Megan$ frameworkpython facemorpher/averager.py --images=IMFDB_final/Ali/HelloBrother/images --out=average.png Traceback (most recent call last): File "facemorpher/averager.py", line 94, in <module> args['--out'], args['--plot']) File "facemorpher/averager.py", line 61, in averager img, points = load_image_points(path, size) File "facemorpher/averager.py", line 46, in load_image_points img = scipy.ndimage.imread(path)[..., :3] File "/Users/Megan/.virtualenvs/cv/lib/python2.7/site-packages/scipy/ndimage/io.py", line 25, in imread raise ImportError("Could not import the Python Imaging Library (PIL)" ImportError: Could not import the Python Imaging Library (PIL) required to load image files. Please refer to http://pypi.python.org/pypi/PIL/ for installation instructions. Can I install Pillow to fix this error, and where should i install my PIL or Pillow path to fix this? Answer: resolved by doing `pip install Pillow` in the virtual env folder. now back to error found at [OpenCV facemorpher 1.0.1 error: no image output, missing library?](http://stackoverflow.com/questions/35532101/opencv- facemorpher-1-0-1-error-no-image-output-missing-library)
Finding maximum of a correlation in Python Question: I have to find the parameters theta such that: [![enter image description here](http://i.stack.imgur.com/rtJnf.gif)](http://i.stack.imgur.com/rtJnf.gif) where r is a known vector and phi is a function that uses the parameters from the previous iteration. How can I implement that optimization in Python? import numpy as np import scipy.optimize as optimize # Gaussian function def gaussian(x, mu, sig): return (1/(sig*np.sqrt(2*np.pi)))*np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.))) # My observed data is a sum of two gaussians step = 0.005 numSignals = 2 x = np.arange(0, 3+step, step) w = np.array([0.4,0.8]) mean = np.array([0.5,0.9]) sigma = np.array([0.1,0.2]) noise = 0.05*np.random.normal(0,1,len(x)) y = w[0]*gaussian(x, mean[0], sigma[0]) + w[1]*gaussian(x, mean[1], sigma[1]) #Initialization, I assume my model is a sum of weighted gaussians and it is empty at the beginning model = 0 i = 0 _mean = np.zeros(numSignals) _sigma = np.zeros(numSignals) _w = np.zeros(numSignals) while i<numSignals: r = y - model # Optimization step J = lambda c: -abs(np.dot(r,gaussian(x,c[0],c[1])))**2 res = optimize.minimize(J, (0.2, 0.5), method='TNC', tol=1e-6) _mean[i] = res.x[0] _sigma[i] = res.x[1] _w[i] = np.dot(gaussian(x,_mean[i],_sigma[i]),r)/np.dot(gaussian(x,_mean[i],_sigma[i]),gaussian(x,_mean[i],_sigma[i])) model = model + _w[i]*gaussian(x,_mean[i],_sigma[i]) print _w[i],_mean[i],_sigma[i] i += 1 this is an initialization algorithm to find values for mean, sigma and weights of a signal, that is a sum of two gaussian functions. After the initialization I use another algorithm that works, but this one gets wrong values (even using as initial values for optimize the real values instead of 0.2 and 0.5 I get 0.51 and 0.54 for mean and 2.2e-6 and 2.4e-6 for sigma). I try to optimize the correlation between a residual (r) and the base functions (gaussian functions) to find the estimated values (_w,_mean,_sigma) Edit 1: I just try to find the parameters (w,mean and sigma) that maximize the expression above (or minimize the negative in my code) so I find estimations to initialize another algorithm. But despite using the real values as initial values in the minimize method from scipy I get wrong values for mean and sigma. Edit 2: gaussian function works perfectly... so before commenting, test the code you refer to, and don't try to humiliate people Answer: I think there's a conceptual, SciPy-unrelated problem with your approach. If I understand you correctly, you have data (`y` in your code) that can be explained as the sum of two (unknown) Gaussians. (I.e., `mean` and `sigma` are only given here because you calculate `y` for the sake of example. Usually, `y` would be the result of some measurement.) You now try to find the parameters of the two Gaussians by first fitting one Gaussian to the data, and then fitting another Gaussian to the difference between that first fit and the data (the residue, in your code `r` in the second iteration). This might approximately give you the underlying Gaussians if one of them was clearly dominating the data. However, in the data you provided, both the influence of both underlying Gaussians has a similar order of magnitude. Thus, in the first iteration, you'll get one Gaussian that alone best approximates the data. Because it has to 'cover' the effect of _both_ underlying Gaussians combined, it cannot be too similar to a single one of them. Trying to then approximate the residue with another (also dissimilar) Gaussian won't rescue you from that. If you want to get satisfying results, you'll have to fit all parameters of your two-Gaussian-model in one go.
Positioning Button in Python Question: Ive researched my question here, [Python Tkinter buttons](http://stackoverflow.com/questions/29370357/python-tkinter-buttons), and here, [Setting the position on a button in Python?](http://stackoverflow.com/questions/10927234/setting-the-position-on- a-button-in-python) Sadly, I'm still stuck. I'm making a game inspired by the game angry red button. I'm attempting to have a second button placed next to a first one, which python autonomatically places in the top center of the screen. When I run the code pasted below, no additional button appears. See screen shot below, [Screen Shot ](http://i.stack.imgur.com/OYtKu.png) Here is my attempt using pack (seen toward the bottom of the code). from tkinter import * s = 0 def kill(): cnv.color('red') def talk(): global s if s == 0: cnv.create_text(100,20,text='why, hello there!', font='Times') s += 1 elif s == 1: cnv.create_text(100,40,text='my name is Phill!', font='Courier') s += 1 elif s == 2: cnv.create_text(100,60,text='why are you clicking me?', font='Times') s += 1 elif s == 3: cnv.create_text(100,80,text='that kinda hurts...', font='Arial') s += 1 elif s == 4: cnv.create_text(100,100,text='ok, what do you want?', font='Courier') s += 1 elif s == 5: cnv.create_text(145,130,text='seriously, stop that!', font=('Arial',28), fill='red') s += 1 elif s == 6: cnv.create_text(100,160,text='...', font='Times') s += 1 elif s == 7: cnv.create_text(100,180,text='You know what?', font='Courier') s += 1 elif s == 8: cnv.create_text(100,200,text="You wanna go?", font='Courier') s += 1 elif s == 9: cnv.create_text(105,220,text='OK!!!', font=('Arial',28), fill='red') v = Button(tk, text="Death",command=kill) v.pack(side="right") l = Button(tk, text="Death",command=kill) l.pack(side="left") s += 1 tk = Tk() btn = Button(tk, text="Phill",command=talk,width=10,height=10) btn.pack() cnv = Canvas(tk, width=1000, height=700) cnv.pack() Any ideas how to make this work with pack, or perhaps with grid? Answer: use `.pack(side=LEFT)` for example, or whatever side you want. I suggest experimenting with this.
Pip installer error Question: I am trying to install `PyAutoGUI` but every time i try i get the error message C:\WINDOWS\system32>C:\Users\nicho\AppData\Local\Programs\Python\Python35-32\Scripts\pip install PyAutoGUI Collecting PyAutoGUI Using cached PyAutoGUI-0.9.33.zip Collecting pymsgbox (from PyAutoGUI) Using cached PyMsgBox-1.0.3.zip Collecting PyTweening>=1.0.1 (from PyAutoGUI) Using cached PyTweening-1.0.3.zip Collecting Pillow (from PyAutoGUI) Using cached Pillow-3.1.1-cp35-none-win32.whl Collecting pyscreeze (from PyAutoGUI) Using cached PyScreeze-0.1.8.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\nicho\AppData\Local\Temp\pip-build-jt08_ns2\pyscreeze\setup.py", line 6, in <module> version=__import__('pyscreeze').__version__, File "c:\users\nicho\appdata\local\temp\pip-build-jt08_ns2\pyscreeze\pyscreeze\__init__.py", line 21, in <module> from PIL import Image ImportError: No module named 'PIL' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\nicho\AppData\Local\Temp\pip-build-jt08_ns2\pyscreeze Can anyone help me? Answer: You should install the `Python Image Library(PIL)`, using the command: sudo pip install PIL --allow-external PIL --allow-unverified PIL
Saving each result on a new line to a csv file, using python Question: I've been trying to create a csv file using python and save a new date on a new row. My intention is to replicate the shell output(shown below), in csv file. However the output I get is only saving the last result and iterating through one date(shown in the csv output below). I'm sure there's an error in my approach but I'm stumped. thanks in advance. from datetime import timedelta, date import csv def daterange(start_date, end_date): for n in range(int ((end_date - start_date).days)): yield start_date + timedelta(n) start_date = date(2014, 12, 28) end_date = date(2015, 1, 10) for single_date in daterange(start_date, end_date): new_date = single_date.strftime("%Y-%m-%d") with open('output.csv', 'wb') as f: writer = csv.writer(f) writer.writerows(new_date) [shell output](http://i.stack.imgur.com/qg6Le.png) [csv output](http://i.stack.imgur.com/bHTHg.png) Answer: When you open a file with `w` mode, python truncates the file. You should open it only once: with open('output.csv', 'wb') as f: writer = csv.writer(f) for single_date in daterange(start_date, end_date): new_date = single_date.strftime("%Y-%m-%d") writer.writerow(new_date)
Pip Django Version Different than Python's Question: I am currently trying to complete the Django tutorial found here: <https://docs.djangoproject.com/en/1.9/intro/tutorial01/> However, when I try to run `python manage.py migrate` I get the error `Unknown command: 'migrate'`. I looked this up and discovered that this means I am using a version of Django that doesn't support migrate. So I ran `python -c "import django; print(django.get_version())"` to see what version of Django Python was using. Turns out it's 1.6.1. This doesn't make sense though because when I do `pip list` I get Django (1.9.2). If I look in my settings.py file it even says "Generated by 'django-admin startproject' using Django 1.9.1." Does anyone know why Python is using a different version of Django than is installed using pip? Answer: It's highly recommended that you run Django in a virtual environment as it will make managing Django a lot easier, and you don't want to mess with the python version on your system. use `virtualenv -p /usr/bin/python3.5 <path/to/new/virtualenv/>` to use virtualenv with a specific python version. Then `pip install Django` to get the latest version of Django. **Edit:** Don't forget that when you're messing with Django settings and files, that you need to activate your virtualenv in your command prompt. Type `source myprojectenv/bin/activate` and your prompt should change to `(myprojectenv)user@host:~/myproject$`
What is "empty" expression in django rest_framework.serializers.BaseSerializer Question: Here is the `__init__` method in django's `rest_framework.serializers.BaseSerializer` class. def __init__(self, instance=None, data=empty, **kwargs): self.instance = instance if data is not empty: self.initial_data = data self.partial = kwargs.pop('partial', False) self._context = kwargs.pop('context', {}) kwargs.pop('many', None) super(BaseSerializer, self).__init__(**kwargs) By default `data=empty`. `empty` is not imported or defined anywhere in `serializers.py`. And I never saw this before in python (Im still beginner tho). How does `empty` work here? From the first look to me it seems that `empty` is an undefined variable here. Answer: `empty` is defined in `rest_framework.fields`: <https://github.com/tomchristie/django-rest- framework/blob/master/rest_framework/fields.py#L39>. It can be used in the place that you mention because it's being imported at line 46: <https://github.com/tomchristie/django-rest- framework/blob/master/rest_framework/serializers.py#L46>.
Year over year matplotlib with legend Question: I'm trying to mimic this graph from Excel [![enter image description here](http://i.stack.imgur.com/P2WLQ.png)](http://i.stack.imgur.com/P2WLQ.png) in python and matplotlib. The dataframe (by_year) looks below with a multiindex of EDIT - Changed table to reflect that the rows are different Month 1 2 3 4 5 6 7 8 9 10 11 12 Year 2012 8 6 8 9 1 2 8 9 4 3 2 6 2013 5 6 2 9 6 2 8 9 4 3 2 6 2014 7 6 3 9 4 2 8 9 4 3 2 6 # create multiple plots on the page (i'm going to print this rather # than display live ax1 = plt.subplot2grid((3, 2), (0,0), colspan=2) ax2 = plt.subplot2grid((3, 2), (1,0)) # loop through the years (each row) and add to chart for idx, row in by_year.iterrows(): row_values = row.values.astype(int).tolist() ax1.bar(month_list, row_values) ax1.legend(str(idx)) Problem 1 - This runs with no errors, however i only get a single set of bars. Don't understand how to fix this. Graph looks like this: [![enter image description here](http://i.stack.imgur.com/oonbr.png)](http://i.stack.imgur.com/oonbr.png) EDIT - Problem is in the ax1.bar(month_list... line. It uses the same starting point for each row and hence the bars are on top of each other. The solution below by @GWW calculates the start position using idx. Which i would really name bar_start. Problem 2 - I can't find anywhere how to add that legend with the data under the table. I can try and create by simply displaying the dataframe (i think :) ) but does Matplotlib already have the functionality? Answer: This should get you started. You will still have to fiddle around with the table properties to make it look better. [![Example Plot](http://i.stack.imgur.com/Hsqt9.png)](http://i.stack.imgur.com/Hsqt9.png) months = [1,2,3,4,5,6,7,8,9,10,11,12] by_year = [ (2012, (8,6,8,9,1,2,8,9,4,3,2,6)), (2013, (5,6,2,9,6,2,8,9,4,3,2,6)), (2014, (7,6,3,9,4,2,8,9,4,3,2,6)), ] colors = ['r','g','b','y'] import pylab as plt fig, ax = plt.subplots(1,1, figsize=(8, 4)) #0.9 to leave a small space between groups of bars import numpy as NP N = 0.95 / (len(by_year)) cell_text = [] for i, (year, row) in enumerate(by_year): print i, year, row idx = NP.arange(0, len(months)) + N * i # * 0.8 to put a small gap between bars ax.bar(idx, row, color=colors[i], width=N * 0.8, label=year) cell_text.append(row) tbl = ax.table(cellText=cell_text, rowLabels=[x[0] for x in by_year], loc='bottom', colLabels=months) prop = tbl.properties() ax.set_xticks([]) lgd = ax.legend(loc='upper left', bbox_to_anchor=(1, 1.0)) fig.show()
Bigram Count using Spark (Python) producing strange output Question: I am trying to do a bigram count using Spark, Python API. I am getting strange output. Multiple lines of: generator object genexpr at 0x11aab40 This is my code: from pyspark import SparkConf, SparkContext import string conf = SparkConf().setMaster('local').setAppName('BigramCount') sc = SparkContext(conf = conf) RDDvar = sc.textFile("file:///home/cloudera/Desktop/smallTest.txt") sentences = RDDvar.flatMap(lambda line: line.split(".")) words = sentences.flatMap(lambda line: line.split(" ")) bigrams = words.flatMap(lambda x:[((x[i],x[i+1]) for i in range(0,len(x)-1))]) result = bigrams.map(lambda bigram: bigram, 1) aggreg1 = result.reduceByKey(lambda a, b: a+b) result.saveAsTextFile("file:///home/cloudera/bigram_out") What is going wrong? Answer: Python seems to be storing the generator expressions as variables in the line: bigrams = words.flatMap(lambda x:[((x[i],x[i+1]) for i in range(0,len(x)-1))]) You probably just need to replace this with something like: bigrams = words.flatMap( lambda x:list((x[i],x[i+1]) for i in range(0,len(x)-1)) ) see [here](http://stackoverflow.com/questions/5164642/python-print-a- generator-expression) for a more in-depth explanation.
Tell compiler about a local it doesn't know about? Question: I have a function called `let`, which modifies the calling namespace to insert a new variable. def let(**nameValuePair): from inspect import stack name, value = nameValuePair.items()[0] stack()[1][0].f_locals[name] = value return value The idea is it allows you insert assignment statements anywhere you want, even where assignment statements aren't typically allowed in Python (albeit, it requires 5 extra characters for `let()`. This works perfectly when called from the global namespace. >>> let(outside = 'World') >>> print(outside) World This fails with the error `NameError: global name 'hello' is not defined`: >>> def breaker(): ... let(hello = 'World') ... print(hello) ... >>> breaker() You might jump to the conclusion that the issue is with my `let` function. It is not - my function performs perfectly. To show you that: >>> def fine(): ... let(another = 'World') ... print(locals()['another']) ... >>> fine() World The issue actually comes from when the Python interpreter compiles `breaker`. To demonstrate, I'll create another function which does the same thing as `breaker`, but using an ordinary assignment instead of `let`, and then I'll decompile both with `dis`. >>> def normal(): ... hello = 'World' ... print(hello) ... >>> normal() World >>> from dis import dis >>> print(dis(normal)) 0 LOAD_CONST 1 ('World') 3 STORE_FAST 0 (hello) 6 LOAD_FAST 0 (hello) 9 PRINT_ITEM 10 PRINT_NEWLINE 11 LOAD_CONST 0 (None) 14 RETURN_VALUE >>> print(dis(breaker)) 0 LOAD_GLOBAL 0 (let) 3 LOAD_CONST 1 ('hello') 6 LOAD_CONST 2 ('World') 9 CALL_FUNCTION 256 12 POP_TOP 13 LOAD_GLOBAL 2 (hello) # <= This is the real problem. 16 PRINT_ITEM 17 PRINT_NEWLINE 18 LOAD_CONST 0 (None) 19 RETURN_VALUE The problem is, the compiler is looking over `breaker`, doesn't see that `hello` gets assigned anywhere in the local scope, and so assumes that it must be a global variable. What can I do about this? When my function gets called, could I, for example, swap out the problematic line that I indicated and replace it with: LOAD_GLOBAL 1 (locals) CALL_FUNCTION 0 LOAD_CONST 1 ('hello') # Or whatever the name of the variable is BINARY_SUBSCR I know that I could quickly fix the immediate problem by simply storing the variable in the global scope, but that could lead to lots of subtle bugs. To name a few: 1. Global variables get written over. 2. Objects might persist in memory for far longer than intended. 3. Something that would be a typo otherwise, is instead valid. (admittedly this one seems quite unlikely). ... Actually, if I can change the compiled code, I could even add a `STORE_GLOBAL` or `DELETE_GLOBAL` after `RETURN_VALUE`, perhaps? Cache the former global variable elsewhere or something? Answer: The documentation for `locals()` notes the following: > **Note** The contents of this dictionary should not be modified; changes may > not affect the values of local and free variables used by the interpreter. I checked and don't see an explicit note in the `inspect` docs about `f_locals` but I don't see why it would be any different.
Python multiple pattern matching from a log file Question: I've got a log file with following format: 2016-02-18 10:01:45.423 [a-b] [one two three] [2126] 2016-02-18 10:01:45.623 [x-y] [one two three four] [123] 2016-02-18 10:01:45.823 [z-w] [one two three four-five] [0] I'd like to split the fields into variables so that e.g. for the first line: Field1 = 2016-02-18 Field2 = 10:01:45.423 Field3 = a-b Field4 = one two three Field5 = 2126 I'm trying to figure out how to get the two first fields as I managed to get the last 3 with the following: >>> import re >>> data = """2016-02-18 10:01:45.423 [a-b] [one two three] [2126]""" >>> PATTERN = re.compile(r'''\[(.*?)\]''') >>> print (PATTERN.split(data)[1::2]) ['a-b', 'one two three', '2126'] >>> The content of the "Field4" may vary in length and the separator between Field2 and Field3 is 2x white space. How do I change the code above to capture each field? Thanks! Answer: It can be done without regular expression also: with open("your_log.log") as f: for x in f: fields = x.strip().split() field1, filed2, field3, field4, field5 = fields[0], fields[1], fields[2], " ".join(fields[3:-1]), fields[-1]
Error in generating colored cmy qr image Question: I have to generate 3 QR images with background color cyan, magenta and yellow and merge them to generate CMY colored QR as shown in image 1. Now after generating images, to merge them by using cv2.merge,converting these into gray image and then merging operation gives me image 2 instead of image 1 (Ignore the color of finder patterns) I am using Python 2.7, Open CV 3.0. Unable to figure out what I am doing wrong. Please help me to get out of this. Thanks in advance. [![Snapshot1](http://i.stack.imgur.com/Ju9WV.png)](http://i.stack.imgur.com/Ju9WV.png) [![Snapshot2](http://i.stack.imgur.com/eeXEJ.png)](http://i.stack.imgur.com/eeXEJ.png) Code I am using is given below: import pyqrcode import cv2 bigcode = pyqrcode.create('When I say it is you', error='L', version=2,mode='binary') bigcode.png('new1.png', scale=6, module_color=[0, 0, 0], background = [0xff,0xff,0]) bigcode1 = pyqrcode.create('peace that triumphant over war ', error='L', version=2, mode='binary') bigcode1.png('new2.png', scale=6, module_color=[0, 0, 0], background = [0xff,0,0xff]) bigcode2 = pyqrcode.create('Love that conquers hate ', error='L', version=2, mode='binary') bigcode2.png('new3.png', scale=6, module_color=[0, 0, 0], background = [0,0xff,0xff]) bigcode.show() b = bigcode1.show() c = bigcode2.show() img1 = cv2.imread('C:/New folder (2)/new1.png') img2 = cv2.imread('C:/New folder (2)/new2.png') img3 = cv2.imread('C:/New folder (2)/new3.png') gray_img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) cv2.imshow('k1',gray_img1) gray_img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) gray_img3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY) k = cv2.merge([gray_img1,gray_img2,gray_img3]) cv2.imshow('k',k) cv2.imwrite('k.png',k) cv2.waitKey(0) Answer: Instead of generating c,m,y,k colored QR, try to convert rgb in cmyk colorspace. this would help in generating correct result.
Detect URLs changes in python Question: I need to detect urls changes when shops have a firesale on, I'm using requests lib with no luck even when a firesale is on it still returns `No deals on today` and check value is still `[u'http:', u'', u'www.dealwebsite.co', u'Electroshop']` primary shop url `http://www.dealwebsite.com/coolshop` if firesale deals are on the primary shop url changes to this like a redirect `http://www.dealwebsite.com/coolshop/firesale` import requests headers = { 'User-Agent': 'Mozilla\/5.0 (Windows NT 6.1; WOW64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/45.0.2454.101 Safari\/537.36' } select_shop = 'Electroshop' url = 'http://www.dealwebsite.co/' + select_shop r = requests.get(url, headers=headers, timeout=3) check = r.url.split('/') if len(check) != 5: print 'No deals on today' exit() else: print 'Firesale Deals on NOW!' Answer: It seems that you can [track redirection](http://docs.python- requests.org/en/master/user/quickstart/#redirection-and-history). For example: requests.get(url, headers=headers, timeout=3, allows_redirect=True) >>> r.url 'url' >>> r.status_code 200 >>> r.history [<Response [301]>] # means that there was a redirect on the way Actually, you could use just a HEAD request to verify the behavior - only if you don't need to parse the result (as a HEAD response body is empty). >>> r = requests.head(url, headers=headers, timeout=3, allow_redirects=True) >>> r.url '..something...' >>> r.history [<Response [301]>] In theory, you could also prevent the redirect completely, and check for the response status. >>> r = requests.get(url, headers=headers, timeout=3, allow_redirects=False) >>> r.status_code 301 >>> r.history [] Now, 301 might mean a redirect to firesale or somewhere else - you don't know. **UPDATE 1** An example with periscope.tv (it seems that the OP has issues with such a website): >>> example = requests.get("https://periscope.tv/couchmode", allow_redirects=True) >>> example.status_code 200 >>> example.history [<Response [307]>] >>> example.history[0].url u'https://periscope.tv/couchmode' >>> example.url u'https://periscope.tv/w/aZwcYHNlcnZpY2V8MURYeHl6WUFaUWdLTerSfgniRKoRgIPbfxxlbAGofYQNBd8WZZTEelJ0KavI?mode=couch' As you can see, example.history[0].url tells you what was the URL that returned a 307 temporary redirect.
Path in the PYTHONPATH not in django path Question: I am writing a web based app based on python and django. I have a source code folder containing **LIBS** directory that has a file named **utils.py**. When I want to install my app a new line is added to ~/.profile file like **export PYTHONPATH=$PYTHONPATH:/home/test/src/LIBS** (The path is added based on the installation path) When I run the below code in the interpreter the path is OK: import sys sys.path > ['', '/usr/lib/python2.7', '/home/test/src/LIBS', > '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', > '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', > '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist- > packages', '/usr/lib/pymodules/python2.7'] Unfortunately, when i want to load the home page of my app the line that imports **utils** raises an exception [![enter image description here](http://i.stack.imgur.com/dPayE.png)](http://i.stack.imgur.com/dPayE.png) What i do wrong? Thanks in advanced. Answer: Your ~/.profile only adds the dir to the PYTHONPATH in the current shell environment. It's not globally available. When django loads, it uses the wsgi.py and another project path. The easiest way to add a globally available path is to add a .pth file. It should be in your python dist-packages directory (depends on the OS): $ sudo nano /usr/lib/python2.7/dist-packages/ /home/test/src/LIBS And save the file. Now the app will be available for all python instances on your machine. If you want to add this path only to a specific django project, in the wsgi.py add: import sys sys.path.append("/home/test/src/LIBS")
StopIteration error in python Question: I am using `wolframalpha` and `wit.ai` together and i am trying to build that `wolframalpha` fetch data from `wit.ai` audio instead of terminal text. My code is: #!/usr/bin/python import speech_recognition as sr import wolframalpha import sys r = sr.Recognizer() with sr.Microphone() as source: print("Say something!") audio = r.listen(source) WIT_AI_KEY = "NQYEITRO5GL2Q2MZFIJE4UHWVNQEUROW" try: print("Wit.ai thinks you said " + r.recognize_wit(audio, key=WIT_AI_KEY)) except sr.UnknownValueError: print("Wit.ai could not understand audio") except sr.RequestError as e: print("Could not request results from Wit.ai service; {0}".format(e)) client = wolframalpha.Client('PR5756-H3EP749GGH') print(r.recognize_wit(audio, key=WIT_AI_KEY)) res = client.query(r.recognize_wit(audio, key=WIT_AI_KEY)) print(next(res.results).text) I am facing this error: MacBook-Air:Documents exepaul$ python ak.py 2016-02-22 23:05:04.429 Python[3003:122880] 23:05:04.428 WARNING: 140: This application, or a library it uses, is using the deprecated Carbon Component Manager for hosting Audio Units. Support for this will be removed in a future release. Also, this makes the host incompatible with version 3 audio units. Please transition to the API's in AudioComponent.h. Say something! Wit.ai thinks you said seven seven Traceback (most recent call last): File "ak.py", line 24, in <module> print(next(res.results).text) StopIteration How can I give data to wolframalpha api? Answer: `StopIteration` is raised when generator is exhausted and has no more values, it's totaly ok to get one. But you need to handle it yourself: try: print(next(res.results).text) except StopIteration: print("No more suggesstions.")
injecting variables into functions; python Question: I have a webdriver class that assumes there is only one driver. This is bad because it can't handle multiple pages at once. I want to make a decorator that will inject `self.driver` into any function decorated if it exists, if not it will allow any function to use the driver passed to it. I should be able to define and function as @get_driver def this_func(**kwargs): #I have access to 'driver' if I have self.driver or if a driver kwarg was given Here it is: import os, time, subprocess, random from functools import wraps from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.select import Select from pyvirtualdisplay import Display class get_driver(object): def __init__(self, func): self.func = func wraps(func)(self) def __call__(self, *args, **kwargs): try: kwargs.update({'driver': self.driver}) except: pass return_ = self.func(*args, **kwargs) return return_ class WebdriverChauffuer(object): def __init__(self, username=None, password=None, start_url=None): self.username = username self.password = password self.start_url = start_url @get_driver def source_code(self, **kwargs): return driver.page_source or None class FirefoxDriver(WebdriverChauffuer): def __init__(self, username=None, password=None, start_url=None, driver=None): super(FirefoxDriver, self).__init__(username=username, password=password, start_url=start_url) def start_driver(self): self.driver = webdriver.Firefox() I am getting a strange error that no args were given, even though I call `source_code` on an instance, which should give it self: In [1]: from my_scripting_library import * In [2]: d = FirefoxDriver() In [3]: d.start d.start_driver d.start_url In [3]: d.start_driver() In [4]: d.get('https://google.com') In [5]: d.source_code() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-7419cf5df019> in <module>() ----> 1 d.source_code() /home/cchilders/scripts/my_scripting_library/webdriver/general.pyc in __call__(self, *args, **kwargs) 24 except: 25 pass ---> 26 return_ = self.func(*args, **kwargs) 27 return return_ 28 TypeError: source_code() takes exactly 1 argument (0 given) There's no difference when I change the return to return_ = self.func(**kwargs) Why can't I call `source_code` anymore? Thank you EDIT: These drivers are to be used for purposes of course, here's an example: class HCCDriver(FirefoxDriver): def __init__(self, init=False): super(HCCDriver, self).__init__(start_url="https://hccadvisor.hccfl.edu") def main_page(self): self.get('https://www.hccfl.edu/hawknet.aspx') def login_webadvisor(self, username="cchilders", password="miley_cirus_is_great_singer", driver=None): self.webadvisor_driver = FirefoxDriver() webadvisor_driver.get(self.start_url) time.sleep(2) driver.access_link(search_text="Log In") driver.find_box_and_fill(search_text="LABELID_USER_NAME", value=username) driver.find_box_and_fill(search_text="CURR.PWD", value=password) driver.submit_form(search_text="SUBMIT") driver.access_link(search_text="Students") def login_email(self): self.start_driver() self.get("http://outlook.com/hawkmail.hccfl.edu") # WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(By.ID, 'ctl00_ContentPlaceHolder1_UsernameTextBox')) self.find_box_and_fill(search_text="ctl00_ContentPlaceHolder1_UsernameTextBox", value="[email protected]") self.find_box_and_fill(search_text="ctl00_ContentPlaceHolder1_PasswordTextBox", value="i_love_honey_booboo") time.sleep(2) self.submit_form("ctl00_ContentPlaceHolder1_SubmitButton") def login_myhcc(self): driver = FirefoxDriver() driver.get("https://hcc.instructure.com") time.sleep(5) find_box_and_fill('ctl00_ContentPlaceHolder1_UsernameTextBox', '[email protected]') driver.find_box_and_fill('ctl00_ContentPlawebadvisor_urlceHolder1_PasswordTextBox', 'if_evolution_was_real_americans_would_stop_worshipping_pres_candidates') driver.click_button('ctl00$ContentPlaceHolder1$SubmitButton') The point is, without a decorator, I foresaw every single function looking like: def this_func(self, driver=None): if not driver: try: driver = self.driver except: raise Exception('There is no driver my good sir') with the `driver=None` and try: driver = self.driver except: raise Exception('There is no driver good sir') parts being repetitive 20, 30 times, etc Answer: Because your decorator is implemented as a class rather than a function, your decorated `source_code` function is not being wrapped in a bound `method` descriptor, since this is done to functions, not classes. That means when you call `self.func`, no `self` argument is being passed in. But your `source_code` method expects a `self` argument, which results in the error `source_code() takes exactly 1 argument (0 given)` On more recent versions of Python 3 you should be getting `foo() missing 1 required positional argument: 'self'`. I'm not sure when they added that clarified message. The comments have given you some ideas about different approaches, but that explains your error.
PySide: QAbstractItemModel not talking to simple controls Question: Using PySide, I am trying to connect several data controls to data from a file that I read from disc. So I made a data model, derived from QAbstractItemModel. Should be trivial, right? But one problem that has me beaten is connecting QLineEdit and QTextEdit controls to show and allow editing of the data in the model. From examples such as the Simple Widget Mapper and the Combo Widget Mapper in the QT documentation, I believe I have to have a data model with one row, and a QWidgetMapper to connect the cells in that row to the edit controls. Here is a very cut-down program that shows the problem. The data model in this example returns the three strings x1, x2 and x3. The strings are changed from e.g. "First (1)" to "First (2)" by calling Update, i.e. by clicking the "Next" button. That is to simulate new values being read from a file or wherever. The main window has a couple of QLineEdits and a QTextEdit, which the mapper should link to the model data. But the data don't show up in the edit controls. To check the model, I added a QTableView. The data show up there alright, and update when "Next" is clicked, so it's not the data model. It's something between there and the edit controls. But I cannot see what I am not doing, that the widget mapper examples are doing. What am I doing wrong? Incidentally, going the other way doesn't work well either. If I add a setData() method to the model, and emit dataChanged, a change typed into the line edit gets to the Table. But even when that happens, the item disappears from the line edit. And after "Next" is clicked, this stops working for the QLineEdit and QTextEdit -- setData() no longer gets called. But if I edit in the table view, setData is still called. Here is the example code: #!/usr/bin/python import sys from PySide.QtCore import ( Qt, QAbstractItemModel,QModelIndex ) from PySide.QtGui import ( QApplication, QMainWindow, QPushButton, QWidget, QTextEdit, QLineEdit, QFormLayout, QTableView, QDataWidgetMapper, ) ############################################################################## class TModel(QAbstractItemModel): """ This model will have 1 row of 3 items There will be a slot that will change the items. If they are displayed in widgets, I want to see them update. """ def __init__(self, parent=None): super(TModel, self).__init__(parent) self.counter = 0 self.x1 = "" self.x2 = "" self.x3 = "" self.Update() def columnCount(self, index=QModelIndex()): return 3 def rowCount(self, index=QModelIndex()): return 1 def index(self, row, column, index=QModelIndex()): if not self.hasIndex(row, column, index): return QModelIndex() return self.createIndex(row, column) def parent(self, index): return QModelIndex() def hasChildren(self, index): return False def data(self, index, role=Qt.DisplayRole): if index.isValid(): if role == Qt.DisplayRole: if index.column() == 0: return self.x1 elif index.column() == 1: return self.x2 elif index.column() == 2: return self.x3 return None def headerData(self, section, orientation, role): if role != Qt.DisplayRole: return None if orientation == Qt.Horizontal: if section == 0: return "col 1" elif section == 1: return "col 2" elif section == 2: return "col 3" def Update(self): self.beginResetModel() self.x1 = "First (%d)"%self.counter self.x2 = "Second (%d)"%self.counter self.x3 = "Third (%d)"%self.counter self.counter += 1 self.endResetModel() ############################################################################## class TMainWindow(QMainWindow): """Main GUI object""" def __init__(self, parent=None): super(TMainWindow, self).__init__(parent) self.DataModel = TModel() self.Mapper = QDataWidgetMapper() self.Mapper.setSubmitPolicy(self.Mapper.AutoSubmit) self.Mapper.setModel(self.DataModel) self.FirstFieldEdit = QLineEdit() self.SecondFieldEdit = QLineEdit() self.ThirdFieldEdit = QTextEdit() self.Mapper.addMapping(self.FirstFieldEdit, 0) self.Mapper.addMapping(self.SecondFieldEdit, 1) self.Mapper.addMapping(self.ThirdFieldEdit, 2) self.Mapper.toFirst() self.UpdateButton = QPushButton("Next") self.UpdateButton.clicked.connect(self.DataModel.Update) formLayout = QFormLayout() formLayout.addRow("&First:", self.FirstFieldEdit) formLayout.addRow("&Second:", self.SecondFieldEdit) formLayout.addRow("&Third:", self.ThirdFieldEdit) formLayout.addRow("", self.UpdateButton) self.testTable = QTableView() self.testTable.setModel(self.DataModel) formLayout.addRow("Table:", self.testTable) W = QWidget() W.setLayout(formLayout) self.setCentralWidget(W) ############################################################################## if __name__ == "__main__": app = QApplication(sys.argv) MainWindow = TMainWindow() MainWindow.show() sys.exit(app.exec_()) Answer: The `QDataWidgetMapper` class is intended to allow displaying and editing records in a model. But your model doesn't return anything when data is requested for editing. So a simple fix would be: def data(self, index, role=Qt.DisplayRole): if index.isValid(): if role == Qt.DisplayRole or role == Qt.EditRole: ... **EDIT** : From the Qt Docs: > QDataWidgetMapper can be used to create data-aware widgets by mapping them > to **sections** of an item model. A section is a **column** of a model if > the orientation is horizontal (the default), otherwise a **row**. [emphasis > added] I would suggest you avoid trying to write a custom model (which is very far from trivial, except for the simplest of cases), and start by using a [QStandardItemModel](http://doc.qt.io/qt-5/qstandarditemmodel.html).
Python3 filling a dictionary concurrently Question: I want to fill a dictionary in a loop. Iterations in the loop are independent from each other. I want to perform this on a cluster with thousands of processors. Here is a simplified version of what I tried and need to do. import multiprocessing class Worker(multiprocessing.Process): def setName(self,name): self.name=name def run(self): print ('In %s' % self.name) return if __name__ == '__main__': jobs = [] names=dict() for i in range(10000): p = Worker() p.setName(str(i)) names[str(i)]=i jobs.append(p) p.start() for j in jobs: j.join() I tried this one in python3 on my own computer and received the following error: .. In 249 Traceback (most recent call last): File "test.py", line 16, in <module> p.start() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/multiprocessing/process.py", line 105, in start In 250 self._popen = self._Popen(self) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/multiprocessing/context.py", line 212, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/multiprocessing/context.py", line 267, in _Popen return Popen(process_obj) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/multiprocessing/popen_fork.py", line 20, in __init__ self._launch(process_obj) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/multiprocessing/popen_fork.py", line 66, in _launch parent_r, child_w = os.pipe() OSError: [Errno 24] Too many open files Is there any better way to do this? Answer: `multiprocessing` talks to its subprocesses via pipes. Each subprocesses requires two open file descriptors, one for read and one for write. If you launch 10000 workers, you'll end opening 20000 file descriptors which exceeds the default limit on OS X (which your paths indicate you're using). You can fix the issue by raising the limit. See <http://superuser.com/questions/433746/is-there-a-fix-for-the-too-many-open- files-in-system-error-on-os-x-10-7-1> for details - basically, it amounts to setting two sysctl knobs and upping your shell's ulimit setting.
Does Python IDE have a module which imports math functions such as cos or sin? Question: Currently, I'm working on a program which takes some user input and uses this information to work out a question e.g cos50 or anything like that. I'm not entirely sure if python has a module which allows these sorts of equations however so I was wondering if anyone knows about one. An example of my coding can be found below: # SINE AND COSINE CALCULATOR # loop = True while loop == True: UserInput = input("Would you like to work out Sine or Cosine rule?") UserInputCaps = UserInput.upper() if "COSINE" in UserInputCaps: D = input("Enter the value of the paired angle:") a = float(input("Enter the value of length A")) b = float(input("Enter the value of length B")) c = (a**2) + (b**2) - (2*a*b)* cos(D) print(c) if "SINE" in UserInputCaps: a = input("Please enter the length") A = input("Please enter the angle") b = input("Please enter the other angle") ans = (a / sin(A)) * sin(b) print(ans) Answer: Python's [`math`](https://docs.python.org/2/library/math.html) module: A simple Google search would have helped.
Caffe : cifar 10_quick testing issue Question: I have trained CIFAR QUICK using caffe, but when I test the cifar10_quick_iter_5000.caffemodel.h5 using a python wrapper I get an accuracy around 52-54% whereas it should be 75%. I do not understand why I am geting such a low accuracy, because when I test Lenet MNIST I get the expected accuracy as per the MNIST example in caffe website. To verify if my method is right or wrong I have tried the cifar trained model file from [Clasificador_Cifar-10](https://github.com/IsaacRocos/Clasificador_Cifar-10.git) and I get and accuracy of 68%. Please let me know if I am missing something when I test the model. import sys import caffe import cv2 import Image import matplotlib import numpy as np import lmdb caffe_root = '/home/fred/CIFAR_QUICK/caffe' MODEL_FILE = '/home/fred/CIFAR_QUICK/caffe/examples/cifar10/cifar10.prototxt' PRETRAINED = '/home/fred/CIFAR_QUICK/caffe/examples/cifar10/cifar10_60000.caffemodel.h5' net = caffe.Net(MODEL_FILE, PRETRAINED,caffe.TEST) caffe.set_mode_cpu() db_path = '/home/fred/CIFAR_QUICK/caffe/examples/cifar10/cifar10_test_lmdb' lmdb_env = lmdb.open(db_path) lmdb_txn = lmdb_env.begin() lmdb_cursor = lmdb_txn.cursor() count = 0 correct = 0 for key, value in lmdb_cursor: print "Count:" print count count = count + 1 datum = caffe.proto.caffe_pb2.Datum() datum.ParseFromString(value) label = int(datum.label) image = caffe.io.datum_to_array(datum) image = image.astype(np.uint8) out = net.forward_all(data=np.asarray([image])) predicted_label = out['prob'][0].argmax(axis=0) print out['prob'] if label == predicted_label: correct = correct + 1 print("Label is class " + str(label) + ", predicted class is " + str(predicted_label)) print(str(correct) + " out of " + str(count) + " were classified correctly") Answer: See my answer [here](http://stackoverflow.com/a/35572495/3579977). You are not subtracting the mean which results in low accuracy. The link to the code, posted above, takes care of that. Apart from this there's nothing wrong with your approach.
Reading serial AMA0 of Arduino writes an empty data Question: I am connected Arduino to the Raspberry via **/dev/ttyACM0**. Despite the python script I want to retrieve data from the Arduino, which is doing, but if you want the data to appear more frequently (1-4 seconds) and the data does not list any. Data is written out irregularly me, which I do not understand :( Arduino code: void setup() { Serial.begin(9600); } void loop() { Serial.print("25.78"); // temperature Β°C delay(1000); Serial.println(); } Raspberry, python code: import serial serialport = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.7) response = serialport.readline() print response serialport.close() Here is an excerpt: pi@raspberrypi:~ $ python test.py pi@raspberrypi:~ $ python test.py pi@raspberrypi:~ $ python test.py pi@raspberrypi:~ $ python test.py 25.78 pi@raspberrypi:~ $ python test.py 25.78 pi@raspberrypi:~ $ python test.py 25.78 pi@raspberrypi:~ $ python test.py pi@raspberrypi:~ $ python test.py I do not know how I could fix it to be 100% functional? Answer: It looks like your read timeout (0.7s) is smaller than the frequency that you write the data (every 1000ms). So if you repeatedly execute the script that reads it, you'll sometimes miss the data. I'd recommend to either increase your read timeout, or decrease the interval that the Arduino sleeps.
Designing an FIR notch filter with python Question: I am writing some code with Python using the scipy.signal library to filter electromagnetic data that is mixed with various undesirable signatures that I want to filter out. For example, I have power line harmonics at various frequencies (i.e. 60, 120 Hz, etc....) with a width of only a few Hz that I would like to remove from the data using a notch filter. Is there already an existing function in python where I can merely inform the code how many data points i wish to use for the filter, the center-line frequency that I wish to remove and the width of the transition band or do I need to design a filter from scratch? If it is the latter I would greatly appreciate an example of notch filter design in Python to include window implementation to minimize aliasing. Answer: There are a few options for the solution on the scipy.signal website, but they introduce allot of ringing, which will translate to artifacts in the convolved signal. After trying many things I found the following function worked the best for implementing an FIR notch filter. # Required input defintions are as follows; # time: Time between samples # band: The bandwidth around the centerline freqency that you wish to filter # freq: The centerline frequency to be filtered # ripple: The maximum passband ripple that is allowed in db # order: The filter order. For FIR notch filters this is best set to 2 or 3, # IIR filters are best suited for high values of order. This algorithm # is hard coded to FIR filters # filter_type: 'butter', 'bessel', 'cheby1', 'cheby2', 'ellip' # data: the data to be filtered def Implement_Notch_Filter(time, band, freq, ripple, order, filter_type, data): from scipy.signal import iirfilter fs = 1/time nyq = fs/2.0 low = freq - band/2.0 high = freq + band/2.0 low = low/nyq high = high/nyq b, a = iirfilter(order, [low, high], rp=ripple, btype='bandstop', analog=False, ftype=filter_type) filtered_data = lfilter(b, a, data) return filtered_data