text
stringlengths
226
34.5k
wxPython: Dynamically Flow Buttons to Next Row on Window-Resize Question: The following wxPython sample code is meant to create some buttons and then add them to a horizontal panel in such a way that the buttons should flow to a new row when they no longer fit in the panel. In addition, the buttons should change position (increase/decrease the number of rows) as the user resizes the frame/window. (please see <http://wxpython- users.1045709.n5.nabble.com/Button-wrap-td2365760.html>). import wx words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua', 'ut', 'enim', 'ad', 'minim', 'veniam', 'quis', 'nostrud', 'exercitation', 'ullamco', 'laboris', 'nisi', 'ut', 'aliquip', 'ex', 'ea', 'commodo', 'consequat', 'duis', 'aute', 'irure', 'dolor', 'in', 'reprehenderit', 'in', 'voluptate', 'velit', 'esse', 'cillum', 'dolore', 'eu', 'fugiat', 'nulla', 'pariatur', 'excepteur', 'sint', 'occaecat', 'cupidatat', 'non', 'proident', 'sunt', 'in', 'culpa', 'qui', 'officia', 'deserunt', 'mollit', 'anim', 'id', 'est', 'laborum'] class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() self.Ctrls() i = 0 for word in words: i += 1 print " word = ",word, " ",i self.gridSizer.SetCols(5) button = wx.Button(self.panel, -1, word, size=wx.Size(70,25)) self.gridSizer.Add(button, 1, wx.EXPAND) self.panel.Layout() def InitUI(self): self.SetSize((800, 400)) self.SetTitle('Dynamically Flow Buttons to Next Row on Window-Resize') self.Centre() self.Show(True) def Sizers(self): self.gridSizer = wx.GridSizer(cols=0, hgap=1, rows=1, vgap=1) self.panel.SetSizer(self.gridSizer) def Ctrls(self): self.Bind(wx.EVT_SIZE, self.OnFrameSize) self.panel = wx.Panel(parent=self,pos=wx.Point(0,0), size=wx.Size(750,550), style=wx.TAB_TRAVERSAL) self.Sizers() def OnFrameSize(self, event): self.UpdateButtonLayout() event.Skip() def UpdateButtonLayout(self): panelwidth = self.panel.GetSize().width print panelwidth factor = panelwidth / 70 print "Factor: ", factor self.gridSizer.SetCols(factor) self.panel.Layout() def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main() When I run this example I get the following error; Traceback (most recent call last): File "test.py", line 68, in <module> main() File "test.py", line 64, in main Example(None) File "test.py", line 26, in __init__ self.gridSizer.Add(button, 1, wx.EXPAND) File "/usr/local/lib/wxPython-3.0.2.0/lib/python2.7/site-packages/wx-3.0-osx_cocoa/wx/_core.py", line 14457, in Add return _core_.Sizer_Add(*args, **kwargs) wx._core.PyAssertionError: C++ assertion "Assert failure" failed at /BUILD/wxPython-src-3.0.2.0/src/common/sizer.cpp(1401) in DoInsert(): too many items (6 > 5*1) in grid sizer (maybe you should omit the number of either rows or columns?) The problem is with line number 26. When I comment that out I see only a single button. Can someone suggest some changes to make it work? Thanks. Answer: What you are looking for is the `wx.WrapSizer`. I updated your code a bit to use it instead: import wx words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua', 'ut', 'enim', 'ad', 'minim', 'veniam', 'quis', 'nostrud', 'exercitation', 'ullamco', 'laboris', 'nisi', 'ut', 'aliquip', 'ex', 'ea', 'commodo', 'consequat', 'duis', 'aute', 'irure', 'dolor', 'in', 'reprehenderit', 'in', 'voluptate', 'velit', 'esse', 'cillum', 'dolore', 'eu', 'fugiat', 'nulla', 'pariatur', 'excepteur', 'sint', 'occaecat', 'cupidatat', 'non', 'proident', 'sunt', 'in', 'culpa', 'qui', 'officia', 'deserunt', 'mollit', 'anim', 'id', 'est', 'laborum'] class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() self.Ctrls() i = 0 for word in words: i += 1 print " word = ",word, " ",i button = wx.Button(self.panel, -1, word, size=wx.Size(70,25)) self.wrapSizer.Add(button, 1, wx.EXPAND) self.Show(True) self.panel.Layout() def InitUI(self): self.SetSize((800, 400)) self.SetTitle('Dynamically Flow Buttons to Next Row on Window-Resize') self.Centre() def Sizers(self): self.wrapSizer = wx.WrapSizer() self.panel.SetSizer(self.wrapSizer) def Ctrls(self): self.panel = wx.Panel(parent=self,pos=wx.Point(0,0), size=wx.Size(750,550), style=wx.TAB_TRAVERSAL) self.Sizers() def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main() Note that you cannot set the number of columns. You can read more about this fun widget at the following: * <http://www.blog.pythonlibrary.org/2014/01/22/wxpython-wrap-widgets-with-wrapsizer/> * <http://wxpython.org/Phoenix/docs/html/WrapSizer.html>
Type Error when I try to make a 3D graph in python Question: I know how to make 3D-graph in Python but for this one I have an error I've never seen. I want to have the graph of : $$f(x,y)=\frac{8\cos(\sqrt{x^2+y^2}}{\sqrt{1+x^2+y^2}}$$ (LaTeX doesn't work here... ???) My code : import math import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D ax = Axes3D(plt.figure()) def f(x,y): return (8*math.cos(math.sqrt(x**2+y**2)))/(math.sqrt(1+x**2+y**2)) X = np.arange(-1,1,0.1) Y = np.arange(-1,1,0.1) X,Y=np.meshgrid(X,Y) Z=f(X,Y) ax.plot_surface(X,Y,Z) plt.show() The error : runfile('C:/Users/Asus/Desktop/Informatiques/nodgim.py', wdir=r'C:/Users/Asus/Desktop/Informatiques') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\Asus\Desktop\WinPython\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 680, in runfile execfile(filename, namespace) File "C:\Users\Asus\Desktop\WinPython\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace) File "C:/Users/Asus/Desktop/Informatiques/nodgim.py", line 22, in <module> Z=f(X,Y) File "C:/Users/Asus/Desktop/Informatiques/nodgim.py", line 16, in f return (8*math.cos(math.sqrt(x**2+y**2)))/(math.sqrt(1+x**2+y**2)) TypeError: only length-1 arrays can be converted to Python scalars Can you explain me what I have to do? Thank you in advance Answer: `math.cos` and `math.sqrt` expect to get a scalar value but instead were passed an [array type](http://docs.scipy.org/doc/numpy/reference/arrays.html) that they cannot handle properly which results in your type error. Essentially Python's built in math functions don't know how to deal with numpy arrays, so to fix this you need to use the mathematical functions that numpy provides to work on these data types: [numpy.cos](http://docs.scipy.org/doc/numpy/reference/generated/numpy.cos.html#numpy.cos) and [numpy.sqrt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.sqrt.html#numpy.sqrt) This will then give you the vectorization you need.
Rpy2 can't find my R libraries on install Question: R built from source, installed locally. R is at `~/bin/R` (which is in my PATH) and its libraries are in `~/lib64/R/`. Installing rpy2 should be simple. It finds the correct R just fine (as it's in the path). Then it can't find the libraries. $python setup.py build install R version 3.2.1 (2015-06-18) -- "World-Famous Astronaut" ... setup.py:211: UserWarning: No include specified warnings.warn('No include specified') setup.py:222: UserWarning: No libraries as -l arguments to the compiler. warnings.warn('No libraries as -l arguments to the compiler.') Compilation parameters for rpy2's C components: include_dirs = [] library_dirs = [] libraries = [] extra_link_args = [] And then we get a million errors that it can't find functions that are in the R libraries. Rpy2's [documentation says](http://rpy.sourceforge.net/rpy2/doc- dev/html/overview.html) there's a simple option for designating where R or its libraries are: python setup.py build --r-home ~/lib64/R/lib install But if you do this, then you get: setup.py:222: UserWarning: No libraries as -l arguments to the compiler. warnings.warn('No libraries as -l arguments to the compiler.') Compilation parameters for rpy2's C components: include_dirs = [] library_dirs = [] libraries = [] extra_link_args = [] usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: option --r-home not recognized It looks like the `--r-home` functionality has been removed. How does one point rpy2 to the correct libraries? * * * Edit: Have now installed R with: ./configure --prefix=${HOME} --enable-R-shlib make make install After that, I can install rpy2 with just `pip install rpy2`. But then, we're still having library problems: import rpy2.robjects as robjects ImportError: libRblas.so: cannot open shared object file: No such file or directory So then I needed to add this to my path: export LD_LIBRARY_PATH="~/lib64/R/lib:$LD_LIBRARY_PATH" And then everything works! Answer: If R is in an unconventional location, the easiest might be help out a bit by setting environment variables (older versions of the doc is talking about `--r-home` but this was a less tested corner and it was removed). Try: export PATH=~/bin/R:${PATH} export LD_LIBRARY_PATH=~/lib64/R/lib:${LD_LIBRARY_PATH} export PKG_CONFIG_PATH=~/lib64/R/lib/pkgconfig/:${PKG_CONFIG_PATH}
Python lazy evaluation numpy ndarray Question: I have a large 2D array that I would like to declare once, and change occasionnaly only _some_ values depending on a parameter, without traversing the whole array. To build this array, I have subclassed the numpy ndarray class with `dtype=object` and assign to the elements I want to change a function e.g. : def f(parameter): return parameter**2 for i in range(np.shape(A)[0]): A[i,i]=f for j in range(np.shape(A)[0]): A[i,j]=1. I have then overridden the `__getitem__` method so that it returns the evaluation of the function with given parameter if it is callable, otherwise return the value itself. def __getitem__(self, key): value = super(numpy.ndarray, self).__getitem__(key) if callable(value): return value(*self.args) else: return value where `self.args` were previously given to the instance of myclass. However, I need to work with float arrays at the end, and I can't simply convert this array into a `dtype=float` array with this technique. I also tried to use numpy views, which does not work either for `dtype=object`. Do you have any better alternative ? Should I override the view method rather than getitem ? **Edit** I will maybe have to use Cython in the future, so if you have a solution involving e.g. C pointers, I am interested. Answer: In this case, it does not make sens to bind a transformation function, to every index of your array. Instead, a more efficient approach would be to define a transformation, as a function, together with a subset of the array it applies to. Here is a basic implementation, import numpy as np class LazyEvaluation(object): def __init__(self): self.transforms = [] def add_transform(self, function, selection=slice(None), args={}): self.transforms.append( (function, selection, args)) def __call__(self, x): y = x.copy() for function, selection, args in self.transforms: y[selection] = function(y[selection], **args) return y that can be used as follows: x = np.ones((6, 6))*2 le = LazyEvaluation() le.add_transform(lambda x: 0, [[3], [0]]) # equivalent to x[3,0] le.add_transform(lambda x: x**2, (slice(4), slice(4,6))) # equivalent to x[4,4:6] le.add_transform(lambda x: -1, np.diag_indices(x.shape[0], x.ndim), ) # setting the diagonal result = le(x) print(result) which prints, array([[-1., 2., 2., 2., 4., 4.], [ 2., -1., 2., 2., 4., 4.], [ 2., 2., -1., 2., 4., 4.], [ 0., 2., 2., -1., 4., 4.], [ 2., 2., 2., 2., -1., 2.], [ 2., 2., 2., 2., 2., -1.]]) This way you can easily support all advanced Numpy indexing (element by element access, slicing, fancy indexing etc.), while at the same time keeping your data in an array with a native data type (`float`, `int`, etc) which is much more efficient than using `dtype='object'`.
Append to File Using Subprocess in Python Question: How do I append to a file without opening it using Linux echo command? I've tried all sort of possibilities but unable to achieve the result. I'm not sure what I'm missing. Documentation said to type out the exact command when shell is set to 'True' _(Yes with security risk)_. The echo command works when I type it in Linux terminal but not through subprocess. I don't see the "test.txt" with 'This is a test string.' >>> string = 'This is a test string.' >>> cmd = 'echo \"' + string + '\" >> test.txt' >>> cmd 'echo "This is a test string." >> test.txt' >>> >>> subprocess.check_call (cmd, shell = True) 0 >>> >>> subprocess.call (['echo', '\"', string, '\"', ' >> ', ' test.txt']) 0 >>> Answer: As discussed in [this answer](http://stackoverflow.com/a/26417712/1142167), when using, `shell=True`, you should pass a string, not a list, as the first argument. Thus the correct code would be: subprocess.call('echo "foo" >> bar.txt', shell=True) Demonstration: >>> import subprocess >>> subprocess.call('echo "foo" >> /tmp/bar.txt', shell=True) 0 >>> open('/tmp/bar.txt').read() 'foo\n' >>>
mongodb group and combine Question: I have a doc that has a schema like `{'year-month-day','others'}` and I want to convert `'year-month-day` to an ISODate time so I can use `$match:{'$gte:targetDate'}` I have several problems: 1. I am using pymongo, which dones support javaciprt, so I can not use `new Date()` in python and at the same time `datetime` is not working as well because it can not read `'$year'`. I think one way to achieve the above goal is first get the substrings of `'year-month-day'` and after aggregation I can use `forEach(function(x){...})` to create a `ISODate` for each date and compare with `target` but doing means I will have to scan through every docs in the database which I dont think is a good choice. 2. If the first is not doable in pymongo, how can I do it by mongodb query? how can I use project to create a column with new data type?(like what I did in the second project). 3. Is there any way to do javascrip inside pymongo? My script is like following: Collection.aggregate([ { '$project':{ 'year':{'$substr':['$year-month-day',0,4]}, 'month':{'$substr':['$year-month-day',5,2]}, 'day':{'$substr':['$year-month-day',8,2]}, 'others':'others' } }, { '$project':{ 'approTime':new Date(Date.UTC('$year','$month','$day')), 'others':'others' } }, { '$group':{ '_id':{ 'approTime':'$approTime', 'others':'others' }, 'count':{'$sum':1} } } Answer: You could try converting the field `'year-month-day'` to mongoDB native ISODate data type by using the **[datetime](https://docs.python.org/2/library/datetime.html)** module which is stored under the hood as the native date object in MongoDB: from pymongo import MongoClient from datetime import datetime client = MongoClient('host', port) db = client['database'] col = db['collection'] attr = 'year-month-day' date_format = "%Y-%m-%d %H:%M:%S.%f" #date_format is the format of the string eg : "%Y-%m-%d %H:%M:%S.%f" for doc in col.find(): if doc[attr]: if type(doc[attr]) is not datetime: isodate = datetime.strptime(doc[attr], date_format) col.update({'_id': doc['_id']}, {'$set': {attr: isodate}}) This can also be done in Mongo shell as: db.collection.find({ "$and": [ { "year-month-day": { "$exists": true } }, { "year-month-day": { "$not": {"$type": 9} } } ] }).forEach(function(doc) { doc["year-month-day"] = new Date(doc["year-month-day"]); db.collection.save(doc); })
Linux command line instructions from python Question: Is there a method for issuing command line instructions directly from the python shell? Answer: You can use `os.system` - import os os.system('<command line instruction>')
Python CSV read file and select columns and write to new CSV file Question: I have a CSV file which has certain columns which I need to extract. One of those columns is a text string from which I need to extract the first and last items. I have a print statement in a for loop which get exactly what I need but cannot figure out how to either get that data into a list or dict. Not sure which is the best to use. Code so far: f1 = open ("report.csv","r") # open input file for reading users_dict = {} with open('out.csv', 'wb') as f: # output csv file writer = csv.writer(f) with open('report.csv','r') as csvfile: # input csv file reader = csv.DictReader(csvfile, delimiter=',') for row in reader: print row['User Name'],row['Address'].split(',')[0],row['Last Login DateTime'],row['Address'].split(',')[7] users_dict.update(row) #users_list.append(row['Address'].split(',')) #users_list.append(row['Last Login DateTime']) #users_list.append(row[5].split(',')[7]) print users_dict f1.close() Input from file: User Name,Display Name,Login Name,Role,Last Login DateTime,Address,Application,AAA,Exchange,Comment SUPPORT,SUPPORT,SUPPORT,124,2015-05-29 14:32:26,"Test Company,Bond St,London,London,1111 111,GB,[email protected],IS",,,LSE, Output on print: SUPPORT Test Company 2015-05-29 14:32:26 IS Answer: Using this code, I've got the line you need: import csv f1 = open ("report.csv","r") # open input file for reading users_dict = {} with open('out.csv', 'wb') as f: # output csv file writer = csv.writer(f) with open('report.csv','r') as csvfile: # input csv file reader = csv.DictReader(csvfile, delimiter=',') for row in reader: print row['User Name'],row['Address'].split(',')[0],row['Last Login DateTime'],row['Address'].split(',')[7] users_dict.update(row) #users_list.append(row['Address'].split(',')) #users_list.append(row['Last Login DateTime']) #users_list.append(row[5].split(',')[7]) print users_dict f1.close() The only changes: * Including the `import csv` at the top. * Indenting the code just after the `with open('out.csv' ......` Does this solve your problem?
How are images actually saved with skimage (Python) Question: I am currently applying the [Zhang-Suen thinning algorithm](https://github.com/linbojin/Skeletonization-by-Zhang-Suen-Thinning- Algorithm/blob/master/thinning.py) to hone down on some filaments I would like to later track. This requires me to output a grayscale image in order to identify objects using OpenCV. import matplotlib import matplotlib.pyplot as plt import skimage.io as io "load image data" Img_Original = io.imread( './data/test1.bmp') # Gray image, rgb images need pre-conversion "Convert gray images to binary images using Otsu's method" from skimage.filter import threshold_otsu Otsu_Threshold = threshold_otsu(Img_Original) BW_Original = Img_Original < Otsu_Threshold # must set object region as 1, background region as 0 ! #... "Apply the algorithm on images" BW_Skeleton = zhangSuen(BW_Original) # BW_Skeleton = BW_Original "Display the results" fig, ax = plt.subplots(1, 2) ax1, ax2 = ax.ravel() ax1.imshow(BW_Original, cmap=plt.cm.gray) ax1.set_title('Original binary image') ax1.axis('off') ax2.imshow(BW_Skeleton, cmap=plt.cm.gray) ax2.set_title('Skeleton of the image') ax2.axis('off') plt.show() The image plotted using matplotlib is exactly what I want (black and white). When I use either skimage or cv2 to write the output image to a file path, I get a similar image in blue and red. My only problem is that I can't convert this blue/red image to grayscale! So in essence, my output image is useless. Forgive me if this is a trivial question, but is there a protocol for writing images to file paths? What should I be looking out for in terms of image types (ie. bytes, colour/grayscale, format) when I use these tools? Thanks in advance! Answer: You can set the color map of the saved data so that when you open the image in OpenCV it will be in grey scale. Here is some sample data as an example: data = np.random.rand(256,256) You can save the [data directly](http://matplotlib.org/api/image_api.html): plt.imsave('test.png', data, cmap = plt.cm.gray) or save the entire [figure](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig): plt.savefig('test2.png')
Flask-Security user_registered Signal Not Received in Python 3.3, but works in 2.7 Question: I'm trying to use the user_registered signal in order to set up default roles for users when they register using flask-security as in the following link: [Setting Default Role in Flask Security](http://stackoverflow.com/questions/17146724/setting-a-default-role- in-flask-security) In my searches I can see that there was a bug that was already addressed for this in flask-security: [Not getting signal from flask- security](http://stackoverflow.com/questions/15060849/not-getting-signal-from- flask-security), [Fix - user_registered signal problem](https://github.com/mattupstate/flask-security/issues/94) I've tried the following to prove if the signal is received by the handler without any luck: @user_registered.connect_via(app) def user_registered_sighandler(sender, **extra): print("print-user_registered_sighandler:", extra) This, however, never gets called even though the user gets registered and the signal should be sent. If it helps I've set the flask-security configuration as follows: app.config['SECURITY_REGISTERABLE'] = True app.config['SECURITY_CONFIRMABLE'] = False app.config['SECURITY_SEND_REGISTER_EMAIL'] = False app.config['SECURITY_CHANGEABLE'] = True app.config['SECURITY_SEND_PASSWORD_CHANGE_EMAIL'] = False Signals from Flask-Login and Flask-Principal are working for me as I managed to confirm that the following code snippets successfully print when the signals are sent: @user_logged_out.connect_via(app) def on_user_logged_out(sender, user): print('USER LOG OUT: made it in',user) @identity_changed.connect_via(app) def identity_changed_ok(sender,identity): print('Identity changed:',identity) For my setup I am using python 3.3 (anaconda) and using the following: Flask==0.10.1,flask-login==0.2.11,flask-principal==0.4.0,flask- security==1.7.4,blinker==1.3. Having looked at the signals in both flask-login and flask-security I'm not sure why the flask-security signals would not be working. **EDIT:** If I add `print(user_registered.receivers)` to a route in my app it will show that I have a receiver: `{139923381372400: <function user_registered_sighandler at 0x7f42737145f0>}`. If I put this same print statement within the registerable.py of flask-security just before the `user_registered.send(app._get_current_object(),user=user, confirm_token=token)` then it lists no receivers: `{}` **EDIT2:** Problem appears to be related to using python 3.3. I created a python 2.7 environment and the user_registered code worked as expected. Full code to reproduce: from flask import Flask,render_template from playhouse.flask_utils import FlaskDB import os from flask.ext.security import Security, PeeweeUserDatastore from flask.ext.security.signals import user_registered from flask.ext.login import user_logged_out from peewee import * from playhouse.signals import Model from flask.ext.security import UserMixin,RoleMixin app = Flask(__name__) app.config['ADMIN_PASSWORD']='secret' app.config['APP_DIR']=os.path.dirname(os.path.realpath(__file__)) app.config['DATABASE']='sqliteext:///%s' % os.path.join(app.config['APP_DIR'], 'blog.db') app.config['SECRET_KEY'] = 'shhh, secret!' app.config['SECURITY_REGISTERABLE'] = True app.config['SECURITY_CONFIRMABLE'] = False app.config['SECURITY_SEND_REGISTER_EMAIL'] = False flask_db = FlaskDB() flask_db.init_app(app) database = flask_db.database class BaseModel(Model): class Meta: database=flask_db.database class User(BaseModel, UserMixin): email=CharField() password=CharField() active = BooleanField(default=True) confirmed_at = DateTimeField(null=True) def is_active(self): return True def is_anonymous(self): return False def is_authenticated(self): return True class Role(BaseModel, RoleMixin): name = CharField(unique=True) description = TextField(null=True) class UserRoles(BaseModel): user = ForeignKeyField(User, related_name='roles') role = ForeignKeyField(Role, related_name='users') name = property(lambda self: self.role.name) description = property(lambda self: self.role.description) user_datastore = PeeweeUserDatastore(database, User, Role, UserRoles) security = Security(app, user_datastore) @user_registered.connect_via(app) def user_registered_sighandler(sender,**extra): print("print-user_registered_sighandler") @user_logged_out.connect_via(app) def on_user_logged_out(sender, user): print('USER LOG OUT: made it in',user) @app.route('/') def index(): print(user_registered.receivers) return render_template('base.html') database.create_tables([User,Role,UserRoles], safe=True) app.run(debug=True) base.html template: <!doctype html> <html> <head> <title>Blog</title> </head> <body> <ul> {% if current_user.is_authenticated() %} <li><a href="{{ url_for('security.logout',next='/') }}">Log out</a></li> <li><a href="{{ url_for('security.register') }}">Register</a></li> {% else %} <li><a href="{{ url_for('security.login',next='/') }}">Login</a></li> <li><a href="{{ url_for('security.register') }}">Register</a></li> {% endif %} {% block extra_header %}{% endblock %} </ul> </body> </html> Answer: I was able to do this with something like: security = Security(app, user_datastore, register_form=ExtendedRegisterForm) @user_registered.connect_via(app) def user_registered_sighandler(app, user, confirm_token): default_role = user_datastore.find_role("Pending") user_datastore.add_role_to_user(user, default_role) db.session.commit()
Formatting Flask app logs in json Question: I'm working with a Python/Flask application and trying to get the logs to be formatted (by line) in json. Using the python-json-logger package, I've modified the formatter for the app.logger as follows: from pythonjsonlogger import jsonlogger formatter = jsonlogger.JsonFormatter( '%(asctime) %(levelname) %(module) %(funcName) %(lineno) %(message)') app.logger.handlers[0].setFormatter(formatter) This works as expected. Any messages passed to `app.logger` are correctly formatted in json. However the application is also automatically logging all requests. This information shows up in stdout as follows: 127.0.0.1 - - [19/Jun/2015 12:22:03] "GET /portal/ HTTP/1.1" 200 - I want this information to be formatted in json as well. I've been looking for the logger/code that is responsible for creating this output with no success. Where is this output generated? Are the mechanisms to change the formatting of this logged information? Answer: When you use the `app.logger` attribute for the first time, Flask sets up some log handlers: * a debug logger that is set to log level `DEBUG` and that filters on `app.debug` being true. * a production logger that is set to `ERROR`. You can remove those handlers again yourself, by running: app.logger.handlers[:] = [] However, the log line you see is not logged by Flask, but by the WSGI server. Both the built-in Werkzeug server (used when you use `app.run()`) and various other WSGI servers do this. Gunicorn for example uses the default Python logger to record access. The built-in WSGI server should never be used in production (it won't scale well, and is not battle-hardened against malicious attackers). For Gunicorn, you can disable _log propagation_ to keep the logging separate: logging.getLogger('gunicorn').propagate = False
How to mock.patch a class imported in another module Question: I have a python class with such a module: **xy.py** from a.b import ClassA class ClassB: def method_1(): a = ClassA() a.method2() then I have ClassA defined as: **b.py** from c import ClassC class ClassA: def method2(): c = ClassC() c.method3() Now in this code, when writing test for xy.py I want to mock.patch ClassC, is there a way to achieve that in python? obviously I tried: mock.patch('a.b.ClassA.ClassC) and mock.patch('a.b.c.ClassC') None of these worked. Answer: You need to patch where `ClassC` is located so that's `ClassC` in `b`: mock.patch('b.ClassC') Or, in other words, `ClassC` is imported into module `b` and so that's the scope in which `ClassC` needs to be patched.
using requests to login to a website that has javascript login form Question: Let me preface by saying I have very little programming experience. I've learned a bunch in the last few days trying to write this program. I am running Python 2.7 on Windows 7 using PyCharm, requests, Beautiful Soup, and lxml. I am trying to scrape data from a website that relies heavily on Javascript. I have two options: 1) The data I need is populated through Javascript and does not necessarily need a login. However I have not been able to figure how to get at this data. I've live monitored headers with live HTTP Headers chrome plugin and I think I've found the Javascript that does it but I'ts beyond my means to figure it out. Its a long bit of code, I'll post it if anyone is interested in taking a look. or 2)On one of the main pages I found a series of ID numbers which I can use to generate URL's for each of the individual items I am analyzing. Problem is I have to be logged in to see these individual item pages. My code is as follows: from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager from BeautifulSoup import BeautifulSoup import ssl # Request a date from user UDate = "06/22/2015" # raw_input('Enter a date mm/dd/yyyy\n') # Open TLSv1 Adapter (Whataver that means) class MyAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1) # Begin a requests session. Every get from here on out will use TLSv1 Protocol import requests payload = { 'LogName': 'xxxxxxxx', 'LogPass': 'xxxxxxxx' } s = requests.Session() s.mount('https://xxxx.xxx', MyAdapter()) # Login with post and Request source code from main page. log = s.post('LoginURL', data=payload) print log.text result = s.get(url) soup = BeautifulSoup(result.content) print soup Neither the post or the get show me a logged in website. The logform id's from the HTML source code look like this: <div id="DivLogForm"> <label for="BadText"><div id="BadText" class="BadText" style="display:none" tabindex="-2">User Name or Password is Invalid</div></label> <div class="LogLabel"> <label for="LogName" > User Name&nbsp;&nbsp;</label><input tabindex="0" id="LogName" class="LogInput" value="" /> </div> <div class="LogLabel"> <label for="LogPass" >User Password&nbsp;&nbsp;</label><input tabindex="0"id="LogPass" type="password" class="LogInput" value="" /> </div> So I'm passing LogName and LogPass with the post. There is also a logform.js with this bit of code $("#LogButton").click(function() { //$('#divLogForm').hide(); //$('#divLoading').show(); var uName = $("#LogName").val(); var uPass = $("#LogPass").val(); var url = "/index.cfm"; $.post(url, {ZACTION:'AJAX',ZMETHOD:'LOGIN',func:'LOGIN',USERNAME:uName, USERPASS:uPass}, function(data){if (data.isOk =="YES"){location.href="/index.cfm";} else {$('.BadText').show(); $('#BadText').focus();}; },"json"); }); The LoginURL in my code is taken from the var url in this script. I have tried using USERNAME & USERPASS and I have tried uName and uPass with my post but these didnt work either. Not sure how to move forward here. Any help is greatly appreciated Answer: The last bit of javascript you posted gives a clue as to why your login POST request isn't working. According to the javascript, you should be sending a dictionary that looks like the following with your login POST: { 'ZACTION': 'AJAX', 'ZMETHOD': 'LOGIN', 'func': 'LOGIN', 'USERNAME': '<enter username>', 'USERPASS': '<enter password>' },
Is there a way to catch 500 errors in django python? Question: I would like to catch 500 exception and return a http 4XX exception instead. Using "except Exception" will catch all exceptions which is not desired. I was wondering is there a way to catch only 500 errors try: <code> except <Exception class>: return http 404 reponse I searched a lot but couldn't figure out how to do the same. Thanks in advance Answer: I'm not sure that returning 404 instead of 500 is a good idea, but you can acheive this by defining a [custom error handler](https://docs.djangoproject.com/en/1.8/topics/http/views/#customizing- error-views) for 500 errors. In your urls.py: handler500 = 'mysite.views.my_custom_error_view' In your views.py: from django.http import HttpResponse def my_custom_error_view(request): """ Return a 404 response instead of 500. """ return HttpResponse("error message", status_code=404)
How to decode ascii from stream for analysis Question: I am trying to run text from twitter api through sentiment analysis from textblob library, When I run my code, the code prints one or two sentiment values and then errors out, to the following error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 31: ordinal not in range(128) I do not understand why this is an issue for the code to handle if it is only analyzing text. I have tried to code the script to UTF-8. Here is the code: from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import sys import csv from textblob import TextBlob # Variables that contains the user credentials to access Twitter API access_token = "" access_token_secret = "" consumer_key = "" consumer_secret = "" # This is a basic listener that just prints received tweets to stdout. class StdOutListener(StreamListener): def on_data(self, data): json_load = json.loads(data) texts = json_load['text'] coded = texts.encode('utf-8') s = str(coded) content = s.decode('utf-8') #print(s[2:-1]) wiki = TextBlob(s[2:-1]) r = wiki.sentiment.polarity print r return True def on_error(self, status): print(status) auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, StdOutListener()) # This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby' stream.filter(track=['dollar', 'euro' ], languages=['en']) Can someone please help me with this situtation? Thank you in advance. Answer: You're mixing too many things together. As the error says, you're trying to decode a byte type. `json.loads` will result in data as string, from that you'll need to encode it. texts = json_load['text'] # string coded = texts.encode('utf-8') # byte print(coded[2:-1]) So, in your script, when you tried to decode `coded` you got an error about decoding `byte` data.
HTTP POST REQUEST using python Question: I've a web server setup in a separate location and I wanted to access it remotely using HTTP POST request. Can someone please guide me how to proceed with it. I need to use Python which runs the HTTP Post request and modifies the contents of the WEB page Answer: Although probably not particularly practical, you could use a socket. A script on the server which receives the POST request would have to modify the desired web pages content upon receipt. import socket sock = socket.socket() sock.connect(('server_domainname.com', 80)) sock.sendall(b'POST / HTTP/1.1\r\nHost: server_domainname.com:80\r\n\r\n')
Python equivalent of C++ member pointer Question: What would be the equivalent of a C++ member pointer in Python? Basically, I would like to be able to replicate similar behavior in Python: // Pointer to a member of MyClass int (MyClass::*ptMember)(int) = &MyClass::member; // Call member on some instance, e.g. inside a function to // which the member pointer was passed instance.*ptMember(3) Follow up question, what if the member is a property instead of a method? Is it possible to store/pass a "pointer" to a property without specifying the instance? One way would obviously be to pass a string and use `eval`. But is there a cleaner way? **EDIT:** There are now several really good answers, each having something useful to offer depending on the context. I ended up using what is described in my answer, but I think that other answers will be very helpful for whoever comes here based on the topic of the question. So, I am not accepting any single one for now. Answer: The closest fit would probably be [`operator.attrgetter`](https://docs.python.org/2/library/operator.html#operator.attrgetter): from operator import attrgetter foo_member = attrgetter('foo') bar_member = attrgetter('bar') baz_member = attrgetter('baz') class Example(object): def __init__(self): self.foo = 1 @property def bar(self): return 2 def baz(self): return 3 example_object = Example() print foo_member(example_object) # prints 1 print bar_member(example_object) # prints 2 print baz_member(example_object)() # prints 3 `attrgetter` goes through the exact same mechanism normal dotted access goes through, so it works for anything at all you'd access with a dot. Instance fields, methods, module members, dynamically computed attributes, whatever. It doesn't matter what the type of the object is, either; for example, `attrgetter('count')` can retrieve the `count` attribute of a list, tuple, string, or anything else with a `count` attribute. * * * For certain types of attribute, there may be more specific member-pointer-like things. For example, for instance methods, you can retrieve the unbound method: unbound_baz_method = Example.baz print unbound_baz_method(example_object) # prints 3 This is either the specific function that implements the method, or a very thin wrapper around the function, depending on your Python version. It's type- specific; `list.count` won't work for tuples, and `tuple.count` won't work for lists. For properties, you can retrieve the property object's `fget`, `fset`, and `fdel`, which are the functions that implement getting, retrieving, and deleting the attribute the property manages: example_bar_member = Example.bar.fget print example_bar_member(example_object) # prints 2 We didn't implement a setter or deleter for this property, so the `fset` and `fdel` are `None`. These are also type-specific; for example, if `example_bar_member` handled lists correctly, `example_bar_member([])` would raise an `AttributeError` rather than returning `2`, since lists don't have a `bar` attribute.
Python Convert set to list, keep getting TypeError: 'list' object is not callable Question: I am trying to write a program that adds items to a list based on a random number. Part of the program is potentially rolling additional items, but all duplicate items should be rerolled. My issue is that when I try to do this using the methods I was able to find (compare list to set of list to test for dups, then save the set to the list), but I keep getting TypeError: 'list' object is not callable. The confusing thing is that when I test this with simple lists I set up, it works fine. This is my code from random import randint # Dice roller function def roll_dice(dice, sides, bonus): count = 0 roll = 0 for count in range(dice): roll += randint(1, sides) roll += bonus return roll list = ['1', '2', '3', '4', '5'] print_list = '' for x in range(0, len(list)-1): print_list += ' ' + list[x] print print_list[1:] # Minor special armor ability roller def armor_special_ability(): reroll = 1 ability = [] abil_list = '' while reroll > 0: result = int(raw_input('Roll:'))#roll_dice(1,100,0) if result <= 25: ability.append('Glamered') elif result <= 32: ability.append('Light Fortification') elif result <= 52: ability.append('Slick') elif result <= 72: ability.append('Shadow') elif result <= 92: ability.append('Silent Moves') elif result <= 96: ability.append('Spell Resistance (13)') elif result <= 97: ability.append('Improved Slick') elif result <= 98: ability.append('Improved Shadow') elif result <= 99: ability.append('Improved Silent Moves') elif result <= 100: reroll += 2 reroll -= 1 if len(ability) > len(set(ability)): reroll += (len(ability) - len(set(ability))) ability = list(set(ability)) return ability print armor_special_ability() Can anyone help me figure out why I keep getting this error? I've spent hours searching the net with no success. Answer: The issue is in line - list = ['1', '2', '3', '4', '5'] You are overwriting the in-built `list` function with your list , after this assignment , if you try to call `list()` it would cause error, as it would try to access the list you defined and call it. Use a different name, do not ever use `list` as a name for a variable (unless you really wanted to overwrite the `list` in-built function) , since it overwrites inbuilt functions.
Mock import of ctypes fails with unsupported operand on Read The Docs Question: I have small Windows module that relies on the **ctypes** core module. On the project RTD site the page for the module comes up empty. Looking at the latest almost successful build log <https://readthedocs.org/builds/apt/2900858/> there is a failure during _make html_ stage. File "/var/build/user_builds/apt/checkouts/latest/knownpaths.py", line 5, in <module> from ctypes import windll, wintypes File "/usr/lib/python2.7/ctypes/wintypes.py", line 23, in <module> class VARIANT_BOOL(_SimpleCData): ValueError: _type_ 'v' not supported Following the FAQ entry <https://read-the- docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that- depend-on-c-modules> I tried to fake import ctypes using `mock`, but doing so cause the build to fail completely. From what I can tell, but I'm no means an expert in this area, it's because mock itself is missing some math functions: File "/var/build/user_builds/apt/checkouts/latest/knownpaths.py", line 13, in GUID ("Data4", wintypes.BYTE * 8) TypeError: unsupported operand type(s) for *: 'Mock' and 'int' Research on the error leads to only 3 search hits, the most relevant about Mock missing (at least) a true division operator: <https://mail.python.org/pipermail/python-bugs-list/2014-March/235709.html> Am I following the right path? Can ctypes be used in a project on RTD and I just need to persevere, or do I need to give up and just use sphinx from my local machine? Here is the current mock block from [my conf.py](https://github.com/maphew/apt/blob/master/docs/source/conf.py#L19): try: #py3 import from unittest.mock import MagicMock except ImportError: #py27 import from mock import Mock as MagicMock class Mock(MagicMock): @classmethod def __getattr__(cls, name): return Mock() MOCK_MODULES = ['ctypes'] sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) _// this is a cross post from<https://github.com/rtfd/readthedocs.org/issues/1342>. Zero responses after a week so am looking farther afield. //_ Answer: Initially I thought it was ctypes itself that needed to be mocked, but it turns out I needed to work closer to home and **mock the module which calls ctypes, not ctypes itself**. - MOCK_MODULES = ['ctypes'] + MOCK_MODULES = ['knownpaths'] Thank you to @Dunes, whose comment I thought was off-track and not going to help. However it gave just enough of a turning to my mind and path of investigation to land me in the right place after all. Not all teachings look like teaching when they first grace one's attention. ;-)
How to reject or accept an incoming call to my GSM modem using AT commands in Python? Question: I've wrote the below Python program to wait for incoming calls and accept or reject them. Based on [this](http://www.zeeman.de/wp- content/uploads/2007/09/ubinetics-at-command-set.pdf) document and [this](https://www.sparkfun.com/datasheets/Cellular%20Modules/AT_Commands_Reference_Guide_r0.pdf) document, the appropriate AT commands to accept an incoming call is `ATA` or `ATS0` or `ATS0<n>`. And also the appropriate commands to reject the incoming call is `ATH` or `AT H`. I tried all the above commands, but the incoming call neither answered nor rejected! **My Python program :** import time import serial phone = serial.Serial("COM10", 115200, timeout=5) try: time.sleep(1) while(1): x = phone.readline() print(x) if (x == b'RING\r\n'): phone.write(b'AT H') # I replaced this 'AT H' with all the above # commands, but nothing changed about the # incoming call. It always ringing. time.sleep(2) finally: phone.close() **Results for`AT H`:** >>> ================================ RESTART ================================ >>> b'' b'' b'\r\n' b'RING\r\n' b'AT H\r\n' b'RING\r\n' b'AT H\r\n' b'RING\r\n' b'AT H\r\n' b'RING\r\n' b'AT H\r\n' b'RING\r\n' **Results for`ATH`:** >>> ================================ RESTART ================================ >>> b'' b'' b'' b'\r\n' b'RING\r\n' b'ATH\r\n' b'RING\r\n' b'ATH\r\n' b'RING\r\n' b'ATH\r\n' b'RING\r\n' **Results for`ATA`:** >>> ================================ RESTART ================================ >>> b'' b'' b'' b'\r\n' b'RING\r\n' b'ATA\r\n' b'RING\r\n' b'ATA\r\n' b'RING\r\n' b'ATA\r\n' b'RING\r\n' **Results for`ATS0`:** >>> ================================ RESTART ================================ >>> b'' b'' b'' b'\r\n' b'RING\r\n' b'ATS0\r\n' b'RING\r\n' b'ATS0\r\n' b'RING\r\n' As you see above, the GSM modem regardless of the AT command that I send to it, continue to ringing. What's wrong about my program? _Note that my modem is a[D-Link DWM-156](http://www.dlink.com/uk/en/support/product/dwm-156-3-75-hsupa-usb- adapter) and I can send SMS or make a call successfully using it in Python._ Thanks in advance. Answer: Add to the end of each `AT` command a **CR** to make it a valid `AT` command
Flask + Celery: working outside of request context Question: today i started using Celery but am having an issue that am not able to resolve. more specifically, my Flask configuration is : from celery import Celery def make_celery(app): celery = Celery(__name__, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery app.config.update(CELERY_BROKER_URL="redis://127.0.0.1:6379", CELERY_RESULT_BACKEND="redis://127.0.0.1:6379", CELERY_IMPORTS=("netdiff"), CELERY_TASK_RESULT_EXPIRES = 300, CELERY_REDIRECT_STDOUTS_LEVEL="DEBUG") celery = make_celery(app) I have 1 Celery task declared as : @celery.task(name="implement_netdiff", bind=True) def implement_netdiff(diff_): I run a Celery worker as : celery -A netdiff.celery worker but, when i am calling the task : diff_ = {'control': {'maintenance': maintenance,},'netelement': {'host': net element, 'ip': ip, 'pyez': None,},} implement_netdiff.apply_async(args=(diff_,)) Celery complains about : [2015-06-20 17:23:45,307: ERROR/MainProcess] Task implement_netdiff[714d5cee-b466-4075-9f8c-1b59b745e706] raised unexpected: TypeError('implement_netdiff() takes exactly 1 argument (2 given)',) Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/home/app/netdiff/netdiff.py", line 19, in __call__ return TaskBase.__call__(self, *args, **kwargs) File "/usr/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) TypeError: implement_netdiff() takes exactly 1 argument (2 given) could you please advise on how this can be resolved ? EDIT: i changed the declaration of the function to be "def implement_netdiff(self, diff_):" and it does not complaining anymore. EDIT: "working outside of request context" was resolved like: def implement_netdiff(self, diff_): with celery.app.app_context(): QUESTION: what `celery.start()` does ? Answer: This is [documented](https://celery.readthedocs.org/en/latest/userguide/tasks.html#task- request-info). By specifying `bind=True` you ask celery to bind your method and get a task type instance as first "`self`" argument.
Matching two vector paths Question: I have several vector paths and a query path and now I am trying to get the path which is most similar to the query path. I can access length(perimeter) of each path, and width and height of their bounding boxes. I am using python and using pyx library for rendering SVG paths and calculating their bounding boxes. Pseudo code looks like... THRESHOLD = //some value qpath = //my query path similar_paths = [] for path in path_list: if (comparable width and comparable height and comparable perimeters): similar_paths.append(path) But It does not seem to give nice results. Any ideas on how to improve the results? Answer: Lets use a simple PyX graph to generate some paths: ![a pyx graph](http://i.stack.imgur.com/zIAWN.png) The paths could also come from an SVG file read in parsed mode. Once you have PyX paths, you can use PyX features to get further information about the paths. In the following simple version I calculate a few points along each path and the sum up their distance. (I do it using method names ending by `_pt`, which work in PostScript points. It is a little faster than using PyX units. Also I converted all paths to normpaths explicitely in the beginning. While this is not necessary, it helps reduces some function calls internally.) Here is the full code (including the graph to generate the sample paths): import math from pyx import * # create some data (and draw it) g = graph.graphxy(width=10, x=graph.axis.lin(min=0, max=2*math.pi)) qpi = g.plot(graph.data.function("y(x)=sin(x)")) opi1 = g.plot(graph.data.function("y(x)=sin(x)+0.1*sin(10*x)")) opi2 = g.plot(graph.data.function("y(x)=sin(x)+0.2*sin(20*x)", points=1000)) g.writePDFfile() # get the corresponding PyX paths qpath = qpi.path.normpath() opath1 = opi1.path.normpath() opath2 = opi2.path.normpath() # now analyse it POINTS = 10 qpath_arclen_pt = qpath.arclen_pt() qpath_points_pt = qpath.at_pt([qpath_arclen_pt*i/(POINTS-1) for i in range(POINTS)]) for opath in [opath1, opath2]: opath_arclen_pt = opath.arclen_pt() opath_points_pt = opath.at_pt([opath_arclen_pt*i/(POINTS-1) for i in range(POINTS)]) print(sum(math.sqrt((qpoint_x_pt-opoint_x_pt)**2 + (qpoint_y_pt-opoint_y_pt)**2) for (qpoint_x_pt, qpoint_y_pt), (opoint_x_pt, opoint_y_pt) in zip(qpath_points_pt, opath_points_pt))) The program just prints out: 25.381154890630064 56.44386644062556 which indicates, that the dashed lines is closer to the solid one than the dotted line. You may also compare tangents, curvatures, the arclen itself etc. ... there are plenty of options depending on your needs.
how can i count how many time program has been executed in python Question: from itertools import permutations import random import pprint import timeit start_time = timeit.default_timer() count = 0 def gird(board_size): print ("\n".join('# ' * inrange + 'Q ' + '# ' * (8-inrange-1)\ for inrange in board_size) + "\n\n= = new board \n") count+=1 coloms = range(8) for board_size in permutations(coloms): if 8 == len(set(board_size[inrange]+inrange for inrange in coloms)): if 8 == len(set(board_size[inrange]-inrange for inrange in coloms)): gird(board_size) elapsed = timeit.default_timer() - start_time print(elapsed) print(count) i want to see how many time this code did run, i have to Measure the search cost (number of iterations until it hits a minima) and percentage of solved problems. this a 8 queen problem. Answer: > how can i count how many time program has been executed in python The _only_ way I can think of to satisfy your problem as you've described it rather then running your function N times is something like this: **Example:** from __future__ import print_function import atexit from os import path from json import dumps, loads def read_counter(): return loads(open("counter.json", "r").read()) + 1 if path.exists("counter.json") else 0 def write_counter(): with open("counter.json", "w") as f: f.write(dumps(counter)) counter = read_counter() atexit.register(write_counter) def main(): print("I have been run {} times".format(counter)) if __name__ == "__main__": main() **Sample Run(s):** $ python foo.py I have been run 1 times $ python foo.py I have been run 2 times $ python foo.py I have been run 3 times However I must point out that this is not a very good way to "measure" the performance of a program or the functions you've written. You should be looking at things like [hotshot](https://docs.python.org/2/library/hotshot.html) or [timeit](https://docs.python.org/2/library/timeit.html) or running your function internally a number of times and measuring the "right things".
Why is multiprocessing copying my data if I don't touch it? Question: I was tracking down an out of memory bug, and was horrified to find that python's multiprocessing appears to copy large arrays, even if I have no intention of using them. Why is python (on Linux) doing this, I thought copy-on-write would protect me from any extra copying? I imagine that whenever I reference the object some kind of trap is invoked and only then is the copy made. Is the correct way to solve this problem for an arbitrary data type, like a 30 gigabyte custom dictionary to use a `Monitor`? Is there some way to build Python so that it doesn't have this nonsense? import numpy as np import psutil from multiprocessing import Process mem=psutil.virtual_memory() large_amount=int(0.75*mem.available) def florp(): print("florp") def bigdata(): return np.ones(large_amount,dtype=np.int8) if __name__=='__main__': foo=bigdata()#Allocated 0.75 of the ram, no problems p=Process(target=florp) p.start()#Out of memory because bigdata is copied? print("Wow") p.join() Running: [ebuild R ] dev-lang/python-3.4.1:3.4::gentoo USE="gdbm ipv6 ncurses readline ssl threads xml -build -examples -hardened -sqlite -tk -wininst" 0 KiB Answer: I'd expect this behavior -- when you pass code to Python to compile, anything that's not guarded behind a function or object is immediately `exec`ed for evaluation. In your case, `bigdata=np.ones(large_amount,dtype=np.int8)` has to be evaluated -- unless your actual code has different behavior, `florp()` not being called has nothing to do with it. To see an immediate example: >>> f = 0/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero >>> def f(): ... return 0/0 ... >>> To apply this to your code, put `bigdata=np.ones(large_amount,dtype=np.int8)` behind a function and call it as your need it, otherwise, Python is trying to be hepful by having that variable available to you at runtime. If `bigdata` doesn't change, you could write a function that gets or sets it on an object that you keep around for the duration of the process. edit: Coffee just started working. When you make a new process, Python will need to copy all objects into that new process for access. You can avoid this by using threads or by a mechanism that will allow you to share memory between processes such as [shared memory maps](https://docs.python.org/2/library/multiprocessing.html#sharing-state- between-processes) or shared [ctypes](https://docs.python.org/2/library/multiprocessing.html#module- multiprocessing.sharedctypes)
Python Regex Search and Count with Symbol Character Question: i try to make some script with python to find and count a word in string. A word is "@sosiora", i have find some example but it's not find "@sosiora" but "sosiora". Here is my script #!/usr/bin/python import re words = ["@sosiora"] exactMatch = re.compile(r'\b%s\b' % '\\b|\\b'.join(words), flags=re.IGNORECASE) print len(exactMatch.findall("@riky ini adalah @sosiora dengan huruf s ")) I don't know but it's always print 0. Please help me, i'm newbie in Python. Thank you Extra : I had edit my code now, but i found some problem again. how to extract the word if i have found them ? here is my code now #!/usr/bin/python import re words = ["@sosiora","@sosiora#1","@sosiora#2","@sosiora#3","@sosiora#4","@sosiora#5"] exactMatch = re.compile('|'.join(words), flags=re.IGNORECASE) print len(exactMatch.findall("@riky ini adalah @Sosiora#1 dengan huruf s ")) if i found "@sosiora#1" or "@sosiora#2", how to extract the number? because i need that number. Answer: The regex you're compiling is wrong... This should work better: #!/usr/bin/python import re words = ["(@sosiora#(\d+))"] exactMatch = re.compile('|'.join(words), flags=re.IGNORECASE) text = "@riky ini adalah @Sosiora#1 dengan huruf s" m = exactMatch.findall(text) print 'Found %d matches' % len(m) print 'First word found: ' + m[0][0] # @Sosiora#1 print 'First index found: ' + m[0][1] # 1
Python - Passing character to C library Question: I've got quite the trouble running a program on Linux i wrote. Since it's quite a large program i won't post the whole code but only the part that gets me confused. I've got a library, written in C++ and compiled on Linux Ubuntu, which does some work and prints an incoming character to the console like this: bool PostCommand( void* pParam, char c, char* szRet, int nLength, int nBlockTime ) { printf("Got: %d", c); //do some work return true; } The whole thing compiles well and my Python program is able to call the function: # -*- coding: ascii -*- from ctypes import cdll,c_char,create_string_buffer,...#don't want to list 'em all m_DLL = cdll.LoadLibrary("./libaddonClient.so") PostCommand = m_DLL.PostCommand PostCommand.argtype = [c_void_p,c_char,c_char_p,c_int,c_int] PostCommand.restype = c_bool print ord('1') sz = create_string_buffer(20); #pObject was generated prior and works fine PostCommand( pObject, '1', sz, 20, 1 ) The console output looks like 49 Got: -124 My question is how the 49 could change into -124. The variable isn't being changed between it's creation and the call of the C++ function or the printf, which follows right after the call. There are no threads accessing this function nor static variables. Answer: Your problem is in the python code, you are passing a string instead of a character, the single quotes and double quotes both work almost exactly the same in python, and `-124` I presume comes perhaps from something that python interpreter does internally, try this PostCommand( pObject, ord('1'), sz, 20, 1 ) What is very likely happening is that the parameter when processed by the interpreter is stored as a c string, which is a `nul` terminated sequence of non-`nul` bytes, hence a pointer is almost surely used, so `-124` has to be the address of the pointer which of course requires more than a byte to be represented.
Regex expression after quotation on python Question: I am trying to develop a program on Python that would get the name of the artists from a twit from Pandora. Like for example if I have this twitter: > I'm listening to "I Can Make It Better" by Luther Vandross on Pandora > #pandora <http://t.co/ieDbLC393F>. I would like to get only the name Luther Vandross back. I do not know much about regex, so I tried to do the following code: print re.findall('".+?" by [\w+]+', text) But the result was "I can Make it Better" by Luther Do you have any idea on how I would be able to develop a regular expression on python to get it? Answer: Your regex is near, but you can change the delimiters to use `" by` and `on`. However, you need to use capturing groups by using parentheses. You can use a regex like this: " by (.+?) on **[Working demo](https://regex101.com/r/oN1uJ8/1)** ![Regular expression visualization](https://www.debuggex.com/i/WeaW9dGrXAk4T3Cw.png) The idea behind this regex is to capture the content between the `" by` and `on`, using a simple nongreedy regex. Match information MATCH 1 1. [43-58] `Luther Vandross` Code import re p = re.compile(ur'" by (.+?) on') test_str = u"I'm listening to \"I Can Make It Better\" by Luther Vandross on Pandora #pandora http://t.co/ieDbLC393F.\n" re.search(p, test_str)
Add object to start of dictionary Question: I am making a group chatting app and I have images associated with the users, so whenever they say something, their image is displayed next to it. I wrote the server in python and the client will be an iOS app. I use a dictionary to store all of the message/image pairs. Whenever my iOS app sends a command to the server (`msg:<message`), the dictionary adds the image and message to the dictionary like so:`dictionary[message] = imageName`, which is converted to lists then strings to be sent off in a socket. I would like to add the incoming messages to the start of the dictionary, instead of the end. Something like #When added to end: dictionary = {"hello":image3.png} #new message dictionary = {"hello":image3.png, "i like py":image1.png} #When added to start: dictionary = {"hello":image3.png} #new message dictionary = {"i like py":image1.png, "hello":image3.png} Is there any way to add the object to the start of the dictionary? Answer: First of all it doesn't added the item at the end of dictionary because dictionaries use hash-table to storing their elements and are unordered. if you want to preserve the order you can use `collections.OrderedDict`.but it will appends the item at the end of your dictionary. One way is appending that item to the fist of your items then convert it to an Orderd: >>> from collections import OrderedDict >>> d=OrderedDict() >>> for i,j in [(1,'a'),(2,'b')]: ... d[i]=j ... >>> d OrderedDict([(1, 'a'), (2, 'b')]) >>> d=OrderedDict([(3,'t')]+d.items()) >>> d OrderedDict([(3, 't'), (1, 'a'), (2, 'b')]) Also as another efficient way if it's not necessary to use a dictionary you can use a `deque` that allows you to append from both side : >>> from collections import deque >>> d=deque() >>> d.append((1,'a')) >>> d.append((4,'t')) >>> d deque([(1, 'a'), (4, 't')]) >>> d.appendleft((8,'p')) >>> d deque([(8, 'p'), (1, 'a'), (4, 't')])
How can I correct my code to produce a nested dictionary? Question: I am trying to create a nested dictionary. I have a list of tuples (called 'kinetic_parameters') which looks like this: ('New Model','v7','k1',0.1) ('New Model','v8','k2',0.2) ('New Model','v8','k3',0.3) I need the second column to be the outer key and the value to be another dictionary with inner key being the third column and value being the number in the fourth. I currently have: for i in kinetic_parameters: dict[i[1]]={} dict[i[1]][i[2]]=i[3] But this code will not deal with multiple keys in the inner dictionary so I lose some information. Does anybody know how to correct my problem? I'm using Python 2.7 and I want the output to look like this: {'v7': {'k1': 0.1}, 'v8':{'k2':0.2, 'k3': 0.3}} Answer: Use a [defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict), and don't use `dict` as a variable name, since we need it to refer to the dictionary type: import collections d = collections.defaultdict(dict) for i in kinetic_parameters: d[i[1]][i[2]]=i[3] This will create the dictionaries automatically.
Calling on a class Question: I'm using geopy and have a question on why an error is coming up. This code sample is from the one provided at [github](https://github.com/geopy/geopy#geocoding). It works as mentioned from geopy.geocoders import Nominatim geolocator = Nominatim() location = geo.geocode("NY") print((location.latitude, location.longitude)) How come the code below provides an error? What's the reason behind it? from geopy.geocoders import Nominatim as geo location = geo.geocode("NY") print((location.latitude, location.longitude)) The error provided by the second code is: Traceback (most recent call last): File "C:/Users/Leb/Desktop/Python/so2.py", line 5, in <module> location = geo.geocode("NY") TypeError: geocode() missing 1 required positional argument: 'query' Answer: You need to instantiate class (create object) from geopy.geocoders import Nominatim as geo location = geo().geocode("NY") print((location.latitude, location.longitude))
Importing Python file from PostgreSQL stored procedure Question: It is possible to have Python code in a PostgreSQL stored procedure. For example: CREATE FUNCTION someProc() RETURNS void AS $$ # Some Python3 code... $$ LANGUAGE plpython3u; But how can I include a python file from this code? The current directory of Python running in PostgreSQL is this: >>> os.getcwd() ... /var/lib/postgresql/9.3/main I tryied the following, which worked: CREATE FUNCTION someProc() RETURNS void AS $$ import sys sys.path.append("/dir/to/file") from python_file import pythonFunction # More Python code $$ LANGUAGE plpython3u; This doesn't seem very good for many obvious reasons. Is there a better way to import a python file, or just calling a python function from a python file? **Edit:** There isn't any specific PostgreSQL method to import a file. But the best way is in the correct answer bellow, which resembles my original solution but it is better. Answer: This is no different to dynamically loading Python code from a file in standalone Python: * [How to import a module given the full path?](http://stackoverflow.com/q/67631/398670) PL/Python3 (untrusted) is just the cpython interpreter running embedded in a PostgreSQL backend process as the same operating system user PostgreSQL its self runs as. With a very few differences - like thread safety - it's just Python.
Calculate number of positive and negative string for each word in a list Question: I am new in python and hope you could help me solve this problem and I am using python 3.4. I have a list that contain word,either positive or negative, and it's frequency This is the original list: `finalSentiment = [('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('hijacked', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('left', 'negative'), ('pay', 'negative'), ('pay', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('befo', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('radical', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('tcot', 'negative'), ('mt', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('loony', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('right', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('tanker', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('people', 'negative'), ('sadly', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('morons', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('oil', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('get', 'negative'), ('account', 'negative'), ('account', 'negative'), ('account', 'negative'), ('account', 'negative'), ('account', 'negative'), ('account', 'negative'), ('account', 'negative'), ('account', 'negative'), ('account', 'negative'), ('account', 'negative'), ('account', 'negative'), ('account', 'negative'), ('account', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('pirates', 'negative'), ('flag', 'negative'), ('flag', 'negative'), ('flag', 'negative'), ('flag', 'negative'), ('flag', 'negative'), ('flag', 'negative'), ('flag', 'negative'), ('flag', 'negative'), ('flag', 'negative'), ('flag', 'negative'), ('flag', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('like', 'negative'), ('day', 'negative'), ('day', 'negative'), ('day', 'negative'), ('day', 'negative'), ('day', 'negative'), ('day', 'negative'), ('day', 'negative'), ('day', 'negative'), ('day', 'negative'), ('malaysia', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('one', 'negative'), ('got', 'negative'), ('got', 'negative'), ('got', 'negative'), ('got', 'negative'), ('got', 'negative'), ('got', 'negative'), ('got', 'negative'), ('long', 'negative'), ('long', 'negative'), ('long', 'negative'), ('long', 'negative'), ('long', 'negative'), ('long', 'negative'), ('long', 'negative'), ('none', 'positive'), ('look', 'positive'), ('time', 'negative'), ('time', 'negative'), ('time', 'negative'), ('time', 'negative'), ('time', 'negative'), ('time', 'negative'), ('time', 'negative'), ('time', 'negative'), ('time', 'negative'), ('time', 'negative'), ('time', 'negative'), ('time', 'negative'), ('fathers', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('terrorist', 'negative'), ('know', 'negative'), ('know', 'negative'), ('know', 'negative'), ('know', 'negative'), ('know', 'negative'), ('know', 'negative'), ('know', 'negative'), ('know', 'negative'), ('know', 'negative'), ('driver', 'negative'), ('driver', 'negative'), ('driver', 'negative'), ('driver', 'negative'), ('driver', 'negative'), ('driver', 'negative'), ('angry', 'negative'), ('angry', 'negative'), ('angry', 'negative'), ('angry', 'negative'), ('angry', 'negative'), ('angry', 'negative'), ('angry', 'negative'), ('angry', 'negative'), ('angry', 'negative'), ('live', 'negative'), ('live', 'negative'), ('live', 'negative'), ('dem', 'negative'), ('dem', 'negative'), ('dem', 'negative'), ('dem', 'negative'), ('dem', 'negative'), ('dem', 'negative'), ('dem', 'negative')]` What i am trying to do is to calculate number of positive and negative for each word from the list that I have. So that if the number of negative is higher, the word is negative. Then I can come out with a new list like: eg: `newList = [('hijacked','negative'),('left','negative'), . . .]` a) I try using the `num = Count(finalSentiment).most_common()[:50]` function and came out with the new list as below. num = [(('hijacked', 'negative'), 302), (('left', 'negative'), 88), (('one', 'negative'), 79), (('befo', 'negative'), 72), (('radical', 'negative'), 70), (('tcot', 'negative'), 70), (('tanker', 'negative'), 55), (('like', 'negative'), 47), (('right', 'negative'), 36), (('oil', 'negative'), 26), (('hijacked', 'positive'), 22), (('pirates', 'negative'), 21), (('people', 'negative'), 21), (('terrorist', 'negative'), 21), (('loony', 'negative'), 18), (('morons', 'negative'), 18), (('get', 'negative'), 17), (('account', 'negative'), 12), (('flag', 'negative'), 11), (('time', 'negative'), 10), (('angry', 'negative'), 9), (('like', 'positive'), 8), (('day', 'negative'), 8), (('know', 'negative'), 8), (('dem', 'negative'), 7), (('tanker', 'positive'), 7), (('long', 'negative'), 6), (('left', 'positive'), 6), (('driver', 'negative'), 6), (('one', 'positive'), 6), (('got', 'negative'), 6), (('tcot', 'positive'), 5), (('radical', 'positive'), 5), (('befo', 'positive'), 5), (('pirates', 'positive'), 3), (('live', 'negative'), 3), (('oil', 'positive'), 2), (('time', 'positive'), 2), (('pay', 'negative'), 2), (('none', 'positive'), 1), (('people', 'positive'), 1), (('morons', 'positive'), 1), (('long', 'positive'), 1), (('account', 'positive'), 1), (('mt', 'negative'), 1), (('got', 'positive'), 1), (('day', 'positive'), 1), (('loony', 'positive'), 1), (('know', 'positive'), 1), (('fathers', 'negative'), 1)] What I want to do is to compare the word frequency either positive or negative is higher. So, if negative is higher I want to create a new list that contain the word and negative. eg: `[('hijacked','negative'),('left','negative'), . . .]` Each word will only have either positive or negative in the list. What I have try to is I try to access each of the item in the list using for loop. for item in num: unique_word = item[0] temp = unique_word[0] temp1 = unique_word[1] frequency = item[1] but I cant figure out how to manipulate the data after I access it. b) I use counter() function and come out with this list: cnt = Counter() for word in finalSentiment: cnt[word] += 1 print(cnt) Counter({('hijacked', 'negative'): 302, ('left', 'negative'): 88, ('one', 'negative'): 79, ('befo', 'negative'): 72, ('tcot', 'negative'): 70, ('radical', 'negative'): 70, ('tanker', 'negative'): 55, ('like', 'negative'): 47, ('right', 'negative'): 36, ('oil', 'negative'): 26, ('hijacked', 'positive'): 22, ('pirates', 'negative'): 21, ('terrorist', 'negative'): 21, ('people', 'negative'): 21, ('morons', 'negative'): 18, ('loony', 'negative'): 18, ('get', 'negative'): 17, ('account', 'negative'): 12, ('flag', 'negative'): 11, ('time', 'negative'): 10, ('angry', 'negative'): 9, ('like', 'positive'): 8, ('day', 'negative'): 8, ('know', 'negative'): 8, ('dem', 'negative'): 7, ('tanker', 'positive'): 7, ('got', 'negative'): 6, ('left', 'positive'): 6, ('one', 'positive'): 6, ('driver', 'negative'): 6, ('long', 'negative'): 6, ('radical', 'positive'): 5, ('befo', 'positive'): 5, ('tcot', 'positive'): 5, ('pirates', 'positive'): 3, ('live', 'negative'): 3, ('time', 'positive'): 2, ('pay', 'negative'): 2, ('oil', 'positive'): 2, ('mt', 'negative'): 1, ('loony', 'positive'): 1, ('morons', 'positive'): 1, ('long', 'positive'): 1, ('got', 'positive'): 1, ('sadly', 'negative'): 1, ('day', 'positive'): 1, ('none', 'positive'): 1, ('fathers', 'negative'): 1, ('account', 'positive'): 1, ('malaysia', 'negative'): 1, ('right', 'positive'): 1, ('people', 'positive'): 1, ('know', 'positive'): 1, ('look', 'positive'): 1}) The problem I have now is how to compare as example the word 'hijacked', the number of negative is higher. So in the new list, 'hijacked' should be 'negative such that: eg: newList = `[('hijacked','negative'),('left','negative'), . . .]` c) OR maybe I should calculate number of positive and negative on my own instead of using the `most_common()` function or `counter()`. My problem to calculate the number of positive and negative is because there are multiple word in the list. If the word is only 'hijacked' with positive and negative attached to it I think I can solve the problem. Any help will be much appreciated. Answer: from collections import Counter counts = Counter(finalSentiment) output = [] for word in set(w for w, s in finalSentiment): if counts.get((word, 'positive'), 0) > counts.get((word, 'negative'), 0): output.append((word, 'positive')) else: output.append((word, 'negative'))
Python for Maya: "Object's name is not unique." when calling object from class to build UI Question: # The Problem: I don't get any syntax errors when i run the script up until i try to build the UI. Everything seems fine until i run the last 2 lines of code. I get the following error : **Error: RuntimeError: file line 41: Object's name 'mst_txtfld_x_value' is not unique.** I made sure to _deleteUI_ in line 8~9, so I'm assuming that the _textField_ is being created twice. Or is there something that I'm not understanding about how classes should work? I am new to classes and would appreciate an explanation why I'm getting this error. # The Code: import maya.cmds as mc from functools import partial class MoveSelTool(object): def __init__(self, *args): pass if(mc.window("ak_move_sel_tool_window", query=True, exists=True)): mc.deleteUI("ak_move_sel_tool_window") def build_window_UI(self): self.window = mc.window("ak_move_sel_tool_window", title="Move Selection Tool") self.columnLayout = mc.columnLayout() self.txt_directions = mc.text(align="left", label="Directions: Input translation increment.\n") self.rowColumn = mc.rowColumnLayout(numberOfColumns=8) self.txt_x = mc.text(label=" X: ", align="right") self.txtfld_x = mc.textField("mst_txtfld_x_value", ann='input units to move X', width=50) self.txt_y = mc.text(label=" Y: ", align="right") self.txtfld_y = mc.textField("mst_txtfld_y_value", ann='input units to move Y', width=50) self.txt_z = mc.text(label=" Z: ", align="right") self.txtfld_z = mc.textField("mst_txtfld_z_value", ann='input units to move Z', width=50) self.txt_space = mc.text(label=" ") self.move_btn = mc.button(label="Move") #ui commands mc.button(self.move_btn, edit=True, command=partial(self.move_selection)) mc.textField("mst_txtfld_x_value", enterCommand=partial(self.move_selection)) mc.textField("mst_txtfld_y_value", enterCommand=partial(self.move_selection)) mc.textField("mst_txtfld_z_value", enterCommand=partial(self.move_selection)) #show ui mc.showWindow(self.window) def query_mst_user_input(self): self.x_value = mc.textField("mst_txtfld_x_value", query=True, text=True) self.y_value = mc.textField("mst_txtfld_y_value", query=True, text=True) self.z_value = mc.textField("mst_txtfld_z_value", query=True, text=True) return (self.x_value, self.y_value, self.z_value) def move_selection(self): self.mst_user_selection = mc.ls(selection=True) self.mst_user_inputs = query_mst_user_input() mc.move(self.mst_user_selection, self.mst_user_inputs[0], self.mst_user_inputs[1], self.mst_user_inputs[2], relative=True) def show(self): self.build_window_UI() mst=MoveSelTool() mst.show() Answer: You forgot the edit flag to set ui command. #ui commands mc.button(self.move_btn, edit=True, command=partial(self.move_selection)) mc.textField("mst_txtfld_x_value", edit=True, enterCommand=partial(self.move_selection)) mc.textField("mst_txtfld_y_value", edit=True, enterCommand=partial(self.move_selection)) mc.textField("mst_txtfld_z_value", edit=True, enterCommand=partial(self.move_selection))
openssl hmac differ from python hmac Question: with: KEY='7vgd39eyxald9sucClM7' DATA='POST\nmultipart/form-data\nWed, 10 Jun 2015 07:27:43 GMT\n/1/classes/item\nx-wbs-uid:f886a495220975d724ff3679a5cc9cef04343076' in command line HASH_BIN=`echo -n "$DATA" | openssl dgst -sha256 -mac HMAC -macopt key:$KEY -binary` openssl enc -e -base64 <<< $HASH_BIN result: VmBdzRcNg0OJZVVLSgg1zcViflug9iqtb6Gsnjqf9F8K in python import hmac, hashlib, base64 hash = hmac.new(KEY, DATA, hashlib.sha256).digest() base64.encodestring(hash).strip() result: u6Poj7Jqrz6+wvXDNyK88pVm5iKUF6RUmq2P2LtHmuE= Can someone give me a help??? Thanks a lot. Answer: It should be caused by the `DATA` string definition in your python code. You need add `r` to treat the `DATA` as a raw string, such as DATA=r'POST\nmultipart/form-data\nWed, 10 Jun 2015 07:27:43 GMT\n/1/classes...' With the `r`, all escape codes in `DATA` will be ignored. That is to say, '\n' will be treated as a newline character, but r'\n' will be treated as the characters \ followed by n. In Python, '\n' // 0x0d r'\n' // 0x5c 0x6e With the `r`, it will output the result equals to output via openssl, VmBdzRcNg0OJZVVLSgg1zcViflug9iqtb6Gsnjqf9F8K
Using counter on array for one value while keeping index of other values Question: After reading the answers on this question [How to count the frequency of the elements in a list?](http://stackoverflow.com/questions/2161752/how-to-count- the-frequency-of-the-elements-in-a-list) I was wondering how to count the frequency of something, and at the same time retreive some extra information, through something like an index. For example a = ['fruit','Item#001'] b = ['fruit','Item#002'] c = ['meat','Item#003'] foods = [a,b,c] Now I want to count how many times fruit is in the list foods. If I use counter on the first index of each array a,b, and c, the results will have the number of fruit, but I can not access which item it was. In essence, if I use `most_common`, I will get a list of the number of times fruit appears, like ('fruit',2), how can I get all the items from both of those occurrences. I would like to avoid using the attributes like this question [Python how to use Counter on objects according to attributes](http://stackoverflow.com/questions/28306700/python-how-to-use- counter-on-objects-according-to-attributes) Example, where it would be doing what I would like, not necessarily what the Counter method actually does. counts = Counter(foods) counts.most_common(10) print counts -> (('fruit',2)('meat',1)) print counts[0].Something_Like_Expand_Method() -> ['fruit','Item#001'],['fruit','Item#002'] Answer: To count how often one value occurs and at the same time you want to select those values, you'd simply select those values and count how many you selected: fruits = [f for f in foods if f[0] == 'fruit'] fruit_count = len(fruits) If you need to do this for all your entries, you really want to _group_ your items, using a dictionary: food_groups = {} for food in foods: food_groups.setdefault(food[0], []).append(food[1]) at which point you can ask for any of the groups, plus their length: fruit = food_groups['fruit'] fruit_count = len(fruit) If you still need to know which food group is most common, you can then just use the `max()` function: most_common_food = max(food_groups, key=lambda f: len(food_groups[f])) # just the food group name most_common_food_items = max(food_groups.values(), key=len) # just the food group name or you can create a `Counter` from the groups by passing in a dictionary mapping key to value length: group_counts = Counter({f: len(items) for f, items in food_groups.iteritems()}) for food, count in group_counts.most_common(2): print '{} ({}):'.format(food, count) print ' items {}\n'.format(', '.join(food_groups[food])) Demo: >>> from collections import Counter >>> a = ['fruit','Item#001'] >>> b = ['fruit','Item#002'] >>> c = ['meat','Item#003'] >>> foods = [a,b,c] >>> food_groups = {} >>> for food in foods: ... food_groups.setdefault(food[0], []).append(food[1]) ... >>> food_groups {'fruit': ['Item#001', 'Item#002'], 'meat': ['Item#003']} >>> group_counts = Counter({f: len(items) for f, items in food_groups.iteritems()}) >>> for food, count in group_counts.most_common(2): ... print '{} ({}):'.format(food, count) ... print ' items {}\n'.format(', '.join(food_groups[food])) ... fruit (2): items Item#001, Item#002 meat (1): items Item#003
sys.argv in a windows environment Question: I'm attempting to learn python using the book 'a byte of python'. The code: import sys print('the command line arguments are:') for i in sys.argv: print(i) print('\n\nThe PYTHONPATH is', sys.path, '\n') outputs: the command line arguments are: C:/Users/user/PycharmProjects/helloWorld/module_using_sys.py The PYTHONPATH is ['C:\\Users\\user\\PycharmProjects\\helloWorld', 'C:\\Users\\user\\PycharmProjects\\helloWorld', 'C:\\Python34\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages'] when the book said that the output should be: The command line arguments are: module_using_sys.py we are arguments The PYTHONPATH is ['/tmp/py', # many entries here, not shown here '/Library/Python/2.7/site-packages', '/usr/local/lib/python2.7/site-packages'] The book is written for python 2, whereas I am using python 3. My question is **why is there a difference?** Answer: You are calling the script wrong Bring up a cmd (command line prompt) and type: cd C:/Users/user/PycharmProjects/helloWorld/ module_using_sys.py we are arguments And you will get the correct output.
Python: can't access newly defined environment variables Question: I can't access my env var: import subprocess, os print os.environ.get('PATH') # Works well print os.environ.get('BONSAI') # doesn't work But the env var is well added in my `/home/me/.bashrc`: BONSAI=/home/me/Utils/bonsai_v3.2 export BONSAI And I can access this env var from a new terminal. Answer: After updating your `.bashrc`, perform `source ~/.bashrc` to apply the changes. Also, merge the two `BONSAI`-related calls into one: export BONSAI=/home/me/Utils/bonsai_v3.2 * * * _UPDATE: It was actually an attempt to update the environment for some Eclipse-based IDE. This is a different usecase altogether. It should be described in the Eclipse[help](http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.cdt.doc.user%2Ftasks%2Fcdt_t_run_env.htm). Also, a similar question was answered [here](http://stackoverflow.com/questions/7048216/environment-variables-in- eclipse)._
Pixel movement and loops Python Question: We are using JES in my intro programming class and I have run into roadblock for my lab. The program is supposed to allow a user to select a picture and then a moth(bug) will start at the center of the picture and make random movements and change pixels to white if they are not already to simulate eating. I am stuck on the movement part. the current program below will load and eat 1 pixel at the very center but make no other movements. Could someone give me a hint as to what I am doing wrong with my random movement calls? from random import * def main(): #lets the user pic a file for the bug to eat file= pickAFile() pic= makePicture(file) show(pic) #gets the height and width of the picture selected picHeight= getHeight(pic) picWidth= getWidth(pic) printNow("The height is: " + str(picHeight)) printNow("The width is: " + str(picWidth)) #sets the bug to the center of the picture x= picHeight/2 y= picWidth/2 bug= getPixelAt(pic,x,y) printNow(x) printNow(y) color= getColor(bug) r= getRed(bug) g= getGreen(bug) b= getBlue(bug) pixelsEaten= 0 hungerLevel= 0 while hungerLevel < 400 : if r == 255 and g == 255 and b == 255: hungerLevel + 1 randx= randrange(-1,2) randy= randrange(-1,2) x= x + randx y= y + randy repaint(pic) else: setColor(bug, white) pixelsEaten += 1 randx= randrange(-1,2) randy= randrange(-1,2) x= x + randx y= y + randy repaint(pic) Answer: Looks like you're never updating the position of the bug within the loop. You change `x` and `y`, but this doesn't have any effect on `bug`. Try: while hungerLevel < 400 : bug= getPixelAt(pic,x,y) #rest of code goes here * * * Incidentally, if you have identical code in an `if` block and an `else` block, you can streamline things by moving the duplicates outside of the blocks entirely. Ex: while hungerLevel < 400 : bug= getPixelAt(pic,x,y) if r == 255 and g == 255 and b == 255: hungerLevel + 1 else: setColor(bug, white) pixelsEaten += 1 randx= randrange(-1,2) randy= randrange(-1,2) x= x + randx y= y + randy repaint(pic)
return a variable value from a subprocess in python Question: I have a code workflow in which from a main script(level 0) I call another script through `subprocess`. This `subprocess script` (level 1) in turn calls another script as a `subprocess`. Now from this level 2 subprocess script I want to return the value of a variable upto the main script(level 0). I have tried `Popen.communicate()` but I am not able to return the value. My current code is as: **main_script.py** def func(): para = ['a','b'] result = subprocess.Popen([sys.executable,"first_subprocess.py"]+para,stdout=subprocess.PIPE) result.wait() return_code = result.returncode out, err = sub_result.communicate() if return_code == 1: return return_code else: if out is not None: print 'return value: ', out if __name__ == '__main__': func() From above script is called `first_subprocess.py` which has: def some_func(): # some other code and multiple print statements para = ['a','b'] result = subprocess.Popen([sys.executable,"second_subprocess.py"]+para,stdout=subprocess.PIPE) result.wait() out, err = result.communicate() return_code = sub_result.returncode if return_code == 0: return out if __name__ == '__main__': some_func() The `second_subprocess.py` returns a value like: def test(): # some other code and multiple print statements val = 'time' print 'returning value' return val if __name__ == '__main__': test() When I try above code I get all the `print` statements in the codes as an output but not the return value. Even if try to `print` the variable value in subprocess instead of doing a return it wont serve the purpose because there are multiple print statements. How can I return the variable value in this case? **UPDATED VERSION:** After @Anthons suggestion I have modifed my `first_subprocess.py` script and `main_script.py` as follows: `first_subprocess.py:` def some_func(): try: key = None if not (key is None): para = ['a','b'] result = subprocess.Popen([sys.executable,"second_subprocess.py"]+para,stdout=subprocess.PIPE) sub_result.wait() out, err = sub_result.communicate() return_code = sub_result.returncode if return_code == 0: for line in out.splitlines(): if not line.startswith('>>>'): continue print line else: sys.exit(0) except: return 1 **Main_script.py:** if out is not None: for line in out.splitlines(): if not line.startswith('>>>'): continue value = line.split(':',1)[1].lstrip() print 'return value:',value` When I execute above I get `UnboundLocalError: local variable 'value' referenced before assignment` at the `print value` command. It seems if I do not execute the code in level 1 script and do a sys.exit() then `out` in main script is neither empty nor none but it has some undefined value and thus the `value` variable doesn't get initialized and throws error Answer: If you just want to return an integer value you can use the exit value. This is not the same a returning from `some_func()`, you would have to do `sys.exit(integer_val)`. If you want to return a string like `time` you should print that ( or write to `sys.stdout` ) and then in the calling process (level 1) parse the output from the subprocess and print it to its own stdout for level 0 to see it. In your case level two should do something like: def test(): # some other code and multiple print statements val = 'time' print 'returning value:', val if __name__ == '__main__': test() And at level 1 you would do: def some_func(): # some other code and multiple print statements para = ['a','b'] result = subprocess.Popen([sys.executable,"second_subprocess.py"]+para,stdout=subprocess.PIPE) result.wait() out, err = result.communicate() return_code = sub_result.returncode if return_code == 0: print out if __name__ == '__main__': some_func() With that main_script.py has something to read from the invocation of your level 1 script. I normally use `subprocess.check_output()` for these kind of passing on info. That throws an exception if the called process has a non-zero exit status (i.e. on error). I can also recommend that if the subprocess writes more info than just the variable, you make the output lines easily parseable by returning something unique at the beginning of the line (so you still can use print statements for debugging the individual scripts **and** get the right value from the output): Level 2: def test(): # some other code and multiple print statements print 'debug: Still going strong' val = 'time' print '>>>> returning value:', val if __name__ == '__main__': test() Level 1: ... out, err = result.communicate() for line in out.splitlines(): if not line.startswith('>>>>'): continue print line ... Level 0: ... out, err = result.communicate() for line in out.splitlines(): if not line.startswith('>>>>'): continue try: value = line.split(':', 1)[1] except IndexError: print 'wrong input line', repr(line) print 'return value: ', value ... * * * The following files work together. Save them under their indicated names **lvl2.py** : # lvl2 import sys def test(): # some other code and multiple print statements print >> sys.stderr, 'argv', sys.argv[1:] print 'debug: Still going strong' val = 'time' print '>>>> returning value:', val return 0 if __name__ == '__main__': sys.exit(test()) **lvl1.py** : # lvl1.py import sys import subprocess def some_func(): para = ['a','b'] sub_result = subprocess.Popen( [sys.executable, "lvl2.py" ] + para, stdout=subprocess.PIPE) sub_result.wait() out, err = sub_result.communicate() return_code = sub_result.returncode if return_code == 0: for line in out.splitlines(): if not line.startswith('>>>'): continue print line else: print >> sys.stderr, 'level 2 exited with' + return_code sys.exit(0) if __name__ == '__main__': sys.exit(some_func()) **lvl0.py** : # lvl0 import subprocess import sys def func(): para = ['a','b'] result = subprocess.Popen( [sys.executable, "lvl1.py"] + para, stdout=subprocess.PIPE) result.wait() return_code = result.returncode out, err = result.communicate() value = None if return_code == 0: for line in out.splitlines(): if not line.startswith('>>>'): continue value = line.split(':',1)[1].lstrip() print else: print 'non-zero exit', return_code print 'return value:', value if __name__ == '__main__': func() Then run `python lvl0.py` to check the output to be argv ['a', 'b'] return value: time Now bring these under your revision control system and start making changes a few lines at a time, every time running `python lvl0.py` to check what you might have broken. Commit each revision so you can roll back to last "known good" state and slowly bring in the rest of your code.
ctypes error AttributeError symbol not found, OS X 10.7.5 Question: I have a simple test function on C++: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <locale.h> #include <wchar.h> char fun() { printf( "%i", 12 ); return 'y'; } compiling: gcc -o test.so -shared -fPIC test.cpp and using it in python with ctypes: from ctypes import cdll from ctypes import c_char_p lib = cdll.LoadLibrary('test.so') hello = lib.fun hello.restype = c_char_p print('res', hello()) but then I get an error: Traceback (most recent call last): File "./sort_c.py", line 10, in <module> hello = lib.fun File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 366, in __getattr__ func = self.__getitem__(name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 371, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: dlsym(0x100979b40, fun): symbol not found Where is a problem? using: > Mac Os X 10.7.5 and Python 2.7 Answer: Your first problem is C++ _name mangling_. If you run `nm` on your `.so` file you will get something like this: nm test.so 0000000000000f40 T __Z3funv U _printf U dyld_stub_binder If you mark it as C style when compiled with C++: #ifdef __cplusplus extern "C" char fun() #else char fun(void) #endif { printf( "%i", 12 ); return 'y'; } `nm` gives: 0000000000000f40 T _fun U _printf U dyld_stub_binder Your second problem is that the python will die with a `Segmentation fault: 11` (on OS X). The C++ is returning a `char`, whereas you are marking it in python as a pointer to a char. Use: hello.restype = c_char instead (alter your `import` statement to match). EDIT: as @eryksun pointed out, you should not use `gcc`, you should use `g++` instead. Otherwise the correct C++ runtime will not be linked. To check on `OS X`: otool -L test.so (`ldd`, the tool normally used on UNIX/Linux, is not distributed with OS X)
What is the Big-O of this function that reverses words in a string Question: I have a simple function, reverseWords(), that reveses the words in a string. eg. an input of a S = "this is a string" gives an output of "siht si a gnirts" I was wondering what the big O of this function is. Is it O(N), O(N^2), or O(N* M)? def reverseWords(S): # code in Python 2.7 listA = S.split() output = [] for element in listA: output.append(element[::-1]) return (" ".join(output)) Is it O(N), O(N^2), or O(N* M)? * O(N^2) because we have a nested loop eg. passing over input once, outer loop, and then reversing each character as the inner loop * O(N*M) same reason as above except M is denoted as the looping over the characters * O(N) because... I forgot the explanation Answer: It's `O(N)`. I assume the part you're unsure about is: for element in listA: output.append(element[::-1]) The thing to note here is that although we do have nested loops (over `listA` and over the characters in each element of it), the total number of characters processed is still only `O(N)`. If `k` is the average number of letters in each word, then you can think of the time as `N/k` (for the outer loop) * `k` (for the inner loop) = `N`. A more direct (I'd say better) way to analyse it is to think, "what do I need to do for each character"?: * scan over it looking for word boundaries in `split()` * copy it to a new string in `split()` * append that new string to a result list (actually we do this less than once per character, but an upper bound is fine for big-O) * advance the iterator over `listA` (again, less than once, only once for each word) * copy it in reverse order into a new string in the slice. * append its containing string to `output` (once for each word) * whatever `join()` does (which I invite you to investigate if you care, or take my word that it's `O(total length of all strings)`). Therefore, provided that the list appends, memory allocation, and whatnot, are all amortised `O(1)`, which in CPython they are, then the overall time complexity is `O(N)` including the `join()`. And since correct terminology is important, since it's `O(N)` it therefore is also `O(N^2)`.
run python code in c++ Question: I was making an app that needs to run python code in c++. But when I run this code it gives an segmentation fault in Linux. Does somebody have a clue what it could be? Py_SetProgramName("programName"); Py_SetPythonHome("/usr/lib/python2.7"); Py_Initialize(); PyRun_SimpleString("import sys"); Py_Finalize(); Answer: Use as follows: #include <Python.h> // Attention: this MUST always be the first file included int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); // optional but recommended Py_Initialize(); PySys_SetArgv(argc, argv); // ...
How to update HTML block in IPython Question: This is related to [another question](http://stackoverflow.com/questions/30989509/automaticaly-update- image-in-ipython-notebook) I posted, but is more specific (and hopefully gets more specific answers). I am trying to display `png` images on an IPython notebook, and update the display as the png files are updated. One possible solution is below. Unfortunately, my implementation does not update the file, and creates a new HTML block at the end of the old one. What I want instead, is to replace the old HTML block with the new one -i.e. replace the content only. As example code, I have two notebooks. One notebook generates `pngs` and saves them in a `figures` directory. import os import glob import time import matplotlib.pyplot as plt import numpy as np for ix in range(20): N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses fig = plt.figure(figsize=(8,8)) plt.scatter(x, y, s=area, c=colors, alpha=0.5) fig.savefig(os.path.join("figures", "fig1.png"), bbox_inches="tight") plt.close(fig) time.sleep(3) A second notebook shows the `png`s It is supposed top show a single png which updates. Instead it stacks the same `png` on itself, every time the `png` is updated. import os import time from IPython.html.widgets import interact, interactive, fixed from IPython.html import widgets from IPython.display import clear_output, display, HTML def get_latest_file_ts(directory="figures", file_name="fig1.png", strip_directory=True): """ Continuously check for modifications to the file file_name in directory. If file has been modified after touched_on, return the Unix timestamp of the modification time. :param directory: string / the directory where the file is :param file_name: string / the file name :param strip_directory: boolean / if True, strip the directory part of the file name :return: """ if strip_directory: fname = os.path.join(directory, file_name) else: fname = file_name try: return os.stat(fname).st_mtime except: print "FileNotFoundException: Could not find file %s" % fname return None def check_if_modified_file(directory="figures", file_name="fig1.png", touched_on=1420070400, sleep_time=1, strip_directory=True): """ Continuously check for modifications to the file file_name in directory. If file has been modified after touched_on, return the Unix timestamp of the modification time. :param directory: string / the directory where the file is :param file_name: string / the file name :param touched_on: float / the Unix timestamp on which the file was last modified :param sleep_time: float / wait time between interactions :param strip_directory: boolean / if True, strip the directory part of the file name :return: """ if strip_directory: fname = os.path.join(directory, file_name) else: fname = file_name while True: try: latest_touch = os.stat(fname).st_mtime if latest_touch == touched_on: time.sleep(sleep_time) else: return latest_touch except: print "FileNotFoundException: Could not find %s" % fname return None def show_figs(directory="figures", file_name="fig1.png"): s = """<figure>\n\t<img src="%s" alt="The figure" width="304" height="228">\n</figure>""" % os.path.join(directory, file_name) display(HTML(s)) timestamp = get_latest_file_ts(directory="figures", file_name="fig1.png", strip_directory=True) show_figs(directory="figures", file_name="fig1.png") cnt = 1 while True and cnt < 4: timestamp = check_if_modified_file(directory="figures", file_name="fig1.png", touched_on=timestamp, sleep_time=1, strip_directory=True) display(HTML("")) show_figs(directory="figures", file_name="fig1.png") time.sleep(1) cnt += 1 (as you can see I have added upper limits on the executions of both the generator and consumer loops) Any help on how to make widgets update HTML content would be awesome. Answer: The problem that you only see the first image is very likely related to caching of the browser. To overcome this issue a simple solution is to add a varying query string to the image src as shown e.g. [here](http://stackoverflow.com/a/126831/2870069). Thus your `show_figs` method could look like: import time def show_figs(directory="figures", file_name="fig1.png"): s = """<figure>\n\t<img src="{0}?{1}" alt="The figure" width="304" height="228">\n</figure>""".format(os.path.join(directory, file_name),time.time()) display(HTML(s)) In combination with the `clear_output` function you should be able to get your updated image.
Open CV 3.0.0 video not processing windows winpython 2.7.9 Question: I wrote the following code to open a video file and the file is in the same directory as the script, moreover the code to write a video feed from the camera to the file is not working! import numpy as np import cv2 cap = cv2.VideoCapture('F:/vtest.avi') print cap.isOpened() if(cap.isOpened()== False): cap.open('F://vtest.avi') print cap.isOpened() while(cap.read()): ret,frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) == ord('q'): break cap.release() cv2.destroyAllWindows() But the code threw the following errors. I tried moving the ffmpeg.dll file in Python directory but to no avail. False False Traceback (most recent call last): File "F:\2.py", line 11, in <module> gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) error: ..\..\..\..\opencv\modules\imgproc\src\color.cpp:3480: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor Answer: Try this: import numpy as np import cv2 cap = cv2.VideoCapture('F:/vtest.avi') while(cap.isOpened()): ret,frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) == ord('q'): break cap.release() cv2.destroyAllWindows() Also, place the video in the same directory as this script and check if it works.
cannot import my util module Question: I'm using `sklearn.externals.joblib` to persist a classifier model to the disk which in reality uses `pickle` module at lower level. I create a custom `CountVectorizer` class named `StemmedCountVectorizer` and saved it in `util.py`, then used it in the script for persisting the model import util from sklearn.externals import joblib vect = util.StemmedCountVectorizer(stop_words='english', ngram_range=(1,1)) bow = vect.fit_transform(sentences) joblib.dump(vect, 'vect.pkl') This my project structure using Flask: |- sentiment/ |- run.py |- my_app/ |- analytic/ |- views.py |- util. py |- vect.pkl I run the app with `python run.py` and try to load the persisted object with `joblib.load` in `views.py` but it does not work, I imported the `util` module but I receive the error: ImportError: No module named util can anybody give a solution to this? thanks Answer: Looks like a package/pythonpath problem. The system need to know where to locale your modules. Do you have `__init.py__` in `my_app` and `analytic` folder? The `__init__.py` file mark directories on disk as Python package directories. And the structure should be like this |- sentiment/ |- run.py |- my_app/ |- __init__.py |- analytic/ |- __init__.py |- views.py |- util. py |- vect.pkl then in your `run.py`, try import with import my_app.analytic.utils or from my_app.analytic.utils import <yourClassName> for details of python package, check [here](https://docs.python.org/2/tutorial/modules.html#packages). And be aware of namespace problem.
Python not sending HTTP POST request to correct URL Question: I was lately making this ask.fm "spam" bot (no ask.fm doesn't have neither an IP limit nor a captcha to stop bots). So anyway, I made sure the url was correct, but every time I send the POST request to ask.fm/usernamehere it sends the request to ask.fm, I'm not sure why. import urllib import urllib2 print("What username do you want to spam?") username = raw_input() print("How many questions do you wanna spam?") numQ = int(raw_input()) print("What is the question that you want to spam?") Quest = raw_input() url = "http://ask.fm/" + username print(url) for i in range(0, numQ): data = urllib.urlencode({'question[question_text]':Quest}) headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36 OPR/30.0.1835.59', 'Host' : 'ask.fm', 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer' : 'https://www.google.com.eg/', 'Accept-Language' : 'en-GB,en-US;q=0.8,en;q=0.6'} req = urllib2.Request(url, data, headers) response = urllib2.urlopen(req) d = response.read() if(d.find("Your question has been sent") != -1): print("Successfully sent!") else: print("Failed to send!") print(d) Basically there's no error, but the request is going to the wrong url, I've checked several times that the variable has the correct url, maybe it's redirecting? But how do I check redirects? And how would I make it act like as if the bot is a normal browser, I've already supplied the default headers for Opera. Answer: I think with the help of [this PHP library](https://github.com/afilini/AskFmApi) I know what the problem is. You're missing the authenticity token, so ask.fm believes your request is fake (because it is). Assuming the PHP library works, this is what you need to do: 1. **Scrape<http://ask.fm> to obtain the token you need to authenticate your request.** For example, if you open up the site in your browser, you'll find something like the following: var AUTH_TOKEN = "aNotgbm1V9WvBGr//it4N2vSfhSBSP6nGZkx7rrnNL0="; The PHP lib does this by getting the whole page into a string and using the RegEx `/(var AUTH_TOKEN = ")(.*)(";)/`. 2. **Include the token when you POST your question.** Change your code to something like data = urllib.urlencode({ 'question[question_text]':Quest, 'authenticity_token':authToken }) Where `authToken` is of course a variable containing the string you scraped from the site (in this example, `aNotgbm1V9WvBGr//it4N2vSfhSBSP6nGZkx7rrnNL0=`). The PHP also adds `'question[force_anonymous]':1`. If the user sets `$anon` to true and they're logged in. 3. **Change your POST URL to<http://ask.fm/[username]/questions/create/>** And that should be about it. I'd make sure you add all the HTTP headers the PHP lib uses as well: CURLOPT_URL => "http://ask.fm/$nickname/questions/create/", CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 10 , CURLOPT_MAXREDIRS => 10, CURLOPT_REFERER => "http://ask.fm/$nickname/", CURLOPT_FOLLOWLOCATION => TRUE, CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0', CURLOPT_HEADER => FALSE, CURLOPT_COOKIEJAR => "cookies.txt", CURLOPT_COOKIEFILE => "cookies.txt", CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_SSL_VERIFYHOST => 2 BTW, [this question](http://stackoverflow.com/questions/7159376/post-request- via-urllib-urllib2) shows a different usage of `urllib2`. Just in case it helps.
How can I add a comment to a YAML file in Python Question: I am writing a YAML file using <https://pypi.python.org/pypi/ruamel.yaml> The code is like this: import ruamel.yaml from ruamel.yaml.comments import CommentedSeq d = {} for m in ['B1', 'B2', 'B3']: d2 = {} for f in ['A1', 'A2', 'A3']: d2[f] = CommentedSeq(['test', 'test2']) if f != 'A2': d2[f].fa.set_flow_style() d[m] = d2 with open('test.yml', "w") as f: ruamel.yaml.dump( d, f, Dumper=ruamel.yaml.RoundTripDumper, default_flow_style=False, width=50, indent=8) I just want to add comment at the top like: # Data for Class A Before the YAML data. Answer: Within your `with` block, you can write anything you want to the file. Since you just need a comment at the top, add a call to `f.write()` before you call ruamel: with open('test.yml', "w") as f: f.write('# Data for Class A\n') ruamel.yaml.dump( d, f, Dumper=ruamel.yaml.RoundTripDumper, default_flow_style=False, width=50, indent=8)
Python: ipaddress AttributeError: 'str' object has no attribute Question: Following the advice given [here](http://stackoverflow.com/questions/30994223/regex-for-range-of- ipv4-addresses), I'm using the check the `ipaddress` module to perform checks of type: In [25]: IPv4Address(u'100.64.1.1') in IPv4Network(u'100.64.0.0/10') Out[25]: True Works fine in IPython. Yet when I turn it into a function: import ipaddress def isPrivateIp(ip): ip4addressBlocks = [u'0.0.0.0/8', u'10.0.0.0/8', u'100.64.0.0/10', u'127.0.0.0/8', u'169.254.0.0/16', u'172.16.0.0/12', u'192.0.0.0/24', u'192.0.2.0/24', u'192.88.99.0/24', u'192.168.0.0/16', u'198.18.0.0/15', u'198.51.100.0/24', u'203.0.113.0/24', u'224.0.0.0/4', u'240.0.0.0/4', u'255.255.255.255/32'] unicoded = unicode(ip) if any(unicoded in ipaddress.IPv4Network(address) for address in ip4addressBlocks): return True else: return False print isPrivateIp(r'169.254.255.1') I get: File "isPrivateIP.py", line 14, in <module> print isPrivateIp(r'169.254.255.1') File "isPrivateIP.py", line 9, in isPrivateIp if any(unicoded in ipaddress.IPv4Network(address) for address in ip4addressBlocks): File "isPrivateIP.py", line 9, in <genexpr> if any(unicoded in ipaddress.IPv4Network(address) for address in ip4addressBlocks): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ipaddress.py", line 705, in __contains__ if self._version != other._version: AttributeError: 'str' object has no attribute '_version' Why so? Answer: You check if the unicode string `ip` is in the network, whereas before you've used an `IPv4Address` instance. Your test must instead be if any(IPv4Address(unicoded) in ipaddress.IPv4Network(address) for address \ in ip4addressBlocks):
EVE REST- Issue with AuthToken in python Eve framework error 401 Question: I am currently working on python-eve library to create a restful API but I'm experiencing some issues when I follow this tutorial to implement a "Token Authentication" I get error 401 saying "please provide proper credential". Here is my user schema: RESOURCE_METHODS = ['GET', 'POST'] ITEM_METHODS = ['GET','PATCH','DELETE'] DOMAIN = { 'user': { 'additional_lookup': { 'url': 'regex("[\w]+")', 'field': 'username', #'url': '[\w]+', }, 'schema': { 'firstname': { 'type': 'string' }, 'lastname': { 'type': 'string' }, 'phone': { 'type': 'string' }, 'username': { 'type': 'string', 'required': True, 'unique': True, }, 'password': { 'type': 'string', 'required': True, }, 'roles': { 'type': 'list', 'allowed': ['user', 'superuser', 'admin'], 'required': True, }, 'token': { 'type': 'string', 'required': True, } }, 'cache_control': '', 'cache_expires': 0, 'allowed_roles': ['superuser', 'admin'], }, 'item': { 'schema': { 'name':{ 'type': 'string' }, 'username': { 'type': 'string' } } }, } Here is my app.py from eve import Eve from eve.auth import TokenAuth import random import string class RolesAuth(TokenAuth): def check_auth(self, token, allowed_roles, resource, method): accounts = app.data.driver.db['eve'] lookup = {'token': token} if allowed_roles: lookup['roles'] = {'$in': allowed_roles} account = accounts.find_one(lookup) return account def add_token(documents): for document in documents: document["token"] = (''.join(random.choice(string.ascii_uppercase) for x in range(10))) app = Eve(settings='settings.py') if __name__ == '__main__': app = Eve(auth=RolesAuth) app.on_insert_accounts += add_token app.run() Any ideas why am ending up with a 401. am using python 3.4 If possible please provide me with working code. I am a noob in this field. Thanks! Answer: You need to encode the token as follows: echo "54321:" | base64 Please do not forget last `:` Since you are directly looking up the `token` (per your code), `username` is not needed.
Passing OSGi bundles for Jython Interpreter on-the-fly Question: we would like to integrate the Jython interpreter into our Eclipse RCP based solution and we need to access the OSGi bundles (e.g. everything from `Activator.getContext().getBundles()` ) from there. How could I pass these bundles to a Jython `PythonInterpreter` object `python.path` property, so I can import these classes from the Jython code? (I get similar error messages when I try to import packages e.g.: `from org.eclipse.chemclipse.msd.converter.chromatogram import ChromatogramConverterMSD`) > ImportError: cannot import name ChromatogramConverterMSD Answer: I managed to find a solution after working on this issue for days. First we need a `ClassLoader` which can load OSGi bundles if necessary: public class JythonClassLoader extends ClassLoader { private final Bundle bundle; public JythonClassLoader(ClassLoader parent, Bundle bundle) { super(parent); this.bundle = bundle; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { // System.out.println("findClass " + name); try { return super.findClass(name); } catch(ClassNotFoundException e) { Class<?> loadClass = bundle.loadClass(name); if(loadClass != null) return loadClass; throw e; } }} Then the `PythonInterpreter` needs to know about this `ClassLoader`. The best is to set up the environment for the `PythonInterpreter` before. The following class does the job: public class JythonEnvironment { private final Bundle bundle; public JythonEnvironment(Bundle bundle) { this.bundle = bundle; } public PySystemState getPySystemState() { Properties properties = new Properties(); String jythonPath = net.openchrom.thirdpartylibraries.jython.Activator.getJythonPath(); properties.setProperty("python.home", jythonPath); properties.setProperty("python.cachedir.skip", "true"); Properties systemProperties = System.getProperties(); PySystemState.initialize(systemProperties, properties, new String[]{""}); PySystemState pySystemState = new PySystemState(); JythonClassLoader classLoader = new JythonClassLoader(getClass().getClassLoader(), bundle); pySystemState.setClassLoader(classLoader); return pySystemState; } public PythonInterpreter getInterpreter() { return new PythonInterpreter(null, getPySystemState()); } public PythonInterpreter getInterpreter(OutputStream outStream, OutputStream errStream) { PythonInterpreter interpreter = new PythonInterpreter(null, getPySystemState()); interpreter.setErr(outStream); interpreter.setOut(errStream); return interpreter; }} The `JythonEnvironment` class needs to know about the bundle. The best if that one can be received through the `Activator`. JythonEnvironment environment = new JythonEnvironment(Activator.getDefault().getBundle()); Hope this answer will save time, if someone else needs to integrate Jython into an Eclipse RCP based solution.
How to reference a html template from a different directory in python flask Question: @app.route('/view', methods=['GET', 'POST']) def view_notifications(): posts = get_notifications() return render_template("frontend/src/view_notifications.html", posts=posts) So in my `project/backend/src/app.py` there's this code. How would I reference the template that's in `project/frontend/src/view_notifications.html` I've tried using `..` but it keeps saying the path isn't found. Is there another way I should be doing this? [Tue Jun 23 12:56:02.597207 2015] [wsgi:error] [pid 2736:tid 140166294406912] [remote 10.0.2.2:248] TemplateNotFound: frontend/src/view_notifications.html [Tue Jun 23 12:56:05.508462 2015] [mpm_event:notice] [pid 2734:tid 140166614526016] AH00491: caught SIGTERM, shutting down Answer: Flask is looking in `templates/frontend/src/view_notifications.html` for your template file. You either need to move your templates file to that location or change the default template folder. According to the Flask docs you can specify a different folder for your templates. It defaults to `templates/` in the root of your app: import os from flask import Flask template_dir = os.path.abspath('../../frontend/src') app = Flask(__name__, template_folder=template_dir) UPDATE: After testing it myself on a Windows machine the templates folder does need to be named `templates`. This is the code I used: import os from flask import Flask, render_template template_dir = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) template_dir = os.path.join(template_dir, 'frontend') template_dir = os.path.join(template_dir, 'templates') # hard coded absolute path for testing purposes working = 'C:\Python34\pro\\frontend\\templates' print(working == template_dir) app = Flask(__name__, template_folder=template_dir) @app.route("/") def hello(): return render_template('index.html') if __name__ == "__main__": app.run(debug=True) With this structure: |-pro |- backend |- app.py |- frontend |- templates |- index.html Changing any instance of `'templates'` to `'src'` and renaming the templates folder to `'src'` resulted in the same error OP received.
Is there method like python popitem for associative arrays in dlang? Question: I want to get any key/value pair from associative array and remove it. In python it's: key, value = assoc.popitem() In D I do: auto key = assoc.byKey.front; auto value = assoc[key]; assoc.remove(key); Is there better way to do this? Is it possible to use byKeyValue() outside foreach? DMD 2.067.1 Answer: > Is it possible to use byKeyValue() outside foreach? Sure: import std.stdio; void main() { int[string] assoc = ["apples" : 2, "bananas" : 4]; while (!assoc.byKeyValue.empty) { auto pair = assoc.byKeyValue.front; assoc.remove(pair.key); writeln(pair.key, ": ", pair.value); } } > Is there better way to do this? I don't think D has a library function equivalent for `popitem`.
getting time zone offset in seconds in Python Question: I need to discover the timezone offset in seconds from UTC. Here's what I am trying now: timeZoneSecondsOffset = calendar.timegm(time.gmtime()) - calendar.timegm(time.localtime()) This works - kind of. It gives a value that is off by one hour. How can I get a more accurate result? Answer: This works for me: import datetime import time for ts in 1435071821, 1419519821: # roughly, now and 6 months ago # as reported by time.time() now = datetime.datetime.fromtimestamp(ts) utcnow = datetime.datetime.utcfromtimestamp(ts) offset = (now - utcnow).total_seconds() now = datetime.datetime.isoformat(now) utcnow = datetime.datetime.isoformat(utcnow) print now, utcnow, offset Result when run on my PC in the US central time zone: 2015-06-23T10:03:41 2015-06-23T15:03:41 -18000.0 2014-12-25T09:03:41 2014-12-25T15:03:41 -21600.0
Angularjs won't work with my google app engine configuration Question: I include google's angularjs scripts but they don't seem to work with the app. If I open the html webpage directly with an internet browser it works fine. The page is just a simple test with ng-model to see what you are typing and it doesn't print {{name}} <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> this is the app: import os from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext.webapp import template class MainHandler(webapp.RequestHandler): def get (self, q): if q is None: q = 'index.html' path = os.path.join (os.path.dirname (__file__), q) self.response.headers ['Content-Type'] = 'text/html' self.response.out.write (template.render (path, {})) def main (): application = webapp.WSGIApplication ([('/(.*html)?', MainHandler)], debug=True) util.run_wsgi_app (application) if __name__ == '__main__': main () this is my app.yaml application: sixth-tribute-676 version: 2 runtime: python27 api_version: 1 threadsafe: no handlers: - url: /(.*\.(gif|png|jpg|ico|js|css)) static_files: \1 upload: (.*\.(gif|png|jpg|ico|js|css)) - url: .* script: main.py Answer: The problem was that I was using `template.render` and `{{name}}` disappeared. I should serve the html without rendering it.
matplotlib RuntimeError in cron job before actual import Question: I have a module I'm writing that uses matplotlib. However, I need it to work with a display(e.g. command-line execution), or when theres no display ( SGE/qsub cluster job, or a cron job). I found this answer ( [Automatic detection of display availability with matplotlib](http://stackoverflow.com/questions/8257385/automatic-detection-of- display-availability-with-matplotlib) ), which works for the command-line execution and within a cluster job. But, in a cron job, it fails to properly import matplotlib, and seems to throw an exception before I import it. In the cronjob, I try to import my module with the following script: import os os.environ['PYTHONPATH'] = 'path/to/my/module/dir:%s' % os.environ['PYTHONPATH'] print 'now loading mymodule...' import mymodule and mymodule.py just has the code from the earlier linked answer: #!/usr/bin/python import os print 'testing import method...' import matplotlib r = 0 try : r = os.system('python -c "import matplotlib.pyplot as plt;plt.figure()"') except RuntimeError : pass print 'r=%d' % r if r != 0: print 'matplotlib: running in cluster, using Agg!' matplotlib.use('Agg') import matplotlib.pyplot as plt I get this error message from the cron service: Traceback (most recent call last): File "<string>", line 1, in <module> File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/pyplot.py", line 109, in <module> _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup globals(),locals(),[backend_name],0) File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/backends/backend_gtkagg.py", line 14, in <module> from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\ File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/backends/backend_gtk.py", line 16, in <module> import gtk; gdk = gtk.gdk File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 64, in <module> _init() File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init _gtk.init_check() RuntimeError: could not open display now loading mymodule... testing import method... r=256 matplotlib: running in cluster, using Agg! I think its trying and failing to import matplotlib, which is throwing a RuntimeError, _before_ getting to my code in mymodule.py . I can see that it gets to my code and runs it, but the Traceback message makes me nervous. Why is it loading matplotlib(and crashing) before I tell it to(with Agg)? How can I fix/hide that traceback message? Answer: As a dirty trick to hide the traceback message, just pipe all errors in the cronjob to `/dev/null`: script.py 2> /dev/null
How to shadow git's built-in commands? Question: I'd like to have the following script run when "git status" is ran with no parameters: #!/usr/bin/env python import subprocess o = subprocess.check_output("git -c color.status=always status", shell=True) started = False done = False for line in o.split('\n'): line = line.rstrip('\r\n') if line.strip() == '' and not done: if started: started = False done = True started = True print(line) continue if started and 'modified: ' in line: filename = line.split('modified:')[1].strip().split('\x1b')[0] p = subprocess.Popen(["git", "diff", filename], stdout=subprocess.PIPE) out = subprocess.check_output("diffstat", stdin=p.stdout).split('|')[1] print('%s %s' % (line.rstrip(), out.split('\n')[0])) else: print(line) How can I achieve that? Answer: Create an alias by placing this line in your `~/.gitconfig`: [alias] status = !sh -c 'foo $@' -- where `foo` is your script, stored somewhere on the PATH. Script `foo` shall recognize if any parameters are passed and use a vanilla `git status` in that case.
Python Agglomerative Clustering Question: I am new on clustering ( using sklearn in Python). I am trying to import Agglomerative Clustering using: from sklearn.cluster import AgglomerativeClustering but I get the following error: from sklearn.cluster import AgglomerativeClustering ImportError: cannot import name AgglomerativeClustering I did install the latest version of sklearn on my UBUNTU machine from <http://scikit-learn.org/>, but still no luck!! Can anyone help me on this? Answer: I'm a bit late in posting this but for everyone else who comes across this error, you would want to see this thread [Why can't I import the AgglomerativeClustering class?](http://stackoverflow.com/questions/32219881/why-cant-i-import-the- agglomerativeclustering-class) You probably need to upgrade your scikit-learn version to make use of agglomerative clustering feature.
PYTHON - Zip each file in directory independently Question: I've been looking through and have tried a few different codes without results. What I'm trying to do is zip each file in a subdirectory/folder independently. Ex: > FileName.prj > > FileName.dwg > > FileName.mp3 Each as it's own .zip Thanks! Answer: Try this import os import zipfile folder = "/tmp/in" dest_folder = "/tmp/out" l = [os.path.join(folder, fname) for fname in os.listdir(folder)] os.chdir(folder) for f in l: f_name = f[f.rfind("/")+1:]+".zip" z = zipfile.ZipFile(f_name, 'w') z.write(f_name[:f_name.rfind(".zip")]) os.rename(folder+"/"+f_name, dest_folder+"/"+f_name) where folder is you folder that contains files you want to zip and dest_folder is folder where the zip files will be written.
Unwanted random iterator in For-Loop Question: I tried to create a function for generating a set number (numbersToChoose) of values between two other values (startFrom and stopAt) but for some reason the iterator (?) in the second for-loop (line 7), in this case a seems to be randomly generated even though I don't see any reason for that. def chooseRandomNumbers(numbersToChoose, startFrom, stopAt): numbers = [(randrange(startFrom, stopAt))] # initialize empty list of numbers for n in range(numbersToChoose-1): # choose random number from 1 to 49 a total of 7 times x = randrange(startFrom, stopAt+1) for a in numbers: # check for already existing elements in "numbers" if x == numbers[a]: # if new random number already exists in "numbers" discard and run loop again n -= 1 # decreases n by 1 so a new (hopefully not already existing) number can be generated else: # generated numbers does not exist in "numbers" yet numbers.append(x) # appends randomly chosen number to list "numbers" return numbers # returns said list "numbers" Any advice on how to deal with this is greatly appreciated. Also please tell me if possible anything else bad in the code (just started python). Answer: Your code to check if generated number is already in the list is wrong. `for a in numbers`, in this loop, you are using `numbers[a]` while `a` is a member of list but not the index of the member. use `in` to test if a number is in list: from random import randrange def chooseRandomNumbers(numbersToChoose, startFrom, stopAt): numbers = [] for n in range(numbersToChoose): x = randrange(startFrom, stopAt+1) if not x in numbers: numbers.append(x) else: n -= 1 return numbers or simply: from random import sample def chooseRandomNumbers(numbersToChoose, startFrom, stopAt): return sample(range(startFrom,stopAt+1),numbersToChoose)
Python writing to a new file each new loop Question: I'm trying to use a while loop to write to a series of new files. Each iteration of the loop should write to a new file, and close it before the next loop begins. I'm using Python 2.7, and I'd like to resolve this without having to install any additional libraries if possible. I've gotten the program to work for writing to a single file, but once I try to use the loop, the program loops indefinitely, writing over and over to the initial file. It isn't closing the first file and moving to the next loop. Here's the code: _Update: The problem has been resolved. I moved everything in the while loop to a separate function, and just called it repeatedly in the while loop while incrementing the chapter value of the argument. Also made sure to account for lower case p in the arrow brackets as well as upper case P. Thanks everyone for the help!_ import urllib storyID = raw_input("Please Enter Story ID: ") chapters = raw_input("Please Enter the number of Chapters: ") countDown = int(chapters) countUp = 1 while countUp <= countDown : storyURL = "https:website/" + storyID + "/" + str(countUp) + "/" f = urllib.urlopen(storyURL) with open ('chapter' + str(countUp) + '.html', 'a') as g: bof = False eof = False while eof == False : line = f.readline() if "<P>" in line and bof == False : bof = True g.write("""<html>\n<meta charset='utf-8'>\n <META NAME='ROBOTS' CONTENT='NOARCHIVE'>\n <META http-equiv='X-UA-Compatible' content='IE=edge'>\n <META NAME='format-detection' content='telephone=no'>\n <META NAME='viewport' content='width=device-width'>\n <meta name="google-translate-customization" content="6babbc5ad0624c76-e1cef323edf23c09-g0466c4b8ae39c7a2-12">\n""") g.write(line) elif "Chapter Navigation" in line and bof == True: eof = True g.write ("</html>") elif bof == True : g.write(line) g.close() countUp = countUp + 1 Answer: Case matters. countUp = countUp + 1 Better yet: countUp += 1
Python Tkinter Radiobutton narrowing user input Question: I'm new to programming, python, and Tkinter and I wanted a nice solution (maybe using state=DISABLED?) to limit the user's options based on the buttons they select. My present code: from Tkinter import * master = Tk() def ok(): master.destroy() v1 = IntVar() v2 = IntVar() v3 = IntVar() v4 = IntVar() v5 = IntVar() Label(master, text="""Which Method do you want to run?""",justify = LEFT, padx = 20).pack() Radiobutton(master, text="Positive",padx = 20, variable=v1, value=1).pack(anchor=W) Radiobutton(master, text="Negative", padx = 20, variable=v1, value=2).pack(anchor=W) Radiobutton(master, text="Both", padx = 20, variable=v1, value=3).pack(anchor=W) Label(master, text="""Choose a tray type:""",justify = LEFT, padx = 20).pack() a1=Radiobutton(master, text="54",padx=20,variable=v2,value=1).pack(anchor=W) a2=Radiobutton(master, text="96",padx = 20, variable=v2, value=2).pack(anchor=W) Label(master, text="""Sort by columns(default) or rows?""",justify = LEFT, padx = 20).pack() b1=Radiobutton(master, text="columns",padx=20,variable=v3,value=1).pack(anchor=W) b2=Radiobutton(master, text="rows",padx = 20, variable=v3, value=2).pack(anchor=W) Label(master, text="""Choose a tray number:""",justify = LEFT, padx = 20).pack() c1=Radiobutton(master, text="Stk1-01",padx = 20, variable=v4, value=1).pack(anchor=W) c2=Radiobutton(master, text="Stk1-02", padx = 20, variable=v4, value=2).pack(anchor=W) c3=Radiobutton(master, text="Stk1-03",padx = 20, variable=v4, value=3).pack(anchor=W) c4=Radiobutton(master, text="Stk1-04", padx = 20, variable=v4, value=4).pack(anchor=W) c5=Radiobutton(master, text="MT1-Frnt",padx = 20, variable=v4, value=5).pack(anchor=W) c6=Radiobutton(master, text="MT1-Rear", padx = 20, variable=v4, value=6).pack(anchor=W) c7=Radiobutton(master, text="MT2-Frnt",padx = 20, variable=v4, value=7).pack(anchor=W) c8=Radiobutton(master, text="MT2-Rear", padx = 20, variable=v4, value=8).pack(anchor=W) Label(master, text="""Would you like to insert a midpoint standard and blank?""",justify = LEFT, padx = 20).pack() Radiobutton(master, text="Yes",padx = 20, variable=v5, value=1).pack(anchor=W) Radiobutton(master, text="No", padx = 20, variable=v5, value=2).pack(anchor=W) Button(master, text="OK", command=ok).pack() master.mainloop() I want a way so that if a1 is selected, c6 through c8 are not able to be selected by the user. Similarly, if a1 is selected, the user would not be able to select either b1 or b2. There's probably a way to use sample=DISABLED to grey out the unselectable answers or maybe use a function to make the options appear once a value is selected. Any help is appreciated! Answer: I made some significant albeit easy changes to your sample code here simply to make things more accessible. I've wrapped all of the Widgets into a class to have better access to them within functions. Basically what you want is simply a callback function on any change of a1 and a2 that will disable c6-8 if 1, else enable them. I also had to make some of your pack statements happen on a seperate line as `Radiobutton(...).pack()` will return `None` and make `self.someRadiobutton`'s `config` inaccessible. Here is the code so you can see what I mean. from Tkinter import * class Window(): def __init__(self, master): self.master = master self.v1 = IntVar() self.v2 = IntVar() self.v3 = IntVar() self.v4 = IntVar() self.v5 = IntVar() Label(master, text="""Which Method do you want to run?""",justify = LEFT, padx = 20).pack() Radiobutton(master, text="Positive",padx = 20, variable=self.v1, value=1).pack(anchor=W) Radiobutton(master, text="Negative", padx = 20, variable=self.v1, value=2).pack(anchor=W) Radiobutton(master, text="Both", padx = 20, variable=self.v1, value=3).pack(anchor=W) Label(master, text="""Choose a tray type:""",justify = LEFT, padx = 20).pack() self.a1=Radiobutton(master, text="54",padx=20,variable=self.v2,value=1, command = self.disable).pack(anchor=W) self.a2=Radiobutton(master, text="96",padx = 20, variable=self.v2, value=2, command = self.disable).pack(anchor=W) Label(master, text="""Sort by columns(default) or rows?""",justify = LEFT, padx = 20).pack() self.b1=Radiobutton(master, text="columns",padx=20,variable=self.v3,value=1) self.b1.pack(anchor=W) self.b2=Radiobutton(master, text="rows",padx = 20, variable=self.v3, value=2) self.b2.pack(anchor=W) Label(master, text="""Choose a tray number:""",justify = LEFT, padx = 20).pack() self.c1=Radiobutton(master, text="Stk1-01",padx = 20, variable=self.v4, value=1).pack(anchor=W) self.c2=Radiobutton(master, text="Stk1-02", padx = 20, variable=self.v4, value=2).pack(anchor=W) self.c3=Radiobutton(master, text="Stk1-03",padx = 20, variable=self.v4, value=3).pack(anchor=W) self.c4=Radiobutton(master, text="Stk1-04", padx = 20, variable=self.v4, value=4).pack(anchor=W) self.c5=Radiobutton(master, text="MT1-Frnt",padx = 20, variable=self.v4, value=5).pack(anchor=W) self.c6=Radiobutton(master, text="MT1-Rear", padx = 20, variable=self.v4, value=6) self.c6.pack(anchor=W) self.c7=Radiobutton(master, text="MT2-Frnt",padx = 20, variable=self.v4, value=7) self.c7.pack(anchor=W) self.c8=Radiobutton(master, text="MT2-Rear", padx = 20, variable=self.v4, value=8) self.c8.pack(anchor=W) Label(master, text="""Would you like to insert a midpoint standard and blank?""",justify = LEFT, padx = 20).pack() Radiobutton(master, text="Yes",padx = 20, variable=self.v5, value=1).pack(anchor=W) Radiobutton(master, text="No", padx = 20, variable=self.v5, value=2).pack(anchor=W) Button(master, text="OK", command=self.ok).pack() def ok(self): self.master.destroy() def disable(self): if self.v2.get() == 1: self.b1.config(state = 'disabled') self.b2.config(state = 'disabled') self.c6.config(state = 'disabled') self.c7.config(state = 'disabled') self.c8.config(state = 'disabled') else: self.b1.config(state = 'normal') self.b2.config(state = 'normal') self.c6.config(state = 'normal') self.c7.config(state = 'normal') self.c8.config(state = 'normal') master = Tk() w = Window(master) master.mainloop() If you wanted to do this without using a class you would have to pass a reference to the relevant `Radiobuttons` and `IntVars` to the `disable` function. If you would like to see how just let me know in a comment.
Python - Grab Random Names Question: Alright, so I have a question. I am working on creating a script that grabs a random name from a list of provided names, and generates them in a list of 5. I know that you can use the command items = ['names','go','here'] rand_item = items[random.randrange(len(items))] This, if I am not mistaken, should grab one random item from the list. Though if I am wrong correct me, but my question is how would I get it to generate, say a list of 5 names, going down like below; random names generated using code Also is there a way to make it where if I run this 5 days in a row, it doesn't repeat the names in the same order? I appreciate any help you can give, or any errors in my existing code. Edit: The general use for my script will be to generate task assignments for a group of users every day, 5 days a week. What I am looking for is a way to generate these names in 5 different rotations. I apologize for any confusion. Though some of the returned answers will be helpful. Edit2: Alright so I think I have mostly what I want, thank you Markus Meskanen & mescalinum, I used some of the code from both of you to resolve most of this issue. I appreciate it greatly. Below is the code I am using now. import random items = ['items', 'go', 'in', 'this', 'string'] rand_item = random.sample(items, 5) for item in random.sample(items, 5): print item Answer: You could use [`random.choice()`](https://docs.python.org/2/library/random.html#random.choice) to get one item only: items = ['names','go','here'] rand_item = random.choice(items) Now just repeat this 5 times (a for loop!) If you want the names just in a random order, use [`random.shuffle()`](https://docs.python.org/2/library/random.html#random.shuffle) to get a different result every time.
Python os.walk topdown true with regular expression Question: I am confused as to why the following ONLY works with `topdown=False` and returns nothing when set to `True` ? The reason I want to use `topdown=True` is because it is taking a very long time to traverse through the directories. I believe that going topdown will increase the time taken to produce the list. for root, dirs, files in os.walk(mypath, topdown=False): #Why doesn't this work with True? dirs[:] = [d for d in dirs if re.match('[DMP]\\d{8}$', d)] for dir in dirs: print(dir) Answer: In your code you were looking for matching names([dmp]\d{8}) to traverse into, while you should be looking for non-matching directories to traverse into while adding matching names to a global list. I modified your code and this works: import os import re all_dirs = [] for root, dirs, files in os.walk("root", topdown=True): subset = [] for d in dirs: if not re.match('[dmp]\d{8}$', d): # step inside subset.append(d) else: # add to list all_dirs.append(os.path.join(root, d)) dirs[:] = subset print all_dirs This returns: > ['root/temp1/myfiles/d12345678', > 'root/temp1/myfiles/m11111111', > 'root/temp2/mydirs/moredirs/m22222222', > 'root/temp2/mydirs/moredirs/p00000001']
find urls in string in Python duplicate Question: Can someone help. As an example the following text output there more than pne hyper link. I’m looking for the first output: **JournalEntries.dox?method=view &number=JE-00000725** Here are my output source and i look for these ones **https://www.zuora.com/apps/JournalEntries.dox?method=view&number=JE-00000725** https://www.zuora.com/apps/JournalEntries.dox?method=view&number=JE-00000726 https://www.zuora.com/apps/javascript:downloadTansactions("JournalEntries.dox?method=downloadTransactions&number=JE-00000726"); https://www.zuora.com/apps/AccountingPeriods.dox?method=view&id=2c92a0f949efde7f0149f05314e640b6 https://www.zuora.com/apps/ChartOfAccountsSetting.do?method=edit&id=2c92a0fb43812a1a0143980f213b7e34 https://www.zuora.com/apps/ChartOfAccountsSetting.do?method=edit&id=2c92a0fb43812a1a0143980f21507e39 https://www.zuora.com/apps/JournalEntries.dox?method=view&number=JE-00000725 https://www.zuora.com/apps/javascript:downloadTansactions("JournalEntries.dox Answer: I saved this in a file with name "url": https://www.zuora.com/apps/JournalEntries.dox?method=view&number=JE-00000725** https://www.zuora.com/apps/JournalEntries.dox?method=view&number=JE-00000726 https://www.zuora.com/apps/javascript:downloadTansactions("JournalEntries.dox?method=downloadTransactions&number=JE-00000726"); https://www.zuora.com/apps/AccountingPeriods.dox?method=view&id=2c92a0f949efde7f0149f05314e640b6 https://www.zuora.com/apps/ChartOfAccountsSetting.do?method=edit&id=2c92a0fb43812a1a0143980f213b7e34 https://www.zuora.com/apps/ChartOfAccountsSetting.do?method=edit&id=2c92a0fb43812a1a0143980f21507e39 https://www.zuora.com/apps/JournalEntries.dox?method=view&number=JE-00000725 https://www.zuora.com/apps/javascript:downloadTansactions("JournalEntries.dox Now my code looks like: import re f = open ("url", "r").readlines() for i in f: if re.search("JournalEntries\.dox\?method\=view\&number\=JE\-00000725",i): print "found it !!"
ImportError: No module named kivy Question: I am new to Ubuntu and Python. Basically I installed kivy just as the website told me to do.First I built the repo $ sudo add-apt-repository ppa:kivy-team/kivy Then I do the apt sudo apt-get install python3-kivy Ok now I fire up Geany and follow the websites instructions to do the infamous "Hello World" then when I run in the program directory ~/Documents/Kivy for me python helloWorld Here is the code for the app import kivy kivy.require('1.9.0') from kivy.app import App from kivy.uix.label import Label class myApp(App): def build(self): return Label(text="Hello World") if __name__ == '__main__': myApp().run() I immediately get the error File "~/Documents/Kivy/helloWorld", line 1, in <module> import kivy Any clue why this is happening? Answer: You said that the apt install is: sudo apt-get install python3-kivy That will install kivy for python3... not python 2 Instead of running: python helloWorld Try typing: python3 helloWorld
Send Mail with python using gmail smtp Question: I am using following code import smtplib import mimetypes from email.mime.multipart import MIMEMultipart from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.text import MIMEText emailfrom = "[email protected]" emailto = "[email protected]" fileToSend = "hi.csv" username = "user" password = "password" msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = emailto msg["Subject"] = "help I cannot send an attachment to save my life" msg.preamble = "help I cannot send an attachment to save my life" ctype, encoding = mimetypes.guess_type(fileToSend) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(fileToSend) # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(fileToSend, "rb") attachment = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open(fileToSend, "rb") attachment = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(fileToSend, "rb") attachment = MIMEBase(maintype, subtype) attachment.set_payload(fp.read()) fp.close() encoders.encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment", filename=fileToSend) msg.attach(attachment) server = smtplib.SMTP("smtp.gmail.com:587") server.starttls() server.login(username,password) server.sendmail(emailfrom, emailto, msg.as_string()) server.quit() I am getting error "Username and password not accepted. learn more at\n5.7.8 <https://support.google.com/mail/answer/14257>" as per written over there, i have changed Allow less secure apps: ON but getting same error! any help?? Answer: The whole purpose of [yagmail](https://github.com/kootenpv/yagmail) (I'm the developer) is to make it really easy to send emails, especially with HTML or attachment needs. Try the following code: import yagmail yag = yagmail.SMTP(username, password) yag.send(emailto, subject = "I now can send an attachment", contents = fileToSend) Notice the magic here: `contents` equal to a file path will automatically attach, using correct mimetype. If you want to send text with it you can do like so: contents = ['Please see the attachment below:', fileToSend, 'cool huh?'] If you want to talk about the attachment instead of sending it, just make sure no argument in the list is ONLY the filepath. contents = 'This filename will not be attached ' + fileToSend You can get yagmail by using pip to install it: pip install yagmail # Python 2 pip3 install yagmail # Python 3
Disable global variable lookup in Python Question: In short, the question: **Is there a way to prevent Python from looking up variables outside the current scope?** Details: Python looks for variable definitions in outer scopes if they are not defined in the current scope. Thus, code like this is liable to break when not being careful during refactoring: def line(x, a, b): return a + x * b a, b = 1, 1 y1 = line(1, a, b) y2 = line(1, 2, 3) If I renamed the function arguments, but forgot to rename them inside the function body, the code would still run: def line(x, a0, b0): return a + x * b # not an error a, b = 1, 1 y1 = line(1, a, b) # correct result by coincidence y2 = line(1, 2, 3) # wrong result I know [it is bad practice to shadow names from](http://stackoverflow.com/a/20125739/3005167) outer scopes. However, there are a few reasons why this is done anyway: * Sometimes it may make sense to have the same names because they refer to the same thing * One might run out of meaningful variable names * laziness Is there a way to prevent Python from looking up variables outside the current scope? (So that accessing `a` or `b` raises an Error in the second example.) On account of being lazy, I would prefer a solution that works without repeated boiler-plate code :) If the issue is ambiguous in terms of Python version, I'm mostly interested in Python 3.3 and above. Answer: No, you cannot tell Python not to look names up in the global scope. If you could, you would not be able to use _any_ other classes or functions defined in the module, no objects imported from other modules, nor could you use built-in names. Your function namespace becomes a desert devoid of almost everything it needs, and the only way out would be to import everything into the local namespace. _For every single function in your module_. Rather than try to break global lookups, keep your global namespace clean. Don't add globals that you don't need to share with other scopes in the module. Use a `main()` function for example, to encapsulate what are really just locals. Also, add unittesting. Refactoring without (even just a few) tests is always prone to create bugs otherwise.
Should yield be used in list comprehension in Scrapy Question: I'm writing a spider. And in that spider I need to yield requests, with different params. It is something like, for i in xrange(0, len(products), k): some_ids = ','.join([a_product['id'] for a_product in products[i: i + k]]) for a_condition in ['c1', 'c2', 'c3']: yield CustomRequest(url='api:endpoint', params=dict(Condition=a_condition, param1='val1', param2=some_ids, ) ) Is there more pythonic way to do this? Answer: > Is there more pythonic way to do this? it's kind of vague question, it depends what you're trying to accomplish, it's difficult to tell how rest of your code looks like. In general [generators are great](http://stackoverflow.com/questions/231767/what-does-the-yield-keyword- do-in-python/231855#231855) so you should use them if you can. They are definitely 'Pythonic' but your top priority should probably be having clean, efficient and working code, adhering to idioms of language is not most important thing IMO.
Load R data frame into Python and convert to Pandas data frame Question: I am trying to run the following code in an R data frame using Python. from fuzzywuzzy import fuzz from fuzzywuzzy import process import os import pandas as pd import timeit from rpy2.robjects import r from rpy2.robjects import pandas2ri pandas2ri.activate() start = timeit.default_timer() def f(x): return fuzz.partial_ratio(str(x["sig1"]),str(x["sig2"])) def fu_match(file): f1=r.load(file) f1=pandas2ri.ri2py(f1) f1["partial_ratio"]=f1.apply(f, axis=1) f1=f1.loc[f1["partial_ratio"]>90] f1.to_csv("test.csv") stop = timeit.default_timer() print stop - start fu_match('test_full.RData') Here is the error. AttributeError: 'numpy.ndarray' object has no attribute 'apply' I guess the problem has to do with the conversion from R to Pandas data frame. I know this is a repeated question, but I have tried all the solutions given to previous questions with no success. Please, any help will be much appreciated. EDIT: Here is the head of .RData. city sig1 sig2 1 19 claudiopillonrobertoscolari almeidabartolomeufrancisco 2 19 claudiopillonrobertoscolari cruzricardosantasergiosilva 3 19 claudiopillonrobertoscolari costajorgesilva 4 19 claudiopillonrobertoscolari costafrancisconaifesilva 5 19 claudiopillonrobertoscolari camarajoseluizreis 6 19 claudiopillonrobertoscolari almeidafilhojoaopimentel Answer: This line f1=pandas2ri.ri2py(f1) is setting `f1` to be a `numpy.ndarray` when I think you expect it to be a `pandas.DataFrame`. You can cast the array into a `DataFrame` with something like f1 = pd.DataFrame(data=f1) but you won't have your column names defined (which you use in `f(x)`). What is the structure of `test_full.RData`? Do you want to manually define your column names? If so f1 = pd.DataFrame(data=f1, columns=("my", "column", "names")) should do the trick. _BUT_ I would suggest you look at using a more standard data format, maybe `.csv`. `pandas` has good support for this, and I expect `R` does too. Check out [the](http://pandas.pydata.org/pandas- docs/dev/generated/pandas.DataFrame.from_csv.html#pandas.DataFrame.from_csv) [docs](http://pandas.pydata.org/pandas- docs/dev/generated/pandas.DataFrame.html).
Python decrypt signatures with only a public key Question: A company wants to send me a **digital signature** i.e this [method](https://en.wikipedia.org/?title=Digital_signature). I only have the **public key**. This signature is used to authenticate who it came from **AND** contains details of the user, which I need. What I don't understand is how I decrypt the signature with only public key and the signature I'm sent. All can do from the example I can find is verify the signature. Without knowing what the encrypted string is you cannot decrypt. from ecdsa import SigningKey, NIST384p sk = SigningKey.generate(curve=NIST384p) vk = sk.get_verifying_key() signature = sk.sign("message") assert vk.verify(signature, "message") I'm I misunderstanding or is there a different type of digital signature they are suggesting? Answer: First, you need to use VerifyingKey. (see also @J0HN excellent comment) Something like (source: <https://github.com/warner/python-ecdsa>): from ecdsa import VerifyingKey, BadSignatureError vk = VerifyingKey.from_pem(open("public.pem").read()) message = open("message","rb").read() sig = open("signature","rb").read() try: vk.verify(sig, message) print "good signature" except BadSignatureError: print "BAD SIGNATURE"
xpath matching wrong node Question: The xpath `//*[h1]` shows different results when tried on python and Firebug. My code: import requests from lxml import html url = "http://machinelearningmastery.com/naive-bayes-classifier-scratch-python/" resp = requests.get(url) page = html.fromstring(resp.content) node = page.xpath("//*[h1]") print node #[<Element center at 0x7fb42143c7e0>] But Firebug matches to a `<header>` tag which is what I desire. Why is this so? How do i make my python code match `<header>` too? Answer: You are missing the User-Agent header and hence the response content returned **403 Forbidden** , add it to request and it works as expected: In [9]: resp = requests.get(url, headers={"User-Agent": "Test Agent"}) In [10]: page = html.fromstring(resp.content) In [11]: node = page.xpath("//*[h1]") In [12]: print node [<Element header at 0x104ff15d0>]
Fitting two non-linear models to data Question: Following the example is given in [`lmfit`](http://cars9.uchicago.edu/software/python/lmfit/parameters.html), I am trying to set up an example which is similar to my problem. My problem originally is that in my data I can fit two or three models, while my model is highly non-linear but it has for each model just a single free parameter. **My example similar to`lmfit` documentation:** x = np.linspace(0, 15, 301) data = (5. * np.sin(2 * x - 0.1) * np.exp(-x*x*0.025) +(-2.6 * np.sin(-0.6 * x + 1.5) * np.exp(-x*x*3.0)+np.random.normal(size=len(x), scale=0.2) )) def fcn2min(params, x, data): model=0 for i in range(2): exec("amp_%d=%s"%(i+1,repr(params['amp_%d'%(i+1)].value))) exec("shift_%d=%s"%(i+1,repr(params['shift_%d'%(i+1)].value))) exec("omega_%d=%s"%(i+1,repr(params['omega_%d'%(i+1)].value))) exec("decay_%d=%s"%(i+1,repr(params['decay_%d'%(i+1)].value))) model += eval("amp_%d"%(i+1)) * np.sin(x * eval("omega_%d"%(i+1)) + eval("shift_%d"%(i+1))) * np.exp(-x*x*eval("decay_%d"%(i+1))) return (model-data)/data params=Parameters() for i in range(2): params.add('amp_%d'%(i+1), value= 10, vary=True, min=-3, max=3) params.add('decay_%d'%(i+1), value= 0.1,vary=True,min=0,max=4.) params.add('shift_%d'%(i+1), value= 0.0, vary=True,min=-np.pi, max=np.pi) params.add('omega_%d'%(i+1), value= 3.0, vary=True,min=-2.5, max=2.5) result = minimize(fcn2min, params, args=(x, data),method='nelder') The obtained rsults: final = data + result.residual # write error report report_fit(params) [[Variables]] amp_1: -1.74789852 (init= 3) decay_1: 0.05493661 (init= 0.1) shift_1: 0.07807319 (init= 0) omega_1: -2.00291964 (init= 2.5) amp_2: -1.30857699 (init= 3) decay_2: 0.82303744 (init= 0.1) shift_2: -0.04742474 (init= 0) omega_2: 2.44085535 (init= 2.5) [[Correlations]] (unreported correlations are < 0.100) The free parameters look completely off however on the final results plot it is clear it follows the distribution of data but the amplitudes are not quite right try: import pylab pylab.plot(x, data, 'k+') pylab.plot(x, final, 'r') pylab.show() except: pass Any suggestion for the modification of the code in order to get the right results? ![enter image description here](http://i.stack.imgur.com/0RRhm.jpg) Answer: Ok, I think I found the issue. I am not sure about the purpose of the line return (model-data)/data but it should just be return (model-data) since that it what you want to minimize. Furthermore, you should also choose initial values that are in the range. The modified code will result in the following output: [[Variables]] amp_1: 5.23253723 (init= 10) decay_1: 0.02762246 (init= 0.1) shift_1: -0.40774606 (init= 0) omega_1: 2.06744256 (init= 3) amp_2: 2.49467996 (init= 10) decay_2: 0.39205207 (init= 0.1) shift_2: 0.23347938 (init= 0) omega_2: -0.71995187 (init= 3) [[Correlations]] (unreported correlations are < 0.100) ![The plot then looks like this:](http://i.stack.imgur.com/3iVLH.png) Here is the entire code: from lmfit import minimize, Parameters, Parameter, report_fit import numpy as np #http://cars9.uchicago.edu/software/python/lmfit/parameters.html # create data to be fitted x = np.linspace(0, 15, 301) data = (5. * np.sin(2 * x - 0.1) * np.exp(-x*x*0.025) + (-2.6 * np.sin(-0.6 * x + 1.5) * np.exp(-x*x*3.0)+np.random.normal(size=len(x), scale=0.2) )) def fcn2min(params, x, data): model=0 for i in range(2): exec("amp_%d=%s"%(i+1,repr(params['amp_%d'%(i+1)].value))) exec("shift_%d=%s"%(i+1,repr(params['shift_%d'%(i+1)].value))) exec("omega_%d=%s"%(i+1,repr(params['omega_%d'%(i+1)].value))) exec("decay_%d=%s"%(i+1,repr(params['decay_%d'%(i+1)].value))) model += eval("amp_%d"%(i+1)) * np.sin(x * eval("omega_%d"%(i+1)) + eval("shift_%d"%(i+1))) * np.exp(-x*x*eval("decay_%d"%(i+1))) return (model-data)#/data params=Parameters() for i in range(2): params.add('amp_%d'%(i+1), value= 10, vary=True, min=0, max=13) params.add('decay_%d'%(i+1), value= 0.1,vary=True,min=0,max=1.4) params.add('shift_%d'%(i+1), value= 0.0, vary=True,min=-np.pi, max=np.pi) params.add('omega_%d'%(i+1), value= 3.0, vary=True,min=-3.5, max=3.5) result = minimize(fcn2min, params, args=(x, data),method='nelder') final = data + result.residual report_fit(params) try: import pylab pylab.plot(x, data, 'k+') pylab.plot(x, final, 'r') pylab.show() except: pass
"pip freeze" gives different modules from "help('modules')" Question: I tried multiple solutions from [this answer](https://stackoverflow.com/questions/739993/how-can-i-get-a-list-of- locally-installed-python-modules) and they seemed to give be different results. I am using `virtualenv` and I was wondering if it has something to do with that. The first method, from the python shell (while the virtual environment is active): import pip installed_packages = pip.get_installed_distributions() installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages]) print(installed_packages_list) This gives the output ['distribute==0.6.34', 'django==1.8.1', 'flup==1.0.3.dev-20110405', 'importlib==1.0.3'] The second method, from the bash shell, again while the virtual environment is active: pip freeze This gives the following list: Warning: cannot find svn location for flup==1.0.3.dev-20110405 Django==1.8.1 Ksplice-Uptrack==1.2.12 MySQL-python==1.2.2 PIL==1.1.7 South==0.7.6 distribute==0.6.34 django-photologue==2.4 dnspython==1.11.1 ethtool==0.6 ## FIXME: could not find svn URL in dependency_links for this package: flup==1.0.3.dev-20110405 importlib==1.0.3 iniparse==0.3.1 iotop==0.3.2 iwlib==1.0 mercurial==1.4 pycurl==7.19.0 pygpgme==0.1 pyzor==1.0.0 urlgrabber==3.9.1 virtualenv==1.9.1 yum-metadata-parser==1.1.2 Could someone explain why this is happening? Basically, I would like to be able to import packages from the second list, but I can't (in particular, my Django server is not able to import MySQLdb, like [this question](https://stackoverflow.com/questions/2952187/getting-error-loading- mysqldb-module-no-module-named-mysqldb-have-tried-pre), even after trying their answers). Answer: Realized what the problem was... pip -V gave pip 1.3.1 from /home/benjam15/.env/env/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg (python 2.6) while I was using python 2.7. Followed [this post](https://stackoverflow.com/questions/2812520/pip-dealing-with-multiple- python-versions) since the server's default "pip" command routed to python 2.6, while I really wanted stuff to install for python 2.7.
How to adjust scaled scikit-learn Logicistic Regression coeffs to score a non-scaled dataset? Question: I am currently using Scikit-Learn's LogisticRegression to build a model. I have used from sklearn import preprocessing scaler=preprocessing.StandardScaler().fit(build) build_scaled = scaler.transform(build) to scale all of my input variables prior to training the model. Everything works fine and produces a decent model, but my understanding is the coefficients produced by LogisticRegression.coeff_ are based on the scaled variables. Is there a transformation to those coefficients that can be used to adjust them to produce coefficients that can be applied to the non-scaled data? I am thinking forward to am implementation of the model in a productionized system, and attempting to determine if all of the variables need to be pre- processed in some way in production for scoring of the model. Note: the model will likely have to be re-coded within the production environment and the environment is not using python. Answer: You can use [pipeline](http://scikit- learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html) with two steps: scaling and regression. It takes raw data as input and produces regression desired. Or if you explicitly want to get coefficients, you can manually combine LogisticRegression coefficients with scaler parameters which are scaler.mean_ and scaler.std_. To do so, note that standardscaler normalized data this way: v_norm = (v - M(v))/ sigma(v). Here M(v) is mean of raw variable v and sigma(v) is it's standard deviation and stored in scaler.mean_ and scaler.std_ arrays respectively. Then LogisticRegression takes this normalized variables and multiplies them by LogisticRegression.coef_ and adds intercept_.
Kivy and android sharedpreferences Question: I am looking for a method to store settings persistently on android device, from Kivy framework. I found Kivy documentation, overall informative, vague in this particular area. It mentions three methods (_sorry, dont have enough reputation to provide clicable links, relative paths to**kivy.org** provided, **I'd be glad if someone could fix those links_**): 1. [Storage] ./docs/api-kivy.storage.html#module-kivy.storage 2. [Settings] ./docs/api-kivy.uix.settings.html 3. [Config] ./docs/api-kivy.config.html In addition to those, I'm aware that I could store data in a file, via pickle or database, but I'd like to use specifically [`sharedpreferences`](http://developer.android.com/reference/android/content/SharedPreferences.html), or at least any Android/Kivy specific persistent storage. 1. However, I was unable to find any comparison, or explanation how they are different, and how they are used. Could anyone shed some light, had used them already? 2. Actually, I'm 80% sure that neither of this method uses Android's shared preferences, thus I thought about using jnius (4), and to do that I've tried (methods 1,2/3?,4), based on simple hello world example: from kivy.app import App from kivy.uix.button import Button import jnius from kivy.config import Config from kivy.storage.dictstore import DictStore class MyApp(App): def build(self): path = "DEFAULT" try: path = Config.get('kivy', 'my_important_variable') print "\t\t\t KIVY 1:", Config.get('kivy', 'my_important_variable') except Exception as err: print ("KIVY, 1, error: {}".format(repr(err))) try: store = DictStore("MY_SETTINGS") path = store.get("my_important_variable") print "\t\t\t KIVY 2:", path except KeyError as err: print ("KIVY, 2, error: {}".format(repr(err))) try: prefs_m = jnius.autoclass('android.preference.PreferenceManager') prefs = prefs_m.getSharedPreferences() path = prefs.getString("my_important_variable", None) print "\t\t\t KIVY 3:", path except jnius.jnius.JavaException as err: print ("KIVY, 3, error: {}".format(repr(err))) btn1 = Button(text=path) btn1.bind(on_press=app.callback) # return btn1 def callback(self, instance): print('The button <%s> is being pressed, SAVING...' % instance.text) try: Config.set('kivy', 'my_important_variable', "my_value_1") except Exception as err: print ("KIVY, 4, error: {}".format(repr(err))) try: store = DictStore("MY_SETTINGS") store.put("MY_SETTINGS", my_important_variable="my_value_2") except Exception as err: print ("KIVY, 5, error: {}".format(repr(err))) try: prefs_c = jnius.autoclass('android.content.SharedPreferences') prefs_m = jnius.autoclass('android.preference.PreferenceManager') prefs = prefs_m.getSharedPreferences() prefs_e = prefs.Editor() prefs_e.putString("my_important_variable", "my_value_3") prefs_e.commit() except Exception as err: print ("KIVY, 6, error: {}".format(repr(err))) try: context = jnius.autoclass('android.content.Context') # do I actually get context or a class here? prefs = context.getPreferences(0).edit(); prefs.putString("my_important_variable", "my_value_4") prefs.commit() except Exception as err: print ("KIVY, 7, error: {}".format(repr(err))) if __name__ == '__main__': app = MyApp() app.run() and here are logcat's results ... each time app is launched I/python ( 5973): KIVY, 1, error: No option 'my_important_variable' in section: 'kivy' I/python ( 5973): KIVY, 2, error: KeyError('my_important_variable',) I/python ( 5973): KIVY, 3, error: JavaException('Unable to find a None method!',) ... button pressed I/python ( 5973): The button <DEFAULT> is being pressed, SAVING... I/python ( 5973): KIVY, 6, error: JavaException('Unable to find a None method!',) I/python ( 5973): KIVY, 7, error: AttributeError("type object 'android.content.Context' has no attribute 'getPreferences'",) Notice, that 4, 5 "error msg's" didn't get called, so in theory they should have worked, but second launch I get same errors. I've run out of ideas how to crack it. Answer: Kivy.Config is used to store settings that relate to the instantiation of the App class. It is usually placed at the very top of your Python script before any other kivy module is imported. This method is not platform specific, but the default path to the config file changes depending on the platform. from kivy.config import Config desktop=Config.getint('kivy', 'desktop') if desktop == 1: print "This app is being run on a desktop." The DictStore is a storage class that stores a dictionary to disk. The filename argument specifies the name of the file where the dictionary is stored. When the get function is called, a Python dictionary is returned. from kivy.app import App from kivy.uix.button import Button from kivy.storage.dictstore import DictStore class TestApp(App): def build(self): try: store = DictStore(filename="MY_SETTINGS") dictionary = store.get("my_important_variable") print "\t\t\t KIVY 2: DictStore Succeeded", except KeyError as err: dictionary = {'name': 'None'} print ("KIVY, 2, error: {}".format(repr(err))) self.text = str(dictionary) btn1 = Button(text=self.text) btn1.bind(on_press=self.callback) # return btn1 def callback(self, instance): print('The button <%s> is being pressed, SAVING...' % instance.text) try: store = DictStore(filename="MY_SETTINGS") store.put("my_important_variable", name="John") except Exception as err: print ("KIVY, 5, error: {}".format(repr(err))) if __name__ == '__main__': TestApp().run() I will provide the code for accessing shared prefs below. If you are interested in learning more please read <http://developer.android.com/guide/topics/data/data-storage.html> and <https://kivy.org/planet/2015/04/python-on%C2%A0android/> from kivy.app import App from kivy.uix.button import Button import jnius class TestApp(App): def build(self): try: PythonActivity = jnius.autoclass('org.renpy.android.PythonActivity') activity = PythonActivity.mActivity cntxt = activity.getApplicationContext() prefs = cntxt.getSharedPreferences("MY_PREFS", cntxt.MODE_PRIVATE ) print "KIVY ACQUIRED SHARED PREFS" myVar = prefs.getString("my_important_variable", "Default String") print "\tKIVY 3: Retrieved SharedPref" except jnius.jnius.JavaException as err: myVar="Error Loading Prefs." print ("KIVY, 3, error: {}".format(repr(err))) self.text = myVar btn1 = Button(text=self.text) btn1.bind(on_press=self.callback) # return btn1 def callback(self, instance): print('The button <%s> is being pressed, SAVING...' % instance.text) try: PythonActivity = jnius.autoclass('org.renpy.android.PythonActivity') activity = PythonActivity.mActivity cntxt = activity.getApplicationContext() prefs = cntxt.getSharedPreferences("MY_PREFS", cntxt.MODE_PRIVATE) editor = prefs.edit() editor.putString("my_important_variable", "This is important!") editor.commit() print "\tKIVY: Added string <This is important!> to shared prefs." except Exception as err: print ("\tKIVY, 6, error: {}".format(repr(err))) if __name__ == '__main__': TestApp().run()
Capture Webcam image using CV2 and Pyglet in Python Question: I'm using CV2 (OpenCV) for Python, and the Pyglet Python libraries to create a small application which will display live video from a webcam and have some text or static images overlayed. I've already made an application with CV2 that just displays the webcam image in a frame, but now I'd like to get that frame inside a pyglet window. Here's what I've cobbled together so far: import pyglet from pyglet.window import key import cv2 import numpy window = pyglet.window.Window() camera=cv2.VideoCapture(0) def getCamFrame(color,camera): retval,frame=camera.read() if not color: frame=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) frame=numpy.rot90(frame) return frame frame=getCamFrame(True,camera) video = pyglet.resource.media(frame, streaming=True) @window.event def on_key_press(symbol, modifiers): if symbol == key.ESCAPE: print 'Application Exited with Key Press' window.close() @window.event def on_draw(): window.clear() video.blit(10,10) pyglet.app.run() When run, I get the following error: Traceback, line 20 in <module> video = pyglet.resource.media(frame, streaming=True) TypeError: unhashable type: 'numpy.ndarray' I'm also open to other options that would let me display text over my live video. I originally used pygame, but in the end, I'll need multiple monitor support, so that's why I'm using pyglet. Answer: There are a number of problems with your approach, but the trickiest thing is converting numpy arrays to textures. I use the approach below, which I discovered at some point elsewhere on SO. In short, you have to utilize the **ctypes** types and structures exposed by `pyglet.gl` in order to generate an array of GLubytes, and then put the contents of the image (a numpy array) into it. Then, because you have a 1-d array of values, you have to specify how Pyglet should make the image, `pImage` here, by specifying the pixel format and pitch. If you get the example below working, you should be able to get `pImg` to update on each call of `on_draw`, and you should be done. import pyglet from pyglet.gl import * from pyglet.window import key import cv2 import numpy import sys window = pyglet.window.Window() camera=cv2.VideoCapture(0) retval,img = camera.read() sy,sx,number_of_channels = img.shape number_of_bytes = sy*sx*number_of_channels img = img.ravel() image_texture = (GLubyte * number_of_bytes)( *img.astype('uint8') ) # my webcam happens to produce BGR; you may need 'RGB', 'RGBA', etc. instead pImg = pyglet.image.ImageData(sx,sy,'BGR', image_texture,pitch=sx*number_of_channels) @window.event def on_key_press(symbol, modifiers): if symbol == key.ESCAPE: print 'Application Exited with Key Press' window.close() @window.event def on_draw(): window.clear() pImg.blit(0,0) pyglet.app.run()
How do get summation of return values in different time python Question: from vaderSentiment.vaderSentiment import sentiment as vaderSentiment count=0; f1 = open('testData.txt')#input file sentence= f1.readline() while sentence: count += 1 print (sentence) vs =vaderSentiment(sentence) print ("\t" + str(vs)) sentence=f1.readline() f1.close This is the code.There input file has many sentences in lines.And result is like this. ex: she is good {'pos': 0.592, 'neu': 0.408, 'neg': 0.0, 'compound': 0.4404} she is well {'pos': 0.512, 'neu': 0.488, 'neg': 0.0, 'compound': 0.2732} I want to get whole text file positive ,negative,neutral seprately.That mean as an example summation of positive counts of sentences.so plz help me .I dont know what to do Answer: This is an example, hope it helps from vaderSentiment.vaderSentiment import sentiment as vaderSentiment testData = ['VADER is smart, handsome, and funny.', 'VADER is smart, handsome, and funny!', 'VADER is very smart, handsome, and funny.', 'VADER is VERY SMART, handsome, and FUNNY.', 'VADER is VERY SMART, handsome, and FUNNY!!!', 'VADER is VERY SMART, really handsome, and INCREDIBLY FUNNY!!!', 'The book was good.', 'The book was kind of good.', 'The plot was good, but the characters are uncompelling and the dialog is not great.', 'A really bad, horrible book.', "At least it isn't a horrible book.", ':) and :D', '', 'Today sux', 'Today sux!', 'Today SUX!', "Today kinda sux! But I'll get by, lol"] result = { 'pos':[] , 'neg':[], 'compound':[], 'neu':[] } for item in testData: vs =vaderSentiment(item) result['pos'].append(vs['pos']) result['neg'].append(vs['neg']) result['compound'].append(vs['compound']) result['neu'].append(vs['neu']) print 'sum:' for i in result.keys(): print '\t',i, '=>', sum(result[i]) sum: neg => 3.542 neu => 5.59 pos => 6.868 compound => 4.7512
python not properly reading in text file Question: I'm trying to read in a text file that looks something like this: Date, StartTime, EndTime 6/8/14, 1832, 1903 6/8/14, 1912, 1918 6/9/14, 1703, 1708 6/9/14, 1713, 1750 and this is what I have: g = open('Observed_closure_info.txt', 'r') closure_date=[] closure_starttime=[] closure_endtime=[] file_data1 = g.readlines() for line in file_data1[1:]: data1=line.split(', ') closure_date.append(str(data1[0])) closure_starttime.append(str(data1[1])) closure_endtime.append(str(data1[2])) I did it this way for a previous file that was very similar to this one, and everything worked fine. However, this file isn't being read in properly. First it gives me an error "list index out of range" for `closure_starttime.append(str(data1[1]))` and when I ask for it to print what it has for data1 or closure_date, it gives me something like ['\x006\x00/\x008\x00/\x001\x004\x00,\x00 \x001\x008\x003\x002\x00,\x00 \x001\x009\x000\x003\x00\r\x00\n'] I've tried rewriting the text file in case there was something corrupt about that particular file, and it still does the same thing. I'm not sure why because last time this worked fine. Any suggestions? Thanks! Answer: This looks like a comma-separated file with UTF-16 encoding (hence the `\x00` null bytes). You'll have to decode the input from UTF-16, like so: import codecs closure_date=[] closure_starttime=[] closure_endtime=[] with codecs.open('Observed_closure_info.txt', 'r', 'utf-16-le') as g: g.next() # skip header line for line in g: date, start, end = line.strip().split(', ') closure_date.append(date) closure_starttime.append(start) closure_endtime.append(end)
Statsmodels mosaic plot ValueError: cannot convert float NaN to integer Question: I have a simple pandas DataFrame, for which I would like to create a mosaic plot. Here is my code: import pandas as pd from statsmodels.graphics.mosaicplot import mosaic mydata = pd.DataFrame({'id2': {64: 'Angelica', 65: 'DXW_UID', 66: 'casuid01', 67: 'casuid01', 68: 'EC93_uid', 69: 'EC93_uid', 70: 'EC93_uid', 60: 'DXW_UID', 61: 'AtmosFox', 62: 'DXW_UID', 63: 'DXW_UID'}, 'id1': {64: 'TGP', 65: 'Retention01', 66: 'default', 67: 'default', 68: 'Musa_EC_9_3', 69: 'Musa_EC_9_3', 70: 'Musa_EC_9_3', 60: 'default', 61: 'default', 62: 'default', 63: 'default'}}) mydata id1 id2 60 default DXW_UID 61 default AtmosFox 62 default DXW_UID 63 default DXW_UID 64 TGP Angelica 65 Retention01 DXW_UID 66 default casuid01 67 default casuid01 68 Musa_EC_9_3 EC93_uid 69 Musa_EC_9_3 EC93_uid 70 Musa_EC_9_3 EC93_uid [11 rows x 2 columns] I can create a mosaic plot just fine when I exclude row 64. mosaic(mydata[mydata.id1!='TGP'], ['id1','id2']) (<matplotlib.figure.Figure object at 0x11E0D3B0>, OrderedDict([(('default', 'DXW_UID'), (0.0, 0.0, 0.594059405940594, 0.49504950495049505)), (('default', 'AtmosFox'), (0.0, 0.49834983498349833, 0.594059405940594, 0.16501650165016499)), (('default', 'casuid01'), (0.0, 0.66666666666666663, 0.594059405940594, 0.33003300330033009)), (('default', 'EC93_uid'), (0.0, 1.0, 0.594059405940594, 0.0)), (('Retention01', 'DXW_UID'), (0.599009900990099, 0.0, 0.09900990099009899, 0.99009900990099009)), (('Retention01', 'AtmosFox'), (0.599009900990099, 0.99339933993399343, 0.09900990099009899, 0.0)), (('Retention01', 'casuid01'), (0.599009900990099, 0.99669966996699666, 0.09900990099009899, 0.0)), (('Retention01', 'EC93_uid'), (0.599009900990099, 1.0, 0.09900990099009899, 0.0)), (('Musa_EC_9_3', 'DXW_UID'), (0.7029702970297029, 0.0, 0.29702970297029707, 0.0)), (('Musa_EC_9_3', 'AtmosFox'), (0.7029702970297029, 0.0033003300330033004, 0.29702970297029707, 0.0)), (('Musa_EC_9_3', 'casuid01'), (0.7029702970297029, 0.0066006600660066007, 0.29702970297029707, 0.0)), (('Musa_EC_9_3', 'EC93_uid'), (0.7029702970297029, 0.0099009900990099011, 0.29702970297029707, 0.99009900990099009))])) The plot comes out fine (with the exception of some of the labels looking a little funny--but that's not the issue). The errors occur when I include row 64. My questions are, why does this row cause this error, and how can I fix it? I can see that the error occurs when trying to draw the image, but it is not at all obvious where the NaN is coming from, especially since the plot before worked just fine. mosaic(mydata, ['id1','id2']) (<matplotlib.figure.Figure object at 0x11D13ED0>, OrderedDict([(('default', 'DXW_UID'), (0.0, 0.0, 0.5373936408419167, 0.49342105263157893)), (('default', 'AtmosFox'), (0.0, 0.49671052631578938, 0.5373936408419167, 0.16447368421052627)), (('default', 'casuid01'), (0.0, 0.66447368421052622, 0.5373936408419167, 0.32894736842105265)), (('default', 'Angelica'), (0.0, 0.99671052631578938, 0.5373936408419167, 0.0)), (('default', 'EC93_uid'), (0.0, 1.0, 0.5373936408419167, 0.0)), (('TGP', 'DXW_UID'), (0.5423197492163009, 0.0, 0.08956560680698614, 0.0)), (('TGP', 'AtmosFox'), (0.5423197492163009, 0.0032894736842105261, 0.08956560680698614, 0.0)), (('TGP', 'casuid01'), (0.5423197492163009, 0.0065789473684210523, 0.08956560680698614, 0.0)), (('TGP', 'Angelica'), (0.5423197492163009, 0.0098684210526315784, 0.08956560680698614, 0.98684210526315785)), (('TGP', 'EC93_uid'), (0.5423197492163009, 1.0, 0.08956560680698614, 0.0)), (('Retention01', 'DXW_UID'), (0.6368114643976712, 0.0, 0.08956560680698614, 0.98684210526315785)), (('Retention01', 'AtmosFox'), (0.6368114643976712, 0.99013157894736836, 0.08956560680698614, 0.0)), (('Retention01', 'casuid01'), (0.6368114643976712, 0.99342105263157876, 0.08956560680698614, 0.0)), (('Retention01', 'Angelica'), (0.6368114643976712, 0.99671052631578938, 0.08956560680698614, 0.0)), (('Retention01', 'EC93_uid'), (0.6368114643976712, 1.0, 0.08956560680698614, 0.0)), (('Musa_EC_9_3', 'DXW_UID'), (0.7313031795790416, 0.0, 0.2686968204209583, 0.0)), (('Musa_EC_9_3', 'AtmosFox'), (0.7313031795790416, 0.0032894736842105261, 0.2686968204209583, 0.0)), (('Musa_EC_9_3', 'casuid01'), (0.7313031795790416, 0.0065789473684210523, 0.2686968204209583, 0.0)), (('Musa_EC_9_3', 'Angelica'), (0.7313031795790416, 0.0098684210526315784, 0.2686968204209583, 0.0)), (('Musa_EC_9_3', 'EC93_uid'), (0.7313031795790416, 0.013157894736842105, 0.2686968204209583, 0.98684210526315785))])) When I run the above, I get this Traceback: File "C:\Python27\lib\site-packages\matplotlib\backends\backend_qt4.py", line 374, in idle_draw self.draw() File "C:\Python27\lib\site-packages\matplotlib\backends\backend_qt4agg.py", line 154, in draw FigureCanvasAgg.draw(self) File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw self.figure.draw(self.renderer) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1034, in draw func(*args) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 2086, in draw a.draw(renderer) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\axis.py", line 1096, in draw tick.draw(renderer) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\axis.py", line 241, in draw self.label1.draw(renderer) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\text.py", line 598, in draw ismath=ismath, mtext=self) File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 188, in draw_text font.get_image(), np.round(x - xd), np.round(y + yd) + 1, angle, gc) ValueError: cannot convert float NaN to integer Traceback (most recent call last): File "C:\Python27\lib\site-packages\matplotlib\backends\backend_qt4.py", line 299, in resizeEvent self.draw() File "C:\Python27\lib\site-packages\matplotlib\backends\backend_qt4agg.py", line 154, in draw FigureCanvasAgg.draw(self) File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw self.figure.draw(self.renderer) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1034, in draw func(*args) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 2086, in draw a.draw(renderer) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\axis.py", line 1096, in draw tick.draw(renderer) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\axis.py", line 241, in draw self.label1.draw(renderer) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "C:\Python27\lib\site-packages\matplotlib\text.py", line 598, in draw ismath=ismath, mtext=self) File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 188, in draw_text font.get_image(), np.round(x - xd), np.round(y + yd) + 1, angle, gc) ValueError: cannot convert float NaN to integer I ran the above code in the spyder IDE, with default settings. A similar issue was addressed [here](https://github.com/matplotlib/matplotlib/issues/4318), and numerical underflow was the culprit. However, if that is the case here, it is not at all obvious why. Answer: According to [the docs](http://statsmodels.sourceforge.net/stable/generated/statsmodels.graphics.mosaicplot.mosaic.html#statsmodels.graphics.mosaicplot.mosaic) the first parameter should be a contingency table. The fact that your way of doing things works at all seems to be an undocumented feature. The behaviour you're seeing (including your "funny" looking labels) is because many of the entries in your contingency table are zero, and something in the labelling code of `mosiac` is having a hard time with that. To see this, convert your `DataFrame` to a contingency table: In [161]: pd.crosstab(mydata.id1, mydata.id2) Out[161]: id2 Angelica AtmosFox DXW-UID EC93-uid casuid01 id1 Musa-EC-9-3 0 0 0 3 0 Retention01 0 0 1 0 0 TGP 1 0 0 0 0 default 0 1 3 0 2 And add a "little bit" to all those zeros. The mosiac then works fine. In [165]: ct = pd.crosstab(mydata.id1, mydata.id2) In [166]: ctplus = ct + 1 In [167]: mosaic(ctplus.unstack()) Which results in the rather beautiful: ![Beautiful mosaic plot](http://i.stack.imgur.com/43O8Q.png) The tiny downside is that it's wrong! But you can remedy that by doing ctplus = ct + 1e-8 to just add a tiny bit to all those zeros. The plot still works (but looks ugly because the labels on all those zero tiles of the mosaic are all on top of each other): ![A much uglier mosaic plot](http://i.stack.imgur.com/sIPYO.png)
Python Flask Export and Download CSV Error Question: I am using Python Flask, and I need to export session data to a CSV file and then prompt to download it My code is from StringIO import StringIO import csv import web @app.route('/exportcsv') def export_csv(): data = session csv_file = StringIO() csv_writer = csv.writer(csv_file) csv_writer.writerow(['Name', 'Age', 'Email']) for i in data : csv_writer.writerow([i[0],i[2],i[3]]) web.header('Content-Type','text/csv') web.header('Content-disposition', 'attachment; filename=it_export.csv') return csv_file.getvalue() When trying to export, I am getting this error message in export_csv web.header('Content-Type','text/csv') File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/webapi.py", line 276, in header ctx.headers.append((hdr, value)) Which is caused by web.py library, I searched all over to find a solution but was always getting irrelevant search results. Any ideas? Answer: Look at [send_file](http://flask.pocoo.org/docs/0.10/api/#flask.send_file) function. You just need to create a file in the memory on the fly. This [snippet](http://flask.pocoo.org/snippets/32/) should do the work for your case! Hope this will help.
Flask-Login:Where user_loader callback should be defined? Question: I am new to python coding but straightaway started experimenting with flask. I am having trouble with flask-login extension Here I am making a simple application which is a blog. This blog is going to be used by one person only. I cannot understand why the user_loader decorator not working which is defined in models.py. I get exception the application NoneType object is not callable. My app structure is like this . |-- app | |-- admin | | |-- __init__.py | | |-- static | | |-- templates | | `-- views.py | |-- config.py | |-- __init__.py | |-- main | | |-- __init__.py | | |-- static | | |-- templates | | `-- views.py | `-- models.py `-- launch.py app.**init** from flask import Flask from main import main from admin import admin from flask.ext.script import Manager from .config import config from flask_debugtoolbar import DebugToolbarExtension from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import Column from flask_bootstrap import Bootstrap from flask.ext.moment import Moment from flask.ext.login import LoginManager app_myblog=Flask(__name__) app_myblog.debug=True app_myblog.config.from_object(config) app_myblog.register_blueprint(main) app_myblog.register_blueprint(admin,url_prefix="/admin" toolbar=DebugToolbarExtension(app_myblog) manager=Manager(app_myblog) db=SQLAlchemy(app_myblog) Bootstrap(app_myblog) moment=Moment(app_myblog) login_manager=LoginManager() login_manager.init_app(app_myblog) login_manager.session_protection='strong' login_manager.login_view='admin.login' In app.models I have defined User class which does not load users from database. In fact it simply loads user from configuration. In same file I have also defined user_loader callback class User(UserMixin): def __init__(self): self.id='1' self.name=app_myblog.config['USERNAME'] self.password=app_myblog.config['PASSWORD'] def get_id(self): return unicode(id) @login_manager.user_loader def load_user(userid): u=User() if u.get_id()==userid: return u else: return None admin.**init** from flask import Blueprint admin=Blueprint('admin',__name__,template_folder='templates',static_folder='static') from . import views admin.views from flask import render_template,request,redirect,url_for from . import admin from flask.ext.login import login_required,login_user from flask_wtf.form import Form from wtforms import StringField,PasswordField,SubmitField from ..models import User class LoginForm(Form): username=StringField('Username') password=PasswordField('Password') submit=SubmitField('Login') @admin.route('/') @login_required def index(): return render_template('admin_home.html') @admin.route('/login',methods=['GET','POST']) def login(): form=LoginForm() if form.validate_on_submit(): login_user(User()) nextx = request.args.get('next') return redirect(nextx or url_for('admin.index')) return render_template('admin_login.html',form=form) Whenever i run the routes which have login_required i get the error TypeError: 'NoneType' object is not callable. Here is the traceback. Traceback (most recent call last): File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request return view_func(**req.view_args) File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_login.py", line 756, in decorated_view elif not current_user.is_authenticated(): File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__ return getattr(self._get_current_object(), name) File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object return self.__local() File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_login.py", line 46, in <lambda> current_user = LocalProxy(lambda: _get_user()) File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_login.py", line 794, in _get_user current_app.login_manager._load_user() File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_login.py", line 363, in _load_user return self.reload_user() File "/home/shivam/Workspaces/PythonWorkSpace/MyBlog/venv/lib/python2.7/site-packages/flask_login.py", line 325, in reload_user user = self.user_callback(user_id) TypeError: 'NoneType' object is not callable Answer: Edit: I created a minimal example of your code and the the difference was that I removed the `get_id(self)` function (+ some extra libraries that isn't needed), beacuse it's part of the `UserMixin` class that you inherit. Are you sure your form is getting validated? Can you describe how you test this step by step? I mean, "go to login.html" -> "enter credentials" -> etc Make sure which call is causing the crash, is it the `redirect` inside your login function?
Run python script from django Question: I added some python file in my django project but that python file did not execute. How can i run that python scrip in django. Answer: OK it seems you want to run a script outside of the HTTP request/response cycle, I'd recommend you make a Django admin command, because a script will need to e.g. have access to the database environment to update records from django.core.management.base import BaseCommand from yourapp.models import Thing import your_script class Command(BaseCommand): help = 'Closes the specified poll for voting' def handle(self, *args, **options): # Do your processing here your_script.process(Thing.objects.all()) With this you can call `./manage.py process_thing` and it'll run independently More on Django admin commands here, <https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/> If the processing is triggered programmatically e.g. from user requests, you'll have to setup a queue and have a task job created for each request, I'd try Celery, more on that here <http://celery.readthedocs.org/en/latest/django/first-steps-with-django.html>
Assigning names to large objects appears to increase memory usage considerably Question: Usually, when I need to invoke a complicated formula, I break it down into two or more lines to make the code more comprehensible. However, when profiling some code that calculates [RMSE](https://en.wikipedia.org/wiki/Root-mean- square_deviation), I discovered that doing this appears to increase my code's memory use. Here's a simplified example: import numpy as np import random from memory_profiler import profile @profile def fun1(): #very large datasets (~750 mb each) predicted = np.random.rand(100000000) observed = np.random.rand(100000000) #calculate residuals as intermediate step residuals = observed - predicted #calculate RMSE RMSE = np.mean(residuals **2) ** 0.5 #delete residuals del residuals @profile def fun2(): #same sized data predicted = np.random.rand(100000000) observed = np.random.rand(100000000) #same calculation, but with residuals and RMSE calculated on same line RMSE = np.mean((observed - predicted) ** 2) ** 0.5 if __name__ == "__main__": fun1() fun2() Output: Filename: memtest.py Line # Mem usage Increment Line Contents ================================================ 5 19.9 MiB 0.0 MiB @profile 6 def fun1(): 7 782.8 MiB 763.0 MiB predicted = np.random.rand(100000000) 8 1545.8 MiB 762.9 MiB observed = np.random.rand(100000000) 9 2308.8 MiB 763.0 MiB residuals = observed - predicted 10 2308.8 MiB 0.1 MiB RMSE = np.mean(residuals ** 2) ** 0.5 11 1545.9 MiB -762.9 MiB del residuals Filename: memtest.py Line # Mem usage Increment Line Contents ================================================ 13 20.0 MiB 0.0 MiB @profile 14 def fun2(): 15 783.0 MiB 762.9 MiB predicted = np.random.rand(100000000) 16 1545.9 MiB 762.9 MiB observed = np.random.rand(100000000) 17 1545.9 MiB 0.0 MiB RMSE = np.mean((observed - predicted) ** 2) ** 0.5 As you can see, the the first function (where the calculation is split) appears to require an additional ~750 mb at peak- presumably the cost of the `residuals` array. However, both functions require the array to be created- the only difference is that the first function assigns it a name. This is contrary to my understanding of the way memory management in python is supposed to work. So, what's going on here? One thought is that this could be some artifact of the memory_profiler module. Watching the Windows task manager during a run indicates a similar pattern (though I know that's not a terribly trustworthy validation). If this is a "real" effect, what am I misunderstanding about the way memory is handled? Or, is this somehow numpy-specific? Answer: `memory_profiler`'s "Mem usage" columns tells you the memory usage after each line completes, not the peak memory usage during that line. In the version where you don't save `residuals`, that array is discarded before the line completes, so it never shows up in the profiler output.
Python Requests POST error: __init__() takes 2 arguments (1 given) Question: So I have a Flask application which uses the Flask-Restless and Flask- SQLAlchemy modules to create an API. My GET requests are working fine, but POST requests are not. From models.py: from application import db class User(db.Model): __bind_key__= 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(80)) def __init__(self, email): self.email = email From application.py (API setup): from flask.ext.sqlalchemy import SQLAlchemy import flask.ext.restless db = SQLAlchemy(application) manager = flask.ext.restless.APIManager(application, flask_sqlalchemy_db=db) manager.create_api(User, methods=['GET', 'POST']) Requests processes GET requests to the API fine, but when I have a POST request like this: import json import requests url = 'http:<ip>:<port>/api/user' data = {'email': '[email protected]'} headers = {'Content-type': 'application/json'} r = requests.post(url, data=json.dumps(data), headers=headers) I get this error: ERROR in views [X:\Python27\lib\site-packages\flask_restless\views.py:413]: need more than 1 value to unpack -------------------------------------------------------------------------------- Traceback (most recent call last): File "X:\Python27\lib\site-packages\flask_restless\views.py", line 409, in extract_error_messages left, right = str(exception).rsplit(':', 1) ValueError: need more than 1 value to unpack I know it has something to do with the json'd email data I'm sending, but I'm having trouble finding out what it wants exactly. Any help is appreciated! Answer: I found the solution! Under models.py: def __init__(self, email): Email (as well as any other model's params) need to have =None def __init__(self, email=None): After that, this code works import requests url = 'http:<ip>:<port>/api/user' data = {'email': '[email protected]'} r = requests.post(url, json=data)
Errno 32: Broken pipe Question: Below is the code for which I am getting Broken Pipe error. I am not getting this error for small data sets. This arises only when the data set is large. I am not able to handle it through exceptions also. ## reading the data from CSV file import csv csv_file='Two_Patterns_TRAIN.csv' data=[] with open (csv_file,'rb') as csv_file: csvreader=csv.reader(csv_file, delimiter=';',quotechar='|') ## fetch the rows one by one for row in csvreader: ## split the rows in columns columns=row[0].split(',') myrow=[] for col in range(len(columns)): ## fetch the columns one by one and append it to the according row myrow.append(float(columns[col])) data.append(myrow) def dtw(seqA, seqB, d = lambda x,y: abs(x-y)): # create the cost matrix numRows, numCols = len(seqA), len(seqB) cost = [[0 for _ in range(numCols)] for _ in range(numRows)] # initialize the first row and column cost[0][0] = d(seqA[0], seqB[0]) for i in xrange(1, numRows): cost[i][0] = cost[i-1][0] + d(seqA[i], seqB[0]) for j in xrange(1, numCols): cost[0][j] = cost[0][j-1] + d(seqA[0], seqB[j]) # fill in the rest of the matrix for i in xrange(1, numRows): for j in xrange(1, numCols): choices = cost[i-1][j], cost[i][j-1], cost[i-1][j-1] cost[i][j] = min(choices) + d(seqA[i], seqB[j]) return cost[-1][-1] def knn(mat,k): ## fetch number of rows and columns of the matrix nrow=len(mat) if nrow<k: print "K can not be larger than n-1" return neigh=[[0]*k for i in range(nrow)] for i in range(nrow): dist=[[0]*2 for count in range(nrow)] for j in range(nrow): dist[j][0]=j+1 dist[j][1]=dtw(mat[i],mat[j]) dist = sorted(dist, key=lambda a_entry: a_entry[1]) neigh[i]=[row[0] for row in dist][1:k+1] # print neigh return neigh a=data[:500] b=data[501:] try: c=knn(a,5) except IOError, e: print e Below is the error I am getting Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner self.run() File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/monitor.py", line 588, in run already_pickled=True) File "/usr/lib/python2.7/dist-packages/spyderlib/utils/bsdsocket.py", line 24, in write_packet sock.send(struct.pack("l", len(sent_data)) + sent_data) error: [Errno 32] Broken pipe Answer: Seems like you are using Spyder IDE. This seems like a known issue in Spyder 2.1.10 , according to [Issue 1474](https://code.google.com/p/spyderlib/issues/detail?id=1474) ([Issue 1106](https://code.google.com/p/spyderlib/issues/detail?can=1&q=1106&colspec=ID%20MS%20Stars%20Priority%20Modified%20Cat%20Type%20Status%20Owner%20Summary&id=1106)) . The fix seems to be available in Spyder 2.2.
Python Add Key to Dict conditionally Question: I'm trying to generate a dict from a list of headers that "associates" columns of data to the same experiment. For example, I want to turn: headers = ["A_1","A_2","A_3","B_1","B_2","B_3"] into cols = { 1 : {'A' : 0, 'B' : 3}, 2: {'A' : 1, 'B' : 5} ... } My code is as follows: cols = {} headers = ["A_1","A_2","A_3","B_1","B_2","B_3"] col_number = 0 for header in headers: run_number = header[-1:] cols[ run_number ] = {} if "A_" in header: cols[ run_number ][ 'A' ] = col_number if "B_" in header: cols[ run_number ][ 'B' ] = col_number col_number += 1 print cols This Outputs only the last "B" columns: {'1': {'B':3}, '2':{'B':5}... } HOWEVER, if I try a simple experiment at the command shell, this notation seems to work well... cols = {} cols[1] = {} cols[1]['A'] = 1 cols[1]['B'] = 2 print cols >> {'1' : {'A':1,'B':2} } why? **EDIT:** Just needed another set of eyes I guess. The issue was this line in the loop... cols[ run_number ] = {} It overwrites cols[ run_number ] to an empty dict every time a column from a pre-existing run_number is reached. Answer: Your loop is overwriting this important variable and setting it to an empty dict: cols[ run_number ] = {} This means it gets through the "A_" strings for the various numbers and then when it's onto the "B_" strings, it overwrites all the `run_number` keys it already created for the "A_" strings. You should try something like the following instead: if run_number not in cols: cols[ run_number ] = {} Alternately, you could try to use [defaultdict](https://docs.python.org/3.5/library/collections.html)
Hit "enter" automatically every n seconds in python Question: I am calling an external program one a loop using a python script and in general everything works well. However, occasionally the program gets stuck performing a certain process. If I hit 'enter' then the program continues to run as desired. Would it be possible to run a process in the background that will hit enter every `n` seconds (whether or not it the program is stuck)? This way I will the program will continue whether or not I am present to guide it. This seems to go against my logic of how python works but I thought maybe there is some way around it. Note: I will be running the python script in bash (ubuntu 15.04) Answer: Run the external process like you have been doing but keep a pipe open to its stdin and periodically write a newline character to it. from subprocess import Popen, PIPE from time import sleep n = 10 # seconds p = Popen(["external_program", "arg1", "arg2"], stdin=PIPE) while <condition>: sleep(n) p.stdin.write(b'\n') p.stdin.flush()
Value difference comparison within a list in python Question: I have a nested list that contains different variables in it. I am trying to check the difference value between two consecutive items, where if a condition match, group these items together. i.e. Item 1 happened on 1-6-2012 1 pm Item 2 happened on 1-6-2012 4 pm Item 3 happened on 1-6-2012 6 pm Item 4 happened on 3-6-2012 5 pm Item 5 happened on 5-6-2012 5 pm I want to group the items that have gaps less than 24 Hours. In this case, Items 1, 2 and 3 belong to a group, Item 4 belong to a group and Item 5 belong to another group. I tried the following code: Time = [] All_Traps = [] Traps = [] Dic_Traps = defaultdict(list) Traps_CSV = csv.reader(open("D:/Users/d774911/Desktop/Telstra Internship/Working files/Traps_Generic_Features.csv")) for rows in Traps_CSV: All_Traps.append(rows) All_Traps.sort(key=lambda x: x[9]) for length in xrange(len(All_Traps)): if length == (len(All_Traps) - 1): break Node_Name_1 = All_Traps[length][2] Node_Name_2 = All_Traps[length + 1][2] Event_Type_1 = All_Traps[length][5] Event_Type_2 = All_Traps[length + 1][5] Time_1 = All_Traps[length][9] Time_2 = All_Traps[length + 1][9] Difference = datetime.strptime(Time_2[0:19], '%Y-%m-%dT%H:%M:%S') - datetime.strptime(Time_1[0:19], '%Y-%m-%dT%H:%M:%S') if Node_Name_1 == Node_Name_2 and \ Event_Type_1 == Event_Type_2 and \ float(Difference.seconds) / (60*60) < 24: Dic_Traps[length].append(All_Traps[Length]) But I am missing some items. Ideas? Answer: For sorted list you may use [groupby](https://docs.python.org/2/library/itertools.html#itertools.groupby). Here is a simplified example (you should convert your date strings to datetime objects), it should give the main idea: from itertools import groupby import datetime SRC_DATA = [ (1, datetime.datetime(2015, 06, 20, 1)), (2, datetime.datetime(2015, 06, 20, 4)), (3, datetime.datetime(2015, 06, 20, 5)), (4, datetime.datetime(2015, 06, 21, 1)), (5, datetime.datetime(2015, 06, 22, 1)), (6, datetime.datetime(2015, 06, 22, 4)), ] for group_date, group in groupby(SRC_DATA, key=lambda X: X[1].date()): print "Group {}: {}".format(group_date, list(group)) Output: $ python python_groupby.py Group 2015-06-20: [(1, datetime.datetime(2015, 6, 20, 1, 0)), (2, datetime.datetime(2015, 6, 20, 4, 0)), (3, datetime.datetime(2015, 6, 20, 5, 0))] Group 2015-06-21: [(4, datetime.datetime(2015, 6, 21, 1, 0))] Group 2015-06-22: [(5, datetime.datetime(2015, 6, 22, 1, 0)), (6, datetime.datetime(2015, 6, 22, 4, 0))]
Identifying Arithmetic progressions in a list of numbers Question: M arithmetic progressions each having N terms (with the terms differing by d1,d2,...dm) are passed as input with the terms shuffled. The program must print the terms in M arithmetic progressions in sequential order with the smallest starting term first. Example Input/Output 1: Input: 2 1 4 8 12 7 16 Output: 1 4 7 8 12 16 Explanation: There are two progressions. Hence 6/2 = 3 terms in each progression. So the first A.M has 1 4 7 and the second has 8 12 16 As 1 < 8, 1 4 7 is printed followed by 8 12 16 Example Input/Output 2: Input: 3 2 6 8 10 15 22 12 11 4 Output: 2 4 6 8 15 22 10 11 12 Explanation: There are three progressions. Hence 9/3 = 3 terms in each progression. So the first A.M has 2 4 6 and the second has 8 15 22. The third has 10 11 12. Note: We cannot have 8 10 12 as the second progression as the remaining numbers 11 15 22 do not for an arithmetic progression.` I thought of an approach to initially sort the numbers and then generate a list of lists containing the difference of each number with every other number. inp=raw_input() inputList=[int(c) for c in inp] inputList.sort() for i in range(0,len(inputList)): for j in range(0,len(inputList)): if(i!=j): #To avoid zeros newlist.append(abs(inputList[j]-inputList[i])) Then, map each of the numbers in the same place with that in the other list. Thus, a sequence can be identified. But it didn't work out. Is there a better way to solve this problem (preferably in Python)? Answer: You can get the combinations of the list after sorting in descending order filtering by checking if the elements are arithmetic progressions then use a Counter dict to keep track of what elements have been used to handle what should be added: def arith_seq(l, m): l.sort(reverse=True) terms = len(l) // m combs = filter(lambda x: all((x[i + 1] - x[i] == x[1] - x[0] for i in range(len(x) - 1))), combinations(l, terms)) out = [] from collections import Counter cn = Counter(l) for ele in combs: if all(cn[c] > 0 for c in ele): out.append(ele[::-1]) for c in ele: cn[c] -= 1 out.sort() return out Using your input: In [6]: inp = 3 In [7]: l = map(int,"2 6 8 10 15 22 12 11 4".split()) In [8]: arith_seq(l,inp) Out[8]: [(2, 4, 6), (8, 15, 22), (10, 11, 12)]
Give sudo access to celery workers Question: I have a python program that needs to executed like this; $ sudo python my_awesome_program.py Now I want to run thousands of instances of this program using celery, of course with different parameters. The Problem is that while celery tries to execute my program it fails and the reason is that it doesn't have `sudo` access. How can I give my celery workers the power of `sudo` to run this program ? I already tried to give sudo access to my user. Changed celery service owner etc. May be a stupid question, but I am lost. P.S **task.py** from celery import Celery import os import socket import struct import select import time import logging # Global variables broker = "redis://%s:%s" % ("127.0.0.1", '6379') app = Celery('process_ips', broker=broker) logging.basicConfig(filename="/var/log/celery_ping.log", level=logging.INFO) # From /usr/include/linux/icmp.h; your milage may vary. ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris. def checksum(source_string): """ I'm not too confident that this is right but testing seems to suggest that it gives the same answers as in_cksum in ping.c """ sum = 0 countTo = (len(source_string) / 2) * 2 count = 0 while count < countTo: thisVal = ord(source_string[count + 1]) * \ 256 + ord(source_string[count]) sum = sum + thisVal sum = sum & 0xffffffff # Necessary? count = count + 2 if countTo < len(source_string): sum = sum + ord(source_string[len(source_string) - 1]) sum = sum & 0xffffffff # Necessary? sum = (sum >> 16) + (sum & 0xffff) sum = sum + (sum >> 16) answer = ~sum answer = answer & 0xffff # Swap bytes. Bugger me if I know why. answer = answer >> 8 | (answer << 8 & 0xff00) return answer def receive_one_ping(my_socket, ID, timeout): """ receive the ping from the socket. """ timeLeft = timeout while True: startedSelect = time.time() whatReady = select.select([my_socket], [], [], timeLeft) howLongInSelect = (time.time() - startedSelect) if whatReady[0] == []: # Timeout return timeReceived = time.time() recPacket, addr = my_socket.recvfrom(1024) icmpHeader = recPacket[20:28] type, code, checksum, packetID, sequence = struct.unpack( "bbHHh", icmpHeader ) if packetID == ID: bytesInDouble = struct.calcsize("d") timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0] return timeReceived - timeSent timeLeft = timeLeft - howLongInSelect if timeLeft <= 0: return def send_one_ping(my_socket, dest_addr, ID): """ Send one ping to the given >dest_addr<. """ dest_addr = socket.gethostbyname(dest_addr) # Header is type (8), code (8), checksum (16), id (16), sequence (16) my_checksum = 0 # Make a dummy heder with a 0 checksum. header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1) bytesInDouble = struct.calcsize("d") data = (192 - bytesInDouble) * "Q" data = struct.pack("d", time.time()) + data # Calculate the checksum on the data and the dummy header. my_checksum = checksum(header + data) # Now that we have the right checksum, we put that in. It's just easier # to make up a new header than to stuff it into the dummy. header = struct.pack( "bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1 ) packet = header + data my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1 def do_one(dest_addr, timeout): """ Returns either the delay (in seconds) or none on timeout. """ logging.info('Called do_one Line 105') icmp = socket.getprotobyname("icmp") try: my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) except socket.error as xxx_todo_changeme: (errno, msg) = xxx_todo_changeme.args if errno == 1: # Operation not permitted msg = msg + ( " - Note that ICMP messages can only be sent from processes" " running as root." ) raise socket.error(msg) raise # raise the original error my_ID = os.getpid() & 0xFFFF send_one_ping(my_socket, dest_addr, my_ID) delay = receive_one_ping(my_socket, my_ID, timeout) my_socket.close() return delay def verbose_ping(dest_addr, timeout=1, count=2): """ Send >count< ping to >dest_addr< with the given >timeout< and display the result. """ logging.info('Messing with : %s' % dest_addr) try: for i in xrange(count): logging.info('line 136') try: delay = do_one(dest_addr, timeout) logging.info('line 139' + str(delay)) except socket.gaierror as e: break logging.info('line 142'+str(delay)) if delay is None: pass else: delay = delay * 1000 logging.info('This HO is UP : %s' % dest_addr) return dest_addr except: logging.info('Error in : %s' % dest_addr) @app.task() def process_ips(items): logging.info('This is Items:----: %s' % items) up_one = verbose_ping(items) if up_one is not None: logging.info('This one is UP: %s' % up_one) **my_awesome_program.py** from task import process_ips if __name__ == '__main__': for i in range(0, 256): for j in range(1, 256): ip = "192.168.%s.%s" % (str(i), str(j)) jobs = process_ips.delay(ip) **/etc/defaults/celeryd** # Names of nodes to start # most will only start one node: CELERYD_NODES="worker1" # but you can also start multiple and configure settings # for each in CELERYD_OPTS (see `celery multi --help` for examples). #CELERYD_NODES="worker1 worker2 worker3" # Absolute or relative path to the 'celery' command: CELERY_BIN="/home/jarvis/Development/venv/bin/celery" #CELERY_BIN="/virtualenvs/def/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="task" # or fully qualified: #CELERY_APP="proj.tasks:app" # Where to chdir at start. CELERYD_CHDIR="/home/jarvis/Development/pythonScrap/nmap_sub" # Extra command-line arguments to the worker CELERYD_OPTS="--time-limit=300 --concurrency=8 --loglevel=DEBUG" # %N will be replaced with the first part of the nodename. CELERYD_LOG_FILE="/var/log/celery/%N.log" CELERYD_PID_FILE="/var/run/celery/%N.pid" # Workers should run as an unprivileged user. # You need to create this user manually (or you can choose # a user/group combination that already exists, e.g. nobody). CELERYD_USER="jarvis" CELERYD_GROUP="jarvis" # If enabled pid and log directories will be created if missing, # and owned by the userid/group configured. CELERY_CREATE_DIRS=1 Answer: You need to set your CELERYD_USER param in settings. Have a look here: <http://celery.readthedocs.org/en/latest/tutorials/daemonizing.html> If you're using supervisor, then in your supervisor conf of celery, you'd need to do this: user=<user-you-want> Also, under [Example Configuration](http://celery.readthedocs.org/en/latest/tutorials/daemonizing.html#example- configuration) section, it's explicitly said to not run your workers as privileged users.
Pandas str.extract: AttributeError: 'str' object has no attribute 'str' Question: I'm trying to repurpose this function from using `split` to using `str.extract` (regex) instead. def bull_lev(x): spl = x.rsplit(None, 2)[-2].strip("Xx") if spl.str.isdigit(): return "+" + spl + "00" return "+100" def bear_lev(x): spl = x.rsplit(None, 2)[-2].strip("Xx") if spl.str.isdigit(): return "-" + spl + "00" return "-100" df["leverage"] = df["name"].map(lambda x: bull_lev(x) if "BULL" in x else bear_lev(x) if "BEAR" in x else "+100" * * * I am using `pandas` for `DataFrame` handling: import pandas as pd df = pd.DataFrame(["BULL AXP UN X3 VON", "BEAR ESTOX 12x S"], columns=["name"]) Desired output: name leverage "BULL AXP UN X3 VON" "+300" "BEAR ESTOX 12x S" "-1200" * * * Faulty regex attempt for `"BULL"`: def bull_lev(x): #spl = x.rsplit(None, 2)[-2].strip("Xx") spl = x.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).strip("x") if spl.str.isdigit(): return "+" + spl + "00" return "+100" df["leverage"] = df["name"].map(lambda x: bull_lev(x) if "BULL" in x else bear_lev(x) if "BEAR" in x else "+100") Produces error: Traceback (most recent call last): File "toolkit.py", line 128, in <module> df["leverage"] = df["name"].map(lambda x: bull_lev(x) File "/Python/Virtual/py2710/lib/python2.7/site-packages/pandas/core/series.py", line 2016, in map mapped = map_f(values, arg) File "pandas/src/inference.pyx", line 1061, in pandas.lib.map_infer (pandas/lib.c:58435) File "toolkit.py", line 129, in <lambda> if "BULL" in x else bear_lev(x) if "BEAR" in x else "+100") File "toolkit.py", line 123, in bear_lev spl = x.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).strip("x") AttributeError: 'str' object has no attribute 'str' I am assuming this is due to `str.extract` capturing a list while `split` works directly with the string? Answer: You can handle the positive case using the following: In [150]: import re df['fundleverage'] = '+' + df['name'].str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X') + '00' df Out[150]: name fundleverage 0 BULL AXP UN X3 VON +300 1 BULL ESTOX X12 S +1200 You can use `np.where` to handle both cases in a one liner: In [151]: df['fundleverage'] = np.where(df['name'].str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X').str.isdigit(), '+' + df['name'].str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X') + '00', '+100') df Out[151]: name fundleverage 0 BULL AXP UN X3 VON +300 1 BULL ESTOX X12 S +1200 So the above uses the vectorised [`str`](http://pandas.pydata.org/pandas- docs/stable/api.html#string-handling) methods [`strip`](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.Series.str.strip.html#pandas.Series.str.strip), [`extract`](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.Series.str.extract.html#pandas.Series.str.extract) and [`isdigit`](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.Series.str.isdigit.html#pandas.Series.str.isdigit) to achieve what you want. **Update** After you changed your requirements (which you should not do for future reference) you can mask the df for the bull and bear cases: In [189]: import re df = pd.DataFrame(["BULL AXP UN X3 VON", "BEAR ESTOX 12x S"], columns=["name"]) bull_mask_name = df.loc[df['name'].str.contains('bull', case=False), 'name'] bear_mask_name = df.loc[df['name'].str.contains('bear', case=False), 'name'] df.loc[df['name'].str.contains('bull', case=False), 'fundleverage'] = np.where(bull_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X').str.isdigit(), '+' + bull_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X') + '00', '+100') df.loc[df['name'].str.contains('bear', case=False), 'fundleverage'] = np.where(bear_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('x').str.isdigit(), '-' + bear_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('x') + '00', '-100') df Out[189]: name fundleverage 0 BULL AXP UN X3 VON +300 1 BEAR ESTOX 12x S -1200
subtract two columns of different Dataframe with python Question: I have two DataFrames, df1: Lat1 Lon1 tp1 0 34.475000 349.835000 1 1 34.476920 349.862065 0.5 2 34.478833 349.889131 0 3 34.480739 349.916199 3 4 34.482639 349.943268 0 5 34.484532 349.970338 0 and df2: Lat2 Lon2 tp2 0 34.475000 349.835000 2 1 34.476920 349.862065 1 2 34.478833 349.889131 0 3 34.480739 349.916199 6 4 34.482639 349.943268 0 5 34.484532 349.970338 0 I want to substract (tp1-tp2) columns and create a new dataframe whose colums are Lat1,lon1,tp1-tp2. anyone know how can I do it? Answer: import pandas as pd df3 = df1[['Lat1', 'Lon1']] df3['tp1-tp2'] = df1.tp1 - df2.tp2 Out[97]: Lat1 Lon1 tp1-tp2 0 34.4750 349.8350 -1.0 1 34.4769 349.8621 -0.5 2 34.4788 349.8891 0.0 3 34.4807 349.9162 -3.0 4 34.4826 349.9433 0.0 5 34.4845 349.9703 0.0
how to run a C code with argc argv from python? Question: I need to run my c code from python, usually as adviced [here](http://stackoverflow.com/questions/4376397/executing-a-c-script-in- python) I do this and works perfectly: from subprocess import call call(["./code", "args", "to", "code"]) I would like to run the code that in order to run needs argv, as a number, so for instance normally from shell I should call simply: ./code #certainNumber I would like to pass a string at the call function, like: D=1 str = "./code %d"(%D) call([str, "args", "to", "code"]) obviously this does not work. I would like to chose from python the parameter that I need to insert in my c code. thanks Answer: As twalberg said this works perfectly: call(["./code", str(variableContainingNumber), "other", "args"])
Correct python code to insert NULL value into MySQL Question: I'm attempting to insert some variables into a MySQL database using python. Sometimes the variables will be strings and sometimes they will be None. A hugely simplified version of what I am attempting is below: import MySQLdb as mdb f = "Bob" m = None l = "Smith" db = mdb.connect("blah blah blah") with db: cur.execute("INSERT INTO name (first, middle, last) VALUES ('{0}', '{1}', '{2}')".format(f, m, l)) The problem is that it inserts 'None' as a string rather than as an actual NULL value. I can solve the problem by changing the last line to: cur.execute("INSERT INTO name (first, middle, last) VALUES (%s, %s, %s)", (f, m, l)) but I believe that this leaves the code vulnerable to MySQL injection attacks. If anyone knows the correct way using the .format method I would be very grateful. Answer: The expected method of inserting data is the following: cur.execute("INSERT INTO name (first, middle, last) VALUES (%s, %s, %s)", (f, m, l)) Formatting a string like in your first example leaves your application vulnerable to SQL injection.
Is it a Python bug that the main thread of a process created in a daemon thread is a daemon itself? Question: When I call `os.fork()` inside a daemon thread, the main thread in the child process has the `daemon` property set to `True`. This is very confusing, since the program keeps running while the only thread is a daemon. According to the docs, if all the threads are daemons the program should exit. Here is an example: import os import threading def child(): assert not threading.current_thread().daemon # This shouldn't fail def parent(): new_pid = os.fork() if new_pid == 0: child() else: os.waitpid(new_pid, 0) t = threading.Thread(target=parent) t.setDaemon(True) t.start() t.join() Is it a bug in the CPython implementation? Answer: The reason for this behaviour is that the daemonization is only relevant for threads _other_ than the main-thread. In the main-thread, the return-value of `current_thread().daemon` is hard-coded to be `False`. See the relevant source code here: <https://github.com/python/cpython/blob/2.7/Lib/threading.py#L1097> So after a fork, there is only one thread, and it's consequently the main- thread. Which means it can never be a daemon-thread. I can not point you to any documentation beyond the source, but it is most certainly _not_ a bug - it would be a bug the other way round, if your expectation was met. The interaction between fork and threads are complex, and as I mentioned: don't mix them before fork.
Python matplotlib animation of a constantly updated data feed Question: I'm trying to make a satellite visualization tool using an animation in matplotlib. I want to plot a 5-image animation and then constantly update this animation every time a new image appears. I could animate the last 5 images like this: from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np from matplotlib import animation fig = plt.figure(figsize=(20,10),frameon=True,tight_layout=True) ax = plt.subplot(111, frameon=False) map = Basemap(projection='cyl',resolution = 'i', area_thresh = 0.1,llcrnrlon=-75, llcrnrlat=-42,\ urcrnrlon=-36, urcrnrlat=-10) map.drawlsmask(land_color='white', ocean_color='lightsteelblue', lakes=False) map.drawcoastlines(color='grey') map.drawcountries(color='grey') map.drawparallels(np.arange(-80., 81., 10.), labels=[1,0,0,0], fontsize=10) map.drawmeridians(np.arange(-180., 181., 10.), labels=[0,0,0,1], fontsize=10) map.drawstates() map.drawmapboundary() imgs = [] im = map.imshow(sat1,cmap='Greys',vmin=190, vmax=300,origin='upper') imgs.append([im]) im2 = map.imshow(sat2,cmap='Greys',vmin=190, vmax=300,origin='upper') imgs.append([im2]) im3 = map.imshow(sat3,cmap='Greys',vmin=190, vmax=300,origin='upper') imgs.append([im3]) im4 = map.imshow(sat4,cmap='Greys',vmin=190, vmax=300,origin='upper') imgs.append([im4]) im5 = map.imshow(sat5,cmap='Greys',vmin=190, vmax=300,origin='upper') imgs.append([im5]) ani = animation.ArtistAnimation(fig,imgs, interval=500) plt.show() I also could display one image and update the image with the newest one, using `FuncAnimation`. But how can I update the list that `ArtistAnimation` displays? I need to `del imgs[0]` and append a new `imshow`. That way I will always display the latest 5 satellite images. Is that possible? Answer: matplotlib is not really suited for such a problem. The GR-framework could be what you are looking for: <http://gr-framework.org/>
Python 3.4 login on aspx Question: I'm trying to login to an aspx page then get the contents of another page as a logged in user. import requests from bs4 import BeautifulSoup URL="https://example.com/Login.aspx" durl="https://example.com/Daily.aspx" user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36' language = 'en-US,en;q=0.8' encoding = 'gzip, deflate' accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' connection = 'keep-alive' headers = { "Accept": accept, "Accept-Encoding": encoding, "Accept-Language": language, "Connection": connection, "User-Agent": user_agent } username="user" password="pass" s=requests.Session() s.headers.update(headers) r=s.get(URL) print(r.cookies) soup=BeautifulSoup(r.content) LASTFOCUS=soup.find(id="__LASTFOCUS")['value'] EVENTTARGET=soup.find(id="__EVENTTARGET")['value'] EVENTARGUMENT=soup.find(id="__EVENTARGUMENT")['value'] VIEWSTATEFIELDCOUNT=soup.find(id="__VIEWSTATEFIELDCOUNT")['value'] VIEWSTATE=soup.find(id="__VIEWSTATE")['value'] VIEWSTATE1=soup.find(id="__VIEWSTATE1")['value'] VIEWSTATE2=soup.find(id="__VIEWSTATE2")['value'] VIEWSTATE3=soup.find(id="__VIEWSTATE3")['value'] VIEWSTATE4=soup.find(id="__VIEWSTATE4")['value'] VIEWSTATEGENERATOR=soup.find(id="__VIEWSTATEGENERATOR")['value'] login_data={ "__LASTFOCUS":"", "__EVENTTARGET":"", "__EVENTARGUMENT":"", "__VIEWSTATEFIELDCOUNT":"5", "__VIEWSTATE":VIEWSTATE, "__VIEWSTATE1":VIEWSTATE1, "__VIEWSTATE2":VIEWSTATE2, "__VIEWSTATE3":VIEWSTATE3, "__VIEWSTATE4":VIEWSTATE4, "__VIEWSTATEGENERATOR":VIEWSTATEGENERATOR, "__SCROLLPOSITIONX":"0", "__SCROLLPOSITIONY":"100", "ctl00$NameTextBox":"", "ctl00$ContentPlaceHolderNavPane$LeftSection$UserLogin$UserName":username, "ctl00$ContentPlaceHolderNavPane$LeftSection$UserLogin$Password":password, "ctl00$ContentPlaceHolderNavPane$LeftSection$UserLogin$LoginButton":"Login", "ctl00$ContentPlaceHolder1$RetrievePasswordUserNameTextBox":"", "hiddenInputToUpdateATBuffer_CommonToolkitScripts":"1" } r1=s.post(URL, data=login_data) print (r1.cookies) d=s.get(durl) print (d.cookies) dsoup=BeautifulSoup(r1.content) print (dsoup) but the thing is that the cookies are not preserved into the session and I can't get to the next page as a logged in user. Can someone give me some pointers on this. Thanks. Answer: When you post to the login page: r1=s.post(URL, data=login_data) It's likely issuing a redirect to another page. So the response to the POST request returns the cookies in the response, then it redirects to another page. The redirect is what is captured in r1 and does not contain the cookies. Try the same command but not allowing redirects: r1 = s.post(URL, data=login_data, allow_redirects=False)
enumerate column headers in CSV that belong to the same tag (key) in python Question: I am using the following sets of generators to parse XML in to CSV: import xml.etree.cElementTree as ElementTree from xml.etree.ElementTree import XMLParser import csv def flatten_list(aList, prefix=''): for i, element in enumerate(aList, 1): eprefix = "{}{}".format(prefix, i) if element: # treat like dict if len(element) == 1 or element[0].tag != element[1].tag: yield from flatten_dict(element, eprefix) # treat like list elif element[0].tag == element[1].tag: yield from flatten_list(element, eprefix) elif element.text: text = element.text.strip() if text: yield eprefix[:].rstrip('.'), element.text def flatten_dict(parent_element, prefix=''): prefix = prefix + parent_element.tag if parent_element.items(): for k, v in parent_element.items(): yield prefix + k, v for element in parent_element: eprefix = element.tag if element: # treat like dict - we assume that if the first two tags # in a series are different, then they are all different. if len(element) == 1 or element[0].tag != element[1].tag: yield from flatten_dict(element, prefix=prefix) # treat like list - we assume that if the first two tags # in a series are the same, then the rest are the same. else: # here, we put the list in dictionary; the key is the # tag name the list elements all share in common, and # the value is the list itself yield from flatten_list(element, prefix=eprefix) # if the tag has attributes, add those to the dict if element.items(): for k, v in element.items(): yield eprefix+k # this assumes that if you've got an attribute in a tag, # you won't be having any text. This may or may not be a # good idea -- time will tell. It works for the way we are # currently doing XML configuration files... elif element.items(): for k, v in element.items(): yield eprefix+k # finally, if there are no child tags and no attributes, extract # the text else: yield eprefix, element.text def makerows(pairs): headers = [] columns = {} for k, v in pairs: if k in columns: columns[k].extend((v,)) else: headers.append(k) columns[k] = [k, v] m = max(len(c) for c in columns.values()) for c in columns.values(): c.extend(' ' for i in range(len(c), m)) L = [columns[k] for k in headers] rows = list(zip(*L)) return rows def main(): with open('2-Response_duplicate.xml', 'r', encoding='utf-8') as f: xml_string = f.read() xml_string= xml_string.replace('&#x0;', '') #optional to remove ampersands. root = ElementTree.XML(xml_string) # for key, value in flatten_dict(root): # key = key.rstrip('.').rsplit('.', 1)[-1] # print(key,value) writer = csv.writer(open("try5.csv", 'wt')) writer.writerows(makerows(flatten_dict(root))) if __name__ == "__main__": main() One column of the CSV, when opened in Excel, looks like this: ObjectGuid 2adeb916-cc43-4d73-8c90-579dd4aa050a 2e77c588-56e5-4f3f-b990-548b89c09acb c8743bdd-04a6-4635-aedd-684a153f02f0 1cdc3d86-f9f4-4a22-81e1-2ecc20f5e558 2c19d69b-26d3-4df0-8df4-8e293201656f 6d235c85-6a3e-4cb3-9a28-9c37355c02db c34e05de-0b0c-44ee-8572-c8efaea4a5ee 9b0fe8f5-8ec4-4f13-b797-961036f92f19 1d43d35f-61ef-4df2-bbd9-30bf014f7e10 9cb132e8-bc69-4e4f-8f29-c1f503b50018 24fd77da-030c-4cb7-94f7-040b165191ce 0a949d4f-4f4c-467e-b0a0-40c16fc95a79 801d3091-c28e-44d2-b9bd-3bad99b32547 7f355633-426d-464b-bab9-6a294e95c5d5 This is due to the fact that there are 14 tags with name ObjectGuid. For example, one of these tags looks like this: <ObjectGuid>2adeb916-cc43-4d73-8c90-579dd4aa050a</ObjectGuid> My question: is there an efficient method to enumerate the headers (the keys) such that each key is enumerated like so with it's corresponding value (text in the XML data structure): It would be displayed in Excel as follows: ObjectGuid_1 ObjectGuid_2 ObejectGuid3 etc..... Please let me know if there is any other information that you need from me (such as sample XML). Thank you for your help. Answer: It is a mistake to add an element, attribute, or annotative descriptor to the data set itself for the purpose of identity… Normalizing the data should only be done if you own that data and know with 100% guarantee that doing so will not have any negative effect on additional consumers (ones relying on attribute order to manipulate the DOM). However what is the point of using a dict or nested dicts (which I don’t quite get either t) if the efficiency of the hashed table lookup is taken right back by making 0(n) checks for this attribute new attribute? The point of this hashing is random look up.. If it’s simply the structured in (key, value) pair, which makes sense here.. Why not just use some other contiguous data structure, but treat it like a dictionary.. Say a named tuple… A second solution is if you want to add additional state is to throw your generator in a class. class order: def__init__(self, lines, order): self.lines = lines self.order - python(max) def __iter__(self): for l, line in enumerate(self.lines, 1); self.order.append( l, line)) yield line when open (some file.csv) as f: lines = oder( f); Messing with the data a Harmless conversion? For example if were to create a conversion dictionary (see below) Well that’s fine, that is until one of the values is blank… types = [ (‘x ’, float’), (‘y’, float’) with open(‘some.csv’) as f: for row in cvs.DictReader(f): row.update((key, conversion (row [ key])) for key, conversion in field_types) [x: ,y: 2. 2] — > that is until there is an empty data point.. Kaboom. So My suggestion would not be to change or add to the data, but change the algorithm in which deal with such.. If the problem is order why not simply treat say a tuple as a named tuple similar to a dictionary, the caveat being mutability however makes sense with data uniformity... *I don’t understand the nested dictionary…That is for the y header values yes? values and order key —> key — > ( key: value ) ? or you could just skip the first row :p.. So just skip the first row.. for line in {header: list, header: list } line.next() # problem solved.. or print(line , end = ‘’) *** Notables -To iterator over multiple sequences in parallel h = [a,b,c] x = [1,2,3] for i in zip(a,b): print(i) (a, 1) (b, 2) -Chaining a = [1,2 , 3] b= [a, b , c ]enter code here for x in chain(a, b): //remove white space
Averaging a list in Python, "Type Error: Cannot perform reduce with flexible type" Question: The code below is supposed to do as follows: 1. Fill an empty list with a specific column of numbers from a csv file. 2. The average of the list values is then calculated and the resulting value is plotted. Problems: I keep getting the error "TypeError: cannot perform reduce with flexible type". All I do know is that it has to do something with condensing down a list. But I'm not sure beyond that. Any help is appreciated. import csv import matplotlib.pyplot as plt import numpy as np channelData = [] channelSel = int(input("Select a channel to view ")) with open('PrivateData.csv', newline='') as f: reader = csv.reader(f) for row in reader: channelData.append(row[channelSel]) averagemV = np.mean(channelData) plt.plot(averagemV) plt.ylabel("Average mV") plt.xlabel("Channel " + str(channelSel)) plt.show() Answer: with open('PrivateData.csv', newline='') as f: reader = csv.reader(f) for row in reader: channelData.append(row[channelSel]) I suspect that this is adding strings that look like floats to `channelData`, rather than actual floats. Try explicitly converting. with open('PrivateData.csv', newline='') as f: reader = csv.reader(f) for row in reader: channelData.append(float(row[channelSel]))
if __name__ == '__main__' not working ipython Question: I'm having trouble getting the `if __name == '__main__'` trick to work in an IPython, Spyder environment. I've tried every approach given in this thread: [if __name__ == '__main__' in IPython](http://stackoverflow.com/questions/22923002/if-name-main-in-ipython) Here are my super simplified modules Module1.py Class UnitTest(): print 'Mod1 UnitTest!' if __name__ == '__main__': UnitTest() Module2.py import Module1 Class UnitTest(): print 'Mod2 UnitTest!' if __name__ == '__main__': UnitTest() So I run Module2.py and I always am seeing both `Mod2 UnitTest` and `Mod1 UnitTest` printed. These are executing in an IPython kernel. I want only the `Mod2 UnitTest` message to display. Any idea what's up? Answer: Well I deleted this question earlier out of embarrassment but might as well share in case any other newb sees this. I forgot to put the UnitTest line inside of the `__init__` method. So the unit test was being run every single time when the class was defined and not when the object was instantiated. The code should be: Module1.py Class UnitTest(): def __init__(self): print 'Mod1 UnitTest!' if __name__ == '__main__': UnitTest() Module2.py import Module1 Class UnitTest(): def __init__(self): print 'Mod1 UnitTest!' if __name__ == '__main__': print 'Mod2 UnitTest!'