input_text
stringlengths
1
40.1k
target_text
stringlengths
1
29.4k
What is the scope for Gmail's OAuth2 IMAP access? I am using <a href="http://code google com/p/google-api-python-client/" rel="nofollow">google-api-python-client</a> and <a href="https://bitbucket org/mjs0/imapclient" rel="nofollow">imapclient</a> libraries to try get IMAP access to Gmail When going through the authentication flow I am getting "invalid scope" errors I have tried both `https://mail google com` and `https://mail google com/mail/feed/atom` as scopes Here is what I am trying to do: ````from oauth2client appengine import OAuth2Decorator SCOPE = "https://mail google com" # SCOPE = "https://mail google com/mail/feed/atom" oauth2decorator_gmail = OAuth2Decorator(client_id="CLIENT_ID" client_secret="CLIENT_SECRET" scope=SCOPE callback_path='/mycallbackurl') class AuthenticateSyncServices(webapp2 RequestHandler): @oauth2decorator_gmail oauth_required def get(self): self response write("Authenticated") ```` And here is the stacktrace: ````INFO 2013-06-06 08:56:36 686 client py:1304] Failed to retrieve access token: { "error" : "invalid_scope" } Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher app/Contents/Resources/GoogleAppEngine-default bundle/Contents/Resources/google_appengine/lib/webapp2-2 5 1/webapp2 py" line 1536 in __call__ rv = self handle_exception(request response e) File "/Applications/GoogleAppEngineLauncher app/Contents/Resources/GoogleAppEngine-default bundle/Contents/Resources/google_appengine/lib/webapp2-2 5 1/webapp2 py" line 1530 in __call__ rv = self router dispatch(request response) File "/Applications/GoogleAppEngineLauncher app/Contents/Resources/GoogleAppEngine-default bundle/Contents/Resources/google_appengine/lib/webapp2-2 5 1/webapp2 py" line 1278 in default_dispatcher return route handler_adapter(request response) File "/Applications/GoogleAppEngineLauncher app/Contents/Resources/GoogleAppEngine-default bundle/Contents/Resources/google_appengine/lib/webapp2-2 5 1/webapp2 py" line 1102 in __call__ return handler dispatch() File "/Applications/GoogleAppEngineLauncher app/Contents/Resources/GoogleAppEngine-default bundle/Contents/Resources/google_appengine/lib/webapp2-2 5 1/webapp2 py" line 572 in dispatch return self handle_exception(e self app debug) File "/Applications/GoogleAppEngineLauncher app/Contents/Resources/GoogleAppEngine-default bundle/Contents/Resources/google_appengine/lib/webapp2-2 5 1/webapp2 py" line 570 in dispatch return method(*args **kwargs) File "/Applications/GoogleAppEngineLauncher app/Contents/Resources/GoogleAppEngine-default bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/util py" line 68 in check_login handler_method(self *args) File "/Users/John/Projects/my-app/backend/oauth2client/appengine py" line 787 in get credentials = decorator flow step2_exchange(self request params) File "/Users/John/Projects/my-app/backend/oauth2client/util py" line 128 in positional_wrapper return wrapped(*args **kwargs) File "/Users/John/Projects/my-app/backend/oauth2client/client py" line 1310 in step2_exchange raise FlowExchangeError(error_msg) FlowExchangeError: invalid_scope ````
From <a href="https://developers google com/gmail/xoauth2_protocol" rel="nofollow">https://developers google com/gmail/xoauth2_protocol</a>: The scope for IMAP and SMTP access is <a href="https://mail google com/" rel="nofollow">https://mail google com/</a>
Python: "unsupported operand types for : 'long' and 'numpy float64' " My program uses genetic techniques to build equations It randomly assembles strings into an equation with one unknown ````"(((x 1) * x) / (4 * 6) ** 2)" ```` One of the strings is: "math factorial(random randint(1 9))" So an equation is typically something like: "`(((x 1) * x) / (4 * 6) ** 2) math factorial(random randint(1 9))`" Fifty different equations are generated and then assigned a fitness value according to how well they approximate the sin function over a range of values ````for x in numpy arange(1 6 4 1): fitness = abs(eval"(((x 1) * x) / (4 * 6) ** 2) math factorial(random randint(1 9)) - numpy sin(x))") ```` The program often throws an exception which is caught by an 'except TypeError' clause The error message is "unsupported operand types for :'long' and 'numpy float64'" When I try "type(numpy sin(1))"it returns type: numpy float64 How do I get 'long' and 'numpy float64' operand types to work together? Any help would be appreciated @catchmeifyoutry: good idea! Unfortunately it is a heck of an equation I have never tried to take one this long apart I have wondered if there is a parsing utility to help resolve all the brackets (((math factorial(random randint(1 9))))-(((x)+((((math factorial(random randint(1 9))))*<them>((math factorial(random randint(1 9)))))-(((6 0)/(((8 0)/(((3 0)-(8 0))/(((5 0)</them>((2 0)/(x)))/(8 0))))+(4 0)))/(8 0))))+(7 0))) I will try to catch the value of x at which it failed
First you are missing a closing bracket in your example and the `(+ or - or / or * or **)` is confusing What are you trying to achieve? Do you just want to insert the result in the string? Try this: ````for x in numpy arange(1 6 4 1): s = "sinus %f is %f!" % (x numpy sin(x)) print type(s) s ```` See <a href="http://docs python org/library/stdtypes html#string-formatting" rel="nofollow">string formatting</a> documentation <them>EDIT</them> Ah yes genetic programming that explains what you are trying to do ;) Based on your updated information I have to guess that your string construction is sometimes faulty somehow Change your code to display the string that causes the exception to be thrown Easiest way is to just print the string before calling eval on it and when the exception is thrown you can see what the last equation was Then if it is not clear what is wrong with it you can post that equation here
python csv: save results to csv file ````import csv with open('test csv' 'rb') as f: data = list(csv reader(f)) import collections counter = collections defaultdict(int) for row in data: counter[row[1]] = 1 for row in data: if counter[row[1]] &gt;= 4: writer = csv writer(open("test1 csv" "wb")) writer writerows(row) ```` i am getting strange output! what is wrong with this code?
An easy example would be something like: ``` writer = csv writer(open("filename csv" "wb")) String[] entries = "first#second#third" split("#"); writer writerows(entries) writer close() ```
ImportError: No module named PyQt5 - OSX Mavericks I am trying to get PyQt5 running on OSX I downloaded and installed the Qt5 binaries Then I downloaded the latest SIP source compiled and installed it Finally I downloaded the latest version of PyQt compiled and installed it ````python configure py --qmake /Users/jsmaupin/Qt/5 1 1/clang_64/bin/qmake --sip /System/Library/Frameworks/Python framework/Versions/2 7/bin/sip ```` I am trying to get this to run on the default Python 2 7 installation It looks like the files were installed into the correct location (as far as I can tell) at /System/Library/Frameworks/Python framework/Versions/2 7/share/sip/PyQt5/ However whenever I try to import anything from PyQt5 python reports that it cannot find PyQt5 The code: ````from PyQt5 import QtCore ```` The result: ````from PyQt5 import QtCore ImportError: No module named PyQt5 ```` I am a Python newbie so help is greatly appreciated!
Okay I hammered at this until I finally found a solution It seems like this might be a bug in the PyQt library installation or somewhere else I created a $PYTHONPATH environment variable to point to the newly installed PyQt py files that hold references to the all of the Qt bindings ````export set PYTHONPATH=$PYTHONPATH:/System/Library/Frameworks/Python framework/Versions/2 7/lib/python2 7/site-packages ```` After that everything worked like magic This includes PyCharm after going to Settings->Project Interpreter->Python Interpreters->Paths (tab) and clicking the "Reload list of paths" button with the blue circular arrows on the bottom
Python bindings; calling C code & performance I will keep my question short and simple Assume I have a python program which calls C++ code from a DLL compiled in C/C++ <blockquote> -Will the speed/performance of the executing code be preserved? </blockquote> Assume I have a python program has a binding to a C++ library (for example - GTK or Wx) <blockquote> -Is the speed going to match that of the library as if it was compiled with a C++ program? </blockquote> Thank you
When Python calls into C++ code the code it executes is the machine code generated by the C++ compiler You will have some cost at the interface level as you have to marshal Python types into C++ types and vice versa but the C++ code itself will run at pretty much the same speed as if it were called from C++; any differences will be due to different locality of dynamically allocated memory due to different memory use patterns (which would cause your C++ code to run at different speeds depending on which C++ application called it as well)
Expire index in mongoDB based on condition I have `boolean` field named `pending` in `Mongoengine` model in Python I want the document to be removed after 1 hour only if `pending=True` If I needed to remove the document after 1 hour unconditionally I would just set expire index Is there some smart and easy way to add some conditional check to expire index? Thank you in advance!
I am afraid it is not directly possible to add some custom logic to the periodic cleaning of expired documents but as described in the <a href="https://docs mongodb com/manual/core/index-ttl/#expiration-of-data" rel="nofollow">docs</a> you could use a expire index and only set the indexed field from your application if `pending = True` - as documents without the field of the expire index are not removed this should work although not exactly what you requested
Python is says my global name is not defined but it is defined? ````def main(): endProgram = 'no' print while endProgram == 'no': print pints = [0] * 7 totalPints = 0 averagePints = 0 highPints = 0 lowPints = 0 pints = getPints(pints) totalPints = getTotal(pints totalPints) averagePints = getAverage(totalPints averagePints) highPints = getHigh(pints highPints) lowPints = getLow(pints lowPints) displayInfo(averagePints highPints lowPints) endProgram = raw_input('Do you want to end program? (yes or no): ') while not (endProgram == 'yes' or endProgram == 'no'): print 'Please enter a yes or no' endProgram = raw_input('Do you want to end program? (yes or no): ') def getPints(pints): counter = 0 while counter < 7: pints[counter] = input('Enter pints collected: ') counter = counter 1 return pints def getTotal(pints totalPints): counter = 0 while counter < 7: totalPints = totalPints pints[counter] counter = counter 1 return totalPints def getAverage(totalPints averagePints): averagePints = float(totalPints) / 7 return averagePints def getHigh(pins highPints): highPints = pints[0] counter = 1 while counter < 7: if pints[counter] &gt; highPints: highPints = pints[counter] counter = counter 1 return highPints def getLow(pints lowPints): lowPints = pints[0] counter = 1 while counter < 7: if pints[counter] < lowPints: lowPints = pints[counter] counter = counter 1 return lowPints def displayInfo(averagePints highPints lowPints): print 'The average number of pints donated is' averagePints print 'The highest pints donated is' highPints print 'The lowest pints donated is' lowPints print main() ````
In your function `getHigh` you have the argument `pins` instead of `pints` and then your try to index `pints[0]`
Search for keywords from a string using sqlite and python I have a search box where some text can be entered and results from a database are returned for example if I was to search for 'John Smith' the record for all the John Smiths would appear However I would like to make the search less specific as in if I was to just search for 'John' that record would appear <strong>This is my query:</strong> ````cur = g db execute('SELECT name id location education FROM accounts WHERE email=? COLLATE NOCASE OR name=? COLLATE NOCASE OR education=? COLLATE NOCASE' (query query query )) ```` As you can see it also returns a search for not just 'name' but 'location' and 'education' too so I would like the keyword search to apply to these too Thanks
You want a `LIKE` statement Your SQL will look like this: ````SELECT name id location education FROM accounts WHERE email='John' COLLATE NOCASE OR name LIKE '%John%' COLLATE NOCASE OR education='John' COLLATE NOCASE ```` Notice the `LIKE` in `OR name LIKE '%John%'` <hr> ````cur = g db execute('SELECT name id location education FROM accounts WHERE email=? COLLATE NOCASE OR name LIKE ? COLLATE NOCASE OR education=? COLLATE NOCASE' (query '%'+query+'%' query )) ```` Again notice that the `OR` statement on `name` has been changed: ````OR name LIKE ? ```` With this though we also changed the passed parameter: ````'%'+query+'%' ```` This will wrap your search string in `%` characters allowing your string to appear anywhere in the field To do this with parameters we need to enclose your parameter in wildcards (`%`)
validatecommand in Tkinter—loop validating? This is what I have so far ````vdcm = (self register(self checkForInt) '%S') roundsNumTB = Entry(self validate = 'key' validatecommand = vdcm) ```` Then the checkForInt() function is defined as so ````def checkForInt(self S): return (S isDigit()) ```` The entry box is meant to take an even number and a number only; not characters If a character is inputted it is rejected This will only work once though If a character is inputted the next keystroke which is an input is not rejected If someone could tell me how to make it permanently check to make sure the string is a digit and an even one at that it would be appreciated This is the error message I get if it is any help ````Exception in Tkinter callback Traceback (most recent call last): File "/System/Library/Frameworks/Python framework/Versions/2 7/lib/python2 7/lib-tk/Tkinter py" line 1470 in __call__ return self func(*args) File "[py directory]" line 101 in checkForInt return (S isDigit()) AttributeError: 'str' object has no attribute 'isDigit' ````
I think the function call is `isdigit()` and not `isDigit()` note the capitalization difference If you want to test that the input is an integer and is even you would have to first convert the string using `int()` and test: ````def checkForEvenInt(self S): if S isdigit(): if int(S) % 2 is 0: return True return False ```` Keep in mind that Python is quite case-sensitive including functions For example here is an iPython session: ````In [1]: def my_func(): return True In [2]: my_func() Out[2]: True In [3]: my_Func() --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-25-ac6a0a3aba88&gt; in <module&gt;() ---> 1 my_Func() NameError: name 'my_Func' is not defined ````
How to easily extract ID from iTunes URL using Python iTunes URLs look like the following: ````http://itunes apple com/us/album/break-of-dawn/id472335316?ign-mpt=uo%3D http://itunes apple com/us/app/monopoly-here-now-the-world/id299110947?mt=8 http://itunes apple com/es/app/revista-/id397781759?mt=8%3Futm_so%3Dtwitter http://itunes apple com/app/id426698291&amp;mt=8" http://itunes apple com/us/album/respect-the-bull-single/id4899 http://itunes apple com/us/album/id6655669 ```` How can I easily extract id number? Example: ````get_id("http://itunes apple com/us/album/brawn/id472335316?ign-mpt=uo") #returns 472335316 ````
You can use a regex something like `"/id(\\d+) *"`; the first capture group will have the id number in it I think you can also write it as `r"/id(\d+) *"` in Python
how to add pythonpath to my files how to set python path for my files !? i tried to run my code on windows 8 using ctrl+B but it gave the following error ````'python' is not recognized as an internal or external command operable program or batch file [Finished in 0 1s with exit code 1] [shell_cmd: python -you "C:\Users\vishal_pc\Documents\python_codes\helloworld py"] [dir: C:\Users\vishal_pc\Documents\python_codes] [path: c:\Program Files (x86)\AMD APP\bin\x86_64;c:\Program Files (x86)\AMD APP\bin\x86;c:\Program Files (x86)\Intel\iCLS Client\;c:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1 0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;c:\Program Files (x86)\ATI Technologies\ATI ACE\Core-Static;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Microsoft\Web Platform Installer\] ```` somebody please help!
You should check this link <a href="http://stackoverflow com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7">Adding python to the path</a> The problem is that your computer cannot find python at this point you need to "show" him where the python is Probably if it will be installed in a directory like C:/Python27 depending on the version of the python you use
Nested Bazel Projects I am trying to build a project that uses TensorFlow Serving so I made a directory my_dir with a WORKSPACE file cloned the serving repo into it put my custom files into a directory my_project configured tensorflow within tensorflow_serving built tensorflow serving from my_dir/serving with ````bazel build //tensorflow_serving/ ```` everything builds fine there then I try to build a python file imitating mnist_export and put it in my_dir and make a BUILD file ````py_binary( name = "export_cnn" srcs = [ "export_cnn py" ] deps = [ "@tf//tensorflow:tensorflow_py" "@tf_serving//tensorflow_serving/session_bundle:exporter" ] ) ```` However when I run ````bazel build //my_project:export_cnn ```` I get the following errors: ````ERROR: /bazel/_bazel_me/3ef3308a843af155635e839105e8da5c/external/tf/tensorflow/core/BUILD:92:1: null failed: protoc failed: error executing command bazel-out/host/bin/external/tf/google/protobuf/protoc '--cpp_out=bazel-out/local_linux-fastbuild/genfiles/external/tf' -Iexternal/tf -Iexternal/tf/google/protobuf/src (remaining 1 argument(s) skipped) tensorflow/core/framework/step_stats proto: File not found tensorflow/core/framework/device_attributes proto: File not found tensorflow/core/framework/graph proto: File not found tensorflow/core/framework/tensor proto: File not found tensorflow/core/protobuf/config proto: File not found tensorflow/core/protobuf/worker proto: Import "tensorflow/core/framework/step_stats proto" was not found or had errors tensorflow/core/protobuf/worker proto: Import "tensorflow/core/framework/device_attributes proto" was not found or had errors tensorflow/core/protobuf/worker proto: Import "tensorflow/core/framework/graph proto" was not found or had errors tensorflow/core/protobuf/worker proto: Import "tensorflow/core/framework/tensor proto" was not found or had errors tensorflow/core/protobuf/worker proto: Import "tensorflow/core/protobuf/config proto" was not found or had errors tensorflow/core/protobuf/worker proto:41:12: "DeviceAttributes" is not defined tensorflow/core/protobuf/worker proto:64:3: "GraphDef" is not defined tensorflow/core/protobuf/worker proto:72:3: "GraphOptions" is not defined tensorflow/core/protobuf/worker proto:141:3: "TensorProto" is not defined tensorflow/core/protobuf/worker proto:180:3: "StepStats" is not defined tensorflow/core/protobuf/worker proto:225:3: "BusAdjacency" is not defined tensorflow/core/protobuf/worker proto:227:3: "BusAdjacency" is not defined tensorflow/core/protobuf/worker proto:232:3: "TensorProto" is not defined tensorflow/core/protobuf/worker proto:272:3: "StepStats" is not defined ```` In my WORKSPACE file I have the following: ````local_repository( name = "tf" path = __workspace_dir__ "/serving/tensorflow" ) local_repository( name = "tf_serving" path = __workspace_dir__ "/serving" ) load('//serving/tensorflow/tensorflow:workspace bzl' 'tf_workspace') tf_workspace("serving/tensorflow/" "@tf") ```` My hypothesis is that because tensorflow is a sub-sub-project it is not putting its generated files in the grandparent-projects bazel-out However I have tried many things and have not been able to get it to work
I have tensorflow serving in a folder and my project in another This is my WORKSPACE file: ````workspace(name = "my_project") local_repository( name = "org_tensorflow" path = __workspace_dir__ "/tf-serving/tensorflow/" ) local_repository( name = "tf_serving" path = __workspace_dir__ "/tf-serving/" ) load('//tf-serving/tensorflow/tensorflow:workspace bzl' 'tf_workspace') tf_workspace("tf-serving/tensorflow/" "@org_tensorflow") # ===== gRPC dependencies ===== bind( name = "libssl" actual = "@boringssl_git//:ssl" ) bind( name = "zlib" actual = "@zlib_archive//:zlib" ) ```` I have also copied zlib BUILD from tensorflow serving to the same place where I have the WORKSPACE file The BUILD file in my project has this rule (similar to yours): ````py_binary( name = "export_model" srcs = [ "export_model py" ] deps = [ "@org_tensorflow//tensorflow:tensorflow_py" "@tf_serving//tensorflow_serving/session_bundle:exporter" ] ) ```` The difference between my code and yours is that I included the dependencies in my root WORKSPACE This code is compiling and working fine for me in one machine I have some issues to compile it in others (ubuntu 14 04) because of one dependency I hope it works for you
During what century were reformed passed that allowed laws passed by the plebeians to have the full force of the law?
5th century BC
pycharm multiple interpreters in same project? I work on a project involving a "scraping" part and a "web" part I use scrapy framework for the scraping flask framework for the web Is it possible to configure PyCharm within the same project to use 2 interpreters one 2 7 for the scrapy part and one 3 x for the flask part ?
Apparently you can only have one interpreter per PyCharm project but you can <a href="https://www jetbrains com/pycharm/help/opening-multiple-projects html" rel="nofollow">open multiple projects</a> If you could split your code base to two projects this would solve the problem
How to get precipitation/rainfall through weather api? I tired <a href="http://openweathermap org/current" rel="nofollow">Open Weather Map</a> because the docs say it has "rain" but when I call it it does not So I tried <a href="https://code google com/p/python-weather-api/wiki/Examples" rel="nofollow">Python Weather API</a> but none of those options from weather com noaa or yahoo weather have rainfall or precipitation So I tried <a href="http://www wunderground com/weather/api/d/docs?d=index&amp;MR=1" rel="nofollow">Wunderground</a> but that only seems to work for US cities and on top of that I cannot be bothered buying a key Anyone know where to go from here? On open weather map it says it has rain but I do not get that in the results: Example of JSON call ````{"coord":{"lon":139 "lat":35} "sys":{"country":"JP" "sunrise":1369769524 "sunset":1369821049} "weather":[{"id":804 "main":"clouds" "description":"overcast clouds" "icon":"04n"}] "main":{"temp":289 5 "humidity":89 "pressure":1013 "temp_min":287 04 "temp_max":292 04} "wind":{"speed":7 31 "deg":187 002} "rain":{"3h":0} # on this line "clouds":{"all":92} "dt":1369824698 "id":1851632 "name":"Shuzenji" "cod":200} ```` However when I call it like so ````from pprint import pprint import requests are = requests get('http://api openweathermap org/data/2 5/weather?q=Vancouver') pprint(r json()) ```` I get something with no rainfall/precipitation ````{you'base': you'cmc stations' you'clouds': {you'all': 0} you'cod': 200 you'coord': {you'lat': 49 25 you'lon': -123 12} you'dt': 1406042326 you'id': 6173331 you'main': {you'humidity': 77 you'pressure': 862 you'temp': 289 33 you'temp_max': 290 93 you'temp_min': 288 15} you'name': you'Vancouver' you'sys': {you'country': you'CA' you'message': 0 1867 you'sunrise': 1406032353 you'sunset': 1406088323} you'weather': [{you'description': you'Sky is Clear' you'icon': you'01d' you'id': 800 you'main': you'Clear'}] you'wind': {you'deg': 104 001 you'speed': 2 75}} ````
According to the <a href="http://openweathermap org/weather-data" rel="nofollow">documentation</a> `weather` `rain 3h` and `snow 3h` are all `optional` parameters suggesting that they will not always be included in the result I interpret that to mean that rain and snow will not be reported if there was no rain or snow at the time in question -- such as in your example where it says "Sky is clear" -- but it is also possible that it means they just do not guarantee rain/snow data
What was the name of the specialty comics line created by Clive Barker for Marvel?
Razorline
How do I draw lines with custom thickness with Pyglet / OpenGL? (Python 3 x) ````if __name__ == '__main__': app = App() game_area = None labels = [pyglet text Label("0"*8 font_name = "Times New Roman" font_size=18 color = (255 0 0 255) x = app width // 2 y = app height // 2 - n anchor_x = "center" anchor_y = "center") for n in range(0 100 18)] @app event def on_draw(): app clear() [label draw() for label in labels] pyglet graphics draw(4 pyglet gl GL_LINES ("v2f" (0 0 0 app height app width / 2 app height app width / 2 0)) ) pyglet app run() ```` This example of mine gives me this: <a href="http://i stack imgur com/zS5ow png" rel="nofollow"><img src="http://i stack imgur com/zS5ow png" alt="enter image description here"></a> I have drawn a rectangle (4 line segments) but they are too thin How can I change the thickness of each line?
I have realized that actually I have to draw triangles in order to achieve "thickness": ````def draw_game_area(): pyglet graphics draw(24 pyglet gl GL_TRIANGLES ("v2f" (ORIGIN ORIGIN ORIGIN app height LINE_SEGMENT_THICKNESS ORIGIN ORIGIN app height LINE_SEGMENT_THICKNESS app height LINE_SEGMENT_THICKNESS ORIGIN ORIGIN ORIGIN ORIGIN LINE_SEGMENT_THICKNESS app width / 2 ORIGIN ORIGIN LINE_SEGMENT_THICKNESS app width / 2 LINE_SEGMENT_THICKNESS app width / 2 ORIGIN app width / 2 - LINE_SEGMENT_THICKNESS app height app width / 2 app height app width / 2 ORIGIN app width / 2 - LINE_SEGMENT_THICKNESS app height app width / 2 ORIGIN app width / 2 - LINE_SEGMENT_THICKNESS ORIGIN ORIGIN app height app width / 2 app height app width / 2 app height - LINE_SEGMENT_THICKNESS ORIGIN app height ORIGIN app height - LINE_SEGMENT_THICKNESS app width / 2 app height - LINE_SEGMENT_THICKNESS)) ) ```` <a href="http://i stack imgur com/kOZHi png" rel="nofollow"><img src="http://i stack imgur com/kOZHi png" alt="enter image description here"></a>
UnboundLocalError: local variable 'restaurantToDelete' referenced before assignment Flask app When I try to delete an item from the database in a Flask view the following error is shown ````UnboundLocalError: local variable 'restaurantToDelete' referenced before assignment ```` ````@app route('/restaurant/<int:restaurant_id&gt;/delete' methods=['GET' 'POST']) def deleteRestaurant(restaurant_id): if request method=='POST': restaurantToDelete=session query(Restaurant) filter_by(id=restaurant_id) one() session delete(restaurantToDelete) session commit() return redirect(url_for('showRestaurants')) else: return render_template('deleterestaurant html' restaurant=restaurantToDelete) ````
Look at the else at that point restaurantToDelete is not defined your code should be something like ````@app route('/restaurant/<int:restaurant_id&gt;/delete' methods=['GET' 'POST']) def deleteRestaurant(restaurant_id): restaurantToDelete=session query(Restaurant) filter_by(id=restaurant_id) one() if request method=='POST': session delete(restaurantToDelete) session commit() return redirect(url_for('showRestaurants')) else: return render_template('deleterestaurant html' restaurant=restaurantToDelete) ````
Sending an img file using Python I am looking to send an img file created using Qemu snapshot feature through the network using Python Its file is of varying size
I think you may want to read the <strong>socket</strong> module doc of python
Attribute Error: next() I want to loop one level deep using `next()` with `os walk` Critical line of my code: ````for root dirs files in os walk(dir) next(1): ```` Error: <blockquote> AttributeError: 'generator' object has no attribute 'next' </blockquote> I tried using ` next(x)` to replace old `next()[1]` as suggested by community but this also does not work
You are using python3 In python3 the `next()` method was replaced by `__next__` These method do <strong>not</strong> accept any argument(i e `a __next__(1)` is an error) They advance the iterator by <them>one</them> To advance it by more elements call `next` repeatedly If you want to advance the iterator by one use I would suggest to use the `next` built-in function: ````&gt;&gt;&gt; L = (x for x in range(10)) &gt;&gt;&gt; next(L) 0 &gt;&gt;&gt; next(L) 1 ```` Note: the `next` built-in function was added in python2 6 I believe so it is safe to use even in python2 <strong>However</strong> in your code it does not make sense calling `next` at all What are you trying to achieve with it? Doing: ````for root dirs files in next(os walk(dir)): ```` Will raise an error since `next` returns the first element of `os walk` which is a three element tuple containings lists of strings But the `for` loop will iterate over the <them>tuple</them> trying to unpack a single list into `root dirs files` If any directory has more or less than 3 files/subdirectories the code will fail <them>If</them> you want to skip only the first directory you will have to call `next` separately: ````iterable = os walk(directory) next(iterable) # throw away first iteration for root dirs files in iterable: # ```` <them>If</them> you wanted to iterate only on the directories as speculated by Martijn then you do not have to do anything in particular Simply do not use the `root` and `files` variables in the loop In this case I would suggest to rename them to `_` which is often used to indicate a variable that we <them>must</them> assign but is not used at all: ````for _ dirs _ in os walk(directory): # Work only on "dirs" Do not care for "_"s ```` <hr> <them>If</them> you want to consume the first `n` elements of an iterable you can use `itertools islice` and `collections deque` to do it fast and without memory consumption: ````from itertools import islice from collections import deque def drop_n_elements(n iterable): deque(islice(iterable n) maxlen=0) ```` And then use it as: ````iterable = os walk(directory) drop_n_elements(N iterable) # throw away first N iterations for root dirs files in iterable: # ```` <hr> It just occurred to me that there is an even faster and easier way to drop the first n elements of an iterable: ````def drop_n_elements(n iterable): next(islice(iterable n n) None) ```` It is slightly faster than using `deque( maxlen=0)` because it does only a single call to the `next` method of `islice`
What violent acts did the Showa regime commit?
Manila massacre and the implementation of a system of forced labour
Flatten a dictionary of dictionaries (2 levels deep) of lists in Python I am trying to wrap my brain around this but it is not flexible enough In my Python script I have a dictionary of dictionaries of lists (Actually it gets a little deeper but that level is not involved in this question ) I want to flatten all this into one long list throwing away all the dictionary keys Thus I want to transform ````{1: {'a': [1 2 3] 'b': [0]} 2: {'c': [4 5 1] would': [3 8]}} ```` to ````[1 2 3 0 4 5 1 3 8] ```` I could probably set up a map-reduce to iterate over items of the outer dictionary to build a sublist from each subdictionary and then concatenate all the sublists together But that seems inefficient for large data sets because of the intermediate data structures (sublists) that will get thrown away Is there a way to do it in one pass? Barring that I would be happy to accept a two-level implementation that works my map-reduce is rusty! <strong>Update:</strong> For those who are interested below is the code I ended up using Note that although I asked above for a list as output what I really needed was a sorted list; i e the output of the flattening could be any iterable that can be sorted ````def genSessions(d): """Given the ipDict return an iterator that provides all the sessions one by one converted to tuples """ for uaDict in d itervalues(): for sessions in uaDict itervalues(): for session in sessions: yield tuple(session) ```` ````# Flatten dict of dicts of lists of sessions into a list of sessions # Sort that list by start time sessionsByStartTime = sorted(genSessions(ipDict) key=operator itemgetter(0)) # Then make another copy sorted by end time sessionsByEndTime = sorted(sessionsByStartTime key=operator itemgetter(1)) ```` Thanks again to all who helped [Update: replaced nthGetter() with operator itemgetter() thanks to @intuited ]
I hope you realize that any order you see in a dict is accidental -- it is there only because when shown on screen <strong>some</strong> order has to be picked but there is absolutely no guarantee Net of ordering issues among the various sublists getting catenated ````[x for d in thedict itervalues() for alist in d itervalues() for x in alist] ```` does what you want without any inefficiency nor intermediate lists
Error when running browse in AppEngine When I run my app it loads fine but when I click on 'Browse' in AppEngine to see if my connected app is loading I get the following: ```` main py line 54 self response out write(template render(path {'name': CONFIG['site_name']} ^ IndentationError: unindent does not match outer indentation level INFO server py:585] default: "GET / HTTP/1 1" 500 - ```` I have fixed this line of code and no matter what I do it does not work
Maybe you mixed indentations of tabs and spaces If so try converting all tabs to spaces and reindent the whole code Check if python versions GAE/local are the same? If nothing helps try commenting everything out and uncomment incrementally part by part until you locate real location of the error
How to return a list from a recursive function in Python? I have the following code: ````def primes(n): acc = [] return do_primes(range(2 n 1) acc) def do_primes(xs acc): if xs: head tail = xs[0] xs[1:] acc append(head) do_primes([x for x in xs if x % head != 0] acc) else: return acc ```` Invoking the code yields to None: ````&gt;&gt;&gt; primes(10) None ````
You need to `return` once more: ````def do_primes(xs acc): if xs: head tail = xs[0] xs[1:] acc append(head) return do_primes([x for x in xs if x % head != 0] acc) else: return acc ````
What is Kaminfegerkinder?
chimney sweep children
Testing Python console programs with Unicode strings in NetBeans 6 9 I try to run the following simple code in NetBeans 6 9 ````s = you"\u00B0 Celsius" print you"{0}" format(s) ```` But I get the following error: ````UnicodeEncodeError: 'ascii' codec cannot encode character you'\xb0' in position 0: ordinal not in range(128) ````
NetBeans's console apparently is not properly set up to handle printing non-ASCII unicode strings In general you should avoid printing unicode strings without explicitly encoding them (e g `u_str encode(some_codec`) first In your specific case you can probably just get away with: ````print you'{0}' format(s) encode('utf-8') ````
How to tell what is a method and what is an object constructor in this class in Python? I am a beginner in Python and PySide Can someone explain me how to recognize what is an object constructor and what is a method in this class (e g QLCDNumber(self) vs addWidget(argv)) and therefore why not calling self vbox instead of vbox? ````import sys from PySide import QtGui QtCore class App(QtGui QWidget): def __init__(self): super(Example self) __init__() self init_ui() def init_ui(self): lcd = QtGui QLCDNumber(self) sld = QtGui QSlider(QtCore Qt Horizontal self) vbox = QtGui QVBoxLayout() vbox addWidget(lcd) vbox addWidget(sld) ````
Class constructors are defined by the method `__init__` All non-static class methods (including the constructor) take a reference to the object itself in the form the `self` parameter which is the first parameter passed You would create a new instance of the `App` class by doing the following: ````app = App() ```` Then to call the method `init_ui` you would do the following: ````app init_ui() ```` If `lcd` `sld` and `vbox` are all member variables of the `App` class then you will need to access them as `self vbox` within the methods
Finding Successors of Successors in a Directed Graph in NetworkX I am working on some code for a directed graph in NetworkX and have hit a block that is likely the result of my questionable programming experience What I am trying to do is the following: I have a directed graph G with two "parent nodes" at the top from which all other nodes flow When graphing this network I would like to graph every node that is a descendant of "Parent 1" one color and all the other nodes another color Which means I need a list Parent 1's successors Right now I can get the first layer of them easily using: ````descend= G successors(parent1) ```` The problem is this only gives me the first generation of successors Preferably I want the successors of successors the successors of the successors of the successors etc Arbitrarily because it would be extremely useful to be able to run the analysis and make the graph without having to know exactly how many generations are in it Any idea how to approach this?
Well the successor of successor is just the successor of the descendants right? ````# First successors descend = G successors(parent1) # 2nd level successors def allDescendants(d1): d2 = [] for d in d1: d2 = G successors(d) return d2 descend2 = allDescendants(descend) ```` To get level 3 descendants call allDescendants(d2) etc Edit: Issue 1: `allDescend = descend descend2` gives you the two sets combined do the same for further levels of descendants Issue2: If you have loops in your graph then you need to first modify the code to test if you have visited that descendant before e g: ````def allDescendants(d1 exclude): d2 = [] for d in d1: d2 = filter(lambda s: s not in exclude G successors(d)) return d2 ```` This way you pass `allDescend` as the second argument to the above function so it is not included in future descendants You keep doing this until `allDescandants()` returns an empty array in which case you know you have explored the entire graph and you stop Since this is starting to look like homework I will let you figure out how to piece all this together on your own ;)
Matplotlib wireframe shows strange wiring I have 3 lists containing X Y and Z values full lists are below: ````X = [132 54 132 54 132 54 132 54 132 54 132 54 132 54 132 54 132 54 132 54 132 54 134 546 134 546 134 546 134 546 134 546 134 546 134 546 134 546 134 546 134 546 134 546 136 551 136 551 136 551 136 551 136 551 136 551 136 551 136 551 136 551 136 551 136 551 138 557 138 557 138 557 138 557 138 557 138 557 138 557 138 557 138 557 138 557 138 557 140 562 140 562 140 562 140 562 140 562 140 562 140 562 140 562 140 562 140 562 140 562 142 568 142 568 142 568 142 568 142 568 142 568 142 568 142 568 142 568 142 568 142 568 144 573 144 573 144 573 144 573 144 573 144 573 144 573 144 573 144 573 144 573 144 573 146 579 146 579 146 579 146 579 146 579 146 579 146 579 146 579 146 579 146 579 146 579 148 584 148 584 148 584 148 584 148 584 148 584 148 584 148 584 148 584 148 584 148 584 150 59 150 59 150 59 150 59 150 59 150 59 150 59 150 59 150 59 150 59 150 59 152 595 152 595 152 595 152 595 152 595 152 595 152 595 152 595 152 595 152 595 152 595 154 601 154 601 154 601 154 601 154 601 154 601 154 601 154 601 154 601 154 601 154 601 156 606 156 606 156 606 156 606 156 606 156 606 156 606 156 606 156 606 156 606 156 606 158 612 158 612 158 612 158 612 158 612 158 612 158 612 158 612 158 612 158 612 158 612 160 617 160 617 160 617 160 617 160 617 160 617 160 617 160 617 160 617 160 617 160 617] Y = [1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375 1317 489501953125 1317 4967041015625 1317 50390625 1317 5111083984375 1317 518310546875 1317 5255126953125 1317 53271484375 1317 5399169921875 1317 547119140625 1317 5543212890625 1317 5615234375] Z = [4251 0 4709 0 4964 0 4841 0 5150 0 5566 0 5849 0 5126 0 4776 0 4159 0 4587 0 15026 0 16042 0 17385 0 18204 0 18756 0 18429 0 20108 0 18208 0 18137 0 15512 0 14252 0 38640 0 40912 0 44742 0 48256 0 51276 0 48700 0 48630 0 47534 0 47528 0 37621 0 36378 0 63476 0 68681 0 72606 0 77005 0 83461 0 84781 0 80830 0 78657 0 74265 0 64688 0 58954 0 72568 0 76691 0 85765 0 88176 0 95847 0 94039 0 92193 0 90114 0 86131 0 73637 0 69138 0 65324 0 69272 0 77007 0 80101 0 87474 0 83800 0 81599 0 80097 0 76092 0 67502 0 61812 0 51300 0 55933 0 61503 0 63763 0 69422 0 67678 0 64683 0 63100 0 59392 0 53528 0 48526 0 39004 0 42287 0 46422 0 48064 0 53608 0 51926 0 49335 0 47674 0 45192 0 40570 0 36978 0 29110 0 31968 0 35257 0 36317 0 40040 0 39242 0 37815 0 36077 0 34165 0 30798 0 28342 0 22130 0 24130 0 27180 0 27668 0 30156 0 29506 0 29791 0 27266 0 26196 0 24205 0 21713 0 16681 0 18604 0 20717 0 21186 0 23593 0 22869 0 23007 0 21917 0 20445 0 18478 0 16866 0 13039 0 14626 0 16060 0 16290 0 18006 0 17579 0 17736 0 17396 0 15980 0 14696 0 12509 0 10144 0 11442 0 12436 0 12937 0 14124 0 13466 0 14254 0 13358 0 12897 0 11405 0 9914 0 8173 0 9561 0 10162 0 11155 0 11221 0 11320 0 11545 0 10513 0 10939 0 9546 0 8476 0 6618 0 8130 0 8309 0 9303 0 9082 0 9210 0 9172 0 8472 0 8792 0 7922 0 6550 0] ```` I create a wireframe using matplotlib as follows: ````X=sorted(set(X)) Y=sorted(set(Y)) X Y=np meshgrid(X Y) fig=plt figure() ax=fig add_subplot(111 projection='3d') ax plot_wireframe(X Y Z) plt show() ```` The code runs does not complain but the picture I get is really strange (to me) so my questions are: - Can anyone explain to me why the wiring (so to speak) is arranged the way it is? - How do i decide 'how' to wire my data (Why would I need to? I was expecting that this function would connect the Z value of each grid coordinate) - How is it possible that the original X Y and Z are of length 165 but after performing my meshgrid X and Y are of length 11 (11*11 = 121 missing 44 values?) <img src="http://i stack imgur com/CI9Tq png" alt="enter image description here">
You will need to reshape the `Z` array: ````XX YY = meshgrid(X Y) ZZ = reshape(Z XX shape) ax plot_wireframe(XX YY ZZ) ````
Django context processor - 'str' object is not callable I am trying to build dynamic sidebar with context processor I take distinct values for sidebar from database table Here is my context processor: ````from clients models import client def sidebar(request): return {'clientlist': client objects order_by('name') distinct('name')} ```` In views py I have following code: ````from django shortcuts import render from django template import loader RequestContext from clients models import client def index(request): allclientlist = client objects all() return render (request 'clients/index html' {'allclientlist': allclientlist} context_instance=RequestContext(request processors=['sidebar'])) ```` `allclientlist` used to generate a table with all clients and their data Next I am trying to build dynamic sidebar with context processor and get following traceback ````Traceback: File "/usr/local/lib/python2 7/site-packages/django/core/handlers/base py" in get_response 115 response = callback(request *callback_args **callback_kwargs) File "/root/projects/webapp/clients/views py" in index 7 return render (request 'clients/index html' {'allclientlist': allclientlist} context_instance=RequestContext(request processors=['sidebar'])) File "/usr/local/lib/python2 7/site-packages/django/template/context py" in __init__ 179 self update(processor(request)) Exception Type: TypeError at /clients/ Exception Value: 'str' object is not callable ```` It worked when it was like: ````def index(request): allclientlist = client objects all() clientlist = client objects order_by('name') distinct('name') return render(request 'clients/index html' {'allclientlist': allclientlist 'clientlist': clientlist}) ```` But to make this menu available in all views I needed to have `clientlist` declaration in all views I wanted to avoid this and stuck Please help me to find this error
If you want `clientlist` included in all views then add `client models sidebar` to your `TEMPLATE_CONTEXT_PROCESSORS` setting and remove the `context_instance` argument from the `render` call in your view - when you use the `render` shortcut the template is automatically rendered with a request context ````def index(request): allclientlist = Client objects all() return render(request 'clients/index html' {'allclientlist': allclientlist}) ```` As an aside the Django convention would be to move the sidebar context processor into a `client context_processors` module and to capitalise your model as `Client`
Check if user input contains a word from an array - Python 3 I am writing a code that asks a set amount of questions I am trying to have the user input an answer and the code checks the users input for any word in a list of several words ````keywordlist = ("pain" "suffering" "hurt") question1 = input("how are you feeling?") if question1 lower() in keywordlist: print("something here") ```` I ended up browsing stackoverflow for the answer and came across a post about splitting a string but I did not understand it It was <a href="http://stackoverflow com/questions/37174119/check-a-string-for-any-items-in-an-array/37174142#37174142">this</a> question using this link I switched my code to : ````if any(word in Question1 for word in keywordlist split(" ")): ```` but I got the error: ````AttributeError: 'tuple' object has no attribute 'split' ```` I am new to Python and need the dumbed down version of the accurate way to do this
Splitting the string should work You can split on spaces so each individual word ends up being an element in a list Like so ````keywordlist = ("pain" "suffering" "hurt") question1 = input("how are you feeling?") question_parts = question1 split(" ") for part in question_parts: if part lower() in keywordlist: print("something here") ````
What is used to embed a youtube video to a webpage?
HTML
app_template_filter with multiple arguments How can I pass two argument to `app_template_filter`<a href="http://flask pocoo org/docs/0 10/api/#flask Blueprint app_template_filter" rel="nofollow"> [docs]</a>? This works well if i use only one argument But in this case i need two ````@mod app_template_filter('posts_page') def posts(post_id company_id): pass ```` <hr> ````{{ post id post company id | posts_page }} ```` <strong>Error:</strong> ````TypeError: posts_page() takes exactly 2 arguments (1 given) ````
From the <a href="http://jinja pocoo org/docs/dev/templates/#filters">Jijna docs</a> <blockquote> Variables can be modified by filters Filters are separated from the variable by a pipe symbol (|) and may have optional arguments in parentheses Multiple filters can be chained The output of one filter is applied to the next </blockquote> Filters are designed to <them>modify</them> one variable at a time You are looking for a <a href="http://flask pocoo org/docs/0 10/templating/#context-processors">`context processor`</a>: <blockquote> Variables are not limited to values; a context processor can also make functions available to templates (since Python allows passing around functions) </blockquote> For example ````@app context_processor def add(): def _add(int1 int2): return int(int1) int(int2) return dict(add=_add) ```` can be used in the template as ````{{ add(a b) }} ```` You can adopt this as your `posts_page` method: ````@app context_processor def posts_page(): def _posts_page(post_id company_id): # return value return dict(posts_page=_posts_page) ````
How many acres were burned in the historic Cedar Fire of 2002?
null
SyntaxError: cannot assign to function call Python 3 3 I would like to know what `SyntaxError: cannot assign to function call (<string&gt; line 6)` means in relation to my specific line of code I have looked around just about everywhere and I am not getting anything I understand simply because I just started learning code yesterday and much of what everyone else has mixed in with their strings of code is confusing Here is what I have entered: ````name = 'Hayley' print(len(name)) while len(name) < 10: print('k') len(name) = len(name) 1 print('Done ') ```` I want the program to add 1 to the length of the name until it is not less than ten anymore It starts off at 6 and then increases by 1 until it hits 10 and the program does not run anymore I am just trying to practice with loops and using a lot of meaningless things just to practice and make sure it sticks in my head I am trying to learn to code for an internship I will work at this summer
Better to remember while a beginner if there is parantheses(round bracket) in the left side of an assignment you should check it again and be extra careful ````len("arg") ```` is a function called with the argument "arg" and it already returns a value Therefore cannot be assigned to something <strong>something can be assigned to it </strong> I cannot truly help you because of not knowing exactly what you are trying to do But what you expected to happen while you tried to increase the length of the string by using the function to measure the length alone Study on what you exactly want and you will get closer to the answer like in all other subjects
Solitaire python I have a code here for moving the card from the deck to the foundation pile I have imported the necessary details etc My problem is its too long Is there any way to make it shorter?? How? Thanks :) ````def dtof(): suit = raw_input("enter suit: ") v = trash pop() if suit == "D": if card suitNumber[v suit] == 1: if card rankNumber[v rank] == 0: Diamond append(v) elif card rankNumber[v rank] == card rankNumber[Diamond[-1] rank] 1: Diamond append(v) else: trash append(v) return Diamond[-1] else: trash append(v) elif suit == "H": if card suitNumber[v suit] == 2: if card rankNumber[v rank] == 0: Heart append(v) elif card rankNumber[v rank] == card rankNumber[Heart[-1] rank] 1: Heart append(v) else: trash append(v) return Heart[-1] else: trash append(v) elif suit == "C": if card suitNumber[v suit] == 4: if card rankNumber[v rank] == 0: Clubs append(v) elif card rankNumber[v rank] == card rankNumber[Clubs[-1] rank] 1: Clubs append(v) else: trash append(v) return Clubs[-1] else: trash append(v) elif suit == "S": if card suitNumber[v suit] == 3: if card rankNumber[v rank] == 0: Spade append(v) elif card rankNumber[v rank] == card rankNumber[Spade[-1] rank] 1: Spade append(v) else: trash append(v) return Spade[-1] else: trash append(v) else: trash append(v) ````
Consider merging Diamond Heart Clubs and Spade into a single dictionary with the key being suit
How to debug parse error when inserting data to BigQuery from Google Cloud Datalab? How can I debug a failure to insert data into BigQuery from Google Cloud Datalab? This is my code but it is throwing an error on the last line `aggregate_data` is a Pandas dataframe with 8172 rows and 92 columns: ````ds = 'calculations' dataset = bq DataSet(ds) dataset create() schema = bq Schema from_dataframe(aggregate_data) table_name = 'cost_ratios' temptable = bq Table(ds ' ' table_name) create(schema=schema overwrite=True) temptable insert_data(aggregate_data) ```` This is the error that is thrown: ````RequestException Traceback (most recent call last) <ipython-input-6-b905b654683e&gt; in <module&gt;() 49 temptable = bq Table(ds ' ' table_name) create(schema=schema 50 overwrite=True) --> 51 temptable insert_data(aggregate_data) /usr/local/lib/python2 7/dist-packages/gcp/bigquery/_table pyc in insert_data(self data include_index index_name) 364 response = self _api tabledata_insertAll(self _name_parts rows) 365 except Exception as e: -> 366 raise e 367 if 'insertErrors' in response: 368 raise Exception('insertAll failed: %s' % response['insertErrors']) RequestException: Parse Error ```` Looking in BQ the table has been created with the correct schema but there is no data in it How can I debug this further? The error above does not tell me much and I cannot see anything in BigQuery
My guess here is that there is data in the Dataframe that is not conforming to the Schema The error is coming from BigQuery and I believe is due to it trying to parse a field based on the type specified in the spec but failing Try catch that exception and print its 'content' property; that will give you the full response from BigQuery and may she would more light on the problem
Equating python datetimes I am working with a few slightly different styles of python datetimes Problem is I would like to be able to equate them and I cannot From the database I am getting datetimes in the format of: ````datetime date(2010 11 15) ```` Which when returned outputs: ````2010-11-15 ```` However on my end I need to turn some dates in a csv file into a date time I do so by using the `datetime datetime strptime` package So here my code looks like this: ````date = '11/15/2010' #The format in the CSV file date = date replace('/' ' ') date2 = datetime datetime strptime(date '%m %d %Y') ```` However date2 when printed outputs: ````2010-11-15 00:00:00 ```` And the two dates though actually equivalent will not evaluate to `True` when I throw a `==` in between them Is there a way to use `datetime datetime strptime` to leave out hours minutes seconds? I would like to conform to the format used in the first example (my database) Thanks
You are trying to compare a `datetime` and a `date` To compare them simply do: ````date2 date() == datetime date(2010 11 15) ```` and you should be fine A bit more context: ````In [1]: import datetime In [2]: datetime date today() Out[2]: datetime date(2013 10 28) In [3]: datetime datetime now() Out[3]: datetime datetime(2013 10 28 11 5 43 997651) In [4]: datetime datetime now() == datetime date today() Out[4]: False In [5]: datetime datetime now() date() == datetime date today() Out[5]: True ````
python regular expression repeated characters I am looking to create a regular expression in python that matches all DNA sequences starting with `T` followed by `18` characters (any characters) and then terminated by either `AA` `TT` `CC` or `GG` I can manage the first part but I cannot seem to find a way to write the end (the double characters) without duplicating the regex 4 times Here is what I have for a sequence ending in `TT`: ````import re seq='ATGTGTGGACACAAGTGACAGTTTACGATGAGGTTACAGCCCGCA' match=re findall('T {18}TT' seq) print match ````
Check out <a href="http://www regular-expressions info/tutorial html" rel="nofollow">a good tutorial</a> There is a concept called alternation It matches any one of the given options: ````r'T {18}(?:TT|AA|CC|GG)' ```` Note that you should use raw strings to encode regexes in Python otherwise you will get problems with escaping characters later
What type of religion is Buddhism?
nontheistic
How to encode data for use in Charm's attribute based encryption? I am using Charm Crypto from Github I would like to use the attribute based encryption algorithms The test code works fine however it uses a random message generated from PairingGroup How do I use my own data for encryption? ````&gt;&gt;&gt; group = PairingGroup('SS512' secparam=512) &gt;&gt;&gt; message = group random(GT) ```` The PairingGroup has encode/decode methods but they are not implemented I just want to try this with "Hello world!"
Look at this class under charm/charm/test/toolbox/symcrypto_test py ````class SymmetricCryptoAbstractionTest(unittest TestCase): def testAESCBC(self): self MsgtestAESCBC(b"hello world") def testAESCBCLong(self): self MsgtestAESCBC(b"Lots of people working in cryptography have no deep \ concern with real application issues They are trying to discover things \ clever enough to write papers about -- Whitfield Diffie ") def testAESCBC_Seperate(self): self MsgTestAESCBCSeperate(b"Lots of people working in cryptography have no deep \ concern with real application issues They are trying to discover things \ clever enough to write papers about -- Whitfield Diffie ") def MsgtestAESCBC(self message): groupObj = PairingGroup('SS512') a = SymmetricCryptoAbstraction(sha1(groupObj random(GT))) ct = a encrypt(message) dmsg = a decrypt(ct); assert message == dmsg 'o: =&gt;%s\nm: =&gt;%s' % (message dmsg) def MsgTestAESCBCSeperate(self message): groupObj = PairingGroup('SS512') ran = groupObj random(GT) a = SymmetricCryptoAbstraction(sha1(ran)) ct = a encrypt(message) b = SymmetricCryptoAbstraction(sha1(ran)) dmsg = b decrypt(ct); assert message == dmsg 'o: =&gt;%s\nm: =&gt;%s' % (message dmsg) ````
When does the spread of antibacterial resistance frequently occurs/
vertical transmission
what does include() in urls py do in django I am new to django I came across include() method I read docs regarding it But could not understand it as it lacked suitable example I am again rewriting this question in a proper way so that it does not sounds baseless Already It had been downvoted a lot due to which I cannot ask new questions any more ? Can you please help me out by giving me a suitable example regarding the scenario in which include() method becomes handy ? Thanks in advance
include() adds urls from your app directory's urls py to the main urls py (in memory) This keeps the main urls py from getting too big to read see <a href="https://docs djangoproject com/en/1 8/topics/http/urls/" rel="nofollow">https://docs djangoproject com/en/1 8/topics/http/urls/</a> The Including Other URLConfs section
Getting internal server error when trying to handle json in django I am trying to receive a json object sent from my jquery post call as seen below in the code I get the "POST OK" callback when the ````simplejson loads(request POST) ```` is commented But as soon i am trying do do something with the request I get Internal server error 500 Any ideas or any other ways to handle json? views py ````@csrf_exempt def post_post(request): print 'post_post' if request method == 'POST': print 'POST' messageData = simplejson load(request POST) return HttpResponse(simplejson dumps("POST OK!")) else: return HttpResponse(simplejson dumps("POST NOT OK!")) ```` projectViewModel js ```` var m = "Hello World"; console log(m); $ ajax({ url: 'postNewPost/' type: 'POST' dataType: 'json' data: {client_response: JSON stringify(m)} success: function(result) { console log(result); } }); ````
It is because you are trying to pass a dictionary to `loads()` method `request POST` is a dictionary with params You can get raw content using `request raw_post_data` Also `simplejson` is deprecated in Django and if you are using Python 2 6+ you should just use Python `json` package (`import json`) Also in your js code you passing param `client_response` with json in it In this case you will need to pass only `request POST['client_response']` to `loads()` method But the better way will be to pass json directly ```` data: JSON stringify(m) ````
Porting python-twisted based code to scala: framework advice needed I am trying to port a significant amount of code written in python with twisted to scala and I am looking for opinions on what framework combination to choose The thing is essentially an RPC (custom protobuf-based xmlrpc)/HTTP server and client that does some database-keeping and transformations but later sends down rpcs to workers which are outside of the scope of this rewrite As a network IO/base for implementing RPC stack I am using netty All the workflows in the old thingy were based on twisted's Deferred and to replace it I am currently considering either ChannelFuture directly or wrapping it inside either scalaz Promise or akka Future I guess one part of the question is - can it be done simpler than manually working with callbacks? I guess if I choose this route I can simplify it later by adding some wrappers and using continuations but maybe I need to use something different from the beginning? I tried to fit the workflow inside actor model but it does not seem to work with stdlib actors Thanks <strong>Update:</strong> Finagle seems to be modeled closely after or at least accidentally similar to twisted twitter util Future looks a lot like twisted's Deferred So I am using it for the moment <strong>Update 2:</strong> The reasons why I ported it in the first place are static typing and performance
Have a look at this <a href="http://brizzled clapper org/id/88/" rel="nofollow">link</a> It is a blog post on performance comparison between Scala and Python Twisted His code (or his advice) might be useful to you
Django ModelForm get next item in list after submit I am not really too sure how to title this question but I am trying to develop a simple webapp with Django What I am trying to do is that the user will manually tag each image and each tag will have a foreign key to a specific image (but each image can have multiple tags) The index page is supposed to display the actual image but I have not figured that out yet Pretty much the problem is I am not sure how to implement it so for each page the index page will show a picture and a box for the image tag After the user submits it will go to the next untagged image / image with the least number of tags Right now the user can submit a tag (and the data is written correctly) but it still stays on the same image I am a Python / Django noob so forgive me :P Here is the relevant source code: forms py: ````class InputForm(forms ModelForm): image = forms ModelChoiceField(queryset=Image objects all() widget=forms HiddenInput()) class Meta: model = Tag ```` models py: ````class Image(models Model): image_location = models CharField(max_length=200) num_tags = models IntegerField(default=0) image_score = models FloatField() def __unicode__(self): return you'%d' % self id class Tag(models Model): image = models ForeignKey(Image) tag_text = models CharField(max_length=200 blank=True) def __unicode__(self): return self tag_text ```` views py: ````def index(request): if request method == 'POST': return HttpResponse(request POST['image']) image = Image objects all()[0] form = InputForm(initial={'image': image}) return render_to_response('imageSite/index html' { 'form':form } context_instance=RequestContext(request)) def submit(request): form = InputForm(request POST) if(form is_valid()): image = form cleaned_data['image']; image num_tags = image num_tags 1 image save() model = form save() model save() return redirect(index) ```` index html: ````<ul&gt; <form action="/imageSite/submit/" method="post"&gt; {%csrf_token %} <table&gt; {{ form as_table }} </table&gt; <input type="submit" value="Submit" /&gt; </form&gt; </ul&gt; ````
The code `return redirect(index)` will not work You will need to return a redirect response with the proper URL to which it should redirect For example: ````redirect_url = '/images/45/' return HttpResponseRedirect(redirect_url) ```` See <a href="https://docs djangoproject com/en/dev/topics/forms/#using-a-form-in-a-view" rel="nofollow">this example</a> in the Django documentation for a full example Note that the value for `redirect_url` needs to be computed in your view: you will need to compute the `Image` object with the least number of tags and use Django's <a href="https://docs djangoproject com/en/dev/topics/http/urls/#reverse" rel="nofollow">`reverse`</a> to cleanly compute the URL of that `Image` object If the form is invalid then you should not perform a redirect
Getting date difference and output: Years - Months How can I get the difference of two dates and output something like `1 Year 3 months`? I am using <a href="http://jinja pocoo org/docs/templates/" rel="nofollow">Jinja2</a> Template engine currently I have: ````{{ context job_history|map(attribute="to_")|first - context job_history|map(attribute="from_")|first }} ```` Which outputs: <blockquote> 370 days </blockquote> I have tried: ````{{ (context job_history|map(attribute="to_")|first - context job_history|map(attribute="from_")|first)/365 }} ```` But this gives me a `TypeError`: ````TypeError: unsupported operand type(s) for /: 'datetime timedelta' and 'int' ```` I think(personal opinion) that the Jinja2 syntax is close to python syntax
Use the ` days` attribute of the returned `datetime timedelta` object: ````{{ (context job_history|map(attribute="to_")|first - context job_history|map(attribute="from_")|first) days/365 }} ```` but you really want to build such information in your Python view code
Schumann described Chopin's music as cannons buried in what?
flowers
How to add an Admin class to a model after syncdb? I added some models in my models py and I want to add an admin class to use a wysiwyg-editor in text-fields Well I know that Django itself does not support migrations and I have used South but it does not work either South does not "see" the change Could it be that South just detects changes to fields but not if I add a new class? How can I tweak Django to detect such changes?
`syncdb` and South are only concerned with descendants of `Model` in apps listed in `INSTALLED_APPS` Everything else is handled by Django directly
'module' has no attribute 'urlencode' When i try to follow python wiki page example related to URL encoding: ````&gt;&gt;&gt; import urllib &gt;&gt;&gt; params = urllib urlencode({'spam': 1 'eggs': 2 'bacon': 0}) &gt;&gt;&gt; f = urllib urlopen("http://www musi-cal com/cgi-bin/query" params) &gt;&gt;&gt; print f read() ```` An error is raised on the second line: ````Traceback (most recent call last): File "<stdin&gt;" line 1 in <module&gt; AttributeError: 'module' object has no attribute 'urlencode' ```` What i am missing? <a href="https://docs python org/2/library/urllib html#urllib urlencode">https://docs python org/2/library/urllib html#urllib urlencode</a>
`urllib` has been split up in Python 3 The `urllib urlencode()` function is now <a href="https://docs python org/3/library/urllib parse html#urllib parse urlencode">`urllib parse urlencode()`</a> and the `urllib urlopen()` function is now <a href="https://docs python org/3/library/urllib request html#urllib request urlopen">`urllib request urlopen()`</a>
How to send hex with Python I want to send a hex code from my Raspberry Pi to the connected Servo Drive I have a RS 485 Shield from Link Sprite for the Communication The Shield works because I get an answer in Python she will My Question is how can I send `0111050200013F0804` to my Servo Drive? The code I have so far is ````import serial port = "/dev/ttyAMAO" usart = serial Serial (port 4800) usart flushInput() usart write("0111050200013F0804") ````
Hex is just a way of displaying binary information in a more concise way Each group of 4 bits is represented by alphanumeric digit ranging from `0` to `F` Therefore if you wanted to represent the following binary `101100011111` in hex it would be `B1F` For more see <a href="http://www codeproject com/Articles/4069/Learning-Binary-and-Hexadecimal" rel="nofollow">this page on code project </a> <h1>Python 3</h1> In Python 3 byte objects are different to strings The first thing that needs to be done is to convert the hex in to a byte object which then can be written on the serial port ````import serial port = "/dev/ttyAMAO" usart = serial Serial (port 4800) message_bytes = bytes fromhex("0111050200013F0804") usart write(message_bytes) ```` <h1>Python 2</h1> In Python 2 strings and bytes are the same thing However you still need to convert the hex text into its equivalent bytes This can be done using the `decode("hex")` on a string ````import serial port = "/dev/ttyAMAO" usart = serial Serial (port 4800) message_bytes = "0111050200013F0804" decode("hex") usart write(message_bytes) ````
How do I list all tga files in a directory (non recursive) in Python? How do I list all tga files in a directory (non recursive) in Python?
```` >>> import os >>> for file in [tga for tga in os listdir(directory) if tga endswith(" tga")]: >>> print file ````
How to write big set of data to xls file? I have really big database which I want write to <strong>xlsx/xls</strong> file I already tried to use <strong>xlwt</strong> but it allows to write only 65536 rows (some of my tables have more than 72k rows) I also found <strong>openpyxl</strong> but it works too slow and use huge amount of memory for big spreadsheets Are there any other possibilities to write excel files? edit: Following kennym's advice i used Optimised Reader and Writer It is less memory consuming now but still time consuming Exporting takes more than hour now (for really big tables- up to 10^6 rows) Are there any other possibilities? Maybe it is possible to export whole table from <strong>HDF5 database</strong> file to <strong>excel</strong> instead of doing it <strong>row after row</strong>- like it is now in my code?
Use the <a href="http://packages python org/openpyxl/optimized html" rel="nofollow">Optimized Reader and Writer</a> of the openpyxl package The optimized reader and writer run much faster and use far less memory than the standard openpyxl methods
What game do the Bluejays play against the Expos?
the Pearson Cup
pandas DataFrame combine_first and update methods have strange behavior I am running into a strange issue (or intended?) where `combine_first` or `update` are causing values stored as `bool` to be upcasted into `float64`s if the argument supplied is not supplying the boolean columns Example workflow in ipython: ````In [144]: test = pd DataFrame([[1 2 False True] [4 5 True False]] columns=['a' 'b' 'isBool' 'isBool2']) In [145]: test Out[145]: a b isBool isBool2 0 1 2 False True 1 4 5 True False In [147]: b = pd DataFrame([[45 45]] index=[0] columns=['a' 'b']) In [148]: b Out[148]: a b 0 45 45 In [149]: test update(b) In [150]: test Out[150]: a b isBool isBool2 0 45 45 0 1 1 4 5 1 0 ```` Was this meant to be the behavior of the `update` function? I would think that if nothing was specified that `update` would not mess with the other columns <hr> <strong>EDIT</strong>: I started tinkering around a little more The plot thickens If I insert one more command: `test update([])` before running `test update(b)` boolean behavior works at the cost of numbers upcasted as `objects` This also applies to DSM's simplified example Based on <a href="https://github com/pydata/pandas/blob/master/pandas/core/frame py#L3830" rel="nofollow">panda's source code</a> it looks like the reindex_like method is creating a DataFrame of dtype `object` while reindex_like `b` creates a DataFrame of dtype `float64` Since `object` is more general subsequent operations work with bools Unfortunately running `np log` on the numerical columns will fail with an `AttributeError`
Before updating the dateframe `b` is been filled by <a href="http://pandas pydata org/pandas-docs/dev/generated/pandas DataFrame reindex_like html" rel="nofollow">reindex_link</a> so that b becomes ````In [5]: b reindex_like(a) Out[5]: a b isBool isBool2 0 45 45 NaN NaN 1 NaN NaN NaN NaN ```` And then use <a href="http://docs scipy org/doc/numpy/reference/generated/numpy where html" rel="nofollow">numpy where</a> to update the data frame The tragedy is that for `numpy where` if two data have different type the more general one would be used For example ````In [20]: np where(True [True] [0]) Out[20]: array([1]) In [21]: np where(True [True] [1 0]) Out[21]: array([ 1 ]) ```` Since `NaN` in `numpy` is floating type it will also return an floating type ````In [22]: np where(True [True] [np nan]) Out[22]: array([ 1 ]) ```` Therefore after updating your 'isBool' and 'isBool2' column become floating type I have added this issue on <a href="https://github com/pydata/pandas/issues/3016" rel="nofollow">the issue tracker for pandas</a>
Pyglet: Sprite draw() and Batch draw() do not work but Image blit does In pyglet which I am learning Image blit() works but Sprite draw() does not nor Batch draw() even in this simple code: ````import pyglet win = pyglet window Window() img = pyglet resource image('test png') spr = pyglet sprite Sprite(img) @win event def on_draw(): win clear() spr draw() if __name__ == '__main__': pyglet app run() ```` The window remains black However I can draw labels for example THe only explaination I found was about graphic cards and "v2i" bugs with some of them but I am afraid to touch at pyglet's code without really knowing what I am doing
The third answer of <a href="http://stackoverflow com/questions/9693934/cannot-draw-sprites-in-pyglet">this thread</a> worked for me even though I am using Ubuntu and not Windows It is actually a hardware problem I replaced the "i" with the "f" at lines 368 and 372 in "v2i" in a file I found at /usr/lib/pymodules/python2 7/pyglet/sprite py Then I saved ran my code and everything was working
Where did the mandolin shrink in popularity?
null
WTForms validation bound to model validation <strong>models py</strong> ````class Invoice(Base Timestampable): __tablename__ = 'invoices' issued_no = db Column( db String(16) nullable=False unique=True default=lambda: Invoice next_issued_no() ) issued_date = db Column(db DateTime nullable=False) exchange_rate = db Column(db Numeric(10 2) nullable=False default=1) currency = db Column(db String(8) nullable=False default='RON') contract_id = db Column(db Integer db ForeignKey('contracts id')) contract = db relationship('Contract') customer_id = db Column(db Integer db ForeignKey('customers id')) customer = db relationship('Customer') due_date = db Column(db DateTime nullable=False) description = db Column(db String(255) nullable=True) rows = db relationship('InvoiceRow') @classmethod def next_issued_no(cls): invoice = cls query with_entities(cls issued_no) \ order_by(desc(cls issued_no)) first() if not invoice: return '100000' return int(invoice issued_no) 1 ```` <strong>forms py</strong> ````class InvoiceForm(Form): issued_date = DateField( 'Issued Date' [validators Required('Required field')] format='%d/%m/%Y' ) exchange_rate = DecimalField( 'Exchange Rate' [validators Required('Required field')] ) currency = SelectField( 'Currency' [validators Required('Required field')] choices=[ ('EUR' 'EUR') ('USD' 'USD') ] ) contract = QuerySelectField( 'Contract' query_factory=lambda: InvoiceForm get_contracts() ) customer = QuerySelectField( 'Customer' query_factory=lambda: InvoiceForm get_customers() ) due_date = DateField( 'Due' [validators Required('Required field')] format='%d/%m/%Y' ) description = TextAreaField( 'Description' [validators Optional()] filters=[strip_filter] ) rows = FieldList( FormField(InvoiceRowForm) label='Rows' min_entries=1 ) // ```` I have to validate the Invoice issued_date based on issued_no which is auto generated issued_date cannot be lower than any other Invoice issued_date where Invoice issued_no is lower e g: ````// valid 100001 01/04/2013 100002 01/05/2013 100003 01/06/2013 // invalid 100001 01/05/2013 100002 01/04/2013 100003 01/06/2013 ```` How can i do that?
You can add a custom validator to your Form class For example: ````class InvoiceForm(Form): # def validate_issued_date(self field): last_invoice = Invoice query order_by(Invoice issued_no desc()) first() if field data < last_invoice issued_date: raise ValidationError('Invoice out of sequence') ````
Scrapy she will gets 301 redirected to URL without parameters <a href="http://doc scrapy org/en/latest/index html" rel="nofollow">Scrapy</a> can request URLs with `GET` parameters to interactively explore the response: ````scrapy she will "https://duckduckgo com/?q=foo" ```` But with some websites my request gets `301` redirected and the URL parameters are stripped: ````DEBUG: Redirecting (301) to <GET http://foo com/mypage/&gt; from <GET http://foo com/mypage/?bar=baz&gt; DEBUG: Crawled (200) <GET http://foo com/mypage/&gt; (referer: None) ```` When I visit `http://foo com/mypage/?bar=baz` in my browser as normal I do not get redirected and the `GET` parameters remain Can anyone suggest how I might avoid being redirected?
Inspired by @paultrmbrth's answer in the comments here is exactly how to get around this problem using <a href="http://en wikipedia org/wiki/User_agent#User_agent_spoofing" rel="nofollow">User Agent spoofing</a> First find your browser's User Agent string (I did this using <a href="http://www whatsmyuseragent com/" rel="nofollow">http://www whatsmyuseragent com/</a> but there may be other ways) Mine was ````Mozilla/5 0 (X11; Ubuntu; Linux x86_64; rv:31 0) Gecko/20100101 Firefox/31 0 ```` Now in `project_name/items py` add the following line: ````USER_AGENT = "whatever the user agent string was" ```` and `scrapy she will "http://foo com/mypage/?bar=baz"` will work as expected
What was the average temperature for July 2011?
17.6 °C
Remap values in pandas column with a dict I have a dictionary which looks like this: `di = {1: "A" 2: "B"}` I would like to apply it to the "col1" column of a dataframe similar to: ```` col1 col2 0 w a 1 1 2 2 2 NaN ```` to get: ```` col1 col2 0 w a 1 A 2 2 B NaN ```` How can I best do this? For some reason googling terms relating to this only shows me links about how to make columns from dicts and vice-versa :-/
There is a bit of ambiguity in your question There are at least <strike>three</strike> two interpretations: - the keys in `di` refer to index values - the keys in `di` refer to `df['col1']` values - the keys in `di` refer to index locations (not the OP's question but thrown in for fun ) Below is a solution for each case <hr> <strong>Case 1:</strong> If the keys of `di` are meant to refer to index values then you could use the `update` method: ````df['col1'] update(pd Series(di)) ```` For example ````import pandas as pd import numpy as np df = pd DataFrame({'col1':['w' 10 20] 'col2': ['a' 30 np nan]} index=[1 2 0]) # col1 col2 # 1 w a # 2 10 30 # 0 20 NaN di = {0: "A" 2: "B"} # The value at the 0-index is mapped to 'A' the value at the 2-index is mapped to 'B' df['col1'] update(pd Series(di)) print(df) ```` yields ```` col1 col2 1 w a 2 B 30 0 A NaN ```` I have modified the values from your original post so it is clearer what `update` is doing Note how the keys in `di` are associated with index values The order of the index values -- that is the index <them>locations</them> -- does not matter <hr> <strong>Case 2:</strong> If the keys in `di` refer to `df['col1']` values then @DanAllan and @DSM show how to achieve this with `replace`: ````import pandas as pd import numpy as np df = pd DataFrame({'col1':['w' 10 20] 'col2': ['a' 30 np nan]} index=[1 2 0]) print(df) # col1 col2 # 1 w a # 2 10 30 # 0 20 NaN di = {10: "A" 20: "B"} # The values 10 and 20 are replaced by 'A' and 'B' df['col1'] replace(di inplace=True) print(df) ```` yields ```` col1 col2 1 w a 2 A 30 0 B NaN ```` Note how in this case the keys in `di` were changed to match <them>values</them> in `df['col1']` <hr> <strong>Case 3:</strong> If the keys in `di` refer to index locations then you could use ````df['col1'] put(di keys() di values()) ```` since ````df = pd DataFrame({'col1':['w' 10 20] 'col2': ['a' 30 np nan]} index=[1 2 0]) di = {0: "A" 2: "B"} # The values at the 0 and 2 index locations are replaced by 'A' and 'B' df['col1'] put(di keys() di values()) print(df) ```` yields ```` col1 col2 1 A a 2 10 30 0 B NaN ```` Here the first and third rows were altered because the keys in `di` are `0` and `2` which with Python's 0-based indexing refer to the first and third locations
Fortran ordered (column-major) numpy structured array possible? I am looking for a way to more efficiently assign column of a numpy structured array Example: ````my_col = fn_returning_1D_array( ) ```` executes more than two times faster on my machine than the same assignment to the column of a structured array: ````test = np ndarray(shape=(int(8e6) ) dtype=dtype([('column1' 'S10') more columns ])) test['column1'] = fn_returning_1D_array( ) ```` I tried creating `test` with fortran ordering but it did not help Presumably the fields stay interleaved in memory Does anybody have any idea here? I would be willing to use low-level numpy interfaces and cython if they could help <hr> <h2>Edit 1: in response to hpaulj's answer</h2> The apparent equivalence of recarray column assignment and "normal" array column assignment results only if the latter is created with row-major order With column-major ordering the two assignments are far from equivalent: <strong>Row-major</strong> ````In [1]: import numpy as np In [2]: M N=int(1e7) 10 In [4]: A1=np zeros((M N) 'f') In [9]: dt=np dtype(' ' join(['f' for _ in range(N)])) In [10]: A2=np zeros((M ) dtype=dt) In [11]: X=np arange(M+0 0) In [13]: %timeit for n in range(N):A1[: n]=X 1 loops best of 3: 2 36 s per loop In [15]: %timeit for n in dt names: A2[n]=X 1 loops best of 3: 2 36 s per loop In [16]: %timeit A1[: :]=X[: None] 1 loops best of 3: 334 ms per loop In [8]: A1 flags Out[8]: C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False ```` <strong>Column-major</strong> ````In [1]: import numpy as np In [2]: M N=int(1e7) 10 In [3]: A1=np zeros((M N) 'f' 'F') In [4]: dt=np dtype(' ' join(['f' for _ in range(N)])) In [5]: A2=np zeros((M ) dtype=dt) In [6]: X=np arange(M+0 0) In [8]: %timeit for n in range(N):A1[: n]=X 1 loops best of 3: 374 ms per loop In [9]: %timeit for n in dt names: A2[n]=X 1 loops best of 3: 2 43 s per loop In [10]: %timeit A1[: :]=X[: None] 1 loops best of 3: 380 ms per loop In [11]: A1 flags Out[11]: C_CONTIGUOUS : False F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False ```` Note that for column-major ordering the two buffers are no longer identical: ````In [6]: A3=np zeros_like(A2) In [7]: A3 data = A1 data In [20]: A2[0] Out[20]: (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) In [21]: A2[1] Out[21]: (1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0) In [16]: A3[0] Out[16]: (0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0) In [17]: A3[1] Out[17]: (10 0 11 0 12 0 13 0 14 0 15 0 16 0 17 0 18 0 19 0) ````
These are not equivalent actions One just generates an array (and assigns it to a variable a minor action) The other generates the array and fills a column of a structured array ````my_col = fn_returning_1D_array( ) test['column1'] = fn_returning_1D_array( ) ```` I think a fairer comparison would to fill in the columns of a 2D array ````In [38]: M N=1000 10 In [39]: A1=np zeros((M N) 'f') # 2D array In [40]: dt=np dtype(' ' join(['f' for _ in range(N)])) In [41]: A2=np zeros((M ) dtype=dt) # structured array In [42]: X=np arange(M+0 0) In [43]: A1[: 0]=X # fill a column In [44]: A2['f0']=X # fill a field In [45]: timeit for n in range(N):A1[: n]=X 10000 loops best of 3: 65 3 µs per loop In [46]: timeit for n in dt names: A2[n]=X 10000 loops best of 3: 40 6 µs per loop ```` I am a bit surprised that filling the structured array is faster Of course the fast way to fill the 2D array is with broadcasting: ````In [50]: timeit A1[: :]=X[: None] 10000 loops best of 3: 29 2 µs per loop ```` But the improvement over filling the fields is not that great I do not see anything significantly wrong with filling a structured array field by field It is got to be faster than generating a list of tuples to fill the whole array I believe `A1` and `A2` have identical data buffers For example if I makes a zeros copy of A2 I can replace its data buffer with `A1's` and get a valid structured array ````In [64]: A3=np zeros_like(A2) In [65]: A3 data=A1 data ```` So the faster way of filling the structured array is to do the fastest 2D fill followed by this `data` assignment But in the general case the challenge is to create a compatible 2D array It is easy when all field dtypes are the same With a mix of dtypes you would have to work at the byte level There are some advanced `dtype` specifications (with offsets etc) that may facilitate such a mapping <hr> Now you have shifted the focus to Fortran order In the case of a 2d array that does help But it will do so at the expense of row oriented operations ````In [89]: A1=np zeros((M N) 'f' order='F') In [90]: timeit A1[: :]=X[: None] 100000 loops best of 3: 18 2 µs per loop ```` One thing that you have not mentioned at least not before the last rewrite of the question is how you intend to use this array If it is just a place to store a number of arrays by name you could use a straight forward Python dictionary: ````In [96]: timeit D={name:X copy() for name in dt names} 10000 loops best of 3: 25 2 µs per loop ```` Though this really is a time test for `X copy()` In any case there is not any equivalent to Fortran order when dealing with dtypes None of the array operations like `reshape` `swapaxes` `strides` broadcasting cross the 'dtype' boundary
Matplotlib plots messed up I have a fairly simple plot that suddenly started going crazy after I changed something with the backends for another project using seaborn where a bug makes it necessary to change backend for correct results However I must have done something that changes the way plots are made completely because somehow the frame of my plots are now gone and the background of plots as well Here are two plots (data is different did not have all backups of the "good ones") left is the way it is supposed to look like right is the current The only thing I changed was to run the command `export MPLBACKEND="module://WXAgg"` I have restarted my computer and even reinstalled matplotlib since then to see if this fixes things But it is still the same Any help would be greatly appreciated I am sure it is only my inexperience that makes this appear so difficult to solve <strong>Edit</strong> I have continued to look at this but still cannot find a solution It does not appear to be my modification with the backend but I have no clue what else to blame I have restored my scripts to older versions that I knew had no problems and I ran the script at another computer without any problems! Here is the script in its current condensed state: ````import matplotlib matplotlib use('pdf') import matplotlib pyplot as plt def ColumnDensity_withTimeList(inputdirs species_list model_data abundances times_list parameter_label plot_dir style single_plots column_density_limit): for s in range(0 len(species_list)): for d in range(0 len(inputdirs)): patches = [] radii = model_data[d]['radii'][: 0] f ax = plt subplots(1 1) for t in range(0 len(times_list)): ax loglog(radii abundances color='black') ax grid(b=True which='major' color='lightgray' linestyle='--') f subplots_adjust(right=0 75) ax2 = ax twinx() ax2 semilogy(radii model_data[d]['temperatures'] 'r--') ax2 set_ylabel('Temperature [K]' color='r') for tl in ax2 get_yticklabels(): tl set_color('r') ax3 = ax twinx() ax3 set_frame_on(True) ax3 patch set_visible(False) ax3 spines['right'] set_position(('axes' 1 2)) ax3 semilogy(radii model_data[d]['densities'] 'b--') ax3 set_ylabel('Density [cm-3]' color='b') for tl in ax3 get_yticklabels(): tl set_color('b') plt savefig(filename " pdf") plt close() ```` <a href="http://i stack imgur com/ZhzqL png" rel="nofollow"><img src="http://i stack imgur com/ZhzqL png" alt="Correct plot"></a> <a href="http://i stack imgur com/9sNJh png" rel="nofollow"><img src="http://i stack imgur com/9sNJh png" alt="Faulty plot"></a>
As far as I can see the only difference between the plots is that on the left boxes are shown and hidden on the right I am not sure what seaborn does but it seems that something you did changed the default settings for those parameters You can turn the boxes on and off explicitly with `plt box('off')/plt box('on')` For the legend you can pass the argument `frameon = True/False` <strong>Edit</strong>: Try the following: find your rcparams file (`matplotlib matplotlib_fname()`) Paste the following lines into it: ````axes facecolor:white axes edgecolor:black legend frameon: True ```` Rerun your script
What school did Dell go to and later drop out of while he ran his business?
University of Texas at Austin
how to split a list in to different strings in python i have a list object like this `value = [<employee 'Mark Twain' as 'Captain'&gt; <employee 'Huckle' as 'Cowboy'&gt;]` now i would like to have the employee and in a seperate variable like emplo[0] and as[0] like ````emplo[0] = 'Mark Twain' as[0] = 'Captain' emplo[1] = 'Huckle' as[1] = 'Cowboy' ```` from the value maybe loop through the list and return the value is there any possible code to split the list value in seperate variables?
It would be better to access the objects' data based on the methods those objects implement or reading whatever their attributes are But in the absence of other information you <them>could</them> split these up assuming that none of the names or jobs ever contain a `'` When you print ````value = [<employee 'Mark Twain' as 'Captain'&gt; <employee 'Huckle' as 'Cowboy'&gt;] ```` that is the `repr` result of each object so you could call `split` on that in two list comprehensions: ````employees = [repr(obj) split("'")[1] for obj in value] positions = [repr(obj) split("'")[3][:-1] for obj in value] ```` `repr(value[0])` will produce `<employee 'Mark Twain' as 'Captain'&gt;` so when you call `split("'")` on that you get a list like this: ````['<employee ' 'Mark Twain' ' as ' 'Captain&gt;'] ```` So calling `[1]` on that result gets the employee name and calling `[3]` will get their job though you will also need to slice the last character off that string as it has `&gt;` that is why I added `[:-1]`
How to have automated headers for python files A proper header format in python is described <a href="http://stackoverflow com/questions/1523427/python-what-is-the-common-header-format"> here </a> Using either VIM or a she will script I would like to have the usual metadata (like `__author__ __authors__ __contact__ __copyright__ __license__ __deprecated__ __date__ and __version__`) added to the file header SVN keywords would also be nice Adding it to new files is the most relevant Adding it to existing files is a bonus <a href="http://ruslanspivak com/2010/11/01/auto-insert-module-header/" rel="nofollow"> Ruslan's Blog </a> has a solution for Emacs But I was unable to find a solution for Python Where has this been done for python without Emacs? VIM can copy text from one file to another <a href="http://stackoverflow com/questions/864118/is-there-a-way-to-have-copyright-text-prepended-to-new-files-in-vim"> like so </a> but maybe there is a nicer way
Here is my C++ files template: ````/***************************************************************************** * @file <file_name&gt; * * @date <date&gt; * @author John Doe * @email jdoe@yourcompany com * * @brief * * @detail * *****************************************************************************/ ```` And here is what I have inside `~/ vimrc`: ````" Reads the template file replacing the tags by the actual " information and insert the result at the beginning of the buffer At " the end creates two blank lines at the end of the file and " position the cursor at the first one function! s:insert_description() let template = $HOME "/ vim/template/cpp template" let file_name = expand("%:t") " Get file name without path let date = strftime("%Y") " Get the current year in format YYYY let i = 0 for line in readfile(template) let line = substitute(line "<file_name&gt;" file_name "ge") let line = substitute(line "<date&gt;" date "ge") call append(i line) let i = 1 endfor execute "normal! Go\<Esc&gt;k" endfunction autocmd BufNewFile * {c++ cpp cc c h hpp} call <SID&gt;insert_description() ```` Basically I read the template file replacing the tags and with the actual information and insert the result at the beggining of the newly created file The function `s:insert_description()` is called whenever vim created a new file This is set by the `autocmd` at the last line You can base yourself at this code and create the equivalent for python
Python - Write a function that takes a string as an argument and displays the letters backward one per line This is an exercise from "How to think like a Computer Scientist" I am learning Python/programming and I am not sure how to do accomplish this task Here is an example in the book that displays the letters forwards I cannot figure out how to get the opposite effect Has to use a while-loop ````fruit = 'banana' index = 0 while index &gt; len(fruit): letter = fruit[index] print letter index = index 1 ````
Well it is basically the same thing but: - You have to start from the last letter instead of the first so instead of `index = 0` you will need `index = len(fruit) - 1` - You have to <them>decrease</them> the index instead of increasing it at the end of the while loop so `index = index 1` becomes `index = index - 1` - The condition of the while loop is different; you want to stay within the loop as long as `index` points to a valid character index Since `index` starts from `len(fruit) - 1` and it gets one smaller after every iteration eventually it will get smaller than zero Zero is still a valid character index (it refers to the first character of the string) so you will want to stay within the loop as long as `index &gt;= 0` -- this will be the `while` condition Putting it all together: ````fruit = 'banana' index = len(fruit) - 1 while index &gt;= 0: letter = fruit[index] print letter index = index - 1 ````
Convert Tweet string in text file to JSON object in Python Here is an example string I have stored in a `txt` file called `file txt`: ````{ "created_at":"Wed Mar 30 23:13:12 0000 2013" "id":3712307838977 "id_str":"12307838977" "timestamp_ms":"7392180” } ```` This data is related to tweets and each tweet is on a new line of the text file Right now I am loading it into python with the following code: ````with open(test_file 'r') as f: data = f read() split('\n') ```` This gives me a list of strings for each tweet I would like to convert it to a json object so I could do something like: ````for tweet in data: created = tweet["created_at'] ```` However I have gotten many different types of errors when attempting to use `json loads(tweet)` Any assisstance?
The problem you are most likely happening is because this part of your string: ````"timestamp_ms":"7392180” ```` More specifically that last quote `”` You are most likely getting this error: ````json decoder JSONDecodeError: Unterminated string starting at: line 1 column 105 (char 104) ```` I do not know how you generated this file but by fixing that and using this double quote `"` the conversion works ````import json with open('new_file txt' 'r') as f: json_data = json loads(f read() strip()) for data in json_data: print(json_data[data]) ```` <hr> Output: ````3712307838977 12307838977 7392180 Wed Mar 30 23:13:12 0000 2013 ````
Filter xml data in Python Please help Python beginner after getting all the data from xml <strong>data_list = xmlTree findall(' //data')</strong> e g here I get 10 rows Now I need to keep only a few rows for which attribute 'name' values match with elements of another list (inputID) with three IDs inside e g remains only 3 rows whose name attribute match with the list elements Thank you
You can remove a node from the tree using ````current_node getparent() remove(current_node) ````
Separately validating username and password during Django authentication When using the standard authentication module in django a failed user authentication is ambiguous Namely there seems to be no way of distinguishing between the following 2 scenarios: - Username was valid password was invalid - Username was invalid I am thinking that I would like to display the appropriate messages to the user in these 2 cases rather than a single "username or password was invalid " Anyone have any experience with simple ways to do this The crux of the matter seems to go right to the lowest level - in the django contrib auth backends ModelBackend class The authenticate() method of this class which takes the username and password as arguments simply returns the User object if authentication was successful or None if authentication failed Given that this code is at the lowest level (well lowest level that is above the database code) bypassing it seems like a lot of code is being thrown away Is the best way simply to implement a new authentication backend and add it to the AUTHENTICATION_BACKENDS setting? A backend could be implemented that returns a (User Bool) tuple where the User object is only None if the username did not exist and the Bool is only True if the password was correct This however would break the contract that the backend has with the django contrib auth authenticate() method (which is <a href="http://docs djangoproject com/en/dev/topics/auth/#django contrib auth authenticate">documented</a> to return the User object on successful authentication and None otherwise) Maybe this is all a worry over nothing? Regardless of whether the username or password was incorrect the user is probably going to have to head on over to the "Lost password" page anyway so maybe this is all academic I just cannot help feeling though EDIT: A comment regarding the answer that I have selected: The answer I have selected is the way to implement this feature There is another answer below that discusses the potential security implications of doing this which I also considered as the nominated answer However the answer I have nominated explains <them>how</them> this feature could be implemented The security based answer discusses whether one <them>should</them> implement this feature which is really a different question
We had to deal with this on a site that used an external membership subscription service Basically you do ````from django contrib auth models import User try: user = User objects get(username=whatever) # if you get here the username exists and you can do a normal authentication except: pass # no such username ```` In our case if the username did not exist then we had to go check an HTPASSWD file that was updated by a Perl script from the external site If the name existed in the file then we would create the user set the password and then do the auth
Editing a lines in a csv file based on previous lines I Am very very new to python I am using it here as I Am told it is good for fileIO I have a CSV file in the following format It records the daily activity for my staff <hr> Date Name Project Manager 01/01/10 Tommy HyperDyne Joe Bloggs 01/01/10 Sue Robot Joe Bloggs 01/01/10 Mark HyperDyne Joe Bloggs 02/01/10 Tommy SICK 03/01/10 Tommy HyperDyne Joe Bloggs <hr> When an employee is marked as SICK the manager field is always blank I want to fill in the Manager field with the previous manager entry for that employee I want to fill in all the blanks in the csv and put in NULLS when we cannot say In pseudocode-ish: ````Forall lines n if n Project = "Sick" y = 1 if n-y name = n name n manager = n-y manager else y++ if y &gt; n n manager = null ```` (could probably wrap that into a for y < n loop perhaps) This would need to be either edit the input file or output a new file I suspect editing the input file would be easier as people can be sick multiple days in a row Would love some advice its been ages since I Have done procedural programming
You could go through each line of input csv read check it and then write it to output csv While you loop through the lines keep a record of the previous manager for each person When you encounter a 'SICK' row lookup the previous manager in your records Here is some incpomplete code to illustrate: ````previous_managers = dict() for line in csv: name = line name project = line project manager = line manager if project == 'SICK': manager = previous_managers[person] or 'NULL' else: previous_managers[person] = manager write(name project manager) ````
Lotka-Volterra equations(predator prey) using Runge-Kutta in Python I am trying to write a program using the Lotka-Volterra equations for predator-prey interactions Solve Using ODE's: ````dx/dt = a*x - B*x*y dy/dt = g*x*y - s*y ```` Using 4th order Runge-Kutta method I need to plot a graph showing both x and y as a function of time from t = 0 to t=30 <blockquote> a = alpha = 1 b = beta = 0 5 g = gamma = 0 5 s = sigma = 2 initial conditions x = y = 2 </blockquote> Here is my code so far but not display anything on the graph Some help would be nice ````#!/usr/bin/env python from __future__ import division print_function import matplotlib pyplot as plt import numpy as np def rk4(f are t h): """ Runge-Kutta 4 method """ k1 = h*f(are t) k2 = h*f(r+0 5*k1 t+0 5*h) k3 = h*f(r+0 5*k2 t+0 5*h) k4 = h*f(r+k3 t+h) return (k1 2*k2 2*k3 k4)/6 def f(are t): alpha = 1 0 beta = 0 5 gamma = 0 5 sigma = 2 0 x y = r[2] r[2] fxd = x*(alpha - beta*y) fyd = -y*(gamma - sigma*x) return np array([fxd fyd] float) tpoints = np linspace(0 30 0 1) xpoints = [] ypoints = [] are = np array([2 2] float) for t in tpoints: xpoints = [r[2]] ypoints = [r[2]] are = rk4(f are t h) plt plot(tpoints xpoints) plt plot(tpoints ypoints) plt xlabel("Time") plt ylabel("Population") plt title("Lotka-Volterra Model") plt savefig("Lotka_Volterra png") plt show() ````
A simple check of your variable `tpoints` after running your script shows it is empty: ````In [7]: run test py In [8]: tpoints Out[8]: array([] dtype=float64) ```` This is because you are using <a href="http://docs scipy org/doc/numpy/reference/generated/numpy linspace html" rel="nofollow">`np linspace`</a> incorrectly The third argument is the number of elements desired in the output You have requested an array of length 0 1 Take a look at `np linspace`'s docstring You will not have a problem figuring out how to adjust your code
Extract and substitute substring between placeholders in string I have an input text ````input = 'I like {sushi} and {tempura} ' ```` and want to get a list and a replaced src from that ````lst = ['sushi' 'tempura'] src = 'I like * and * ' ```` I can use any tokens in the input/output strings instead of `{}` and `*` such as `[]` or something
````import re input = 'I like {sushi} and {tempura} ' regex = re compile(r'\{([^\}]*)\}') lst = regex findall(input) #['sushi' 'tempura'] mod_str = regex sub('*' input) #I like * and * print (lst) print (mod_str) ```` You can also do the replacement with string formatting: ````mod_str = input format(**dict((x '*') for x in lst)) ```` <hr> regex breakdown (note I used a raw string [`r' '`]): - `\{` -- Look for literal '{' - `[^\}]` -- match anything that is not a literal '}' - `*` -- match it as many times as possible - `\}` -- match a literal '}' Parenthesis added to make a grouping in the match for `re findall` <hr> As pointed out by DSM another common idiom for finding the text between tokens is: ````r"\{( *?)\}" ```` which means: - `\{` -- match literal '{' - `( *?)` -- match anything but do not be greedy about it -- (do not eat stuff that the re will be able to use for the next portion of the match) - `'\}'` -- match literal '}'
What is causing Python not to recognize a variable defined in a for loop? I was hoping that someone could explain to me what I am doing to cause a variable defined in a for loop to not be recognized when I attempt to call it later on Basically I have got a large list of frequencies that each have a bunch of possible molecules matches listed under them and I marked the correct molecule with a '%' when I identified it to come back to later Now I am trying to pull those frequency-molecule matches out for something else and my method was this: ````frequencies = [17 987463 etc] # large list for k in frequencies: g = open('list' 'r') for line in g: if line[0:9] == k[0:9]: # if the entry in the list matches the observed frequency for _ in range(25): check = str(g next()) # check all lines under it for a % symbol if check[0] == '%': q = check split('\t')[-1] break # if you find it save the last entry and stop the for loop Continue until you find it else: continue else: continue table write(str(q)) table write(str(k)) ```` But this says "UnboundLocalError: local variable 'q' referenced before assignment" If I would defined q inside a function I would understand but I am confused why it is saying this because you can write something like ````for i in range(5): x=i**2 print x ```` and get 16 so we know that variables defined in for loops will exist outside of them I thought that whatever the problem was it could be fixed by making a global variable so I added in a line so that middle part read: ````if check[0]=='%': global q q=check split('\t')[-1] ```` but then it says "NameError: global name 'q' is not defined" Could someone please explain what I am doing wrong? Thank you
The assignment is never executed This will never evaluate to true: ```` if line[0:9]==k[0:9]: ```` `g read()` will yield a `str` object while the elements of `frequencies` are `float`s You probably want something like: ````if line[0:9]==str(k)[0:9] ```` This will convert the `float` k to a `str` and then trim it to 9 characters including the separator(` `)
What has been designed to help with the gallery?
Gothic access tower with lift
Python semi-noob can someone explain why this phonomena occurs in 'Lists' I am working on a small app that pulls data out of a list stored in a list passes it through a class init and then displays/allows user to work Everything was going fine until i tried to format the original 'list' in the IDLE so it was easier to read (for me) so I would change 9 to 09 8 to 08 etc It was a simple formating/spacing change and it broke the entire god damn program citing 'invalid token' WTF is this I thought So then I opened the interpreter and started typing: ````&gt;x = [5 5] #Control &gt;x [5 5] &gt;&gt;&gt; y=[05 05] #control2 &gt;&gt;&gt; y [5 5] &gt;&gt;&gt; z = [05 "ge"] #test 'Integer' before string apparantly works &gt;&gt;&gt; z [5 'ge'] &gt; a = ["ge" 09] #test2 String before 'integer' cocks things up SyntaxError: invalid token &gt;&gt;&gt; b= ["ge" 9] #test3 this works fine &gt;&gt;&gt; b ['ge' 9] ```` I guess my question is why does this occur? Why is python interpret these integers as 'tokens' when they follow strings but as integers when they follow integers?
It is nothing to do with lists or strings When you prefix a number with `0` it is interpreted as <a href="http://en wikipedia org/wiki/Octal" rel="nofollow">octal</a> And 9 is not a valid octal digit! ````Python 2 7 6 Type "help" "copyright" "credits" or "license" for more information &gt;&gt;&gt; 09 File "<stdin&gt;" line 1 09 ^ SyntaxError: invalid token &gt;&gt;&gt; 011 9 ```` Note that in Python3 this gives you the error for any 0-prefixed number presumably to reduce confusion of the type you are experiencing To specify octal in Python3 you must use `0o` as a prefix ````Python 3 3 3 Type "help" "copyright" "credits" or "license" for more information &gt;&gt;&gt; 09 File "<stdin&gt;" line 1 09 ^ SyntaxError: invalid token &gt;&gt;&gt; 011 File "<stdin&gt;" line 1 011 ^ SyntaxError: invalid token &gt;&gt;&gt; 0o11 9 &gt;&gt;&gt; 0o9 File "<stdin&gt;" line 1 0o9 ^ SyntaxError: invalid token &gt;&gt;&gt; ````
CSV with spaces around the comma Assume I have a CSV file with spaces around the comma: ````'1' '2' '3' '4' '5' '6' '7' '8' ```` If I use the Python CSV package the `4` and `8` values are treated differently: ````&gt;&gt;&gt; with open('/tmp/nums csv' 'rU') as fin: for row in csv reader(fin quotechar="'"): print row ['1' '2' '3' " '4'"] ['5' '6' '7' " '8'"] ```` Is there a way to fix this using the CSV module? I know that I can read and parse the file myself but I am interested if there is a dialect setting in the CSV package to fix this
Set <a href="http://docs python org/2/library/csv html#csv Dialect skipinitialspace" rel="nofollow">`skipinitialspace` to `True`</a> to skip any whitespace following a delimiter: <blockquote> When `True` whitespace immediately following the <them>delimiter</them> is ignored The default is `False` </blockquote> Demo: ````&gt;&gt;&gt; import csv &gt;&gt;&gt; demo='''\ '1' '2' '3' '4' '5' '6' '7' '8' ''' &gt;&gt;&gt; for row in csv reader(demo splitlines(True) skipinitialspace=True quotechar="'"): print row ['1' '2' '3' '4'] ['5' '6' '7' '8'] ````
Adding data to related table with SQLAlchemy I have this to SQLAlchemy(using the Flask SqlAlchemy) objects defined: ````class User(db Model): id = db Column(db Integer primary_key=True) username = db Column(db String(20) unique=True) password = db Column(db String(30)) email = db Column(db String(45) unique=True) friends = db relationship('Friend' backref='user' lazy='dynamic') def __init__(self username password email): self username = username self password = password self email = email def __repr__(self): return "<User('%s' '%s' '%s')&gt;" % (self username self email self id) class Friend(db Model): id = db Column(db Integer primary_key=True) userId = db Column(db Integer db ForeignKey('user id')) friendId = db Column(db Integer) created = db Column(db DateTime) def __init__(self userId friendId): self userId = userId self friendId = friendId self created = datetime datetime now() def __repr__(self): return "<Friend(%i %i)&gt;" % (self userId self friendId) ```` As I understand to add a friend I should be able to do something like this: First getting the user: ````MyUser = bpdata User query filter_by(id=1) first() ```` Getting the friend: ````MyFriend = bpdata User query filter_by(id=2) first() ```` Now I would like to do: ````MyUser Friends Append(MyFriend) ```` Is this possible or do I just have to add the friend IDs directly into the table Friend?
Figured this one out my self What I needed to do was: ````MyUser friends append(Friend(MyUser id MyFriend id)) ```` and then commit the update <strong>Update:</strong> Ok I found the proper way of doing what I wanted First I do not need the Friend table/class at all Full code: ````association_table = db Table('association' db Column('user_id' db Integer db ForeignKey('user id')) db Column('friend_id' db Integer db ForeignKey('user id')) ) class User(db Model): id = db Column(db Integer primary_key=True) username = db Column(db String(20) unique=True) password = db Column(db String(30)) email = db Column(db String(45) unique=True) friends = db relationship("User" secondary=association_table backref='added_by' primaryjoin=id == association_table c user_id secondaryjoin=id == association_table c friend_id) ```` With this I can now do following: ````&gt;&gt;&gt; user1 = User query filter_by(id=1) first() &gt;&gt;&gt; user1 friends [] &gt;&gt;&gt; user2 = User query filter_by(id=2) first() &gt;&gt;&gt; user1 friends append(user2) &gt;&gt;&gt; user1 friends [<User('user1' 'user1@admin com' '2')&gt;] &gt;&gt;&gt; user1 friends[0] added_by [<User('admin' 'admin@admin com' '1')&gt;] ````
In what year did France start transmissions using and 819 line system?
1949
How to convert bar graphs into data? I have several thousand bar graphs to convert that follow the following format: <img src="http://i stack imgur com/OfkOl png" alt="Example Bar Graph"> I need to convert these to actual data date My plan has been to use something perhaps ImageMagick to extract the date pass it through OCR and then slice up the bars in some fashion so as to get the value The Y axis is in 4 hour increments (so each tick or graph represents 4 hours of a day) These red bars below do change colors at certain thresholds so it is more of a white vs nonwhite for detection of the bars Example output desired: ````1996-11-27 000000 UTC 3 0 1996-11-27 040000 UTC 3 0 1996-11-27 080000 UTC 2 0 1996-11-27 0120000 UTC 2 0 1996-11-27 0160000 UTC 1 0 ```` What might a solution for extracting these bars and assigning values based on height?
Some how evaluate the height of the pixels A script to do so? That is where you have to get creative
In brewing, what do starches become during the mashing process?
sugars
Python sequence translation I have a list of tuples like `[(0 34) (1 77) (2 6) (3 60) (6 2) (7 5) (9 13) (14 2)]` I need to keep the tuples order and reenumerate second elements with integers from 0 to n - 1 where n is the list length The result should be `[(0 4) (1 6) (2 2) (3 5) (6 0) (7 1) (9 3) (14 0)]` I began writing a function that accepts integer sequences but not integer pairs: ````def translation(seq): return [sorted(set(seq)) index(x) for x in seq] &gt;&gt;&gt; translate([34 77 6 60 2 5 13 2]) [4 6 2 5 0 1 3 0] ```` `
Maybe this: ````xs = [(0 34) (1 77) (2 6) (3 60) (4 2) (5 5) (6 13)] secs = sorted(set(x[1] for x in xs)) res = [(x[0] secs index(x[1])) for x in xs] print res # [(0 4) (1 6) (2 2) (3 5) (4 0) (5 1) (6 3)] ```` or one single comprehension (but with quadratic performance): ````res = [(x[0] sum(1 for y in xs if y[1] < x[1])) for x in xs] ````
How can I extract the message? <pre class="lang-html prettyprint-override">`<div style="width: 400px;" id="accordion" class="ui-accordion ui-widget ui-helper-reset" role="tablist"&gt; <h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-accordion-icons ui-accordion-header-active ui-state-active ui-corner-top" role="tab" id="ui-accordion-accordion-header-0" aria-controls="ui-accordion-accordion-panel-0" aria-selected="true" tabindex="0"&gt;<span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-s"&gt;</span&gt; Description</h3&gt; <div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active" style="display: block;" id="ui-accordion-accordion-panel-0" aria-labelledby="ui-accordion-accordion-header-0" role="tabpanel" aria-expanded="true" aria-hidden="false"&gt; this is the message I want to extract </div&gt; </div&gt; ```` How can I extract the message using PyQuery? ````from pyquery import PyQuery as pq d = pq('http://www somesite com') ```` I have tried: - `d('#ui-accordion-accordion-panel-0') text()` - `d('ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active') text()` - `d('#accordion#ui-accordion-accordion-panel-0') text()` If I use `d('#accordion') text()` every text under that `div`is displayed so I do not understand why my first example does not return anything
You can use the css path like this : ````d('#accordion') find(' ui-accordion-content') text() # or : d("#accordion ui-accordion-content") text() # or : d(" ui-accordion-content") text() ```` See example : <div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override">`document write("<br&gt;<br&gt;<br&gt;Content : " $("#accordion ui-accordion-content") text());```` <pre class="snippet-code-html lang-html prettyprint-override">`<script src="https://ajax googleapis com/ajax/libs/jquery/2 1 1/jquery min js"&gt;</script&gt; <div style="width: 400px;" id="accordion" class="ui-accordion ui-widget ui-helper-reset" role="tablist"&gt; <h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-accordion-icons ui-accordion-header-active ui-state-active ui-corner-top" role="tab" id="ui-accordion-accordion-header-0" aria-controls="ui-accordion-accordion-panel-0" aria-selected="true" tabindex="0"&gt;<span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-s"&gt;</span&gt; Description</h3&gt; <div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active" style="display: block;" id="ui-accordion-accordion-panel-0" aria-labelledby="ui-accordion-accordion-header-0" role="tabpanel" aria-expanded="true" aria-hidden="false"&gt; this is the message I want to extract </div&gt; </div&gt;```` </div> </div>
Is there a way to control windows with Python? I am trying to create a script that will upload a file to a website I have no control of the website so the file has to be uploaded via clicking and typing Aka - wait for upload window to pop up - type name/path of file - click "Open" or "upload" (or whatever) button Because the window is part of the OS (not a browser window) I cannot control it with Selenium or something like that (as far as I know Plz let me know if I am wrong) This means I need the script to do this I already have it working for Windows (made it with AutoIt) however I also need it to run on Unix systems (Linux) So I am asking is there a way to do it with Python or something? If I can make one script that will run on both that would be awesome (AutoIt is Windows-only) I have knowledge of Java Python and AutoIt but if none of those can do it I can learn something else Thanks EDIT: Ok so apparently using HTTP POST is the way to do it however I am not sure how to do this I am going to do more research on that Thanks @Chrules for bring this to my attention
Now that you want to do it via an HTTP request the <a href="http://docs python-requests org/en/latest/index html" rel="nofollow">Requests</a> library is highly recommended It is really that simple: ````&gt;&gt;&gt; url = 'http://httpbin org/post' &gt;&gt;&gt; files = {'report xls': open('report xls' 'rb')} &gt;&gt;&gt; are = requests post(url files=files) ````
DJANGO: blank select option missing in form I have the following: MODEL PY ````LIST = (('Manager' 'Manager') ('Non-Manager' 'Non-Manager') ) class Employee(models Model): fname = models CharField(max_length=15 blank=False null=False) manager = models CharField(max_length=15 choices=LIST blank=True null=True) comment = models TextField(blank=True null=True) def __unicode__(self): return self fname class EmployeeForm(forms ModelForm): fname = forms CharField(required=True label='First Name') manager = forms CharField(required=False widget=Select(choices=LIST) label='Their Position?') comment = forms CharField(required=False widget=forms Textarea(attrs={'cols': 50 'rows': 10}) label='Comments') class Meta: model = Employee ```` If I remove manager from the EmployeeForm I get a "------" as an option in the forms drop down menu but if I keep manager in the EmployeeForm (and I need to in order to override the fields label) it removes the "------" How do I allow the EmployeeForm to keep the "------" option?
What about something like: ````manager = forms CharField(required=False widget=Select(choices=(('' '----------') ) LIST) label='Their Position?') ````
GAE NDB "Result cannot be set twice" error I hit this <them>Result cannot be set twice</them> Runtime error on GAE Ndb async queries when doing `ndb Future wait_all(futures)` on a bunch of async queries Something like this: ````futures = [] for item in items: item _future_get = MyEntity query( ) get_async() futures append(item _future_get) ndb Future wait_all(futures) # ```` It fails on the `wait_all` with <them>Result cannot be set twice</them> This error message is nowhere mentionned on SO Google has 2-3 mentions of it dating back to 2011 and with no clear explanation More info: items are ndb entities from a previous fetch But they do not really matter here (at least I think) since the query is performed on MyEntity I am used to attaching futures to the object they relate to in this way so it is easier to sort out when all have completed The stack trace: ```` File "/home/my_project/app/main/admin/my_module py" line 166 in admin_base_cleanup_details ndb Future wait_all(futures) File "/usr/lib/python2 7/google_appengine/google/appengine/ext/ndb/tasklets py" line 350 in wait_all ev run1() File "/usr/lib/python2 7/google_appengine/google/appengine/ext/ndb/eventloop py" line 235 in run1 delay = self run0() File "/usr/lib/python2 7/google_appengine/google/appengine/ext/ndb/eventloop py" line 197 in run0 callback(*args **kwds) INFO 2016-04-26 08:40:04 152 module py:808] default: "GET /admin/cleanup/details?mode=status HTTP/1 1" 500 - File "/usr/lib/python2 7/google_appengine/google/appengine/ext/ndb/tasklets py" line 475 in _on_future_completion self _help_tasklet_along(ns ds_conn gen val) File "/usr/lib/python2 7/google_appengine/google/appengine/ext/ndb/tasklets py" line 386 in _help_tasklet_along self set_result(result) File "/usr/lib/python2 7/google_appengine/google/appengine/ext/ndb/tasklets py" line 265 in set_result raise RuntimeError('Result cannot be set twice ') RuntimeError: Result cannot be set twice ```` Some more precisions: - Yes it does happen on GAE as well as on local dev - No it does not fail every single time but often enough I found it has to do with concurrency from another thread The web page started 2 requests through ajax calls: one for an update query with some async calls that would take quite a few seconds and another one like a periodic status update quicker but also with async calls It is the latter that failed not always but very often Since then I avoided overlapping the two requests and it stopped failing It still seems like a bug since overlapping requests is not something forbidden
You are using get_async() which "Asynchronously returns the first query result" whereas you should probably use fetch_async() to get a Future <a href="https://cloud google com/appengine/docs/python/ndb/queryclass#Query_get_async" rel="nofollow">https://cloud google com/appengine/docs/python/ndb/queryclass#Query_get_async</a>
When did Daft Punk begin producing a new sound?
end of the 1990s and into the 2000s
Python Form Processing Problem I am a newbie I wanted to know how to handle array based fields in CGI? ````<form name="frmLogin" method="get" action=""&gt; Username: <input type="text" name="login[username]" /&gt;<br/&gt; Password: <input type="password" name="login[password]" /&gt;<br/&gt; <input type="submit" name="login[submit]" /&gt; </form&gt; ```` I have a form like above How can I get the login field as a dictionary where keys will be username password submit with their corresponding values i can get individually by this => form["login[username]"] value but what if I do not know the key i e checkbox[] Do I need to process the posts and manipulate by manual coding or there is any other way to do it? in php $_GET['login'] will give me the array of defined key value pair I need something like that Thanks
I do not think the `cgi FieldStorage` has a similar method as the one you describe in php However you could write something like this to accomplish the same thing given the <them>name[attr]</them> format you have on your field names: ````def get(form prefix): output = {} def parse(key): name = key split('[')[1] rstrip(']') output[name] = form[key] map(parse [key for key in form keys() if key startswith(prefix)] return output ```` So your in cgi it would look something like: ````form = cgi FieldStorage() login_info = get(form 'login') print login_info['username'] print login_info['password'] ````
Can i distribute traffic between 2 servers I have a server with a web front-end (WebServer) This WebServer makes a call to a service on another server (Server2) Due to heavy load I have added another instance of Server2 (Server3) I want to distribute the load between Server 2 and Server 3 I know load balancers usually do this type of thing - but its not suitable in this scenario I want to add some logic on the webserver to distribute the load - something very simple Is there any python libraries out there that will do this? I am not really sure what I am looking for or what to Google
I went with a custom round-robin type of thing in python - which was pretty easy ````SERVER1 = "http://172 18 128 24/Z/" SERVER2 = "http://172 18 128 24/Z/" import random server = random sample((CLEANSER1 CLEANSER2) 1)[0] ````
Spyder does not run Python scripts after matplotlib upgrade I was coding in Python 2 7 with <strong>Spyder 2 1 9</strong> using <strong>matplotlib 1 1</strong> The operating system is Linux Ubuntu 12 04 LTS I requested the upgrade of matplotlib with `sudo pip --upgrade python-matplotlib` The upgrade went well: the end message is `successfully installed matplotlib numpy foos bars` Now if I open an interpreter in the terminal and type ```` import matplotlib print(matplotlib __version__) ```` the answer is <strong>1 5 1</strong> This version of matplotlib is installed in `/usr/local/lib/python2 7/dist-packages/matplotlib/__init__ pyc` if this piece of information can be useful However when I come back to the Spyder IDE and I try to run any of the scripts that were dwelling there (key F5) nothing happens any longer No interpreter window gets active within Spyder Ditto if I create a brand new 'hallo world' script The internal console in Spyder does work it is just the <them>scripts</them> that are not executed whether new or old This is a snapshot of Spyder internal console in the new setting: <a href="http://i stack imgur com/17XR8 png" rel="nofollow"><img src="http://i stack imgur com/17XR8 png" alt="Spyder internal console sees the new version of matplotlib"></a> What is the possible because of this? How do I get Spyder working again as usual?
There were many <a href="https://github com/spyder-ide/spyder/issues/2793" rel="nofollow">bugs</a> when using matplotlib 1 5 on Spyder versions up to 2 3 7 I guess you should downgrade matplotlib
Iterating over two lists at the same time in Python Suppose I have the following: ````cell_list = ['B1' 'B2' 'B3'] cell_data = ['1' '2' '3'] ```` How can I build a single loop (presumably a `for` loop) with the following result in Python? ````B1: 1 B2: 2 B3: 3 ````
The easiest way would be to `zip` the lists and apply the `dict` to the result: ````result = dict (zip (cell_list cell_data)) ```` Having said that if you absolutely have to use a `for` loop like the question tags suggest you could loop over the lists and treat one as potential keys and the other as potential values: ````result = {} for i in range(len(cell_list)): result[cell_list[i]] = cell_data[i] ````
Jsch - Sending command over SSH connection I want to send a simple command with a java application over my windows computer to activate a python script on my raspberry pi which should control the GPIO ports of my raspberry Pi I do not get really into Jsch my SSH connection already works but not sending commands Here is my actual code: ````package sshtest; import java io ByteArrayInputStream; import java io InputStream; import com jcraft jsch *; import java io InputStream; public class SSHTest { public static void main(String[] args) { String host="DELETED"; String user="pi"; String password="DELETED"; String command =("cd Desktop"); String command2 =("sudo python IO2 py all high"); try{ java util Properties config = new java util Properties(); config put("StrictHostKeyChecking" "no"); JSch jsch = new JSch(); Session session=jsch getSession(user host 22); session setPassword(password); session setConfig(config); session connect(); System out println("Connected"); Channel channel = session openChannel("exec"); InputStream is = new ByteArrayInputStream(command getBytes()); channel setInputStream(is); InputStream iss = new ByteArrayInputStream(command2 getBytes()); channel setInputStream(iss); session disconnect(); }catch(Exception e){ e printStackTrace(); } } } ````
You should use `ChannelExec setCommand(java lang String)` to start it and wait while `Channel isClosed()` returns `false` BY THE WAY JSch has an example for this: <a href="http://www jcraft com/jsch/examples/Exec java html" rel="nofollow">http://www jcraft com/jsch/examples/Exec java html</a>
Who assist the chapter of Westminster?
the Receiver General and Chapter Clerk
Error: can only concatenate list (not "int") to list I am getting this error when I try to populate users First_Name in a csv file Can someone show me what I am doing wrong ```` import csv # Define users valid_input = False while not valid_input: users =raw_input('Number of users: ') try: users = range(0 int(users)) valid_input = True except: print "Invalid input" pass First_Name = ["Test"+str(user) for user in range (1 users+1)] Last_Name = ["User%s" %user for user in users] Email_Addresses = [] for user in users: email= raw_input("Email domain for user %d: " %user) Email_Addresses append(Last_Name[user] email) Password = ["Password1" for user in users] Group =["Test" for user in users] Admin = ["Yes" for user in users] # open a file for writing # open a file for writing with open('users csv' 'wb') as csv_out: writer = csv writer(csv_out) writer writerows(zip(Email_Addresses Password First_Name Last_Name Group Admin)) ```` This is the Traceback I am getting Traceback (most recent call last): First_Name = ["Test"+str(user) for user in range (1 users+1)] TypeError: can only concatenate list (not "int") to list
`users` is a list: ````users = range(0 int(users)) ```` but you then try to create a <them>new</them> range from that list: ````First_Name = ["Test"+str(user) for user in range (1 users+1)] ```` where `users 1` is an attempt to add `1` to a list Do not do that Just loop over your existing range: ````First_Name = ["Test"+str(user 1) for user in users] ````
Pandas: transforming the DataFrameGroupBy object to desired format I have a data frame as follows: ````import pandas as pd import numpy as np df = pd DataFrame({'id' : range(1 9) 'code' : ['one' 'one' 'two' 'three' 'two' 'three' 'one' 'two'] 'colour': ['black' 'white' 'white' 'white' 'black' 'black' 'white' 'white'] 'amount' : np random randn(8)} columns= ['id' 'code' 'colour' 'amount']) ```` <strong>I want to be able to group the `id`s by `code` and `colour` and then sort them with respect to `amount` </strong> I know how to `groupby()`: ````df groupby(['code' 'colour']) head(5) id code colour amount code colour one black 0 1 one black -0 117307 white 1 2 one white 1 653216 6 7 one white 0 817205 three black 5 6 three black 0 567162 white 3 4 three white 0 579074 two black 4 5 two black -1 683988 white 2 3 two white -0 457722 7 8 two white -1 277020 ```` However my desired output is as below where I have two columns: 1 `code/colour`contains the key strings and 2 `id:amount` contains `id` - `amount` tuples sorted in descending order wrt `amount`: ````code/colour id:amount one/black {1:-0 117307} one/white {2:1 653216 7:0 817205} three/black {6:0 567162} three/white {4:0 579074} two/black {5:-1 683988} two/white {3:-0 457722 8:-1 277020} ```` How can I transform the `DataFrameGroupBy` object displayed above to my desired format? Or shall I not use `groupby()` in the first place? <strong>EDIT:</strong> Although not in the specified format the code below kind of gives me the functionality I want: ````groups = dict(list(df groupby(['code' 'colour']))) groups['one' 'white'] id code colour amount 1 2 one white 1 331766 6 7 one white 0 808739 ```` How can I reduce the groups to only include the `id` and `amount` column?
Here is an "ugly" way of doing this First things first- your desired output will not play so well within Pandas since `dict` is unhashable; so you may lose the real benefit! ````od = OrderedDict() for name group in df groupby(['code' 'colour']): # Convert the group to a dict temp = group[['id' 'amount']] sort(['amount'] ascending=[0]) to_dict() # Extract id:amount temp2 = {temp['id'][key]: temp['amount'][key] for key in temp['amount'] iterkeys()} od["%s/%s" % (name)] = temp2 ```` This is only a start! Not exactly what you are looking for
Global text caret position in Linux I need to find global caret position in Linux The problem is similar to <a href="http://www codeproject com/Articles/34520/Getting-Caret-Position-Inside-Any-Application/" rel="nofollow" title="Getting Caret Position Inside Any Application">this one for Windows</a> Do you guys have any idea? More information: I am trying to make input method for a certain Indic language I am using IBus libraries in Python I need to create something like the lookup table found in IBus but my requirements are such that I decided its better if I make the whole thing again using tk (or something) The link in the question solves this problem for windows where a tooltip follows the text caret So I need something just like that but for X-Windows
There is no such thing as a caret position in X11 While the older UIM framework did a fairly good job of displaying the input method UI near the cursor position this failed often enough that it was abandoned You might want to take a look at the <a href="http://www scim-i am org/" rel="nofollow">SCIM</a> framework Note that it is usually preferred to hint the application at the completion state rather than provide a separate editor as this gives a more seamless integration
pip install /tmp/pip-c436mD-unpack/master the member espeed-bulbs-71d0cce/docs/social is invalid: I am trying to instally bulbs on my Ubuntu 12 04 I have installed the following packages ````sudo apt-get install python2 7-dev sudo apt-get install libyaml-dev ```` I have installed ```` sudo pip install https://github com/espeed/bulbs/tarball/master ```` The output is as follows ````Downloading/unpacking https://github com/espeed/bulbs/tarball/master Downloading master (unknown size): 177Kb downloaded Cannot determine compression type for file /tmp/pip-c436mD-unpack/master In the tar file /tmp/pip-c436mD-unpack/master the member espeed-bulbs-71d0cce/docs/social is invalid: "linkname 'espeed-bulbs-71d0cce/docs//home/james/projects/bulbflow com/www/root/templates/social html' not found" Running setup py egg_info for package from https://github com/espeed/bulbs/tarball/master warning: no previously-included files matching '*~' found under directory ' ' warning: no previously-included files matching '* pyc' found under directory ' ' no previously-included directories found matching '*/*/old' no previously-included directories found matching '*/old' Requirement already satisfied (use --upgrade to upgrade): distribute in /usr/lib/python2 7/dist-packages (from bulbs==0 3 29-20140426) Requirement already satisfied (use --upgrade to upgrade): httplib2&gt;=0 7 2 in /usr/lib/python2 7/dist-packages (from bulbs==0 3 29-20140426) Requirement already satisfied (use --upgrade to upgrade): pyyaml&gt;=3 10 in /usr/local/lib/python2 7/dist-packages/PyYAML-3 11-py2 7-linux-x86_64 egg (from bulbs==0 3 29-20140426) Requirement already satisfied (use --upgrade to upgrade): six in /usr/local/lib/python2 7/dist-packages (from bulbs==0 3 29-20140426) Requirement already satisfied (use --upgrade to upgrade): omnijson in /usr/local/lib/python2 7/dist-packages/omnijson-0 1 2-py2 7 egg (from bulbs==0 3 29-20140426) Requirement already satisfied (use --upgrade to upgrade): python-dateutil==1 5 in /usr/lib/python2 7/dist-packages (from bulbs==0 3 29-20140426) Cleaning up ```` Is the line ````In the tar file /tmp/pip-c436mD-unpack/master the member espeed-bulbs-71d0cce/docs/social is invalid: "linkname 'espeed-bulbs-71d0cce/docs//home/james/projects/bulbflow com/www/root/templates/social html' not found" ```` displayed above an error ? And does it mean that the install of bulbs has not succeeded?
Do not worry about that message -- that is not an error -- from the output above it looks like Bulbs is installed Start up Rexster and and then try it out ````&gt;&gt;&gt; from bulbs rexster import Graph &gt;&gt;&gt; g = Graph() &gt;&gt;&gt; james = g vertices create(name="James") &gt;&gt;&gt; julie = g vertices create(name="Julie") &gt;&gt;&gt; g edges create(james "knows" julie) ````
Adding nonzero items from a dictionary to another dictionary I have a set of reactions (keys) with values (0 0 or 100) stored in mydict Now I want to place non zero values in a new dictionary (nonzerodict) ````def nonzero(cmod): mydict = cmod getReactionValues() nonzerodict = {} for key in mydict: if mydict values() != float(0): nonzerodict[nz] = mydict values print nz ```` Unfortunately this is not working My questions: - Am I iterating over a dictionary correctly? - Am I adding items to the new dictionary correctly?
You are testing if the <them>list of values</them> is not equal to `float(0)` Test <them>each value</them> instead using the key to retrieve it: ````if mydict[key] != 0: nonzerodict[key] = mydict[key] ```` You are iterating over the keys correctly but you could also iterate over the key-value pairs: ````for key value in mydict iteritems(): if value != 0: nonzerodict[key] = value ```` Note that with floating point values chances are you will have <them>very small</them> values close to zero that you may want to filter out too If so test if the value is <them>close</them> to zero instead: ````if abs(value) &gt; 1e-9: ```` You can do the whole thing in a single dictionary expression: ````def nonzero(cmod): return {k: v for k v in cmod getReactionValues() iteritems() if abs(v) &gt; 1e-9} ````
How to stop loop partially? So i am writing a basic programme to turn an LED on using a potentiometer this is my code: ````def pot(): import RPi GPIO as GPIO import time GPIO setwarnings(False) GPIO setmode(GPIO BCM) GPIO setup(4 GPIO OUT) GPIO setup(22 GPIO IN) GPIO output(4 GPIO LOW) try: while True: if (GPIO input(22) == GPIO HIGH): print("switch activated") GPIO output(4 GPIO HIGH) if (GPIO input(22) == GPIO LOW): GPIO output(4 GPIO LOW) else: GPIO output(4 GPIO LOW) except KeyboardInterrupt: GPIO cleanup() pot() ```` When i activate the potentiometer i only want "switch activated" to be printed once but i want the LED to keep running until i deactivate the potentiometer As the code is "switch activated" will obviously print constantly while the pot is activated I have tried using a break and other such things but they all either ended the programme or turned off the LED as well How can i solve this?
You need to move `print("switch activated")` outside the loop if you only want it to be executed once
Python reading tags in string json? I am using a telnet api for logitech media server for functions not included in pylms python library I am stuck handling the response of a request Below is an example of a response as a single string ````players 0 2 count:2 playerindex:0 playerid:a5:41:d2:cd:cd:05 ip:127 0 0 1:60488 name:127 0 0 1 model:softsqueeze displaytype:graphic-280x16 connected:1 playerindex:1 playerid:00:04:20:02:00:c8 ip:192 168 1 22:3483 name:Movy model:slimp3 displaytype:noritake-katakana connected:1 ```` I want to extract name and ip tags for the above example Looking on Internet is this json formating? I Have tried reading with json load and json dump python module but no luck The closes i have got is using `split(" ")` and then `split(":")` but this falls over when a tag is made up of two words ie contains a space To sum it up how do I get a list of "name: " tags?
Try a <a href="http://docs python org/2/library/re html" rel="nofollow">regular expression</a> to extract the info I have not tried it in Python but I think <a href="https://www debuggex com/r/uuahp1ZnRio2jDS1" rel="nofollow">this</a> should work It might help if you tell us what the expected result is ````import re regex = re compile("ip:([^\\ ]{0 })\\ name:([^\\ ]{0 })") testString = "" # fill this in matchArray = regex findall(testString) # the matchArray variable contains the list of matches ```` (from debuggex com snippet)