input_text
stringlengths 1
40.1k
| target_text
stringlengths 1
29.4k
⌀ |
---|---|
Avoid twitter api limitation with Tweepy I saw in some thread in stack exchange that the limitation can be in function of the number of requests per 15 minutes and depends also on the complexity of the alghorithm except that this is not a complex one So I use this code : ````import tweepy import sqlite3 import time db = sqlite3 connect('data/MyDB db') # Get a cursor object cursor = db cursor() cursor execute('''CREATE TABLE IF NOT EXISTS MyTable(id INTEGER PRIMARY KEY name TEXT geo TEXT image TEXT source TEXT timestamp TEXT text TEXT rt INTEGER)''') db commit() consumer_key = "" consumer_secret = "" key = "" secret = "" auth = tweepy OAuthHandler(consumer_key consumer_secret) auth set_access_token(key secret) api = tweepy API(auth) search = "#MyHashtag" for tweet in tweepy Cursor(api search q=search include_entities=True) items(): while True: try: cursor execute('''INSERT INTO MyTable(name geo image source timestamp text rt) VALUES(? ? ? ? ? ? ?)''' (tweet user screen_name str(tweet geo) tweet user profile_image_url tweet source tweet created_at tweet text tweet retweet_count)) except tweepy TweepError: time sleep(60 * 15) continue break db commit() db close() ```` I am always having the twitter limitation error : ````Traceback (most recent call last): File "stream py" line 25 in <module> include_entities=True) items(): File "/usr/local/lib/python2 7/dist-packages/tweepy/cursor py" line 153 in next self current_page = self page_iterator next() File "/usr/local/lib/python2 7/dist-packages/tweepy/cursor py" line 98 in next data = self method(max_id = max_id *self args **self kargs) File "/usr/local/lib/python2 7/dist-packages/tweepy/binder py" line 200 in _call return method execute() File "/usr/local/lib/python2 7/dist-packages/tweepy/binder py" line 176 in execute raise TweepError(error_msg resp) tweepy error TweepError: [{'message': 'Rate limit exceeded' 'code': 88}] ```` | The problem is that your `try: except:` block is in the wrong place Inserting data into the database will never raise a `TweepError` - it is iterating over `Cursor items()` that will I would suggest refactoring your code to call the `next` method of `Cursor items()` in an infinite loop That call should be placed in the `try: except:` block as it can raise an error Here is (roughly) what the code should look like: ````# above omitted for brevity c = tweepy Cursor(api search q=search include_entities=True) items() while True: try: tweet = c next() # Insert into db except tweepy TweepError: time sleep(60 * 15) continue except StopIteration: break ```` This works because when Tweepy raises a `TweepError` it has not updated any of the cursor data The next time it makes the request it will use the same parameters as the request which triggered the rate limit effectively repeating it until it goes though |
Access data via BigQuery in python I am trying to access data in python using bigquery api here is my code I have placed the pem file inside the same folder but script returns an error <strong>"googleapiclient errors HttpError: https://www googleapis com/bigquery/v2/projects/digin-1086/queries?alt=json returned "Not found: Table digin-1086:dataset my_table"></strong> ```` from bigquery import get_client # BigQuery project id as listed in the Google Developers Console project_id = 'digin-1086' # Service account email address as listed in the Google Developers Console service_account = '77441948210-4fhu1kc1driicjecriqupndkr60npnh@developer gserviceaccount com' # PKCS12 or PEM key provided by Google key = 'Digin-d6387c00c5a' client = get_client(project_id service_account=service_account private_key_file=key readonly=True) # Submit an async query job_id _results = client query('SELECT * FROM dataset my_table LIMIT 1000') # Check if the query has finished running complete row_count = client check_job(job_id) # Retrieve the results results = client get_query_rows(job_id) ```` | The error says it cannot find your table nothing to do with the pem file You need to make the table exits in the dataset |
Apache looks for Python 2 6 instead of 2 7 My OS already has Python 2 6 6 and I have installed Python 2 7 3 as an alternative (Python's working fine) I have installed `mod_python` also but when I try to execute a Python file on an Apache server it shows me a list of errors where I can see it seeks to Python 2 6 6 library But I need to work with python 2 7 3 Can anyone help me to get rid of it? Actually I do not know if Apache is configured well or not! I am on CentOS 6 2 | Have a look at <a href="http://code google com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPythonHome" rel="nofollow">this</a> However note this part: <blockquote> If you want to use a different version of major/minor version of Python than currently used you must recompile mod_wsgi against the alternate version of Python </blockquote> I am not quite sure that if you simply swap the `WSGIPythonHome` variable it will work If you have installed `mod_wsgi` with `yum` you will probably have a `mod_wsgi` for `Python 2 6 x` which is distributed with `CentOS 6 x` If you really want to use `Python 2 7 x` you may have to build `mod_wsgi` from source (which is actually not that hard) |
On Magnus's ten point scale what would a homosexual person be considered? | a homosexual individual may be A5, B0 |
Tuple comparison in Python According to <a href="https://docs python org/2/reference/expressions html#notin" rel="nofollow">this</a> : <blockquote> Tuples and lists are compared lexicographically using comparison of corresponding elements This means that to compare equal each element must compare equal and the two sequences must be of the same type and have the same length If not equal the sequences are ordered the same as their first differing elements For example cmp([1 2 x] [1 2 y]) returns the same as cmp(x y) If the corresponding element does not exist the shorter sequence is ordered first (for example [1 2] < [1 2 3]) </blockquote> If I understand correctly ````(a b c) < (d e f) ```` gives True if ````a < d and b < e and c < f ```` why ````(1 2 3) < (2 0 4) ```` gives True? how can I do such a comparison? | Your understanding is flawed It is not `and` - it is a cascading comparison ````a < d or (a == d and b < e) or (a == d and b == e and c < f) ```` Another way of understanding this for arbitrary length tuples ````def tuple_less_than(tuple1 tuple2): for item1 item2 in zip(tuple1 tuple2): if item1 != item2: return item1 < item2 return len(tuple1) < len(tuple2) ```` |
ElementTree does not write data in UTF-8 I am pulling in data from a database and attempting to create an XML file from this data The data is in UTF-8 and can contain characters such as `á` `Å¡` or `Ä` This is the code: ````import xml etree cElementTree as ET tree = ET parse(metadata_file) # some commands that alter the XML tree write(metadata_file encoding="UTF-8") ```` When writing the data the script fails with: ````Traceback (most recent call last): File "get-data py" line 306 in <module> main() File "get-data py" line 303 in main tree write(metadata_file encoding="UTF-8") File "/usr/lib64/python2 7/xml/etree/ElementTree py" line 820 in write serialize(write self _root encoding qnames namespaces) File "/usr/lib64/python2 7/xml/etree/ElementTree py" line 939 in _serialize_xml _serialize_xml(write e encoding qnames None) File "/usr/lib64/python2 7/xml/etree/ElementTree py" line 939 in _serialize_xml _serialize_xml(write e encoding qnames None) File "/usr/lib64/python2 7/xml/etree/ElementTree py" line 937 in _serialize_xml write(_escape_cdata(text encoding)) File "/usr/lib64/python2 7/xml/etree/ElementTree py" line 1073 in _escape_cdata return text encode(encoding "xmlcharrefreplace") UnicodeDecodeError: 'ascii' codec cannot decode byte 0xc3 in position 32: ordinal not in range(128) ```` The only way to prevent this is to decode the data written to the XML file with: ````text = text decode('utf-8') ```` but then the resulting file will contain e g `&#269;` rather than a `Ä` Any idea how I can write the data to the file and keep it in UTF-8? <strong>Edit:</strong> This is the example of what the script does: ````]$ echo "<data></data>" > test xml ]$ cat test xml <data></data> ]$ python Python 2 7 5 (default Nov 3 2014 14:33:39) [GCC 4 8 3 20140911 (Red Hat 4 8 3-7)] on linux2 Type "help" "copyright" "credits" or "license" for more information >>> import xml etree cElementTree as ET >>> tree = ET parse(' /test xml') >>> root = tree getroot() >>> new = ET Element("elem") >>> new text = "á Å¡ or Ä" >>> root append(new) >>> tree write(' /text xml' encoding="UTF-8") Traceback (most recent call last): File "<stdin>" line 1 in <module> File "/usr/lib64/python2 7/xml/etree/ElementTree py" line 820 in write serialize(write self _root encoding qnames namespaces) File "/usr/lib64/python2 7/xml/etree/ElementTree py" line 939 in _serialize_xml _serialize_xml(write e encoding qnames None) File "/usr/lib64/python2 7/xml/etree/ElementTree py" line 937 in _serialize_xml write(_escape_cdata(text encoding)) File "/usr/lib64/python2 7/xml/etree/ElementTree py" line 1073 in _escape_cdata return text encode(encoding "xmlcharrefreplace") UnicodeDecodeError: 'ascii' codec cannot decode byte 0xc3 in position 0: ordinal not in range(128) ```` | The question does not make clear what kind of object `metadata_file` is If an ordinary file object is used there are no errors and the output is as expected: ````>>> import xml etree cElementTree as ET >>> stream = open('test xml' 'wb+') >>> stream write(you"""\ <root>characters such as á Å¡ or Ä </root> """ encode('utf-8')) >>> stream seek(0) >>> tree = ET parse(stream) >>> stream close() >>> ET tostring(tree getroot()) '<root>characters such as &#225; &#353; or &#269; </root>' >>> stream = open('test xml' 'w') >>> tree write(stream encoding='utf-8' xml_declaration=True) >>> stream close() >>> open('test xml') read() "<?xml version='1 0' encoding='utf-8'?>\n<root>characters such as \xc3\xa1 \xc5\xa1 or \xc4\x8d </root>" ```` |
When did the Cubs sign a developmental agreement with the Kane County Cougars? | 2012 |
Find files with multiline strings matched I have a folder with many files of such blocks of pattern: ````115 55 175:500 123:400 [blahblah] [blahblah] [blahblah] 200 * [blahblah] [blahblah] [blahblah] ```` Each block starts at a line starting with a number and ends before the next line starting with a number I need to find files containing "115 55" and " 123:400" in the same block There could be any number of lines between the two like: ````115 55 [blahblah] [blahblah] 123:400 ```` Summary: Find the names of files with "115 55" and next having " 123:400" before hitting a line starting with a number Note:This is a UDR (Usage Data Record) file if it may help Python Perl sed or awk would help Thanks in advance! | ````perl -lne '/^115 55/ /^\d/ and /^ 123:400/ or next;print $ARGV;close ARGV' *udr ```` |
What fuel is used for the torch? | propane. |
convert pgsql int array into python array I have numeric data (int) stored in pgsql as arrays These are `x y w h` for rectangles in an image e g `{(248 579) (1 85)}` When reading to my python code (using psycopg) I get it as a string (?) I am now trying to find the best way to obtain a python array of ints from that string Is there a better way than to split the string on ' ' and so on p s I did try ` astype(int)` construct but that would not work in this instance | Assuming that you would not be able to change the input format you could remove any unneeded characters then split on the ` `'s or do the opposite order ````data = '{(248 579) (1 85)}' data translate(None '{}()') split(' ') ```` will get you a list of strings And ````[int(x) for x in data translate(None '{}()') split(' ')] ```` will translate them to integers as well |
What internet standards were also unlear as of December, 2012? | content standards online |
Why is My Django Form Executed Twice? Can someone explain to me why form 2 executed twice? In another word I would see 2 print statements "Hello from form 2 " in the console The first print statement occurred after I clicked "Submit" from form 1 Second print statement comes after the second "Submit" I clicked from form 2 How do I make it to only print once? <strong>views py</strong> ````def form1 (request): NameFormSet = formset_factory (NameForm formset = BaseNodeFormSet extra = 2 max_num = 5) if request method == 'POST': name_formset = NameFormSet (request POST prefix = 'nameform') if name_formset is_valid (): data = name_formset cleaned_data request session ['data'] = data return HttpResponseRedirect ('form2') else: name_formset = NameFormSet (prefix = 'nameform') context = {'name_formset': name_formset} return render (request 'nameform/form1 html' context) def form2 (request): data = request session ['data'] print ('Hello from form 2') # <==== This statement printed twice in the console CheckBoxFormSet = formset_factory (CheckBox extra = 2 max_num = 5) if request method == 'POST': checkbox_formset = CheckBoxFormSet (request POST prefix = 'checkbox') if checkbox_formset is_valid (): for i form in enumerate (checkbox_formset cleaned_data): data [i] update (form) # Join cleaned data with original data del request session ['data'] context = {'data': data} return render (request 'nameform/success html' context) checkbox_formset = CheckBoxFormSet (prefix = 'checkbox') context = {'checkbox_formset': checkbox_formset 'data': data} return render (request 'nameform/form2' context) ```` <strong>Update 1:</strong> The "print" statement is actually a backend method that processes the data obtained from form 1 and display it in form 2 Leaving where it is now would cause that method to process the information twice I have no issue or error doing it this way but it is unnecessary For example: ````def form2 (request): data = request session ['data'] n errors = getInfo (data) # <==== This statement performed twice in the console if request method = 'POST': if checkbox_formset is_valid (): for i form in enumerate (checkbox_formset cleaned_data): data [i] update (form) # Join cleaned data with original data n process_new_data (data errors) del request session ['data'] context = {'data': data 'errors': error} return render (request 'nameform/success html' context) else: checkbox_formset = CheckBoxFormset (prefix = 'checkbox') context = {'data': data 'errors': error} return render (request 'nameform/form2 html' context) ```` <strong>Update 2</strong>: Since my explanation is a little long allow me address Ale question here Yes I fully understand why it processed twice To briefly answer your question putting getInfo inside 'POST' will give me a context unbound error because of the context "errors" dictionary does not exist in the first redirect ````context = {'data': data 'errors': errors} ```` I would to update my post so that I can explain why I cannot use your method GetInfo takes the data from form1 processes it and passes it on to form 2 to display I could do all that in form1 but then I would have to redo it in form2 because form2 will not know what 'n' or 'errors' is without passing it through sessions I am just trying to see if there is a better way to do this | The form2 view is run twice once as a redirect from form1 which creates the form and renders the template missing the `if request method == 'POST'` part as this time around the request is a 'GET' When you submit form2 back to the same view method it prints the line you indicate again this time the code in the if block executes as the request is a 'POST' The key is this line that redirects to the form2 view: ````return HttpResponseRedirect ('form2') ```` |
The superior colliculus is related to what sensual control of vertebrates? | visual |
How can I make the background of an image appear transparent without PIL? I am trying to make a GUI in tkinter that uses one image as an overlay on top of another but when I place the image over the lower one the transparent area of the image appears as grey I have searched for solutions to this but all the results that I have found have pointed towards using PIL Is it possible for me to use transparent or partially transparent images in the python tkinter module <strong>without using PIL</strong>? | You could use some basic photoshop tools like the magic wand tool to remove the background but keep in mind some PNG format images have a faint background This is either in the from of a watermark or the image background was rendered with a lower opacity than the rest of the image Your GUI may also have a layer placed above the images by default Does it appear on each image seperatly when loaded into the GUI? |
How do I set a button as the focus using tkinter? I want to open a window with the focus set to the first button so I do not have to tab to it If the widget is an Entry widget I can write ````widget_name focus() ```` There does not appear to be an equivalent for a button widget | To me there seems to be an equivalent ````tkinter Button = class Button(Widget) | Button widget | | Method resolution order: | Button | Widget | BaseWidget | Misc | Pack | Place | Grid | builtins object | focus = focus_set(self) | Direct input focus to this widget | | If the application currently does not have the focus | this widget will get the focus if the application gets | the focus through the window manager ```` and in `tkinter py` ````class Misc: # focus = focus_set # XXX b/w compat? ```` |
Getting the number of seconds since the Epoch from a string in any time zone I need to calculate the number of seconds since the epoch from a well-formed string such as `you'Wed Jun 24 20:19:10 PDT 2015'` The following code does that: ````def seconds_from_epoch(date date_pattern='%a %b %d %H:%M:%S %Z %Y'): epoch = int(time mktime(time strptime(date date_pattern))) return epoch >>> d=you'Wed Jun 24 20:19:10 PDT 2015' >>> s=seconds_from_epoch(d) >>> s 1435202350 ```` The problem is that the strings come from an unpredictable variety of time zones and the solution above only works if the timezone is the same as that of the running Python script itself (or apparently GMT/UTC which does not help) So what I need is something that does exactly the same as the code above but for all time zones | ````def total_seconds(dt): #just in case you are using a python that the datetime library does not provide this automagically print dt days*24*60+dt seconds from dateutil parser import parse as date_parse print total_seconds(date_parse(date_string)) ```` you will need to ` pip install python-dateutil` |
Difficulty having Django find database user I am writing a web app which has a page for admin tasks One of the tasks is that the admin users must be able to edit other users details Alas I have fallen at quite a simple roadblock I have set up a very simple jQuery AJAX Get request successfully transferring a string to the server and back This is just background but not the issue The issue lies in retrieving other user's objects At the moment with a username I know exists this code which is accessed in views py produces a 500 Internal Server Error ````@login_required def user_edit_getuser(request): # Like before get the request's context context = RequestContext(request) inputname = request GET['inputNameSend'] user_obj = User objects get(inputname) return HttpResponse(inputname) #later will return a JSON String ```` | `get` takes keyword arguments only: the key is the field to look up ````user_obj = User objects get(username=inputname) ```` Also you should probably deal with the possibility that the GET request has no `inputNameSend` key For JS development you can usually see the error page in the Chrome dev tools/Firebug console in the Network tab |
Python Pygame: Fire multiple bullets for Space Invader game I am trying to make a Space Invaders game using Pygame However I am having trouble figuring out how to make the spaceship continuously shoot multiple bullets and have the bullets move along with it The only way I have actually made the program shoot multiple bullets is through a `for loop` although the bullets stop shooting once the `for loop` hits its end Should I create a list to store all the bullets? Any help is appreciated :D Below is my Python code so far (It only has the spaceship that fires one bullet) ````from __future__ import print_function import pygame import os sys from pygame locals import * x_location = 357 y_location = 520 bullet_location_x = x_location 35 bullet_location_y = y_location - 5 def load_image(path colorkey): # loads an image given the file path try: image = pygame image load(path) except pygame error message: print("Cannot load image: {0}" format(path)) # print out error message image = image convert() # convert image so that it can be displayed properly if colorkey is not None: if colorkey is -1: colorkey = image get_at((0 0)) image set_colorkey(colorkey RLEACCEL) return image image get_rect() # Return the image and the image's rectangular area def main(): global x_location y_location bullet_location_x bullet_location_y pygame init() background_color = (0 0 0) # green background width height = (800 600) # width and height of screen screen = pygame display set_mode((width height)) # set width and height pygame display set_caption('space invaders') # set title of game clock = pygame time Clock() # create the clock spaceship_img spaceship_rect = load_image("spaceship png" (0 0 0)) bullet_img bullet_rect = load_image("bullet png" (0 0 0)) while True: screen fill(background_color) # make the background green ############################################################## # DISPLAY BULLET # ############################################################## screen blit(bullet_img (bullet_location_x bullet_location_y)) # Render the images screen blit(spaceship_img (x_location y_location)) keys = pygame key get_pressed() # get the keysnpressed for event in pygame event get(): # check the events if event type == pygame QUIT: # if the user presses quit pygame quit() # quit pygame sys exit() # terminate the process if event type == KEYDOWN: if event key == K_LEFT: screen fill(background_color) x_location -= 5 screen blit(spaceship_img (x_location y_location)) if event key == K_RIGHT: screen fill(background_color) x_location = 5 screen blit(spaceship_img (x_location y_location)) if event key == K_UP: screen blit(bullet_img (bullet_location_x bullet_location_y)) display_bullets = True pygame display flip() # refresh the pygame window clock tick(60) # Makes the game run at around 60 FPS bullet_location_y -= 5 pass if __name__ == '__main__': main() ```` | You should separate your game into a loop that contains 3 different functions: ````LOOP UPDATE_LOGIC INPUT_HANDLING DRAW_ELEMENTS END-LOOP ```` In the <strong>input_handling</strong> put a bullet into a list of bullets if the player is not in cool-down In the <strong>update_logic</strong> iterate of the bullet list calculating the positions through time and cool-down time of the player In the <strong>draw_elements</strong> simply draw every thing on your scene (iterate over the bullet list) and you can use different timers for the draw and update_logic That way will help you to add new elements to your game easily |
How to know which process is currently downloading some stuffs on system? I want to write a python script for Linux that shutdowns the machine after all current downloads are over For that I need to know which are the currently downloading processes on system How do I know which are those processes which are downloading some stuffs from the network? Are these processes managed by operating system or are they controlled by the application software? | Maybe you shold take a look at this : <a href="http://voorloopnul com/blog/a-python-netstat-in-less-than-100-lines-of-code/" rel="nofollow">http://voorloopnul com/blog/a-python-netstat-in-less-than-100-lines-of-code/</a> |
lxml xpath does not ignore " " I have this HTML: ````<td class="0"> <b>Bold Text</b>&nbsp; <a href=""></a> </td> <td class="0"> Regular Text&nbsp; <a href=""></a> </td> ```` Which when formatted with xpath ````new_html = tree xpath('//td[@class="0"]/text() | //td[@class="0"]/b/text()') ```` Prints: ````['Bold Text' '' 'Regular Text'] ```` As you can see the `&nbsp;` character has not been ignored and is actually read as an extra entry in td How can I get a better output? | Instead I would iterate over all the desired `td` elements and get the <a href="http://lxml de/lxmlhtml html#html-element-methods" rel="nofollow">` text_content()`</a>: ````[td text_content() strip() for td in tree xpath('//td[@class="0"]')] ```` Prints: ````[you'Bold Text' you'Regular Text'] ```` |
Western Armenian /tʰ/ compares to eastern Armenian /tʰ/ and what? | /d/ |
A pattern for transforming and combining multiple data types behind a simple interface I am having difficulty conceptualizing a sane abstraction for a small event logging framework and have not come across anything comparable in the wild that would apply here Overview: our web application needs to log events from the server side The event data is json encoded to written to a flat file An event might be a page view a signup an error condition etc All events would contain a set of core data like web request information and session state Any event should be able to define additional data to be recorded Ideally the interface to fire an event would be extremely minimal Event definitions and data requirements should be defined in a single configuration file Data validation and data transformations should be hidden behind this configuration file In other words the interface to log an event should require only an event name and the data structures to be transformed and recorded in the event My original thinking was that a single data structure would be mapped to a single function whose responsibility is to transform the data structure into a dictionary that would eventually be merged into the final event object then json encoded and written to the file I am referring to these as "composer" functions In Django terms something in the configuration file would map for example the HTTP request object that is passed to the view to a "request_composer" function The function would construct a dictionary of data that is pulled out of that request object The event that is emitted from the view would be required to pass in that "request" object I suppose my question is if there is a pattern or abstraction that I have overlooked that cleanly transforms arbitrary data structures and merges them into a final data structure I feel like this "single data type maps to a single transformation function" is a little kludgy and inelegant It also breaks down when it makes sense for a single transformer to accept more than one argument | That sounds a lot like Facade (simple interface to complex implementation) possibly combined with Strategy (switch between several concrete implementations of a process at runtime or during configuration/startup) and Builder (provide a common abstract description of a complex object that several different strategies can transform to an actual representation) You may find that once you use Strategy the use of Facade is not necessary <a href="http://en wikipedia org/wiki/Builder_pattern" rel="nofollow">http://en wikipedia org/wiki/Builder_pattern</a> <a href="http://en wikipedia org/wiki/Facade_pattern" rel="nofollow">http://en wikipedia org/wiki/Facade_pattern</a> <a href="http://en wikipedia org/wiki/Strategy_pattern" rel="nofollow">http://en wikipedia org/wiki/Strategy_pattern</a> So a bit more concrete: The Facade will have two methods: Log and SetLogger If you use Prototype you will have a type for an Event and a type for each component of the event You will only use Prototype if you have a very complex event to log or need to log it in several very different ways There will be an interface for a Logger (Strategy) This is used in the Facade for the SetLogger method If you are using Prototype the interface for both Facade Log and Logger Log will probably have a method like log(PrototypeEvent e) Follow link below for a simple logger that does not use Prototype but does use Strategy There is no Facade here as the front-end class really only keeps track of the current logger <a href="http://stackoverflow com/questions/12833436/i-am-going-to-create-simple-logger-using-c-sharp-so-what-are-the-design-patterns/12833915#12833915">I am going to create simple logger using C# so what are the design patterns I can use to create this as best practice?</a> |
How to get table cell value from QTableWidget in pyside? `form_shift` is form name `tblSession` is `QTableWidget` object ````shift_id=form_shift tblSession item(1 0) text() ```` Error: ````AttributeError: 'NoneType' object has no attribute 'text' ```` | This works just fine for me Perhaps your table does not have an item at those coordinates? ````table = QtGui QTableWidget(5 3 self) for row in range(5): for col in range(3): table setItem(row col QtGui QTableWidgetItem("(%d %d)" % (row col))) print("1 0: %s" % table item(1 0) text()) ```` |
Concatenating Strings: str str or "{:s}{:s}" format()? Is there any difference between ````str_ = "foo" "bar" ```` and ````str_ = "{:s}{:s}" format("foo" "bar") ```` or is it simply preference? | <them>Semantically?</them> No both end up joining `"foo"` and `"bar"` and assigning them to `str` <them>Computationally?</them> Surely Python will create the literal for `"foobar"` during compilation the `str = "foo" "bar"` assignment will be faster <them>From a readability aspect?</them> Again `str = "foo" "bar"` is surely more clear and concise <hr> The common errata in both your examples is that you are assigning to `str` which is a built-in name so do not you mask it |
Python Django Global Variables I am looking for simple but recommended way in Django to store a variable in memory only When Apache restarts or the Django development server restarts the variable is reset back to 0 More specifically I want to count how many times a particular action takes place on each model instance (database record) but for performance reasons I do not want to store these counts in the database I do not care if the counts disappear after a server restart But as long as the server is up I want these counts to be consistent between the Django she will and the web interface and I want to be able to return how many times the action has taken place on each model instance I do not want the variables to be associated with a user or session because I might want to return these counts without being logged in (and I want the counts to be consistent no matter what user is logged in) Am I describing a global variable? If so how do I use one in Django? I have noticed the files like the urls py settings py and models py seems to be parsed only once per server startup (by contrast to the views py which seems to be parsed eache time a request is made) Does this mean I should declare my variables in one of those files? Or should I store it in a model attribute somehow (as long as it sticks around for as long as the server is running)? This is probably an easy question but I am just not sure how it is done in Django Any comments or advice is much appreciated Thanks Joe | You <strong>must not</strong> declare global variables Settings (constants) are OK if done right But variables violate with <them>shared-nothing</them> architecture and might cause a lot of trouble (best case they will be inconsistent) I would simply store those statistics in the cache (Well actually I would store them in the database but you made clear you <them>believe</them> it will have a negative impact on performance so ) The new `incr()` and `decr()` methods are especially suitable for counting See <a href="http://docs djangoproject com/en/dev/topics/cache/#the-low-level-cache-api"> docs</a> for more info |
Python regular expression capture re-use I am trying to create a Python regular expression that will match a string if and only if that string begins and ends with the same lower-case letter The following seems like it ought to work but matches every string: `(?P<st>[a-z]) *(?P=st)$` Any suggestions will be appreciated | ````^([a-z]) *\1$ ```` This will require `back reference` See demo <a href="https://regex101 com/r/iV6mP5/5#python" rel="nofollow">https://regex101 com/r/iV6mP5/5#python</a> ````import re p = re compile(r'^([a-z]) *\1$' re MULTILINE) test_str = "a sdf sd fdsf sd a\nsdfdsf ASDSDSAD@#$@#ASDASDs\nsadasd Wdsda" re findall(p test_str) ```` |
passing a variable from class to class I am trying to create a game-save file in python using a dict which looks like this: ```` user = { 'Name': 'craig' 'HP': 100 'ATK': 20 'DEF' : 10 'GOLD' : 300 'INV' : [0 pants] 'GEAR' : [0 axe] 'CityLevel' : 0 'BadAns': 0 } ```` I am passing it through classes just like in <a href="http://learnpythonthehardway org/book/ex43 html" rel="nofollow">excercise 43 of learn python the hard way</a> the code in "############ code here #######" works but replacing all of that with name = temp does not pass the 'user' variable along with the return like the current code does ````class User(): def enter(self user): def writing(self user): pickle dump(user open('users pic' 'a')) print "Is this your first time playing?" answer = prompt() if answer == 'yes': print "Welcome to the Game!" print "What do you want to name your character?" user['Name'] = prompt() writing(self user) print "You will start out in the city at the city entrance Good luck!" gamesupport print_attributes(player) return 'City Entrance' elif answer == 'no': print "what is your character's name?" charname = prompt() temp = pickle load(open('users pic')) ###################################### user['Name'] = temp['Name'] user['GOLD'] = temp['GOLD'] user['HP'] = temp['HP'] user['ATK'] = temp['ATK'] user['DEF'] = temp['DEF'] user['GEAR'] = temp['GEAR'] user['CityLevel'] = temp['CityLevel'] ############################################ print user return 'City Entrance' else: print "we are screwed" ```` the 'print user' works as expected and prints everything correctly even if i just use 'user = temp' but then the user variable is not saved and passed on to the rest of the game why is this and how can I fix it? having to type in each attribute line by line is not good because then I cannot append anything to 'user' and have it save and load up again | This has to do with how Python references objects Take a look at this example: ````>>> test = {} >>> test2 = test >>> test2 is test True >>> def runTest(test): print test is test2 test = {} print test is test2 >>> runTest(test) True False ```` As you can see in the `runTest` function if you use `test = ` the variable references a new dictionary The way to solve this is to use the `update` method This copies all values from the source dictionary into the target dictionary: ````>>> source = {'a':'b' 'c': would'} >>> target = {'a':'g' 'b':'h'} >>> target update(source) >>> print target {'a':'b' 'b':'h' 'c': would'} ```` |
flask dropbox causing error: ImportError: No module named _winreg So whenever I import dropbox into my Flask project I get this error For example even in the sample project <a href="https://github com/WoLpH/dropbox/blob/master/example/flask_app/simple_dropbox_app py" rel="nofollow">https://github com/WoLpH/dropbox/blob/master/example/flask_app/simple_dropbox_app py</a> I suspect that the error is caused by this line: ````12 DEBUG = True ```` But I do not know why This is the error I get from running the sample project with no modification ````/Downloads/dropbox-master/example/flask_app$ python simple_dropbox_app py * Running on http://127 0 0 1:5000/ (Press CTRL+C to quit) * Restarting with stat Traceback (most recent call last): File "simple_dropbox_app py" line 167 in <module> main() File "simple_dropbox_app py" line 163 in main app run() File "/usr/local/lib/python2 7/dist-packages/flask/app py" line 772 in run run_simple(host port self **options) File "/usr/local/lib/python2 7/dist-packages/werkzeug/serving py" line 622 in run_simple reloader_type) File "/usr/local/lib/python2 7/dist-packages/werkzeug/_reloader py" line 269 in run_with_reloader reloader run() File "/usr/local/lib/python2 7/dist-packages/werkzeug/_reloader py" line 159 in run for filename in chain(_iter_module_files() self extra_files): File "/usr/local/lib/python2 7/dist-packages/werkzeug/_reloader py" line 70 in _iter_module_files for package_path in getattr(module '__path__' ()): File "/usr/lib/python2 7/dist-packages/six py" line 116 in __getattr__ _module = self _resolve() File "/usr/lib/python2 7/dist-packages/six py" line 105 in _resolve return _import_module(self mod) File "/usr/lib/python2 7/dist-packages/six py" line 76 in _import_module __import__(name) ImportError: No module named _winreg ```` <blockquote> <strong>ImportError: No module named _winreg</strong> </blockquote> | Just `sudo pip install flask --upgrade` The latest version fix this bug! |
trigger after_update() in IPackageController by API call I am developing a plug-in for CKAN and I need to trigger a function when a resource is updated or created When you modify a resource it affects the parent dataset by changing the date in last_modified I want to change the date every time that a resource is added/modified When I update a resource I suppose to update the dataset as well and I am expecting an after_update() call in IPackageController This is the behaviour when I use the admin interface after I edited a resource IPackageController after_update() is triggered Calling the API is a different story that event is not triggered at all by calling ```/api/3/action/resource_update``` <pre class="lang-py prettyprint-override">`import ckan plugins as plugins class MyControllerPlugin(plugins SingletonPlugin): plugins implements(plugins IPackageController inherit=True) def after_create(self context resource): print "============== AFTER CREATE" def after_update(self context resource): print "============== AFTER UPDATE" ```` How can I trigger this event by API? thanks | Calling /api/3/action/resource_update does not trigger the IPackageController's after_update function as it is the resource that is being updated not the package If you call /api/3/action/package_update it should get called? Or you can use IResourceController's after_update to handle when the resource is updated |
What does improving visibilitiy by using a right handed pattern do for the ATC? | null |
What are some good ways of estimating 'approximate' semantic similarity between sentences? I have been looking at the nlp tag on SO for the past couple of hours and am confident I did not miss anything but if I did please do point me to the question In the mean time though I will describe what I am trying to do A common notion that I observed on many posts is that semantic similarity is difficult For instance from <a href="http://stackoverflow com/questions/2037832/semantic-similarity-between-sentences">this</a> post the accepted solution suggests the following: ````First of all neither from the perspective of computational linguistics nor of theoretical linguistics is it clear what the term 'semantic similarity' means exactly Consider these examples: Pete and Rob have found a dog near the station Pete and Rob have never found a dog near the station Pete and Rob both like programming a lot Patricia found a dog near the station It was a dog who found Pete and Rob under the snow Which of the sentences 2-4 are similar to 1? 2 is the exact opposite of 1 still it is about Pete and Rob (not) finding a dog ```` My high-level requirement is to utilize k-means clustering and categorize the text based on semantic similarity so all I need to know is whether they are an approximate match For instance in the above example I am OK with classifying 1 2 4 5 into one category and 3 into another (of course 3 will be backed up with some more similar sentences) Something like find related articles but they do not have to be 100% related I am thinking I need to ultimately construct vector representations of each sentence sort of like its fingerprint but exactly what this vector should contain is still an open question for me Is it n-grams or something from the wordnet or just the individual stemmed words or something else altogether? <a href="http://stackoverflow com/questions/1254627/what-tried-and-true-algorithms-for-suggesting-related-articles-are-out-there">This</a> thread did a fantastic job of enumerating all related techniques but unfortunately stopped just when the post got to what I wanted Any suggestions on what is the latest state-of-the-art in this area? | I suggest you try a topic modelling framework such as Latent Dirichlet Allocation (LDA) The idea there is that documents (in your case sentences which might prove to be a problem) are generated from a set of latent (hidden) topics; LDA retrieves those topics representing them by word clusters An <a href="http://nlp fi muni cz/projekty/gensim/models/ldamodel html" rel="nofollow">implementation of LDA in Python</a> is available as part of the free Gensim package You could try to apply it to your sentences then run <them>k</them>-means on its output |
Which country did Hitler align Germany with? | Italy |
Along with underground, open pit and in-situ leaching, what sort of mining is used to expel uranium? | null |
Dictionary values missing I am doing the very last exercise on <a href="http://automatetheboringstuff com/chapter5/" rel="nofollow">http://automatetheboringstuff com/chapter5/</a> For some reason I am not able to get the `displayInventory(inv)` function to return the correct values outside of the `addToInventory()` function Here is the code: ````def displayInventory(inventory): print("Inventory:") item_total = 0 for k v in inventory items(): print(str(v) ' ' k) item_total = v print("Total number of items: " str(item_total)) def addToInventory(inventory addedItems): for k in addedItems: if k in inventory: inv[k] = inv[k] 1 print('You have ' str(inv[k]) ' ' k 's') else: print(k ' is not in inventory') inventory setdefault(k 1) print() displayInventory(inv) #does work inv = {'gold coin': 42 'rope': 1} displayInventory(inv) print() dragonLoot = ['gold coin' 'dagger' 'gold coin' 'gold coin' 'ruby'] inv = addToInventory(inv dragonLoot) print() displayInventory(inv) #Does not work ```` I get the error: `AttributeError: 'NoneType' object has no attribute 'items'` It looks like the `inv` dictionary is empty Why it is emptied and why the values are different outside of the function? | Your `addToInventory()` function returns `None` because you do not have a specific `return` statement Since the function alters the dictionary <them>in place</them> you should just not use the return value; remove the `inv =` part: ````# ignore the return value; do not replace `inv` with it addToInventory(inv dragonLoot) ```` |
Simple application of QThread I am getting a grip on QThread in order to not lock my GUI while performing possibly longer threads in the background I am trying for practice to write a simple application: A countdown timer which I can start by clicking on a button "Start" thereby initiating a countdown loop which I can pause by clicking on a button "Pause" I want to do it in the "proper way" of using QThread (explained <a href="https://mayaposch wordpress com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/" rel="nofollow" title="over here">over here</a>) i e subclassing QObject and then attach an instance of this subclass to a QThread via moveToThread I did the GUI with QTDesigner and this is what I modified so far (from other examples on the Net) in Python: ````from PyQt4 import QtGui QtCore from PyQt4 QtCore import QThread SIGNAL import time sys mydesign class SomeObject(QtCore QObject): def __init__(self lcd): super(self __class__ self) __init__() self lcd = lcd self looping = True finished = QtCore pyqtSignal() def pauseLoop(self): print "Hello?" self looping = False def longRunning(self): count = 10 self lcd display(count) while count > 0 and self looping: time sleep(1) count -= 1 self lcd display(count) self finished emit() class ThreadingTutorial(QtGui QMainWindow mydesign Ui_MainWindow): def __init__(self): super(self __class__ self) __init__() self setupUi(self) #an instance of SomeObject gets attached to #an instance of wrapper class QThread() #objThread is a wrapper object for an instance of # self-defined class SomeObject self objThread = QtCore QThread() self obj = SomeObject(self lcdNumber) self obj moveToThread(self objThread) #connect all the signals self obj finished connect(self objThread quit) self objThread started connect(self obj longRunning) self startCountdown clicked connect(self objThread start) self pauseButton clicked connect(self obj pauseLoop) if __name__ == "__main__": app = QtGui QApplication(sys argv) form = ThreadingTutorial() form show() app exec_() ```` The GUI is not locked but the function pauseLoop() only gets executed after the loop is finished How do I have to do it in order to accomplish my goal to be able to pause the loop in longRunning()? Thanks in advance! <strong>update:</strong> With the help of Steve's and three_pineapples's remarks I come up with following solution using the inner event loop of objThread: ````from PyQt4 import QtGui QtCore from PyQt4 QtCore import QThread SIGNAL QTimer import time sys mydesign class SomeObject(QtCore QObject): def __init__(self): super(self __class__ self) __init__() self looping = True self count = 10 self timer = QTimer(self) self timer start(1000) self connect(self timer SIGNAL("timeout()") self longRunning) finished = QtCore pyqtSignal() iterated = QtCore pyqtSignal() def pauseLoop(self): self looping = False def longRunning(self): if self count > 0 and self looping: self count -= 1 self iterated emit() else: self finished emit()# sends signal for stopping event loop class ThreadingTutorial(QtGui QMainWindow mydesign Ui_MainWindow): def __init__(self): super(self __class__ self) __init__() self setupUi(self) #an instance of SomeObject gets attached to #an instance of wrapper class QThread() #objThread is a wrapper object for an instance of # self-defined class SomeObject self objThread = QtCore QThread() self obj = SomeObject() self lcdNumber display(self obj count) self obj moveToThread(self objThread) #connect all the signals self obj finished connect(self objThread quit) self obj iterated connect(lambda: self lcdNumber display(self obj count)) self objThread started connect(self obj longRunning) self startCountdown clicked connect(self objThread start) self pauseButton clicked connect(self obj pauseLoop) if __name__ == "__main__": app = QtGui QApplication(sys argv) form = ThreadingTutorial() form show() app exec_() ```` | This is happening because you tell Qt to run the code for your `SomeObject` object in a single thread In your code you have two threads your main GUI thread and your `self objThread` The `pauseLoop()` is called in the same thread as `longRunning()` which means `longRunning()` must complete before `pauseLoop()` can run Instead you need to call `pauseLoop()` from a different thread not `self objThread` Note that when you start changing data from two different threads (your main thread and your new thread) you could start to run into race conditions Since you are only setting one boolean variable you will be fine but it is something to keep in mind <strong>Edit</strong>: As pointed out in the comment by `three_pineapples` accessing GUI objects (ex: `QWidget`) should only be done in the main GUI thread To show how this would work I have updated this answer to use signals to update the LCD in the GUI thread instead of just printing the value to stdout I also added code to print out the current thread at different sections ````from PySide import QtGui QtCore from PySide QtCore import QThread SIGNAL import time sys class SomeObject(QtCore QObject): updateCounter = QtCore Signal(int) finished = QtCore Signal() def __init__(self): super(self __class__ self) __init__() self looping = True def pauseLoop(self): self looping = False print 'Pause Loop: '+str(QThread currentThreadId()) def longRunning(self): print 'Long Running: '+str(QThread currentThreadId()) count = 10 while count > 0 and self looping: count -= 1 self updateCounter emit(count) time sleep(1) self finished emit() class ThreadingTutorial(QtGui QWidget): def __init__(self): super(self __class__ self) __init__() # self thisLayout = QtGui QVBoxLayout(self) self startCountdown = QtGui QPushButton('Start' self) self pauseButton = QtGui QPushButton('Stop' self) self lcd = QtGui QLabel('' self) self thisLayout addWidget(self startCountdown) self thisLayout addWidget(self pauseButton) self thisLayout addWidget(self lcd) # print 'Main GUI Thread: '+str(QThread currentThreadId()) self objThread = QtCore QThread() self obj = SomeObject() self obj moveToThread(self objThread) self obj updateCounter connect(self _updateTimer) # self obj finished connect(self objThread quit) self objThread started connect(self obj longRunning) self startCountdown clicked connect(self objThread start) self pauseButton clicked connect(self _stopTimer) def _stopTimer(self): self obj pauseLoop() def _updateTimer(self num): self lcd setText(str(num)) print 'Update Timer: '+str(QThread currentThreadId()) if __name__ == "__main__": app = QtGui QApplication(sys argv) form = ThreadingTutorial() form show() app exec_() ```` Example output: ````Main GUI Thread: 3074717376 Long Running: 3034471232 Update Timer: 3074717376 Update Timer: 3074717376 Update Timer: 3074717376 Update Timer: 3074717376 Update Timer: 3074717376 Update Timer: 3074717376 Pause Loop: 3074717376 ```` |
How many students does the University of Houston have? | 40,000 |
How to store stream of tweets in a single dict? I wrote a code to get data from twitters streaming api using tweepy A small part of the code is given below: ````class listener(StreamListener): def on_status(self status): try: k = [status author screen_name encode('utf-8') (status retweeted)] ```` Now this may seem silly k is a list which changes continuously How can I store all k's in a single dictionary Is it possible? | Add a variable (a list though you mentioned wanting a dict) to the class ````class listener(StreamListener): tweets = [] def bar(self status): k = [status author screen_name encode('utf-8') (status retweeted)] self tweets append(k) >>> f = Foo() >>> f bar('1') >>> f bar('2') >>> f bar('3') >>> f tweets [['1' '1'] ['2' '2'] ['3' '3']] ```` <a href="https://docs python org/2/tutorial/classes html" rel="nofollow">More information on classes can be found here </a> |
Wrong decoding with utf_7 I use the following python code to decode a "text" file: ````import codecs os sys fd = open("c:/a txt" 'rb') rb = fd read() s = codecs decode(rb 'utf_7') print(s) ```` and get following errors on running: ````UnicodeDecodeError: 'utf7' codec cannot decode byte 0xc3 in position 3: unexpected special character ```` But the "text" file can be decoded by the iconv utility shown as follows: ````$iconv -f UTF-8 -t UTF-7 a txt 01 ANYA2AC5AOkAywDVAMEAqw ```` So what is wrong? | The equivalent of the `iconv` that you gave is: ````s = rb decode('utf-8') encode('utf-7') ```` You were missing a step |
Python multiprocessing sharedctype array - cannot write for testing reasons I start only 1 process One given argument is an array that shall be changed from that process ````class Engine(): Ready = Value('i' False) def movelisttoctypemovelist(self movelist): ctML = [] for zug in movelist: ctZug = ctypeZug() ctZug VonReihe = zug VonReihe ctZug VonLinie = zug VonLinie ctZug NachReihe = zug NachReihe ctZug NachLinie = zug NachLinie ctZug Bewertung = zug Bewertung ctML append(ctZug) return ctML def findbestmove(self board settings enginesettings): print ("Computer using" multiprocessing cpu_count() "Cores ") movelist = Array(ctypeZug [] lock = True) movelist = self movelisttoctypemovelist(board movelist) bd = board boardtodictionary() process = [] for i in range(1): p = Process(target=self calculatenullmoves args=(bd movelist i self Ready)) process append(p) p start() for p in process: p join() self printctypemovelist(movelist settings) print ("Ready:" self Ready value) def calculatenullmoves(self boarddictionary ml processindex ready): currenttime = time() print ("Process" processindex "begins to work ") board = Board() board dictionarytoboard(boarddictionary) ml[processindex] Bewertung = 2 4 ready value = True print ("Process" processindex "finished work in" time()-currenttime "sec") def printctypemovelist(self ml): for zug in ml: print (zug VonReihe zug VonLinie zug NachReihe zug NachLinie zug Bewertung) ```` I try to write 2 4 directly in the list but no changing is shown when calling "printctypemovelist" I set "Ready" to True and it works I used information from <a href="http://docs python org/2/library/multiprocessing html#module-multiprocessing sharedctypes" rel="nofollow">http://docs python org/2/library/multiprocessing html#module-multiprocessing sharedctypes</a> I hope someone can find my mistake if it is too difficult to read please let me know | The problem is that you are trying to share a plain Python list: ````ctML = [] ```` Use a proxy object instead: ````from multiprocessing import Manager ctML = Manager() list() ```` See Python doc on <a href="http://docs python org/2/library/multiprocessing html#sharing-state-between-processes" rel="nofollow">Sharing state between processes</a> for more detail |
What was a factor in deciding where to divide the occupation zones? | the capital of Korea |
Buildout tries to update system-wide Distribute installation and refuses to run Buildout does not like my system-wide Distribute installation and refuses to run: ````plone@s15447224:~/mybuildout$ python bootstrap py Creating directory '/home/plone/mybuildout/bin' Creating directory '/home/plone/mybuildout/parts' Creating directory '/home/plone/mybuildout/eggs' Creating directory '/home/plone/mybuildout/develop-eggs' Getting distribution for 'distribute==0 6 14' Before install bootstrap Scanning installed packages Setuptools installation detected at /usr/lib/python2 6/dist-packages Non-egg installation Removing elements out of the way Already patched /usr/lib/python2 6/dist-packages/setuptools egg-info already patched After install bootstrap Creating /usr/local/lib/python2 6/dist-packages/setuptools-0 6c11-py2 6 egg-info error: /usr/local/lib/python2 6/dist-packages/setuptools-0 6c11-py2 6 egg-info: Permission denied An error occurred when trying to install distribute 0 6 14 Look above this message for any errors that were output by easy_install While: Bootstrapping Getting distribution for 'distribute==0 6 14' Error: Could not install: distribute 0 6 14 ```` Is there some way to tell buildout to install its own Distribute and not to mess with system-wide Python installation? I know about virtualenv But it seems to be an overkill just to install virtualenv to make buildout happy There must be some other way Python 2 6 Plone 4 1 Ubuntu 10 4 | kgs provided by zope pin the version of setuptools and distribute: <a href="http://download zope org/zopetoolkit/index/1 0 2/ztk-versions cfg" rel="nofollow">http://download zope org/zopetoolkit/index/1 0 2/ztk-versions cfg</a> setuptools = 0 6c11 distribute = 0 6 14 The best is to remove python-setuptools package from your system bootstrap is here to be sure you have setuptools or distribute (-d option) but your buildout is asking these versions Quite weird |
Cropping text on matplotlib plot I am making a plot and I <them>want</them> the text to crop at the edge Right now it hangs over the edge which is great for readability but not what I actually want Here is a toy version of what I am doing: ````import numpy as np import matplotlib pyplot as plt %matplotlib inline fig = plt figure() ax = fig add_subplot(111) ax scatter(np random random(10) np random random(10)) ax text(0 8 0 5 "a rather long string") plt show() ```` <a href="http://i stack imgur com/UPLQo png" rel="nofollow"><img src="http://i stack imgur com/UPLQo png" alt="my matplotlib example"></a> Just to be clear I want to crop my `text` element but not anything else â e g I want to leave the `0 9` in the <them>x</them>-axis alone | You should set a clipbox for the text as <a href="http://matplotlib org/api/text_api html#matplotlib text Text" rel="nofollow">described in the documentation</a>: ````import numpy as np import matplotlib pyplot as plt %matplotlib inline fig = plt figure() ax = fig add_subplot(111) ax scatter(np random random(10) np random random(10)) ax text(0 8 0 5 "a rather long string" clip_box=ax clipbox clip_on=True) ax set_xlim(0 1) plt show() ```` This results in <a href="http://i stack imgur com/656yL png" rel="nofollow"><img src="http://i stack imgur com/656yL png" alt="enter image description here"></a> |
Move Lat & Lon point to a new routable position I am collecting raw data from a GPS It looks not very accurate: <a href="http://i stack imgur com/BuwQR png" rel="nofollow"><img src="http://i stack imgur com/BuwQR png" alt="gps raw data"></a> I would like to move points to nearest routable point ( in a offline cleaning process if it is possible ) What I did: I digging on forums searching for a magic solution ;) May be the closest is to use openstreetmap extract and query it something like: ````( way (around:100 41 12345 4 12345) [highway~"^(primary|secondary|tertiary|residential)$"] [name]; >;) ```` But I have no experience in this environment I do not know how to make query and get desired new point ( python will be wonderful but I am open to other solutions ) Perhaps I am totally wrong I have my mind open to any solution | There are various solutions for <a href="https://wiki openstreetmap org/wiki/Conflation" rel="nofollow">Map Matching (also called Conflation) with OSM</a> available for example GraphHopper Also take a look at this <a href="https://gis stackexchange com/questions/5761/different-approaches-for-map-matching-links-ideas">related question on gis stackexchange com</a> |
regarding re-factoring python code so I have this python file which looks out for all the "label" tags in a XML file and does some modification with it label is a string containing at max three lines the code is manipulating XML file ```` #1 label="Number of Packets Transmitted by the Source Node of the Path to the Destination Node Of the Path" #2 label="Number of Packets Transmitted by the Source node of the path to the destination node of the path" ```` notice in label #2 words in second and third line are not in upper case which is not what I want I want help in correcting logic of my program such that I should not write label twice ````import os from io import StringIO BytesIO def splitAndMakeTitleCase(line): # does something not relevant to context fileList = open("AllFiles") for fileStr in fileList: fileName = fileStr rstrip('\n') openFile = open(fileName) openNewFile = open(fileName+'TitleCase xml' 'w') lines = openFile readlines() for lineIndex in range(0 len(lines)): line = lines[lineIndex] skip = 0 if "label=" in line and "const" not in line: segs = line split('"') if len(segs) >= 3: pass else: openNewFile write(lines[lineIndex]) secondTitleCaseLine = splitAndMakeTitleCase(lines[lineIndex 1]) skip = lineIndex 1 openNewFile write(secondTitleCaseLine) if '"' not in lines[lineIndex 1]: thirdTitleCaseLine = splitAndMakeTitleCase(lines[lineIndex 2]) skip = lineIndex 1 openNewFile write(thirdTitleCaseLine) openNewFile write(lines[lineIndex]) openFile close() openNewFile close() #cmd = "mv " fileName "TitleCase xml " fileName #os system(cmd) ```` | In your for loop you have the first if and then within that you do some printing to the file Then after that you do another print of the line to the file I think that you probably want that last line in a else like this: ````for fileStr in fileList: fileName = fileStr rstrip('\n') openFile = open(fileName) openNewFile = open(fileName+'TitleCase xml' 'w') lines = openFile readlines() for lineIndex in range(0 len(lines)): line = lines[lineIndex] skip = 0 if "label=" in line and "const" not in line: segs = line split('"') if len(segs) >= 3: pass else: openNewFile write(lines[lineIndex]) secondTitleCaseLine = splitAndMakeTitleCase(lines[lineIndex 1]) skip = lineIndex 1 openNewFile write(secondTitleCaseLine) if '"' not in lines[lineIndex 1]: thirdTitleCaseLine = splitAndMakeTitleCase(lines[lineIndex 2]) skip = lineIndex 1 openNewFile write(thirdTitleCaseLine) else: openNewFile write(lines[lineIndex]) openFile close() openNewFile close() #cmd = "mv " fileName "TitleCase xml " fileName #os system(cmd) ```` |
When are Internet Archive timestamps harmful for patent offices? | null |
Python - caching a property to avoid future calculations In the following example `cached_attr` is used to get or set an attribute on a model instance when a database-expensive property (`related_spam` in the example) is called In the example I use `cached_spam` to save queries I put print statements when setting and when getting values so that I could test it out I tested it in a view by passing an `Egg` instance into the view and in the view using `{{ egg cached_spam }}` as well as other methods on the `Egg` model that make calls to `cached_spam` themselves When I finished and tested it out the she will output in Django's development server showed that the attribute cache was missed several times as well as successfully gotten several times It seems to be inconsistent With the same data when I made small changes (as little as changing the print statement's string) and refreshed (with all the same data) different amounts of misses / successes happened How and why is this happening? Is this code incorrect or highly problematic? ````class Egg(models Model): fields @property def related_spam(self): # Each time this property is called the database is queried (expected) return Spam objects filter(egg=self) all() # Spam has foreign key to Egg @property def cached_spam(self): # This should call self related_spam the first time and then return # cached results every time after that return self cached_attr('related_spam') def cached_attr(self attr): """This method (normally attached via an abstract base class but put directly on the model for this example) attempts to return a cached version of a requested attribute and calls the actual attribute when the cached version is not available """ try: value = getattr(self '_p_cache_{0}' format(attr)) print('GETTING - {0}' format(value)) except AttributeError: value = getattr(self attr) print('SETTING - {0}' format(value)) setattr(self '_p_cache_{0}' format(attr) value) return value ```` | Nothing wrong with your code as far as it goes The problem probably is not there but in how you use that code The main thing to realise is that model instances do not have identity That means that if you instantiate an Egg object somewhere and a different one somewhere else even if they refer to the same underlying database row they will not share internal state So calling `cached_attr` on one will not because the cache to be populated in the other For example assuming you have a RelatedObject class with a ForeignKey to Egg: ````my_first_egg = Egg objects get(pk=1) my_related_object = RelatedObject objects get(egg__pk=1) my_second_egg = my_related_object egg ```` Here `my_first_egg` and `my_second_egg` both refer to the database row with pk 1 but they are <them>not</them> the same object: ````>>> my_first_egg pk == my_second_egg pk True >>> my_first_egg is my_second_egg False ```` So filling the cache on `my_first_egg` does not fill it on `my_second_egg` And of course objects will not persist across requests (unless they are specifically made global which is horrible) so the cache will not persist either |
How to append another argument in the __init__() of subclass? So basically I have a parent class with some arguments in the <strong>init</strong>() now I want to define a subclass I want to redefine the <strong>init</strong>() in the subclass just append a new argument in it Is there any convenient way to complete this? Here is my code: ````class Car(object): condition = "new" def __init__(self model color mpg): self model = model self color = color self mpg = mpg def display_car(self): #print "This is a "+self color+" "+self model+" with "+str(self mpg)+" MPG " print self condition def drive_car(self): self condition = "used" class ElectricCar(Car): def __init__(self model color mpg battery_type): self model = model self color = color self mpg = mpg self battery_type = battery_type my_car = Car("DeLorean" "silver" 88) my_car = ElectricCar("Fuck me" "Gold" 998 "molten salt") print my_car condition my_car drive_car() print my_car condition ```` The new argument is `battery_type` | You can use `super()` to access the parent class' `__init__()` and let parent init its attributes Example - ````class ElectricCar(Car): def __init__(self model color mpg battery_type): super(ElectricCar self) __init__(model color mpg) self battery_type = battery_type ```` |
Texas consisted of what type of building in the 1960's? | null |
urllib2 try and except on 404 I am trying to go through a series of numbered data pages using urlib2 What I want to do is use a try statement but I have little knowledge of it Judging by reading up a bit it seems to be based on specific 'names' that are exceptions eg IOError etc I do not know what the error code is I am looking for which is part of the problem I have written / pasted from 'urllib2 the missing manual' my urllib2 page fetching routine thus: ````def fetch_page(url useragent) urlopen = urllib2 urlopen Request = urllib2 Request cj = cookielib LWPCookieJar() txheaders = {'User-agent' : useragent} if os path isfile(COOKIEFILE): cj load(COOKIEFILE) print "previous cookie loaded " else: print "no ospath to cookfile" opener = urllib2 build_opener(urllib2 HTTPCookieProcessor(cj)) urllib2 install_opener(opener) try: req = urllib2 Request(url useragent) # create a request object handle = urlopen(req) # and open it to return a handle on the url except IOError e: print 'Failed to open "%s" ' % url if hasattr(e 'code'): print 'We failed with error code - %s ' % e code elif hasattr(e 'reason'): print "The error object has the following 'reason' attribute :" print e reason print "This usually means the server does not exist " print "is down or we do not have an internet connection " return False else: print if cj is None: print "We do not have a cookie library available - sorry " print "I cannot show you any cookies " else: print 'These are the cookies we have received so far :' for index cookie in enumerate(cj): print index ' : ' cookie cj save(COOKIEFILE) # save the cookies again page = handle read() return (page) def fetch_series(): useragent="Firefox etc " url="www example com/01 html" try: fetch_page(url useragent) except [something]: print "failed to get page" sys exit() ```` The bottom function is just an example to see what I mean can anyone tell me what I should be putting there ? I made the page fetching function return False if it gets a 404 is this correct ? So why does not except False: work ? Thanks for any help you can give ok well as per advice here i have tried: ````except urlib2 URLError e: except URLError e: except URLError: except urllib2 IOError e: except IOError e: except IOError: except urllib2 HTTPError e: except urllib2 HTTPError: except HTTPError: ```` none of them work | You should catch `urllib2 HTTPError` if you want to detect a 404: ````try: req = urllib2 Request(url useragent) # create a request object handle = urllib2 urlopen(req) # and open it to return a handle on the url except urllib2 HTTPError e: print 'We failed with error code - %s ' % e code if e code == 404: # do stuff else: # other stuff return False else: # ```` <hr> To catch it in fetch_series(): ````def fetch_page(url useragent)   urlopen = urllib2 urlopen   Request = urllib2 Request   cj = cookielib LWPCookieJar() try: urlopen() # except IOError e: # else: # def fetch_series():   useragent=âFirefox etc â   url=âwww example com/01 html   try:     fetch_page(url useragent)   except urllib2 HTTPError e:     print âfailed to get pageâ ```` <a href="http://docs python org/library/urllib2 html">http://docs python org/library/urllib2 html</a>: <blockquote> `exception urllib2 HTTPError` Though being an exception (a subclass of `URLError`) an `HTTPError` can also function as a non-exceptional file-like return value (the same thing that `urlopen()` returns) This is useful when handling exotic HTTP errors such as requests for authentication `code` An HTTP status code as defined in RFC 2616 This numeric value corresponds to a value found in the dictionary of codes as found in `BaseHTTPServer BaseHTTPRequestHandler responses` </blockquote> |
What percentage of the state's delegates had Bob Graham taken as the front-runner? | null |
Python target the element before a given element in a list I have a dictionary: ````d = {'a': ['Thing' 'City' 10] 'b': ['Thing' 'City' 5]} ```` and so on and `num = 10` I want to go through the dictionary and check to see if num matches up with any of the other numbers in the lists of the dictionary If so I want to grab the 2 elements before the number and return all 3 So for example in this case since `num = 10` and `a` has a `10` it should return `['Thing' 'City' 10]` So far I have this: ````for i in d keys(): # goes through the dictionary for item in d[i]: if type(item) == int: # if the item is an int if num = item: l append(item) #l append the items before it ```` I guess my question then boils down to this: How do I get the items before a given element in the list? So in this case I have the 10 but also want the Thing and City Thank You! | Try something like this: ````for key item in d items(): for idx subitem in enumerate(item): if isinstance(subitem int) and subitem == num: l extend(subitem[idx-2:idx+1]) ```` |
No valid context when using glutMouseFunc in python I am trying to write program in Python using PyOpenGL which I need to use glutMouseFunc for some mouse functionality but when I run the program I get the following error: ````Traceback (most recent call last): File "teapot py" line 80 in <module> glutMouseFunc(mouseHandle) File "/usr/lib/python2 7/dist-packages/OpenGL/GLUT/special py" line 137 in __call__ contextdata setValue( self CONTEXT_DATA_KEY cCallback ) File "/usr/lib/python2 7/dist-packages/OpenGL/contextdata py" line 57 in setValue context = getContext( context ) File "/usr/lib/python2 7/dist-packages/OpenGL/contextdata py" line 40 in getContext """Attempt to retrieve context when no valid context""" OpenGL error Error: Attempt to retrieve context when no valid context ```` I tried googling it but I could not find any related result Here is my code: ````from OpenGL GL import * from OpenGL GLUT import * t = 0 def init(): r=1 g=0 b=0 glColor3f(r g b) glClearColor(1 0 1 0 1 0 0 0) glMatrixMode(GL_PROJECTION) glLoadIdentity() def display(): glClear(GL_COLOR_BUFFER_BIT) glViewport(0 0 150 100) drawSquare() glViewport(0 100 150 200) drawCircle() glViewport(0 200 150 300) drawTriangle() glViewport(0 300 150 400) drawFan() if(t==1): glViewport(150 0 800 600) drawFan() if(t==2): glViewport(150 0 800 600) drawTriangle() if(t==3): glViewport(150 0 800 600) drawCircle() if(t==4): glViewport(150 0 800 600) drawSquare() glFlush() def drawFan(): glBegin(GL_TRIANGLE_FAN) glVertex2f(0 0 0 0) glVertex2f(0 3 0 3) glVertex2f(0 3 -0 3) glVertex2f(-0 3 0 3) glVertex2f(-0 3 -0 3) glEnd() def drawTriangle(): glBegin(GL_TRIANGLES) glVertex2f(0 5 0 0) glVertex2f(0 0 0 5) glVertex2f(-0 5 0 0) glEnd() def drawCircle(): glutSolidSphere(0 5 30 30) def drawSquare(): glBegin(GL_POLYGON) glVertex2f(0 5 0 5) glVertex2f(-0 5 0 5) glVertex2f(-0 5 -0 5) glVertex2f(0 5 -0 5) glEnd() def mouseHandle(button state x y): if(button == GLUT_LEFT_BUTTON and x < 150 and y < 170): t=1 glutPostRedisplay() print "1: x=" x " y=" y "\n" elif(button == GLUT_LEFT_BUTTON and x < 150 and 170 < y and y < 280): t=2 glutPostRedisplay() elif(button == GLUT_LEFT_BUTTON and x < 150 and 345 < y and y < 451): t=3 glutPostRedisplay() elif(button == GLUT_LEFT_BUTTON and x < 150 and 525 < y and y < 578): t=4 glutPostRedisplay() else: glutPostRedisplay() glutInit('') glutMouseFunc(mouseHandle) glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB) glutInitWindowSize(800 600) glutCreateWindow('Hello GLUT') glutDisplayFunc(display) init() glutMainLoop() ```` | Ok after some dwelling I found out how to solve it I must have moved the `glutMouseFunc` call after `glutDisplayFunc` just like below: ````glutInit('') glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB) glutInitWindowSize(800 600) glutCreateWindow('Hello GLUT') glutDisplayFunc(display) glutMouseFunc(mouseHandle) init() glutMainLoop() ```` |
how to make pytesser (Tesseract) work? I am trying to make pytesser (downloadable <a href="https://code google com/p/pytesser/" rel="nofollow">here</a>) work on my mac OS but I do not succeed I installed Tesseract PIL and all the dependencies I unzipped pytesser in my python lib folder and modified the script file into `__init__ py` in the init file I modified the path to the `tesseract exe` file as suggested <a href="http://aehwamong tistory com/91" rel="nofollow">here</a> and <a href="http://stackoverflow com/questions/15567141/installing-pytesser">here</a> that is: ````tesseract_exe_name = 'my lib path/pytesser/tesseract' # Name of executable to be called at command line ```` that is what I get as error: ````Traceback (most recent call last): File "<pyshell#50>" line 1 in <module> print image_to_string(picz) File "/Library/Frameworks/Python framework/Versions/2 7/lib/python2 7/pytesser/__init__ py" line 31 in image_to_string call_tesseract(scratch_image_name scratch_text_name_root) File "/Library/Frameworks/Python framework/Versions/2 7/lib/python2 7/pytesser/__init__ py" line 21 in call_tesseract proc = subprocess Popen(args) File "/Library/Frameworks/Python framework/Versions/2 7/lib/python2 7/subprocess py" line 679 in __init__ errread errwrite) File "/Library/Frameworks/Python framework/Versions/2 7/lib/python2 7/subprocess py" line 1228 in _execute_child raise child_exception OSError: [Errno 8] Exec format error ```` it seems that the module does not manage to run the exe file I tried to change the path add the extension exe but I always get the same error | Several solutions for a python tesseract wrapper: <strong>Python-Tesseract</strong>: First of get homebrew and brew install python then `easy_install` <a href="https://bitbucket org/3togo/python-tesseract/downloads/python_tesseract-0 9 1-py2 7-macosx-10 10-x86_64 egg" rel="nofollow">https://bitbucket org/3togo/python-tesseract/downloads/python_tesseract-0 9 1-py2 7-macosx-10 10-x86_64 egg</a> source: <a href="https://code google com/p/python-tesseract/wiki/HowToCompileForHomebrewMac" rel="nofollow">https://code google com/p/python-tesseract/wiki/HowToCompileForHomebrewMac</a> <strong>pytesseract</strong>: This what I was using previously before getting python-tesseract `pip install pytesseract` Then you have to go to `/usr/local/lib/python2 7/site-packages` and go to pytesseract then `pytesseract py` Change the file path in the python script to where tesseract is located on your computer |
What language was learned by Geza Vermes when he was a child? | null |
Django: Query by pk of all models I need to query across multiple tables by primary_keys which are unique (uuids) My idea was to use model inheritance for querying all models at once I have got a BaseItem and all other models are subclasses of this BaseItem model Now my query does not return what I expected and needed Here is a sample model: ````from django db import models from django contrib auth models import User class BaseRev(models Model): rev_id = models CharField(max_length=32 primary_key=True) item_id = models CharField(max_length=32 blank=True null=True) creation_date = models DateTimeField() class NamedRev(BaseRev): name = models CharField(max_length=64 blank=True null=True) description = models CharField(max_length=256 blank=True null=True) creator = models ForeignKey('UserProfile' related_name='namedrev_creator' blank=True null=True) ```` When I create a NamedRev with pk = "1234" and make a query like ````BaseRev objects get(pk="1234") ```` I get a result with the correct pk but it is of type BaseItem According to the docs that is the correct behaviour as the the rev_id field does only exist in the BaseRev table and the addional fields for the NamedRev in the NamedRev table How do I get "proper" and complete (with all fields) objects of type NamedRev for the given query? Cheers Jan | What if you set your parent class to be abstract: ````class BaseRev(models Model): rev_id = models CharField(max_length=32 primary_key=True) item_id = models CharField(max_length=32 blank=True null=True) creation_date = models DateTimeField() class Meta: abstract = True ```` |
How to store tree structure in sql? Here is my schema using sqlite I am not sure if this is a good way to create tree structure in sql as I have to traverse many time to obtain the entire tree as oppose to extracting the entire tree base on top comment and construct the tree in python Can someone give me some suggestions ````BEGIN; CREATE TABLE "tree_comment" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT "text" text NOT NULL "parent_id" integer NULL REFERENCES "tree_comment" ("id")); CREATE INDEX "tree_comment_6be37982" ON "tree_comment" ("parent_id"); COMMIT; ```` | Since the data structure does not have a natural representation in relational databases there are several ways to store them depending on the use case and the database In <a href="http://www slideshare net/billkarwin/sql-antipatterns-strike-back?src=embed" rel="nofollow">this presentation</a> from slide 48 there are two methods described My favourite one is <a href="https://bojanz wordpress com/2014/04/25/storing-hierarchical-data-materialized-path/" rel="nofollow">materialized path</a> which is very simple and capable Hope it helps |
Library for sending HTTP requests in file-like objects I am currently using Python <a href="http://docs python-requests org/en/latest/" rel="nofollow">requests</a> for HTTP requests but due to limitations in the API I am unable to keep using the library I need a library which will allow me to write the request body in a streaming file-like fashion as the data which I will be sending will not all be immediately available plus I would like to save as much memory as possible when making a request Is there an easy-to-use library which will allow me to send a PUT request like this: ````request = HTTPRequest() request headers['content-type'] = 'application/octet-stream' # etc request connect() # send body with open('myfile' 'rb') as f: while True: chunk = f read(64 * 1024) request body write(chunk) if not len(chunk) == 64 * 1024: break # finish request close() ```` More specifically I have one thread to work with Using this thread I receive callbacks as I receive a stream over the network Essentially those callbacks look like this: ````class MyListener(Listener): def on_stream_start(stream_name): pass def on_stream_chunk(chunk): pass def on_stream_end(total_size): pass ```` I need to essentially create my upload request in the `on_stream_start` method upload chunks in the `on_stream_chunk` method then finish the upload in the `on_stream_end` method Thus I need a library which supports a method like `write(chunk)` to be able to do something similar to the following: ````class MyListener(Listener): request = None def on_stream_start(stream_name): request = RequestObject(get_url() "PUT") request headers content_type = "application/octet-stream" # def on_stream_chunk(chunk): request write_body(chunk sha256(chunk) hexdigest()) def on_stream_end(total_size): request close() ```` The `requests` library supports file-like objects and generators for <them>reading</them> but nothing for <them>writing</them> out the requests: pull instead of push Is there a library which will allow me to push data up the line to the server? | As far as I can tell `httplib`'s <a href="http://docs python org/2/library/httplib html#httpconnection-objects" rel="nofollow">`HTTPConnection request`</a> does exactly what you want I tracked down the function which actually does the sending and as long as you are passing a file-like object (and not a string) it chunks it up: ````Definition: httplib HTTPConnection send(self data) Source: def send(self data): """Send `data' to the server """ if self sock is None: if self auto_open: self connect() else: raise NotConnected() if self debuglevel > 0: print "send:" repr(data) blocksize = 8192 if hasattr(data 'read') and not isinstance(data array): if self debuglevel > 0: print "sendIng a read()able" ## {{{ HERE IS THE CHUCKING LOGIC datablock = data read(blocksize) while datablock: self sock sendall(datablock) datablock = data read(blocksize) ## }}} else: self sock sendall(data) ```` |
Numpy avoid loop in 3d array difference nested summation I have a simple problem for Numpy: I have 3d coordinates and I want to compute the overlap between two distinct configurations with the following function ````def Overlap(rt r0 a): s=0 for i in range(len(rt)): s+=(( pl norm(r0[i]-rt axis=1) <=a) astype('int')) sum() return s` ```` Where `rt` and `r0` represent two `m by 3` tables the configurations Practically it computes the distance between a vector in the first configuration and any other vector in the second checks for a threshold value `a` and returns the total sum after a loop over all the positions Is there a smart way to avoid the explicit for loop? I have the feeling that the complexity cannot really be changed but there is maybe a way to avoid the slowness of the native for construct | How about the following: ````from scipy spatial distance import cdist import numpy as np overlap = np sum(cdist(rt r0) <= a) ```` When `m` is 1000 on my machine this is about 9x faster It is much faster for small arrays |
Change resolution of half-degree netCDF to quarter degree netCDF using nco tools I can change the resolution of a netCDF file to a coarser one by doing something like this: ````ncks --dmn lon 0 1384 5 --dmn lat 0 583 4 original nc reduced nc ```` How do I go the other way? I e change resolution of coarser scale netCDF to finer scale? | Increasing resolution with NCO requires <a href="http://nco sf net/nco html#regrid" rel="nofollow">regridding</a> available in NCO 4 5 1+ This currently requires you have a SCRIP/ESMF-compliant mapfile which can be generated from SCRIP-compliant <a href="http://nco sf net/nco html#grid" rel="nofollow">gridfiles</a> with e g ESMF_RegridWeightGen You would need to install ESMF a simple package on many free OS's e g on MacPorts 'port install esmf' |
python and mysql connector requires quoting of unsigned int I am using mysql connector 1 0 9 and Python 3 2 This query fails due to a syntax error (mysql connector throws ProgrammingError the specific MySQL error is just "there is a syntax error to the right of "%(IP)s AND DATE_SUB(NOW() INTERVAL 1 HOUR) < accessed": ````SELECT COUNT(*) FROM bad_ip_logins WHERE IP = %(IP)s AND DATE_SUB(NOW() INTERVAL 1 HOUR) < accessed ```` But if I quote the variable IP it works: ````SELECT COUNT(*) FROM bad_ip_logins WHERE IP = '%(IP)s' AND DATE_SUB(NOW() INTERVAL 1 HOUR) < accessed ```` In context: ````IP = 1249764151 # IP converted to an int conn = mysql connector connect(db_params) curs = conn cursor() query = "SELECT COUNT(*) FROM bad_ip_logins WHERE IP = %(IP)s AND DATE_SUB(NOW() INTERVAL 1 HOUR) < accessed" params = {'IP' IP} curs execute(query params) ```` My understanding is that you never have to quote variables for a prepared statement (and this is true for every other query in my code even ones that access the IP variable on this table) Why do I need to quote it in this single instance and nowhere else? If this is not doing a prepared statement I would be interested in hearing about that as well I was not able to inject anything with this - was it just quoting it in such a way as to prevent that? If it matters this is the table description: ````+----------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | ----------+------------------+------+-----+---------+-------+ | IP | int(10) unsigned | YES | | NULL | | | user_id | int(11) | YES | | NULL | | | accessed | datetime | YES | | NULL | | ----------+------------------+------+-----+---------+-------+ ```` | Do not use string interpolation Leave the SQL parameter to the database adapter: ````cursor execute('''\ SELECT COUNT(*) FROM bad_ip_logins WHERE IP = %s AND DATE_SUB(NOW() INTERVAL 1 HOUR) < accessed''' (ip )) ```` Here we pass the parameter `ip` in to the `execute()` call as a separate parameter (in a tuple to make it a sequence) and the database adapter will take care of proper quoting filling in the `%s` placeholder |
Eclipse missing requirements during Eclipse package installation I am trying to install PyDev on my Ubuntu 12 4 04 <a href="http://codingtip blogspot it/2012/04/how-to-install-eclipse-and-pydev-for html" rel="nofollow">following these instructions</a> When I select the PyDev packages among the Eclipse package list Eclipse tells me: <blockquote> Cannot complete the install because one or more required items could not be found Software being installed: Pydev Mylyn Integration 0 4 0 (org python pydev mylyn feature feature group 0 4 0) Missing requirement: Pydev Mylyn Integration 0 4 0 (org python pydev mylyn feature feature group 0 4 0) requires 'org eclipse mylyn context core 0 0 0' but it could not be found </blockquote> Do you know how to solve this? <strong>EDIT:</strong> I selected the "Use all the available download websites" option and it started the download But it got new errors: <blockquote> An error occurred while collecting items to be installed session context was:(profile=PlatformProfile phase=org eclipse equinox internal p2 engine phases Collect operand= action=) Problems downloading artifact: osgi bundle com python pydev 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile8427466212879929206 jar An error occurred while processing the signatures for the file: /tmp/signatureFile8427466212879929206 jar Problems downloading artifact: osgi bundle com python pydev analysis 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile6225334791154145595 jar An error occurred while processing the signatures for the file: /tmp/signatureFile6225334791154145595 jar Problems downloading artifact: osgi bundle com python pydev codecompletion 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile1625250666117296864 jar An error occurred while processing the signatures for the file: /tmp/signatureFile1625250666117296864 jar Problems downloading artifact: osgi bundle com python pydev debug 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile5513082187501911158 jar An error occurred while processing the signatures for the file: /tmp/signatureFile5513082187501911158 jar Problems downloading artifact: osgi bundle com python pydev fastparser 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile605486589496460440 jar An error occurred while processing the signatures for the file: /tmp/signatureFile605486589496460440 jar Problems downloading artifact: osgi bundle com python pydev refactoring 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile144672797460509165 jar An error occurred while processing the signatures for the file: /tmp/signatureFile144672797460509165 jar Problems downloading artifact: osgi bundle org python pydev 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile6260050602791980202 jar An error occurred while processing the signatures for the file: /tmp/signatureFile6260050602791980202 jar Problems downloading artifact: osgi bundle org python pydev ast 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile7925013072583879479 jar An error occurred while processing the signatures for the file: /tmp/signatureFile7925013072583879479 jar Problems downloading artifact: osgi bundle org python pydev core 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile6502114115388448316 jar An error occurred while processing the signatures for the file: /tmp/signatureFile6502114115388448316 jar Problems downloading artifact: osgi bundle org python pydev customizations 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile646114539488211012 jar An error occurred while processing the signatures for the file: /tmp/signatureFile646114539488211012 jar Problems downloading artifact: osgi bundle org python pydev debug 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile5554172731601599412 jar An error occurred while processing the signatures for the file: /tmp/signatureFile5554172731601599412 jar Problems downloading artifact: osgi bundle org python pydev django 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile2081112544030499068 jar An error occurred while processing the signatures for the file: /tmp/signatureFile2081112544030499068 jar Problems downloading artifact: org eclipse update feature org python pydev feature 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile8761783145012931325 jar An error occurred while processing the signatures for the file: /tmp/signatureFile8761783145012931325 jar Problems downloading artifact: osgi bundle org python pydev help 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile4140872971434327198 jar An error occurred while processing the signatures for the file: /tmp/signatureFile4140872971434327198 jar Problems downloading artifact: osgi bundle org python pydev jython 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile1472620833557689910 jar An error occurred while processing the signatures for the file: /tmp/signatureFile1472620833557689910 jar Problems downloading artifact: osgi bundle org python pydev mylyn 0 4 0 Error reading signed content:/tmp/signatureFile6287310346304363477 jar An error occurred while processing the signatures for the file: /tmp/signatureFile6287310346304363477 jar Problems downloading artifact: org eclipse update feature org python pydev mylyn feature 0 4 0 Error reading signed content:/tmp/signatureFile2932536020816821753 jar An error occurred while processing the signatures for the file: /tmp/signatureFile2932536020816821753 jar Problems downloading artifact: osgi bundle org python pydev parser 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile2860560593863228850 jar An error occurred while processing the signatures for the file: /tmp/signatureFile2860560593863228850 jar Problems downloading artifact: osgi bundle org python pydev refactoring 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile5444565411686316987 jar An error occurred while processing the signatures for the file: /tmp/signatureFile5444565411686316987 jar Problems downloading artifact: osgi bundle org python pydev shared_core 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile644095121866711816 jar An error occurred while processing the signatures for the file: /tmp/signatureFile644095121866711816 jar Problems downloading artifact: osgi bundle org python pydev shared_interactive_console 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile708235382114637181 jar An error occurred while processing the signatures for the file: /tmp/signatureFile708235382114637181 jar Problems downloading artifact: osgi bundle org python pydev shared_ui 3 5 0 201405201709 Error reading signed content:/tmp/signatureFile8183417620218922292 jar An error occurred while processing the signatures for the file: /tmp/signatureFile8183417620218922292 jar </blockquote> | It occurs because you are using probably older version of eclipse like Helios I got the same problem But when I switched to the KEPLER version the error vanished I hope it helps!! |
Time complexity of a huge list in python 2 7 I have a list which has approximately 177071007 items and i am trying to perform the following operations a) get the first and last occurance of a unique item in the list b) the number of occurances ````def parse_data(file op_file_test): ins = csv reader(open(file 'rb') delimiter = '\t') pc = list() rd = list() deltas = list() reoccurance = list() try: for row in ins: pc append(int(row[0])) rd append(int(row[1])) except: print row pass unique_pc = set(pc) unique_pc = list(unique_pc) print "closing file" #takes a long time from here! for a in range(0 len(unique_pc)): index_first_occurance = pc index(unique_pc[a]) index_last_occurance = len(pc) - 1 - pc[::-1] index(unique_pc[a]) delta_rd = rd[index_last_occurance] - rd[index_first_occurance] deltas append(int(delta_rd)) reoccurance append(pc count(unique_pc[a])) print unique_pc[a] delta_rd reoccurance[a] print "printing to file" map_file = open(op_file_test 'a') for a in range(0 len(unique_pc)): print >>map_file "%d %d %d" % (unique_pc[a] deltas[a] reoccurance) map_file close() ```` However the complexity is in the order of O(n) Would there be a possibility to make the for loop 'run fast' by that i mean do you think yielding would make it fast? or is there any other way? unfortunately i do not have numpy | Try replacing list by dicts lookup in a dict is <them>much</them> faster than in a long list That could be something like this: ````def parse_data(file op_file_test): ins = csv reader(open(file 'rb') delimiter = '\t') # Dict of pc > [rd first occurence rd last occurence list of occurences] occurences = {} for i in range(0 len(ins)): row = ins[i] try: pc = int(row[0]) rd = int(row[1]) except: print row continue if pc not in occurences: occurences[pc] = [rd rd i] else: occurences[pc][1] = rd occurences[pc] append(i) # (Remove the sorted is you do not need them sorted but need them faster) for value in sorted(occurences keys()): print "value: %d delta: %d occurences: %s" % ( value occurences[value][1] - occurences[value][0] " " join(occurences[value][2:]) ```` |
Django Link to class based views url I created with django a page where I can delete my blog articles using the <a href="https://docs djangoproject com/en/1 8/topics/class-based-views/" rel="nofollow">class based views</a> I want to add link to each article but I am struggling to do it <strong>here is the code to link to the class based view</strong> <strong>views py</strong> ````user_delete_article = Article objects filter(user=request user) ```` <strong>template html</strong> ````{% for article in user_delete_article %} <p><a class="readmore" href="{% url "article views DeleteView" article id %}">{{ article titre }}</a></p> {% endfor %} ```` <strong>urls py</strong> ````url(r'^delete/(?P<id>\d+)/$' DeleteView as_view() name="DeleteView") ```` How can I make this work? | Assuming this is django 1 8 ```` <a href="{% url "DeleteView" id=article id %}"> ```` |
Weird pdfs from Generalised Extreme Value (GEV) Maximum Likelihood fitted data I am doing some data analysis involving fitting datasets to a Generalised Extreme Value (GEV) distribution but I am getting some weird results Here is what I am doing: ````from scipy stats import genextreme as gev import numpy data = [1 47 0 02 0 3 0 01 0 01 0 02 0 02 0 12 0 38 0 02 0 15 0 01 0 3 0 24 0 01 0 05 0 01 0 0 0 06 0 01 0 01 0 0 0 05 0 0 0 09 0 03 0 22 0 0 0 1 0 0] x = numpy linspace(0 2 20) pdf = gev pdf(x *gev fit(data)) print(pdf) ```` And the output: ````array([ 5 64759709e+05 2 41090345e+00 1 16591714e+00 7 60085002e-01 5 60415578e-01 4 42145248e-01 3 64144425e-01 3 08947114e-01 2 67889183e-01 2 36190826e-01 2 11002185e-01 1 90520108e-01 1 73548832e-01 1 59264573e-01 1 47081601e-01 1 36572220e-01 1 27416958e-01 1 19372442e-01 1 12250072e-01 1 05901466e-01 1 00208313e-01 9 50751375e-02 9 04240603e-02 8 61909342e-02 8 23224528e-02 7 87739599e-02 7 55077677e-02 7 24918532e-02 6 96988348e-02 6 71051638e-02 6 46904782e-02 6 24370827e-02 6 03295277e-02 5 83542648e-02 5 64993643e-02 5 47542808e-02 5 31096590e-02 5 15571710e-02 5 00893793e-02 4 86996213e-02 4 73819114e-02 4 61308575e-02 4 49415891e-02 4 38096962e-02 4 27311763e-02 4 17023886e-02 4 07200140e-02 3 97810205e-02 3 88826331e-02 3 80223072e-02]) ```` The problem is that the first value is huge totally distorting all the results its show quite clearly in a plot: <img src="http://i stack imgur com/PixRu png" alt="pdf"> I have experimented with other data and random samples and in some cases it works The first value in my dataset is significantly higher than the rest but it is a valid value so I cannot just drop it Does anyone have any idea why this is happening? <strong>Update</strong> Here is another example showing the problem much more clearly: ````In [1]: from scipy stats import genextreme as gev kstest In [2]: data = [0 01 0 0 0 28 0 0 0 0 0 0 0 01 0 0 0 0 0 13 0 07 0 03 0 01 0 42 0 11 0 0 0 0 0 0 0 0 0 25 0 0 0 0 0 26 1 32 0 06 0 02 1 57 0 07 1 56 0 04] In [3]: fit = gev fit(data) In [4]: kstest(data 'genextreme' fit) Out[4]: (0 48015007915450658 6 966510064376763e-07) In [5]: x = linspace(0 2 200) In [6]: plot(x gev pdf(x *fit)) Out[6]: [<matplotlib lines Line2D at 0x97590f0>] In [7]: hist(data) ```` Note specifically line 4 shows a p-value of about 7e-7 way below what is normally considered acceptable Here is the plot produced: <img src="http://i stack imgur com/xMGNX png" alt="2nd Figure"> | First I think you may want to keep you location parameter fixed at `0` Second you got zeros in your data the resulting fit may have `+inf` `pdf` at `x=0` e g for the GEV fit or for the Weibull fit Therefore the fit is actually correct but when you plot the `pdf` (including `x=0`) the resulting plot is distorted Third I really think `scipy` should drop the support for `x=0` for a bunch of distributions such as `Weibull` For `x=0` `R` gives a nice warning of `Error in fitdistr(data "weibull") : Weibull values must be > 0` that is helpful ````In [103]: p=ss genextreme fit(data floc=0) ss genextreme fit(data floc=0) Out[103]: (-1 372872096699608 0 0 011680600795499299) In [104]: plt hist(data bins=20 normed=True alpha=0 7 label='Data') plt plot(np linspace(5e-3 1 6 100) ss genextreme pdf(np linspace(5e-3 1 6 100) p[0] p[1] p[2]) 'r--' label='GEV Fit') plt legend(loc='upper right') plt savefig('T1 png') ```` <img src="http://i stack imgur com/6dU3y png" alt="enter image description here"> ````In [105]: p=ss expon fit(data floc=0) ss expon fit(data floc=0) Out[105]: (0 0 14838807003769505) In [106]: plt hist(data bins=20 normed=True alpha=0 7 label='Data') plt plot(np linspace(0 1 6 100) ss expon pdf(np linspace(0 1 6 100) p[0] p[1]) 'r--' label='Expon Fit') plt legend(loc='upper right') plt savefig('T2 png') ```` <img src="http://i stack imgur com/Ude8k png" alt="enter image description here"> ````In [107]: p=ss weibull_min fit(data[data!=0] floc=0) ss weibull_min fit(data[data!=0] floc=0) Out[107]: (0 67366030738733995 0 0 10535422201164378) In [108]: plt hist(data[data!=0] bins=20 normed=True alpha=0 7 label='Data') plt plot(np linspace(5e-3 1 6 100) ss weibull_min pdf(np linspace(5e-3 1 6 100) p[0] p[1] p[2]) 'r--' label='Weibull_Min Fit') plt legend(loc='upper right') plt savefig('T3 png') ```` <img src="http://i stack imgur com/CUZ3o png" alt="enter image description here"> <hr> <h1>edit</h1> Your second data (which contains even more `0`'s )is a good example when MLE fit involving location parameter can become very challenging especially potentially with a lot of float point overflow/underflow involved: ````In [122]: #fit with location parameter fixed scanning loc parameter from 1e-8 to 1e1 L=[] #stores the Log-likelihood P=[] #stores the p value of K-S test for LC in np linspace(-8 1 200): fit = gev fit(data floc=10**LC) L append(np log(gev pdf(data *fit)) sum()) P append(kstest(data 'genextreme' fit)[1]) L=np array(L) P=np array(P) In [123]: #plot log likelihood a lot of overflow/underflow issues! (see the zigzag line?) plt plot(np linspace(-8 1 200) L '-') plt ylabel('Log-Likelihood') plt xlabel('$log_{10}($'+'location parameter'+'$)$') ```` <img src="http://i stack imgur com/3A4tg png" alt="enter image description here"> ````In [124]: #plot p-value plt plot(np linspace(-8 1 200) np log10(P) '-') plt ylabel('$log_{10}($'+'K-S test P value'+'$)$') plt xlabel('$log_{10}($'+'location parameter'+'$)$') Out[124]: <matplotlib text Text at 0x107e3050> ```` <img src="http://i stack imgur com/1YSXu png" alt="enter image description here"> ````In [128]: #The best fit between with location paramter between 1e-8 to 1e1 has the loglikelihood of 515 18 np linspace(-8 1 200)[L argmax()] fit = gev fit(data floc=10**(np linspace(-8 1 200)[L argmax()])) np log(gev pdf(data *fit)) sum() Out[128]: 515 17663678368604 In [129]: #The simple MLE fit is clearly bad loglikelihood is -inf fit0 = gev fit(data) np log(gev pdf(data *fit0)) sum() Out[129]: -inf In [133]: #plot the fit x = np linspace(0 005 2 200) plt plot(x gev pdf(x *fit)) plt hist(data normed=True alpha=0 6 bins=20) Out[133]: (array([ 8 91719745 0 8492569 0 1 27388535 0 0 42462845 0 0 0 0 0 0 0 0 0 0 0 42462845 0 0 0 8492569 ]) array([ 0 0 0785 0 157 0 2355 0 314 0 3925 0 471 0 5495 0 628 0 7065 0 785 0 8635 0 942 1 0205 1 099 1 1775 1 256 1 3345 1 413 1 4915 1 57 ]) <a list of 20 Patch objects>) ```` <img src="http://i stack imgur com/4lXte png" alt="enter image description here"> <hr> <h1>Edit goodness of fit test for GEV</h1> A side note on KS test You are testing the goodness-of-fit to a GEV with its parameter ESTIMATED FROM THE DATA itself In such a case the p value is invalid see: itl nist gov/div898/handbook/eda/section3/eda35g htm There seems to be a lot of studies on the topic of goodness-of-fit test for GEV I have not found any available implementations for those yet <a href="http://onlinelibrary wiley com/doi/10 1029/98WR02364/abstract" rel="nofollow">http://onlinelibrary wiley com/doi/10 1029/98WR02364/abstract</a> <a href="http://onlinelibrary wiley com/doi/10 1029/91WR00077/abstract" rel="nofollow">http://onlinelibrary wiley com/doi/10 1029/91WR00077/abstract</a> <a href="http://www idrologia polito it/~laio/articoli/16-WRR%20EDFtest pdf" rel="nofollow">http://www idrologia polito it/~laio/articoli/16-WRR%20EDFtest pdf</a> |
How to make an object of a class extending Enum I have the following Python class ````from enum import Enum class Color(Enum): red = 1 blue = 2 green = 3 ```` But when I try to create an object it `color = Color()` it throws an error telling `TypeError: __call__() takes at least 2 arguments (1 given)` What is the other expected argument | Per the docstring in the <a href="https://hg python org/releasing/3 4/file/8671f89107c8/Lib/enum py" rel="nofollow">source code</a> (note that this method is defined on the metaclass `EnumMeta`): <blockquote> [`__call__`] is used both when an enum class is given a value to match to an enumeration member (i e `Color(3)`) and for the functional API (i e `Color = Enum('Color' names='red green blue')`) </blockquote> The required positional argument `value` is either one of the values of an existing enumerator or the name of a new one This is covered in the documentation <a href="https://docs python org/3/library/enum html#programmatic-access-to-enumeration-members-and-their-attributes" rel="nofollow">here</a> for the former and <a href="https://docs python org/3/library/enum html#functional-api" rel="nofollow">here</a> for the latter |
Simple syntax for bringing a list element to the front in python? I have an array with a set of elements I would like to bring a given element to the front but otherwise leave the order unchanged Do folks have suggestions as to the cleanest syntax for this? This is the best I have been able to come up with but it seems like bad form to have an N log N operation when an N operation could do ```` mylist = sorted(mylist key=lambda x: x == targetvalue reverse=True) ```` Cheers /YGA | To bring (for example) the 5th element to the front use: ````mylist insert(0 mylist pop(5)) ```` |
Python 3: When to use dict when list of tuples? I have `id`s of jail prisoners for example Each prisoner has a name I know how dictionarys work and I know how tuples work and I know how lists work but sometimes I see a dictionary being used and sometimes a list of tuples Which one should I use in my case? ````d = { 1: "Mike" 2: "Bob" 3: "Tom" } ```` vs ````l = [ (1 "Mike") (2 "Bob") (3 "Tom") ] ```` And to generalize the question: WHEN should I use a dict and when should I use a list of tuples what are the benefits of one? | In your case I would use a dictionary There are several reasons you might want to consider using one - <strong>The dictionary allows for usage of its API to manipulate keys</strong> and values inside it something that would require more code to with a list of tuples For instance consider this: To get the names of the prisoners using the dictionary you just do this: ````d values() ```` To do the same thing with the list of tuples you would need to do this: ````names = [] for tup in l: names append(tup[1]) ```` - <strong>The dictionary values are mutable</strong> meaning they can be allowed to be changed <strong>You can not do the same thing with a tuple</strong> (it is <strong>immutable</strong>) E g ````d[1] = 'Fotis' ```` To achieve the same thing with a list of tuples you would have to substitute the tuple that you want to manipulate with a new one E g ````l[1] = (2 'Max') ```` |
When was the International Photography Hall of Fame relocated? | 2013 |
SSLError: [Errno 1] _ssl c:510: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed I am trying to install openstack and ovsVapp in my server Everything goes well during initial stage Later got an error in n-cpu saying SSLError: [Errno 1] _ssl c:510: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed And one more error saying in n-cpu /usr/local/bin/nova-compute --config-file /etc/nova/nova conf No handlers could be found for logger "oslo_config cfg" | Edit the file `/usr/local/lib/python2 7/dist-packages/oslo_vmware/service py` at line 141 comment out the line saying `self verify = cacert if cacert else not insecure` and add one extra line `self verify = False` i e ````#self verify = cacert if cacert else not insecure self verify = False ```` and re run the n-cpu again Or execute ` /unstack sh` and ` /stack sh` for fresh setup |
%run vs copy/paste discrepancy in function containing global commands in python Below is an import function for reading in a csv file into python I use the global command to create a global variable "data" and read the csv file into the "data" variable for the user to use If I copy/paste the code into my client it works just fine However when I "read" the file containing the code in with %run the function will run but the "data" global variable will not be created (e g I call "data" and get an error) Note: I know this code is not polished yet but I am not sure why I am having the problem I am having ````def dat(): import pandas as pd file = raw_input('Enter your csv file: ') global data try: data = pd read_csv(file) print "\nI've created the following variables for you: 'data' will contain your datafile that we just imported " except: print "I am so sorry but I have no idea what just went wrong " ```` some of the data in the csv file look like this: ````Les1 Les2 Les3 2 4 4 3 3 3 1 5 3 2 4 3 ```` | <strong>test csv</strong> ````Les1 Les2 Les3 2 4 4 3 3 3 1 5 3 2 4 3 ```` Code ````import pandas as pd def dat(): file = raw_input('Enter your csv file: ') global data try: data = pd read_csv(file) print data print "\nI've created the following variables for you: 'data' will contain your datafile that we just imported " except: print "I am so sorry but I have no idea what just went wrong " dat() ```` Output: ````Enter your csv file: test csv Les1 Les2 Les3 0 2 4 4 1 3 3 3 2 1 5 3 3 2 4 3 I have created the following variables for you: 'data' will contain your datafile that we just imported ```` |
Which individual added a humanist view into the Middle Ages? | null |
How do I sum tuples in a list where the first value is the same? I have a list of stocks and positions as tuples Positive for buy negative for sell Example: `p = [('AAPL' 50) ('AAPL' -50) ('RY' 100) ('RY' -43)]` How can I sum the positions of stocks to get the current holdings? `Result = [(AAPL 0) (RY 57)]` | How about this? You can read about <a href="http://docs python org/2/library/collections html#collections defaultdict">`collections defaultdict`</a> ````>>> from collections import defaultdict >>> testDict = defaultdict(int) >>> p = [('AAPL' 50) ('AAPL' -50) ('RY' 100) ('RY' -43)] >>> for key val in p: testDict[key] = val >>> testDict items() [('AAPL' 0) ('RY' 57)] ```` |
how to do a reverse on a url with primary key in django I have the following url entry for my app: ````url(r'^(?P<pk>\d+)/(?P<action>add|edit)/type/$' 'customer views edit' name='customer-edit') ```` I want to post to this url with a reverse When I do the following I get the error NoReverseMatch: ````self client post(reverse('customer-edit') {'something:'something'} follow=True) ```` This is the full error: NoReverseMatch: Reverse for 'customer-edit' with arguments '()' and keyword arguments '{}' not found Do I need to pass args or kwargs to the reverse? If so what would they look like to match the url above? | To pass `args` to an url you can pass a variable named `args` of type `tuple` to `reverse`: ````self client post(reverse('customer-edit' args=(1 'add' )) {'something:'something'} follow=True) ```` another problem is that the `dict` has a `Syntax Error` ````self client post(reverse('customer-edit' args=(1 'add' )) {'something' : 'something'} follow=True) ```` Hope this helps you! |
Save numpy array as binary to read from FORTRAN I have a series of numpy array i need to save these numpy array in a loop as a raw binary float32 (without any header information) which need to be read from FORTRAN ````import numpy as np f=open('test bin' 'wb+') for i in range(0 10): np_data=np random rand(10 5) fortran_data=np asfortranarray(np_data 'float32') fortran_data tofile(f) f close() ```` Is this the correct way so that I can read this binary file created in python from FORTRAN correctly Your suggestions will be highly apprecitaed | You will need the meta data of the array to read it in FORTRAN This website (<a href="https://scipy github io/old-wiki/pages/Cookbook/InputOutput html" rel="nofollow">https://scipy github io/old-wiki/pages/Cookbook/InputOutput html</a>) has some information on using libnpy to write and an example code fex f95 to read the binary file |
Pass python objects to ng-init angularjs in my views py i have ````TaskNameList = Task objects all() ```` this is my detail html ```` 77 <script src="{% static "angularjs-1 4 3/angular min js" %}"></script> 78 79 <div ng-app=""> 80 <div ng-init="friends = {{ TaskNameList }}"> 81 </div> 82 <label>Search: <input ng-model="searchText"></label> 83 <table id="searchTextResults"> 84 <tr><th>Name</th> 85 <tr ng-repeat="friend in friends | filter:searchText"> 86 <td>{$ friend name $}</td> 87 </tr> 88 </div> 89 </table> ```` i think I have a problem passing values from python to ng-int | You need to pass <them>TaskNameList</them> as JSON from your view to your template In your code <them>TaskNameList</them> is django's query and in template it will become string representation of python list of classes (<them>Task</them> model instances) If <them>Task</them> model has only JSON serializable attributes you should be able to do something like this: ````TaskNameList = json dumps(list(Task objects all() values())) ```` Anyway I think it is bad idea It will be much better to create REST API endpoint for <them>Task</them> model and then access it using angular's ng-resource |
Python script through socket Hello I have a socket setup and I want to send python commands to be executed on the second computer So far I can send the command `s send('print "hello world"')` and with `m recv(1024)` on the second machine Can I do something like `x = m recv(1024)` and then on the next line just an `x` to execute what has been received? Please note I have the sockets setup and running with one machine as the server and one as the client But I have never been sure if I have been using `recv` and `send` correct because I have had no way of testing them Thanks | If you use eval you can execute python code as a string: ````eval('print "Hello world"') ```` This will print Hello world To directly print the input in Python 3 (<strong>!</strong>): ````eval(m recv(1024) decode('utf-8')) ```` Python 2: ````exec(m recv(1024)) ```` <strong>!</strong> Like Peter Wood said in the comment you have to be careful with what you receive; everybody that has access to your server can send <them>any</them> code they want they could create files just by sending code Make sure only <strong>you</strong> have access to it and to be on the safe side make a blacklist of functions or even better a whitelist |
Cannot get response from returned Request in Scrapy I just want to pass url to another parser It did not work as shown in the doc so I have reduced my code to the minimum and still nothing Tried with yield also ````# -*- coding: utf-8 -*- import scrapy import cfscrape from scrapy spiders import Spider import json rez=[] class LinkbaseSpider(Spider): name = "mine" allowed_domains = ["127 0 0 1"] start_urls = ( 'file://127 0 0 1/home/link html' ) def parse(self response): request= scrapy Request("http://www google com" callback=self parse2) return request def parse2(self response): self logger info("Visited %s" response url) print("00000000000000000000000") ```` | Assuming your indentation is actually correct there is an `OffSiteMiddleware` that filters your requests based on `allowed_domains` In this case `google com` is not allowed because the `allowed_domains` are set to `["127 0 0 1"]` You can workaround it by setting <a href="http://doc scrapy org/en/latest/topics/request-response html#scrapy http Request" rel="nofollow">`dont_filter=True`</a> when instantiating a `Request`: ````def parse(self response): return scrapy Request("http://www google com" callback=self parse2 dont_filter=True) ```` FYI in case you are interested here is how the middleware works internally: <a href="https://github com/scrapy/scrapy/blob/342cb622f1ea93268477da557099010bbd72529a/scrapy/spidermiddlewares/offsite py#L30" rel="nofollow">source code</a> |
cx_Oracle problem trying to import python I am trying to run python in an Apache WS in a linux RHEL x86_64 After Install and configure Python2 5 and Apache I install Oracle Instant Client (basic and sdk) in a by an rpm file withou any problem ````oracle-instantclient-basic-10 2 0 4-1 x86_64 rpm oracle-instantclient-devel-10 2 0 4-1 x86_64 rpm ```` I set the envoirment variables ````export ORACLE_HOME=/appl/paths/instantclient_10_2 export LD_LIBRARY_PATH=$ORACLE_HOME/lib export PATH=$ORACLE_HOME/bin:$PATH ```` Then install cx_Oracle by an rpm file too and again withou any problem ````cx_Oracle-5 0 3-10g-unicode-py25-1 x86_64 rpm ```` When I try to import cx_Oracle in python I got the message ````Python 2 5 2 (r252:60911 Jul 1 2010 17:47:36) [GCC 4 1 2 20080704 (Red Hat 4 1 2-46)] on linux2 Type "help" "copyright" "credits" or "license" for more information >>> import cx_Oracle Traceback (most recent call last): File "<stdin>" line 1 in <module> ImportError: /appl/paths/python2 5/site-packages/cx_Oracle so: undefined symbol: OCIDBShutdown ```` I google for answers without success Any tip? | The problem was in the ORACLE_HOME there was a misspelling on it |
Read a list from txt file in Python I need to read a list from a txt file and import as a list variable into my py file I could use the import function but the program must be compiled and when it is compiled to an exe all the imports ends converted into a non-modificable files so the solution is to read from a txt The code that I use is similar to this First I got my list in a txt file like this: ````[['preset1' 'a1' 'b1'] ['preset2' 'a2' 'b2'] ['preset3' 'a3' 'b3'] ['preset4' 'a4' 'before']] ```` Then I read the list in python: ````file = open('presets txt' 'r') content = file readline() newpresets = content split("'") file close() ```` And I supposed that with the split function to delete the ' symbols the program take the content as a list and not as a string but this not works So I need how to read the content of the file and not interpretate as a string Anyone could help me? Thanks | try to use `ast literal_eval` : ````>>> a = str([['preset1' 'a1' 'b1'] ['preset2' 'a2' 'b2'] ['preset3' 'a3' 'b3'] ['preset4' 'a4' 'before']]) >>> a "[['preset1' 'a1' 'b1'] ['preset2' 'a2' 'b2'] ['preset3' 'a3' 'b3'] ['preset4' 'a4' 'before']]" >>> import ast >>> ast literal_eval(a) [['preset1' 'a1' 'b1'] ['preset2' 'a2' 'b2'] ['preset3' 'a3' 'b3'] ['preset4' 'a4' 'before']] >>> ```` |
When did Roman Catholicism become suppressed? | as early as 1520 |
Need help returning correct url after using CreateView I am having difficulty returning the correct URL after submitting my form I can get it to work by directing it to the index page however I would like it to direct to the newly created project url for example I want the url to look like this: www example com/username/project-slug I have been trying for about 5 hours now with no luck :-( Any help would be much appreciated! views ````class CreateProject(CreateView): model = UserProject form_class = UserProjectForm template_name = 'howdidu/create_project html' #success_url = "/" def form_valid(self form): form instance user = self request user self object = form save() return super(CreateProject self) form_valid(form) def get_success_url(self): return reverse_lazy('index') ```` urls ````urlpatterns = patterns('' url(r'^$' views index name='index') url(r'^register_profile/$' views register_profile name='register_profile') url(r'^update_profile/$' views update_profile name='update_profile') url(r'^create_project/$' views CreateProject as_view() name='create_project') url(r'^(?P<username>\w+)/$' views profile_page name='user_profile') url(r'^(?P<project_title_slug>[\w-]+)/$' views project_page name='user_project') ) ```` models ````class UserProject(models Model): user = models ForeignKey(User) title = models CharField(max_length=100) project_overview = models CharField(max_length=1000) project_picture = models ImageField(upload_to='project_images' blank=True) date_created = models DateTimeField(auto_now_add=True) project_views = models IntegerField(default=0) project_likes = models IntegerField(default=0) project_followers = models IntegerField(default=0) slug = models SlugField(max_length=100 unique=True) #should this be unique or not? def save(self *args **kwargs): self slug = slugify(self title) super(UserProject self) save(*args **kwargs) def __unicode__(self): return self title ```` project urls ```` url(r'^admin/' include(admin site urls)) url(r'' include('howdidu urls')) url(r'^accounts/register/$' MyRegistrationView as_view() name='registration_register') #redirects to home page after registration (r'^accounts/' include('registration backends simple urls')) url(r'^(?P<username>\w+)/' include('howdidu urls')) #do i need this? ```` | You can do this in `get_success_url` ````def get_success_url(self): username = self kwargs get('username' None) project_slug = self kwargs get('project_title_slug' None) return reverse('user_project' kwargs={ 'username': username 'project_title_slug': project_slug }) ```` `user_project` is the name of the url but i do not know if that is the one you need to match Change whatever you need to match the example with your urls definition |
Multiplying two lists in python? I am trying to print a chess-board like list and I am hoping it will look something like this :) `row=1 2 3 4 5 6 7 8` `column = a b c d e f g` ````board=[[1A] [1B] [1C] etc ] ```` Is there any way to do this? I am still a newbie with python | You can do: ````row = [1 2 3 4 5 6 7 8] column = ['a' 'b' 'c' would' 'e' 'f' 'g' 'h'] board = [[str(i)+j upper() for j in column] for i in row] >>> print board ['1A' '1B' '1C' '1D' '1E' '1F' '1G' '1H'] ['2A' '2B' '2C' '2D' '2E' '2F' '2G' '2H'] ['8A' '8B' '8C' '8D' '8E' '8F' '8G' '8H'] ```` <h3>What is happening</h3> The code above uses double list-comprehension to create eight lists of eight elements each thus creating a product of the rows and columns and giving a 2-D board <h3>Simpler visualization</h3> ````>>> a = ['a' 'b' 'c'] >>> b = ['a' 'b' 'c'] >>> print [[i+j for j in a] for i in b] [['aa' 'ab' 'ac'] ['ba' 'bb' 'because'] ['ca' 'cb' 'cc']] ```` |
Generate various events in 'Web scraping with beautiful soup' Is there any way to generate various events like: - filling an input field - submitting a form - clicking a link - Handling redirection etc via python beautiful soup library If not what is the best way to do above (basic functionality) | BeautifulSoup is a tool for parsing and analyzing HTML It cannot talk to web servers so you would need another library to do that like `urllib2` (builtin but low-level) or `requests` (high-level handles cookies redirection https etc out of the box) Alternatively you can look at `mechanize` or `windmill` or if you also require JavaScript code to be executed `phantomjs` |
String Index Out Of Range When Reading Text File I keep on getting this error on the second last line of my program and I am not sure why all I am doing is reading a line from a text file ````if (items[0]) == 86947367 : with open("read_it txt") as text_file: try: price = int(text_file readlines()[2]) except ValueError: print("error") else: new_price = int(price * (items2[0])) print("£" new_price) price_list append(new_price) product = (text_file readline()[1]) print(product) ```` | <strong>problem:</strong> ````price = int(text_file readlines()[2]) ```` the readlines() because the readline() to return none or something like that try to store readlines() in a <strong>tmp var and then</strong> ````price = tmp[2] product =tmp[1] ```` |
Is OptionParser in conflict with sphinx? I am trying to write a documentation for my project in sphinx and whenever sphinx encounters OptionParser in my module it gives me: ````sphinx-build: error: no such option: -b ```` I thought that it is impossible so I wrote a simple module to check this: ````from optparse import OptionParser """some comment here""" parser = OptionParser(conflict_handler='resolve') parser add_option('' '--force' action='store_true' dest='force' default=False help='gqdel will skip asking questions and delete them all '); parser add_option('' '--verbose' action='store_true' dest='verbose' default=False help='Report additional information from gqdel') (options args) = parser parse_args() """and here""" print "foo" ```` And it gives me the same error My rst looks like this: ````some title ========== automodule:: test :members: ```` | Here is what I think happens: When Sphinx runs <a href="http://sphinx pocoo org/ext/autodoc html">autodoc</a> imports your module and the toplevel code in the module is executed An OptionParser instance is created and it processes the command line arguments and options passed to sphinx-build <a href="http://sphinx pocoo org/invocation html#invocation">one of which is <strong>-b</strong></a> Your OptionParser does not allow this option I would put the OptionParser code in a function so that it is not executed when the module is imported |
What type of accomidations are domesticated turkey normally grown in? | Commercial turkeys are usually reared indoors under controlled conditions |
How to hide the 'set' keyword in output while using set in python Ok so I have two lists in python ````a = ['bad' 'horrible'] b = ['bad' 'good'] ```` I am using the set operator to compare the two lists and give an output if a common word exists between the two sets ````print set(a) & set (b) ```` This gives the output as ````set(['bad']) ```` Is there anyway to remove the keyword 'set' in the output?? I want the output to look like ````['bad'] ```` | Simply convert set to list: ````list(set(['bad'])) ```` |
How to make PyParsing recognize \x escapes? I want to use PyParsing to parse BNF-based rules A rule may look like: ````A > 'You can use \xABCD to display hexadecimal numbers' ```` Where A is a nonterminal symbol The assignment operand is '->' The last item is a quoted string I use PyParsing in the following manner: ````Left= Word(alphanums) Op = oneOf('= := > ::=') Right = QuotedString('"') | QuotedString("'") Rule = Left+ Op+ Right Rule parseString("A > '_\x5555 a'") # Get an error of ValueError: invalid \x escape ```` So would you please tell me how to regconize \x escapes with QuotedString? Any help would be appreciated | Just use `\\` to escape the `\`: ````"A > '_\\x5555 a'" ```` |
python 2 7 unicode writer robust to NoneType I was hoping to use UnicodeWriter from <a href="http://docs python org/2/library/csv html#csv-examples" rel="nofollow">the official examples</a> not to hiccup on Unicode data when trying to do a CSV write However if I have blanks/missing/NaN in the list that should be a row I get this error: ```` self writer writerow([s encode("utf-8") for s in row]) AttributeError: 'NoneType' object has no attribute 'encode' ```` Is there an easy fix? I repeat the 'official code' below: ````class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f" which is encoded in the given encoding """ def __init__(self f dialect=csv excel encoding="utf-8" **kwds): # Redirect output to a queue self queue = cStringIO StringIO() self writer = csv writer(self queue dialect=dialect **kwds) self stream = f self encoder = codecs getincrementalencoder(encoding)() def writerow(self row): self writer writerow([s encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue data = self queue getvalue() data = data decode("utf-8") # and reencode it into the target encoding data = self encoder encode(data) # write to the target stream self stream write(data) # empty queue self queue truncate(0) def writerows(self rows): for row in rows: self writerow(row) ```` | A previous question (though about string conversion of numbers) solved this problem too see <a href="http://stackoverflow com/a/11884299/938408">this answer</a> Just add a conversion to unicode: `self writer writerow([unicode(s) encode("utf-8") for s in row])` |
When was the first public group for Humanist founded? | 1929 |
How to give value to a drop down calendar using selenium and python I am new to selenium and i am building this code where i have to give a certain value to the drop down calendar and i am totally confused Below is the html code for the website calendar i am trying to use Do help ```` <input id="reportDate" name="criteria reportDate" value="30-Nov-2015" class="form-control datepicker-control form-date" type="text"> ```` This is the code i used so far ````driver=webdriver Chrome() driver get('url') driver find_element_by_id('reportData') click() ```` i am not sure as to how to proceed after this i already wrote the code to get the date value in "30-Nov-2015" format which is in the variable "date" Sorry if the code is too small to work on totally new to this | I am assuming you have to select the date from the dropdown calender you can use Select class for that ````driver=webdriver Chrome() driver get('url') select = Select(driver find_element_by_id("reportData")) select select_by_visible_text("30-Nov-2015") ```` you can also use - ````select select_by_value("30-Nov-2015") ```` You can see the WebDriver API bindings in Python here: <a href="http://selenium-python readthedocs org/en/latest/api html" rel="nofollow">http://selenium-python readthedocs org/en/latest/api html</a> The Select() class is at section 7 12 UI Support |
Are adolescents with authoritative parents more or less likely to complete secondary education by age 22? | more |
How to close tkinter window without a button? I am an A-level computing student and I am the only one in my class who can code using Python Even my teachers have not learned the language I am attempting to code a login program that exits when the info is put in correctly and displays a welcome screen image (I have not coded that part yet) It has to close and display a fail message after 3 failed login attempts I have encountered many logic errors when attempting to alter my attempts variable for the elif statement to work after many failed logins as well as getting the tkinter window to terminate/close based on the relevant if/elif statement This is failing to work and I have looked at many code examples on this site and cannot find anything could I please get some help with fixing my code? Code: <pre class="lang-py prettyprint-override">`from tkinter import * #Importing graphics attempts = 0 #Defining attempts variable def OperatingProgram(): #Defining active program class Application(Frame): global attempts def __init__(self master): super(Application self) __init__(master) #Set __init__ to the master class self grid() self InnerWindow() #Creates function def InnerWindow(self): #Defining the buttons and input boxes within the window global attempts print("Booted log in screen") self title = Label(self text=" Please log in you have " str(attempts) " incorrect attempts ") #Title self title grid(row=0 column=2) self user_entry_label = Label(self text="Username: ") #Username box self user_entry_label grid(row=1 column=1) self user_entry = Entry(self) #Username entry box self user_entry grid(row=1 column=2) self pass_entry_label = Label(self text="Password: ") #Password label self pass_entry_label grid(row=2 column=1) self pass_entry = Entry(self) #Password entry box self pass_entry grid(row=2 column=2) self sign_in_butt = Button(self text="Log In" command = self logging_in) #Log in button self sign_in_butt grid(row=5 column=2) def logging_in(self): global attempts print("processing") user_get = self user_entry get() #Retrieve Username pass_get = self pass_entry get() #Retrieve Password if user_get == 'octo' and pass_get == 'burger': #Statement for successful info import time time sleep(2) #Delays for 2 seconds print("Welcome!") QuitProgram() elif user_get != 'octo' or pass_get != 'burger': #Statement for any failed info if attempts >= 2: #Statement if user has gained 3 failed attempts import time time sleep(2) print("Sorry you have given incorrect details too many times!") print("This program will now end itself") QuitProgram() else: #Statement if user still has enough attempts remaining import time time sleep(2) print("Incorrect username please try again") attempts = 1 else: #Statement only exists to complete this if statement block print("I do not know what you did but it is very wrong ") root = Tk() #Window format root title("Log in screen") root geometry("320x100") app = Application(root) #The frame is inside the widget root mainloop() #Keeps the window open/running def QuitProgram(): #Defining program termination import sys sys exit() OperatingProgram() ```` | Consider for a moment the following two lines in your logging_in method: ````if user_get == 'octo' and pass_get == 'burger': elif user_get != 'octo' or pass_get != 'burger': ```` so if the login credentials are correct the code after the first test is executed If they are incorrect the code after the second test is executed However the code that you want to see executed after multiple failures is under a third test clause: ````elif attempts >= 3: ```` The thing is the thread of execution will never see this test as either the first or second one will have already evaluated to true (login credentials are correct login credentials are incorrect) - it would need to be possible for them both to evaluate to false before the value of attempts would ever be checked The easiest way to fix this would be to change your ````elif attempts >= 3: ```` line to read ````if attempts >= 3: ```` adjusting the else clause/adding a new one if you feel it is necessary |
In python class variable is static is I want to use different instance is there any solution? In python I want to make a class variable static so I can to use it from a different instance is there any solution? | I do not follow your question fully Could you explain better Does this help?: <a href="http://stackoverflow com/questions/68645/static-class-variables-in-python">Static class variables in Python</a> |
Spark using Python : save RDD output into text files I am trying the word count problem in spark using python But I am facing the problem when I try to save the output RDD in a text file using saveAsTextFile command Here is my code Please help me I am stuck Appreciate for your time ````import re from pyspark import SparkConf SparkContext def normalizewords(text): return re compile(r'\W+' re UNICODE) split(text lower()) conf=SparkConf() setMaster("local[2]") setAppName("sorted result") sc=SparkContext(conf=conf) input=sc textFile("file:///home/cloudera/PythonTask/sample txt") words=input flatMap(normalizewords) wordsCount=words map(lambda x: (x 1)) reduceByKey(lambda x y: x+y) sortedwordsCount=wordsCount map(lambda (x y):(y x)) sortByKey() results=sortedwordsCount collect() for result in results: count=str(result[0]) word=result[1] encode('ascii' 'ignore') if(word): print word "\t\t"+ count results saveAsTextFile("/var/www/myoutput") ```` | since you collected `results=sortedwordsCount collect()` so its not RDD It will be normal python list or tuple As you know `list` is python object/data structure and `append` is method to add element ````>>> x = [] >>> x append(5) >>> x [5] ```` <blockquote> Similarly `RDD` is sparks object/data structure and `saveAsTextFile` is method to write the file Important thing is its distributed data structure </blockquote> So we cannot use `append` on RDD or `saveAsTextFile` on list `collect` is method on RDD to get to RDD to driver memory As mentioned in comments save `sortedwordsCount` with saveAsTextFile or open file in python and use `results` to write in a file |
How to interact with social websites (auto youtube posting finding titles of new videos etc ) from the command line I would like to write a script to access data on a website such as: 1) automatically searching a youtuber's profile for a new posting and printing the title of it to stdout 2) automatically posting a new video question or comment to a website at a specified time For a lot of sites there is a required login so that is something that would need to be automated as well I would like to able to do all this stuff from the command line What set of tools should I use for this? I was intending to use Bash mostly because I am in the process of learning it but if there are other options like Python or Javascript please let me know In a more general sense it would be nice to know how to read and directly interact with a website's JS; I have tried looking at the browser console but I cannot make much sense of it | Python or Node (JS) will probably be a lot easier for this task than Bash primarily because you are going to have to do OAuth to get access to the social network Or if you are willing to get a bit "hacky" you could issue scripts to PhantomJS and automate the interaction with the sites in question |
How to represent networkx graphs with edge weight using nxpd like outptut Recently I asked the question <a href="http://stackoverflow com/questions/29774105/representating-graphs-with-ipython">How to represent graphs with ipython</a> The answer was exactly what i was looking for but today i am looking for a way to show the edge valuation on the final picture The edge valuation is added like this : ````import networkx as nx from nxpd import draw # If another library do the same or nearly the same # output of nxpd and answer to the question that is # not an issue import random G = nx Graph() G add_nodes_from([1 2]) G add_edge(1 2 weight=random randint(1 10)) draw(G show='ipynb') ```` And the result is here <img src="http://i stack imgur com/olpju png" alt="Result provided by ipython notebook"> I read the `help` of `nxpd draw` (did not see any web documentation) but i did not find anything Is there a way to print the edge value ? <strong>EDIT</strong> : also if there is a way to give a formating function this could be good For example : ````def edge_formater(graph edge): return "My edge %s" % graph get_edge_value(edge[0] edge[1] "weight") ```` <strong>EDIT2</strong> : If there is another library than nxpd doing nearly the same output it is not an issue <strong>EDIT3</strong> : has to work with `nx {Graph|DiGraph|MultiGraph|MultiDiGraph}` | If you look at the <a href="https://github com/chebee7i/nxpd/blob/master/nxpd/nx_pydot py" rel="nofollow">source</a> `nxpd draw` (function `draw_pydot`) calls `to_pydot` which filters the graph attributes like: ````if attr_type == 'edge': accepted = pydot EDGE_ATTRIBUTES elif attr_type == 'graph': accepted = pydot GRAPH_ATTRIBUTES elif attr_type == 'node': accepted = pydot NODE_ATTRIBUTES else: raise Exception("Invalid attr_type ") d = dict( [(k v) for (k v) in attrs items() if k in accepted] ) ```` If you look up <a href="https://github com/erocarrera/pydot/blob/master/pydot py" rel="nofollow">`pydot`</a> you find the `pydot EDGE_ATTRIBUTES` which contains valid Graphviz-attributes The `weight` strictly refers to edge-weight by Graphviz if I recall and `label` is probably the attribute you need Try: ````G = nx Graph() G add_nodes_from([1 2]) weight=random randint(1 10) G add_edge(1 2 weight=weight label=str(weight)) ```` <hr> Note that I have not been able to test if this works just downvote if it does not |
Unequal to equal dimensions for a matrix I am trying to implement a custom formula for generating an equal size matrix (with custom number of rows and columns) based on certain math formula I stuck on storing the values from an unequal size matrix to my output matrix that needs to be of equal dimensions (3x3 5x5 9x9 etc) This is the code: ````def mex3(): print "Say input size (d)" d = int(raw_input("> ")) h = np empty([d d] dtype=np float) global lx global ly global x global y lx_list = [] ly_list = [] x_list = [] y_list = [] value = [] b = np array([0 0] dtype=np float) a = 1 for line in range(h shape[0]): for col in range(h shape[1]): lx = col - (d - 1)/2 ly = (d - 1)/2 - line lx_list append(lx) ly_list append(ly) lam = np column_stack((lx_list ly_list)) for i in lx_list: val = i - b[0] x_list append(val) for j in ly_list: val = j - b[1] y_list append(val) xy = np column_stack((lx_list ly_list)) #This is the part that does not work for line in range(h shape[0]): for col in range(h shape[1]): for i in xy[0]: for j in xy[1]: val = 0 val = (1 - i**2 - j**2) * math exp(-((i**2)+(j**2))/2) h[line col] = val return h ```` My h matrix output only stores the last value in the 'val' variable and not the corresponding values from xy matrix Edit: For example: Say my xy matrix has is of this form: ````[[-1 1 ] [ 0 1 ] [ 1 1 ] [-1 0 ] [ 0 0 ] [ 1 0 ] [-1 -1 ] [ 0 -1 ] [ 1 -1 ]] ```` The corresponding h matrix should be like: ````[[-1 1 0 1 1 1 ] [-1 0 0 0 1 0 ] [-1 -1 0 -1 1 -1 ] ```` But note that i need the resulted value stored from the 'val' variable and not the -1 1 pair So the output should be like: ````[[-0 36787944 0 -0 36787944] [ 0 1 0 ] [-0 36787944 0 -0 36787944]] ```` Following the answer I tried this but does not work: ````global i j for line in range(h shape[0]): for col in range(h shape[1]): i = 0 j = 0 for i in xy[0]: for j in xy[1]: val = (1 - i**2 - j**2) * math exp(-((i**2)+(j**2))/2) h[line col] = val i = 1 j = 1 ```` | Your current issue would be clear if you take a closer look at your loop - ````#This is the part that does not work for line in range(h shape[0]): for col in range(h shape[1]): for i in xy[0]: for j in xy[1]: ```` The above actually completely loops through `xy[0]` and `xy[1]` calculating each for each `i j` the value according to your formula and then setting it to `h[line col]` That is why for each element in `h` it has the last val calculated only since the previous `val`s get overwritten as you are doing all this in a nested loop What you want would be to move i j outside the loop completely and increment them for each iteration of loop - ````for line in range(h shape[0]): for col in range(h shape[1]): ```` Example Code - ````i = 0 for line in range(h shape[0]): for col in range(h shape[1]): val = (1 - xy[i][0]**2 - xy[i][1]**2) * math exp(-((xy[i][0]**2)+(xy[i][1]**2))/2) h[line col] = val i = 1 ```` |
Python: Add JSON into Existing JSON Suppose I have two json files I would like to be able to load both then add the entries from the second into the first This may include adding fields or list entries Something like the following example: file1 json: { "fruit": [ { "name": "apple" "color": "red" } { "name": "orange" "color": "orange" } ] } file2 json: { "fruit": [ { "name": "strawberry" "color": "red" "size": "small" } { "name": "orange" "size": "medium" } ] } result: { "fruit": [ { "name": "apple" "color": "red" } { "name": "orange" "color": "orange" "size": "medium" } { "name": "strawberry" "color": "red" "size": "small" } ] } At first I thought to load them into dictionaries and try something like update: ````import simplejson filea = open("file1 json" 'r') dicta = simplejson loads(filea read()) fileb = open("file2 json" 'r') dictb = simplejson loads(fileb read()) filea close() fileb close() dicta update(dictb) ```` Since both dictionaries have an entry for "fruit" I was hoping that they would merge but it simple overrides the entry in dicta with the entry in dictb I realize I could write code to loop through this example but the actual files I am using are far larger and more complicated I was wondering if there was a library out there that did something like this already before I go reinventing the wheel For what it is worth I am using Python 2 6 2 Thanks for any advice or suggestions! | You will need to extend the lists checking each value There is no way Python can now you want to merge them based on `name` item of dictionaries: ````def merge(lsta lstb): for i in lstb: for j in lsta: if j['name'] == i['name']: j update(i) break else: lsta append(i) for k v in dictb items(): merge(dicta setdefault(k []) v) ```` So the `dicta` variable will be: ````{'fruit': [{'color': 'red' 'name': 'apple'} {'color': 'orange' 'name': 'orange' 'size': 'medium'} {'color': 'red' 'name': 'strawberry' 'size': 'small'}]} ```` |
Why is Spain a part of federalism? | null |