input_text
stringlengths 1
40.1k
| target_text
stringlengths 1
29.4k
⌀ |
---|---|
Wrong solution for distinct Sub-sequences of a sequence I am trying to solve <a href="https://leetcode com/problems/distinct-subsequences/" rel="nofollow">this problem</a> Problem is: Given a string S and a string T count the number of distinct subsequences of T in S <blockquote> A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters (ie "ACE" is a subsequence of "ABCDE" while "AEC" is not) Here is an example: S = "rabbbit" T = "rabbit" Answer should be 3 </blockquote> ````class permute: def __init__(self): self count = 0 def count_permute(self s t i j): print(i j) if t in s: self count = 1 return if i >= len(s) or j >= len(t): return self count_permute(s t i+1 j) if s[i] == t[j] and j == (len(t)-1): self count = 1 self count_permute(s t i+1 j+1) else: self count_permute(s t i+1 j+1) def print_count(self): print(self count) p = permute() p count_permute("rabbbit" "rabbit" 0 0) p print_count() ```` There is also dynamic programming solution which I know by creating a matrix However I wanted to know where I am going wrong with this recursive approach? Currently it is printing 6 but answer should be 3 | The program fails because its logic does not seem particularly connected to a algorithm that would solve the problem I have some trouble figuring out what you intended given the one-letter variable names and the lack of comments I do understand the statement <strong>if i >= len(s) or j >= len(t): return</strong> -- if we have run off the end of either string quit looking Similarly the last half of the function can work given proper support but it is not enough to do its job in this context I do not get the first <strong>if</strong> action: you find <strong>t</strong> as a wholesale substring of <strong>s</strong> Counting one subsequence is correct but then you quit looking How do you plan to get past 1 given ("abababab" "ab")? You find the first count 1 and then quit altogether Similarly it fails when handed your one test case counting all too many cases I also tested this with ("bababababab" "aa"); it claims 25 solutions counting ghosts and fumbling the index advances If I remove the 'b' characteres on the two ends it counts 20 This should be a clue as to your terminal counting For ("aacbaaa" "aba") it counts 31 occurrences instead of the actual 6 In the current code you need to keep looking after you find an initial match You need both of your recursive calls here (using <strong>j</strong> and <strong>j+1</strong>) You also need to restrict those end-of-search over-counts Finally I strongly recommend some basic brute-force debugging: stuff in print statements to track the progress of the routine Track entry and exit parameter values and return conditions I inserted the following tracing statement to help find my way: ````def count_permute(self s t i j): print "ENTER" \ "\ts=" s[i:] "; i=" i \ "\tt=" t[j:] "; j=" j ```` This is only a beginning If you do not find a quick solution I recommend that you go back to the pseudo-code from which you wrote the above Desk-simulate the algorithm on a couple of simple cases such as the ones I supplied Make sure that you have your basic recursion steps <them>cleanly</them> handled: - Termination condition - Detection cases - Recursive calls I think you have a decent handle on the last one and you are almost there on #2 You are not that far from a working solution; keep plugging along! |
python use raw_input for range filenames Currently I have got a script that consumes text filename (for example 1 txt) from raw input opens it and then parses it for my needs: ````fname = raw_input("Enter file name: ") fh = open(str(fname)) ```` There are 10 files in the directory: 1 txt 2 txt 10 txt So how can I input range filenames in raw input like from 2 txt to 6 txt and parse these files 1 by 1 Instead of running script every time for a single file? | I will assume that the file names are `n tx`t where `n >= 1` then ````def parse(flie): pass # this is where you parse the file lower = raw_input("Enter start: ") # assume int upper = raw_input("Enter end: ") # assume int and >= lower files = [str(i)+' txt' for i in range(int(lower) int(upper)+1)] for file in files: parse(file) ```` |
Hex number (0-15) and return ascii representation For a cryptography application I am reading in strings that represent hexadecimal ( "36E06921" "27EA3C74" ) and need to xor them together and return a str of the result ("110A5555") I am able to xor char by char and get decimal result but am having issues getting the ascii representation of the result So 0x3 xor 0x3 = 0x0 What Is the best way to get value 0 into ascii value 0x30? Current attempt at implementation: ````def xor_hexstrings(xs ys): bin_x = binascii unhexlify(xs) bin_y = binascii unhexlify(ys) hex_str = "" for x y in zip(xs ys): # fails with error TypeError: 'int' does not support the buffer interface xored = binascii b2a_hex(int(x 16) ^ int(y 16)) hex_str = xored return None ```` EDIT: Close only issue is with zero Following example shows recommended solution returns empty string for zero ````>>> hex(int('0' 16)) lstrip("0x") '' >>> hex(int('1' 16)) lstrip("0x") ```` | I think what you are asking here is to convert an integer into it is respective string representation At least that is what the example 0x0 -> 0x30 would seem to suggest If so just cast to a string in python with the `str()` function ````>>> ord(str(0)) 48 ```` Just for reference 48 equals 0x30 and the <a href="https://docs python org/2/library/functions html#ord" rel="nofollow">ord()</a> function gives you integer representation of a character EDIT: Check out the format function Seems to have expected behavior! ````>>> format(0x0 'x') '0' ```` |
Python Tkinter multiple line input as integer in list I have a problem reading multiple lines of coordinates (like x y) from a Tkinter Textbox The user input will be this: ````41 3 21 12 68 10 etc ```` Each Line represents an x y coordinate X and Y are seperated by I need to read this coordinates from the text box and process it in a way that an array forms Like this: ````[[41 3] [21 12] [68 10] ```` What i have so far: ````from Tkinter import * def get_Data(): text_from_Box = Text_Entry get("1 0" 'end-1c') split("\n") print text_from_Box master = Tk() Label(master text = "Enter coordinates here:") grid(row = 0 sticky = W) Text_Entry = Text(master height = 30 width = 30) Text_Entry grid(row = 1 column = 0) Button(master text = 'Start Calculation' command = get_Data) grid(row = 2 column = 0 sticky = W) mainloop() ```` | You have to `split` again at the `' '` and convert to `int` (or `float`): ````def get_Data(): text_from_Box = Text_Entry get("1 0" 'end-1c') split("\n") numbers = [[int(x) for x in pair split(" ")] for pair in text_from_Box] print numbers ```` |
What did Liberius have to promise to do in order to return? | comply with the bishops |
Splitting a dictionary in python based on memory size I am in the process of moving a distributed file system into aws simpledb using boto and I am running into an issue that does not have a clear solution to me The current state of my code is as follows: ````def insert(documents): data = {hash_doc(d): _decode(d) for d in documents if hash_doc(d)} domain batch_put_attributes(data) ```` Basically the issue that I am hitting is that the request up to aws made in the `batch_put_attributes` function has a maximum size of 1MB Obviously I want to minimize the number of requests I am making but I also cannot hit the 1MB limit Is there any nice pythonic way to basically say <blockquote> Split this iterable into chunks that are all below a certain memory size but as few chunks as possible </blockquote> I feel a little bad for not including more code but I just have not found something that tractable on this one and I feel like there should be a pretty straightforward solution | Maybe do something like the following to preprocess it a bit: ````size_d = defaultdict(list) for k v in data items(): size_d[sys getsizeof(v)] append(v) ```` Then just make a function to fill up a 1MB bucket of items pop any item that you decide to send so you do not reuse it Could probably optimize it a bit by sorting the items by size Pretty sure this is the <a href="http://en wikipedia org/wiki/Knapsack_problem" rel="nofollow">knapsack problem</a> so if you find an optimal solution let us all know :) |
combine() argument 1 must be datetime date not str - When displaying time - Django When I try to use this code: ````date = datetime datetime now() strftime('%I:%M') ```` it gives me this error: "combine() argument 1 must be datetime date not str" I am not sure what I am doing wrong Could someone please help? Thank you! EDIT: I think my error is here: ````naive_start = datetime datetime combine(date datetime time min) ```` What should I do differently? | The type of your `date` var is not `date/datetime` instance its a `string` ````>>> import datetime >>> date = datetime datetime now() strftime('%I:%M') >>> type(date) <type 'str'> ```` And i guess you are trying to use it with `datetime datetime combine` ````>>> datetime datetime combine(date datetime time(10 23)) Traceback (most recent call last): File "<stdin>" line 1 in <module> TypeError: combine() argument 1 must be datetime date not str ```` While you should use `date/datetime` object ````>>> datetime datetime combine(datetime datetime now() datetime time(10 23)) datetime datetime(2015 2 23 10 23) ```` |
Django unable to render logout template Have the following problem; I am following Django by Example Antonio Mele The exercise here is to set up user login and logout Using the default contrib auth views When the code in the book is used The logout view is that of the admin page logout; seems to be same issue as described here <a href="http://stackoverflow com/questions/15467831/django-logout-redirects-me-to-administration-page">django logout redirects me to administration page</a> Have tried all there no success I have been working on this problem My code now works in that the admin template is no longer rendered However I am still unable to use my own logout html I can redirect to my own login html but not the logout html The logging out itself is working User can log in and out only this issue with the templates I now only receive one browser error <blockquote> The page is not redirecting properly Iceweasel has detected that the >server is redirecting the request for this address in a way that will >never complete This problem can sometimes be caused by disabling or >refusing to accept cookies </blockquote> checked the cookies can see csrf token is accepted <strong>no traceback available no errors :-(</strong> If I use the code below all works with one exception I am redirected at logout to the Django Administration logout template and not my own logout html This is when using coede in the book My own modified code with a seperate logout function also did not work generating a maximum recurson error Editing the URLS PY stops the rendering of the admin template but the modified code seems to have an issue in the urls i e THIS IS NOT WORKING !!!!! ```` url(r'^logout/$' 'django contrib auth views logout' {'next_page': '/account/logout'} name='logout') ```` THIS WORKS PERFECTLY !!!! ```` url(r'^logout/$' 'django contrib auth views logout' {'next_page': '/account/login'} name='logout') ```` The code from the book is as follows FROM BOOK SETTINGS PY ````from django core urlresolvers import reverse_lazy LOGIN_REDIRECT_URL = reverse_lazy('dashboard') LOGIN_URL = reverse_lazy('login') LOGOUT_URL = reverse_lazy('logout') ```` FROM BOOK VIEWS PY ````from django http import HttpResponse from django shortcuts import render redirect from django contrib auth import authenticate login logout from django contrib auth decorators import login_required from django contrib import messages from forms import LoginForm @login_required def dashboard(request): return render(request 'account/dashboard html' {'section': 'dashboard'}) def user_login(request): if request method == 'POST': form = LoginForm(request POST) if form is_valid(): cd = form cleaned_data user = authenticate(username=cd['username'] password=cd['password']) if user is not None: if user is_active: login(request user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: form = LoginForm() return render(request 'account/login html' {'form': form}) ```` FROM BOOK MAIN URLS PY ````from django conf urls import include url from django contrib import admin urlpatterns = [ url(r'^admin/' include(admin site urls)) url(r'^account/' include('account urls')) ] ```` MYAPP(account) URLS PY ````from django conf urls import url from import views urlpatterns = [ # url(r'^login/$' views user_login name='login') url(r'^$' views dashboard name='dashboard') # login / logout urls url(r'^login/$' 'django contrib auth views login' name='login') url(r'^logout/$' 'django contrib auth views logout' name='logout') url(r'^logout-then-login/$' 'django contrib auth views logout_then_login' name='logout_then_login') ```` <strong>MY MODIFIFED CODE</strong> I have now include a seperate logout definition in my view's and now also pass a {key:value} pair of {'next_page': '/account/logout'} if the logout def is used and mapped in the urls file it generates a maximum recursion error at line logout(request) ````def logout(request): logout(request) request session flush() request user = AnonymousUser # Redirect to a success page return HttpResponseRedirect(request '/account/logout html' context_instance = RequestContext(request)) ```` without this def the only error generated is """ The page is not redirecting properly """Iceweasel has detected that the server is redirecting the request for this address in a way that will never complete ````This problem can sometimes be caused by disabling or refusing to accept cookies """" ```` """ I checked cookies in the browser and see the csrf_token being accepted For me the strange thing is that if the code: {'next_page': '/account/logout'} is changed to {'next_page': '/account/login'} everything works perfectly Have tried all suggestions found am at a loss any help appreciated MY CODE VIEWS PY ````from django shortcuts import render from django http import HttpResponse HttpResponseRedirect from django contrib auth import authenticate login logout from forms import LoginForm from django contrib auth decorators import login_required from django template import RequestContext from django contrib auth models import User # Create your views here @login_required def dashboard(request): return render(request 'account/dashboard html' {'section': 'dashboard' }) def user_login(request): cd = None if request method=='POST': form = LoginForm(request POST) if form is_valid(): cd = form cleaned_data user = authenticate(username=cd['username'] password=cd['password']) if user is not None: if user is_active: login(request user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled Account') else: return HttpResponse('Invalid Login') else: form = LoginForm() return render(request 'account/login html' {'form': form} context_instance = RequestContext(request)) def logout(request): logout(request) request session flush() request user = AnonymousUser # Redirect to a success page return HttpResponseRedirect(request '/account/logout html' context_instance = RequestContext(request)) ```` MY CODE account/urls py ````from django conf urls import url patterns from import views urlpatterns = [ # post views #url(r'^login/$' views user_login name='login') # login/logout urls url(r'^$' views dashboard name='dashboard') url(r'^login/$' 'django contrib auth views login' name='login') url(r'^logout/$' 'django contrib auth views logout' {'next_page': '/account/logout'} name='logout') url(r'^logout-then-login/$' 'django contrib auth views logout_then_login' name='logout_then_login') ] ```` MY CODE MAIN URLS PY ````from django conf urls import include url from django contrib import admin urlpatterns = [ url(r'^admin/' include(admin site urls)) url(r'^account/' include("account urls")) ] ```` MYCODE SETTINGS PY ````LOGIN_REDIRECT_URL = reverse_lazy('dashboard') LOGIN_URL = reverse_lazy('login') LOGOUT_URL = reverse_lazy('logout') INSTALLED_APPS = ( 'account' 'django contrib admin' 'django contrib auth' 'django contrib contenttypes' 'django contrib sessions' 'django contrib messages' 'django contrib staticfiles' ) MIDDLEWARE_CLASSES = ( 'django middleware csrf CsrfViewMiddleware' 'django contrib sessions middleware SessionMiddleware' 'django middleware common CommonMiddleware' 'django contrib auth middleware AuthenticationMiddleware' 'django contrib auth middleware SessionAuthenticationMiddleware' 'django contrib messages middleware MessageMiddleware' 'django middleware clickjacking XFrameOptionsMiddleware' 'django middleware security SecurityMiddleware' ) # urlpatterns = patterns('django contrib auth views' # #url(r'^login/$' 'login' { 'template_name': 'registration/login html'} name='login' ) # #url(r'^logout/$' 'logout' { 'template_name': 'registration/logout html' 'next_page':reverse('index') } name='logout' ) # ) ```` MYCODE logout html ````{% extends "base1 html" %} {% block title %}Logged Out{% endblock %} {% block content %} <h1> Logged Out </h1> <p> You have been successfully logged out You can <a href="{% url "login" %}">Log-in again</a> </p>{% endblock %} ```` MYCODE base1 html ````{% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" type="text/css" href="{% static 'css/base css' %}"> </head> <body> <div id="header"> <span class="logo"> BookMarks </span> {% if user is_authenticated %} <ul class="menu"> <li {% if section == "dashboard" %}class="selected"{% endif %}> <a href="{% url 'dashboard' %}">My dashboard</a> </li> <li {% if section == "images" %}class="selected"{% endif %}> <a href="#">Images</a> </li> <li {% if section == "people" %}class="selected"{% endif %}> <a href="#">People</a> </li> </ul> {% endif %} {%if user is_authenticated %} <span class="user"> Hello {{ user first_name }} {{ user last_name }} <a href="{% url 'logout' %}">Logout</a> {% else %} <a href='{% url "login" %}'>Log-in</a> {% endif %} </span> </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> ```` | You are using `contrib auth`'s `logout` view in your `urls py` This view redirects to the URL specified by `'next_page'` You provide `'/account/logout'` as `next_page` -- where again the `logout` view is called! That leads to an (infinite) <a href="https://en wikipedia org/wiki/URL_redirection#Redirect_loops" rel="nofollow">redirect loop</a>: the view redirects to itself Try instead: in your own `logout` view: ````# no redirecting here! return render(request 'account/logout html' context_instance=RequestContext(request)) ```` Add a url for that view in `account/urls py`: ````url(r'^post-logout/$' logout name='post-logout') # logout being your own view ```` Then provide that url as `'next_page'` to the actual (`auth`) logout: ````url(r'^logout/$' 'django contrib auth views logout' {'next_page': '/account/post-logout'} name='logout') ```` |
Getting the "feels like" temperature based on wind and temperature in python Based on the wind-speed (meter per second) and temperature (in Celsius) how can I calculate the real "feels like" temperature What I want is something like feels_like(3 -5) to return -9 based on the formula on the button of <a href="http://om yr no/forklaring/symbol/effektiv-temperatur/" rel="nofollow">http://om yr no/forklaring/symbol/effektiv-temperatur/</a> (sorry English translation at <a href="http://translate google com/translate?hl=en&sl=no&tl=en&you=http%3A%2F%2Fom yr no%2Fforklaring%2Fsymbol%2Feffektiv-temperatur%2F" rel="nofollow">http://translate google com/translate?hl=en&sl=no&tl=en&you=http%3A%2F%2Fom yr no%2Fforklaring%2Fsymbol%2Feffektiv-temperatur%2F</a> ) | This should do the trick ````In [1]: feels_like = lambda w t: int(13 12+(0 615*float(t))-(11 37*(float(w)*3 6)**0 16)+(0 3965*float(t))*((float(w)*3 6)**0 16)) In [2]: calc_feels_like(3 -5) Out[2]: -9 ```` |
Which magazine tied to the post-punk movement lost half of its circulation? | NME |
Python receives `<function add>` from `input()` (newbie) I am trying to make my first program in Python however I am having a problem Why is `op1` not being assigned the value I input? ````print ("Hello user") num1 = int(input("Choose a number: ")) num2 = int(input("Choose another number: ")) op1 = (input("Choose an operation [add multiply minus divide]: ")) print (op1) ```` No matter what I enter into `op1` I always receive this message from `print (op1)`: ````<function add at 0x10cff1938> ```` | If you are using Python 2 7 _ then if you are reading in strings you need to use `raw_input` instead of `input` Also discussed <a href="http://stackoverflow com/questions/21122540/python-input-error-nameerror-name-is-not-defined">here</a> |
How to access decoded JSON values in txt file I am sending a JSON request to a server and need to access a time-stamp so it dynamically changes based on another time variable I am using requests to send a post request with the JSON as a txt file My JSON is here I would like to be able to access the dateAndTime field so that I can use the current time to send my query The json is consumed by the server as `data2 =jsonpickle encode(jsonpickle decode(f2 read()) )` `f2` is the json file Here is my post request that I would ultimately have this changed; `dateAndTime` parameter in `r2 = requests post(url2 data=data2 headers=headers2 timeout=(connect_timeout 10))` ``` { "RequestSpecificDetail": { "ParentSRNumberForLink": "" } "MetaData": { "appVersion": "1 34" "deviceModel": "x86_64" "dateAndTime": "01/15/2015 12:46:36" "deviceToken": "A2C1DD9D-D17D-4031-BA3E-977C250BFD58" "osVersion": "8 1" } "SRData": { "SRNumber": "1-3580171" } }``` | The trick is to get the data as a dictionary You can use literal_eval for this: ````import ast data_as_dict = ast literal_eval(data2) ```` You can get the current time with: ````import datetime now = datetime now() strftime('%m/%d/%Y %H:%M:%S') data_as_dict['MetaData']['dateAndTime'] = now ```` Then you can pass data_as_dict instead of data2; probably using the 'json=data_as_dict' argument instead of 'data=' when calling requests post() Use <a href="https://docs python org/2/library/datetime html#strftime-strptime-behavior" rel="nofollow">this link</a> for information about all the formatting options |
On what date was the 2012 Human Development Report released? | null |
Django testing change request I have a middleware from secretballot ````class SecretBallotMiddleware(object): def process_request(self request): request secretballot_token = self generate_token(request) def generate_token(self request): raise NotImplementedError class SecretBallotIpMiddleware(SecretBallotMiddleware): def generate_token(self request): return request META['REMOTE_ADDR'] class SecretBallotIpUseragentMiddleware(SecretBallotMiddleware): def generate_token(self request): s = '' join((request META['REMOTE_ADDR'] request META get('HTTP_USER_AGENT' ''))) return md5(s encode('utf8')) hexdigest() ```` and I use this in my view (e g 'different_view'): ````token = request secretballot_token ```` How can I change this token form request in my tests? ````class BasicTest(TestCase): def test_one(self): self client request['secretballot_token']='asd' #?? response = self client post('/different_view/') ```` And I want to send post in this test to /different_view/ but with my own changed token | If you are looking to the test the view without running through the middleware you can use `RequestFactory` to generate a request and pass it directly into your view ````def test_one(self): # create a request request = RequestFactory() post('/different_view') request secretballot_token = 'asd' # function based view response = different_view(request) # class based view response = DifferentView as_view()(request) ```` If you need to test the middleware along with the view you should pass HTTP headers in your tests instead ````def test_one(self): # pass http headers response = self client post(path='/different_view'/ REMOTE_ADDR='12 34 56 78' HTTP_USER_AGENT=' ' ) ```` |
Create zip file from in memory file in python I am retrieving files from S3 bucket using the following code an it works fine ````file = io BytesIO() k get_contents_to_file(file) ```` Now I want to add this in memory file to a zip file The code below takes filename as argument but I have an in memory file ````zip_file write(filename zip_path) ```` I am using python 3 4 for my project | Try to use `writestr` <blockquote> Signature: writestr(zinfo_or_arcname data compress_type=None) Docstring: Write a file into the archive The contents is 'data' which may be either a 'str' or a 'bytes' instance; if it is a 'str' it is encoded as UTF-8 first 'zinfo_or_arcname' is either a ZipInfo instance or the name of the file in the archive </blockquote> |
xpath pattern for all specific forms in html page I have to locate all "login-form"-like forms in the html page The requirement for such for is that it contains text input field password field and button (submit or just a button) There should not be any element names mentioned because it should work through different language mutations And I need to find all forms in the page which fits these requirements I guess it could be done using xpath but I cannot figure out any working pattern By the way I am using webdriver with python | So you need an XPath expression to match every `form` element (`//form`) which has among its descendants an `input` element of `type=password` (`[ //input[@type='password']]`) a standard `input` field (`[ //input[not(@type) or @type='' or @type='text']]`) and a submit button (`[ //input[@type='submit'] or //button[not(@type) or @type='' or @type='submit']]`) All together becomes ````//form[ //input[@type='password']][ //input[not(@type) or @type='' or @type='text']][ //input[@type='submit'] or //button[not(@type) or @type='' or @type='submit']] ```` It may not match every form since for the submit button and the text input field it is difficult to make an always working rule The problem when dealing with such elements is that they have many `type` values and if it is provided an invalid <them>type</them> they defaults to the `text` or `submit` state For example a input element my have the `type` attribute set to `nonvalidtype` and it will still be a standard text input Also the `type` attribute is case insensitive and the correct XPath expression that considers this is more complicated it also needs XPath 2 0: ````//form[ //input[lower-case(@type)='password']][ //input[not(@type) or @type='' or lower-case(@type)='text']][ //input[lower-case(@type)='submit'] or //button[not(@type) or @type='' or lower-case(@type)='submit']] ```` |
Django Slice is not working on a zip I have been tinkering with Django and Python recently and while trying to limit a for loop in my code I have noticed that the slice function is not working What I am trying to do is scrape data from a gig listing website (I have permission) and list the next 5 gig listings on my own site The data scraping in views py does work fine but returns ~40 results I have tried using |slice:":5" to trim the for loop in my HTML but it does not seem to work and still displays all 40 listings Is it possible to use slice with a zip of arrays? Is there a better way to do it? **HTML** ````{% for dates venuelinks venues times in gig|slice:":5" %} <ul> <li>{{dates}}</li> <li><a href="{{venuelinks}}">{{venues}}</a></li> <li>{{times}}</li> </ul> {% endfor %} ```` **Views py method** ````response = requests get($URL) #anonymised for stackoverflow soup = bs4 BeautifulSoup(response text "html parser") dates = [x text for x in soup select('$CONDITION')] venues = [x text for x in soup select('$CONDITION')] venuelinks = [x attrs get('href') for x in soup select('$CONDITION')] times = [x text for x in soup select('$CONDITION')] gigs = zip(dates venuelinks venues times) t = loader get_template('index html') html = t render({'gig': gigs}) return HttpResponse(html) ```` | If you are using python3 then you cannot slice zips You could try converting the zip to a list with: ````>>> gigs = list(zip(dates venuelinks venues times)) ```` But this will defeat many of the purposes of slicing like not generating large sets of data in the first place However as you are creating lists already I guess that is not a huge issue for you |
Python converting back slash to forward slash I am trying to copy dir1 to dir2 Dir1 contains sub-folders and files In the moment of copy I am creating url like this `C:/dirA/dir1` and `C:/dirB/dir2` As you see all slashes are forwarded When run I get this error ```` No such file or directory path C:/dirB/dir2\\folder1\\file txt ```` As you see sub-folder and file have backslashes I really do not know how to change that backslashes because when I create a paths I do not know the names of sub-folders/files I cannot post entire code because it is huge To copy I use `distutils dir_util copy_tree` | It looks like you can use `os path normpath` on parts of your path to normalize them for current OS before you concatenate on Windows it will use correct slashes |
How to fix auto update of time in pygame? I am trying to make a game in which you have to click the apple and then it goes off to random position You have 5 seconds (for now) and you have to click the apple image many times as you cannot My game works but i have two problems: 1)After the game ends the program does not respond 2)The time keeps on updating itself (it keeps on flickering) i do not want that How do I correct these two bugs? Here is my code: ````import pygame import time import random pygame init() foodimg=pygame image load("food png") foodrect=foodimg get_rect() #Colours white = (255 255 255) black = (0 0 0) red = (255 0 0) #Game Display display_width = 1080 display_height = 720 gameDisplay = pygame display set_mode((display_width display_height)) pygame display set_caption('Click It! ~ Snapnel Productions') gameDisplay fill((white)) font=pygame font SysFont("Arial" 30) a=6 running=True while running: gameDisplay fill((white)) time=pygame time get_ticks()/1000 if a==time: print "Game over" break for event in pygame event get(): if event type==pygame QUIT: running=False pygame quit() quit() if event type == pygame MOUSEBUTTONDOWN: # Set the x y postions of the mouse click x y = event pos if foodrect collidepoint(x y): foodrect center=(random randint(5 1060) random randint(5 700)) print "New Position: " foodrect center continue gameDisplay blit(foodimg foodrect) pygame display flip() showtime=font render("Time: "+str(time) 0 (0 0 0)) gameDisplay blit(showtime (950 10)) pygame display flip() ```` <a href="http://i stack imgur com/K1MSh png" rel="nofollow">Here</a> is my food image | For me the program exits normally (i ran it on linux python 2 6) To remove flockering: ````gameDisplay blit(foodimg foodrect) #pygame display flip() < -- remove that showtime=font render("Time: "+str(time) 0 (0 0 0)) gameDisplay blit(showtime (950 10)) pygame display flip() # because you should do it after the text is drawed ```` Flip is used to update surface You need to update surface after you have everything drawed What you do is fill everything white update and then draw a text update So you have text drawed and filled white every tick |
When were groove recordings developed? | final quarter of the 19th century, |
Get Intermediate Value in Python? I am trying to write a Python `sys excepthook` which in addition to printing out the stack trace for the code as you wrote it also prints out the `repr` for each evaluated value For example if I ran the following code: ````def greeting(): return 'Hello' def name(): return greeting() name() ```` Instead of just printing out: ````Traceback (most recent call last): File "<stdin>" line 1 in <module> greeting() name() TypeError: cannot concatenate 'str' and 'NoneType' objects ```` It would also print out `'Hello' None` so I can immediately see which value was invalid and know the right area of the code to look in (obviously this is a very simple example) I know that the CPU needs to store these intermediate values in some temporary registers I suspect that internally Python has to do something similar and I am hoping that there is some way I can access those temporary values possibly through the `inspect` module or something similar | Use a pythonic `try/except` block: ````g = greeting() n = name() try: g n except: raise ValueError('g: %s n: %s' % (g n)) ```` For @LukasGraf a reading list on "proper Python coding practices": - <a href="http://doughellmann com/2009/06/19/python-exception-handling-techniques html" rel="nofollow">Python Exception Handling Techniques</a> - <a href="http://eli thegreenplace net/2008/08/21/robust-exception-handling/" rel="nofollow">Robust exception handling</a> - <a href="http://www jeffknupp com/blog/2013/02/06/write-cleaner-python-use-exceptions/" rel="nofollow">Write Cleaner Python: Use Exceptions</a> - <a href="https://google-styleguide googlecode com/svn/trunk/pyguide html#Exceptions" rel="nofollow">Google Python Style Guide</a> - <a href="https://www python org/dev/peps/pep-0008/#programming-recommendations" rel="nofollow">PEP 0008 -- Style Guide for Python Code: Programming Recommendations</a> - <a href="http://python net/~goodger/projects/pycon/2007/idiomatic/handout html#eafp-vs-lbyl" rel="nofollow">Code Like a Pythonista: Idiomatic Python -- EAFP vs LBYL</a> |
python code not seeing a class variable iniialized in the __init__() function I am running into a weird error with spynner though the question is a generic one Spynner is the stateful web-browser module for python It works fine when it works but I almost with every run I get a failure saying this -- ````Traceback (most recent call last): File "/usr/local/lib/python2 7/dist-packages/spynner-2 16 dev0-py2 7 egg/spynner/browser py" line 1651 in createRequest self cookies AttributeError: 'Browser' object has no attribute 'cookies' Segmentation fault (core dumped) ```` The problem here is its segfaulting and not letting me continue Looking at the code for spynner I see that the cookies variable is in fact initialized in the `__init__()` function for the Browser class like this: ````self cookies = [] ```` Now on failure its really saying that the `__init__()` is not run since its not seeing the cookies variable I do not understand how that can be possible Without restricting to the spynner module can someone venture a guess as to how a python object could fail with an error like this? EDIT: I definitely would have pasted my code here except its not all in one place for me to compactly show it I should have done it earlier but here is the overall structure and how I instantiate and use spynner ````# helper class to get url data class C: def __init__(self): self browser = spynner Browser() def get_data(self url): try: self browser load(url) return self browser html except: raise # class that does other stuff among saving url data to disk class B: def save_url_to_disk(self url): urlObj = C() html = urlObj get_data(url) # do stuff with html # class that drives everything class A: def do_stuff_and_save_url_data(self url): fileObj = B() fileObj save_url_to_disk(url) driver = A() # call this function for multiple URLs driver do_stuff_and_save_url_data(url) ```` The way I run it is --- ````# xvfb-run python myfile py ```` The segfault is probably something else I am doing May be its because of the xvfb I am using and not handling properly? I do not know yet I need to mention that I am relatively new to python I noticed that when I run the code above with say '<a href="http://www google com" rel="nofollow">http://www google com</a>' I get the segfault every other time | The code block of `do_stuff_and_save_url_data()` does not use the reference `self`: then the execution of this function does not depend on `driver` The code block of `save_url_to_disk()` also does not use the reference `self`: then the execution of this second function does not depend on the object `fileObj` Only the code block of `get_data()` uses the reference `self` and more precisely the reference `self browser`: so its execution and result depends on the attribute `browser` of the instance `urlObj` from class `C` This attribute is in fact a browser instance named `browser` of the `spynner Browser` class In the end you <them>"do stuff with html"</them> with just the data outputed by `spynner Browser() html` And creation of `driver` and `fileObj` are not mandatory in any way Another point is that when the instruction `driver do_stuff_and_save_url_data(url)` is executed the method `driver do_stuff_and_save_url_data(url)` is first created then executed and finally "destroyed" (or more precisely forgot somewhere in the RAM) because it has not been assigned to any identifier Then the identifier `fileObj` which is an identifier belonging to the local namespace of the function `driver do_stuff_and_save_url_data()` is lost too which means the instance <strong>fileObj</strong> of class `B` is also lost for ulterior use since it has no more assigned identifier alive It is the same for `save_url_to_disk()`: after the creation and execution of the method `fileObj save_url_to_disk(url)` the object <strong>urlObj</strong> of class `C` which contains an instance of browser ( an object created by `spynner Browser()` ) is lost: the created browser and all its data is lost I wonder if this is not because of this destruction of the browser instance after each execution of `do_stuff_and_save_url_data()` and `save_url_to_disk()` that the cookies information would not be destroyed before an ulterior call So in my opinion your code only embeds two functions in two definitions of classes `A` and `B` and they are used as being considered functions not as methods 1/ I do not think it is a good coding pattern When one wants only plain functions they must be written outside of any class 2/ The problem is that if operations are triggered by functions a new browser is created each time these functions are activated even if they have the mantle of methods You will say me that you want these functions to act with data provided by the browser defined by `spynny Browser()` That is why I think that they must not be functions embeded in classes as now but real methods attached to a stable instance of a browser That is the aim of object to keep in the same namespace the data and the tools to treat the data <blockquote> - </blockquote> All that said I would personnally write: ````class C(spynner Browser): def __init__(self): spynner Browser __init__(self) def get_data(self url): try: self html = self load(url) html except: raise # method that does other stuff among saving url data to disk def save_url_to_disk(self url): get_data(url) # do stuff with self html # method that drives everything def do_stuff_and_save_url_data(self url): self save_url_to_disk(url) driver = C() driver do_stuff_and_save_url_data(url) ```` But I am not sure to have well undesrtood all your considerations and I warn that I did not know spynner before reading your post All that I have written could be stupid relatively to your real problem Keep a critic eye on my post please |
using mysql and mongodb in django1 8 I am creating a django web application in which I need to use both mysql and mongodb I have used mongoengine for this thus: ````mongoengine connect("mongodb://username:password@localhost:27017/dbname") ```` In my django/settings py: ````DATABASES = { 'default': 'ENGINE': "django db backends mysql" 'NAME': "dbname" "USER": "username" "PASSWORD": "password" "HOST": "localhost" "PORT": "3306" } ```` How can I configure one more connection for MongoDB here and use it to return in `routers py` I am using Django 1 8 so I cannot use `django-norel/django-mongodb-engine` | ````DATABASES = { 'default': { "ENGINE": "django db backends mysql" "NAME": "dbname" "USER": "username" "PASSWORD": "password" "HOST": "localhost" "PORT": "3306" } 'users': { 'NAME': 'user_data' 'ENGINE': 'django db backends mysql' 'USER': 'mysql_user' 'PASSWORD': 'priv4te' } } ```` The migrate management command operates on only one database at a time By default it operates on the default database but by providing `a --database` argument you can tell migrate to synchronize a different database So to synchronize all models onto all databases you would need to call: ````$ /manage py migrate $ /manage py migrate --database=users ```` I hope it helps |
How to count empty responses in Scrapy ? I want to know how many and which of my requests did not return any data with Scrapy There are many cases like when a 404 response is returned or when the server returned something but did not scraped any data because the format was not the one expected (e g when I am extracting from a type of particular named div and it actually does not exists in one of the url's) Thanks ! | <blockquote> e g when I am extracting from a type of particular named div and it actually does not exists in one of the url's) </blockquote> This is not actually an empty response in HTTP terms Your selector just did not match You have to implement this logic by yourself: ````sel = Selector(response) data = sel xpath('//div[@class="class"]') extract() if not data: # increment failure stats here return # else fill the item ```` For stats you could use a <a href="http://doc scrapy org/en/latest/topics/stats html" rel="nofollow">Scrapy stats collector</a> |
Is it possible to call 2 x code from 3 x code in Python I have code written in python 2 6 that is using(depending on) other third-party libraries that are written in python 2 6 also These third-party libraries are old and won´t be translated to python 3 x in a near future or in some cases never My question is if it is possible to write 3 x code that can call code(functions) from the 2 6 code ex: write 3 x python code that can call 2 6 code that in turn calls the third-party libraries and returns the result if there is any back to the 3 x code If you have any examples or know if this is possible or not or can point me in the right direction it would be great Thank you for your time | You have a couple of options: - Port the libraries yourself - this is not as hard as it might seem although not ideal - Use some kind of IPC to interface between python 3 x and 2 x installations - Just stick with python 2 x I would recommend option 3 for the reasons you identify - it looks like a lot of libraries are only going to be available for 2 x Frankly there are not any compelling reasons to switch to 3 x Update: you have a fourth option which is to use something like PyPi to create a python executable which can cope with running the two languages at once If the languages seriously end up with a split between sets of essential libraries then someone will probably do this |
Tkinter Python script not displaying the output of she will script such as mail unix command I have the following script in Python : ````import Tkinter import subprocess from Tkinter import * top = Tkinter Tk() top geometry( "800x600" ) def helloCallBack(): #print "Below is the output from the she will script in terminal" text = Text( top ) text insert( INSERT "*****************************************************\n" ) text insert( INSERT "Below is the output from the she will script in terminal\n" ) text insert( INSERT "*****************************************************\n" ) p = subprocess Popen( ' /secho sh' \ stdout = subprocess PIPE \ stderr = subprocess PIPE \ she will = True \ ) output errors = p communicate() #--------------------------------------------------- DEBUG FRAMING STEP 1 print "DEBUG [stdout] sent:" repr( output ) "<EoString>" print "DEBUG [stderr] sent:" repr( errors ) "<EoString>" #--------------------------------------------------- DEBUG FRAMING STEP 2 text insert( "end" "DEBUG-prefix-to-validate-Tkinter-action <BoString>" \ output \ "<EoString>" \ ) text pack() #--------------------------------------------------- DEBUG FRAMING STEP 3 print "DEBUG FRAMING <EoCall>" B = Tkinter Button( top text ="Hello" command = helloCallBack ) B pack() top mainloop() ```` When my she will script which is secho sh has some simple commands such as `ls` the program outputs normally as in the below screenshot (I could not uplaod an image here as I am a newbee to stack overflow) <a href="http://tinyurl com/tkinterout" rel="nofollow">http://tinyurl com/tkinterout</a> Where as if I have some complex she will script even if it is a one liner such as : ````mail -f ~/Desktop/Test/Inbox mbox ```` <strong>The display is just the text "Below is the output " and nothing else </strong> I have referred to <a href="http://stackoverflow com/questions/25028717/run-a-she will-script-from-python-gui">this</a> <a href="http://stackoverflow com/questions/15362372/display-realtime-output-of-a-subprocess-in-a-tkinter-widget">this</a> and many other stack overflow posts related to the same But I could not get a satisfactory answer as none I found deals with commands such as mail ( which let us the user to interact with the terminal after executing the command) How to tackle this problem? | Here is a working example of what I suggested as the second alternative in the comment above ````import subprocess as sp p = sp Popen('''python -i -c "print('hello world')"''' stdin=sp PIPE stdout=sp PIPE stderr=sp PIPE universal_newlines=True) out err = p communicate(input='quit()') print("out = {}err = {}" format(out err)) ```` prints ````out = hello world err = >>> ```` Without `universal_newlines=True` the input arg must be bytes: `p communicate(input=b'quit()')` It appears that console interpreter prompts go to stderr not stdout |
Could not install rpy2 correctly: undefined symbol omp_get_num_procs I try to install rpy2 on my computer with R 3 1 2 from the source using ````python setup py install --user ```` It output success but when I try to test it using ````python -m rpy2 tests ```` It give me the following output: ````rpy2 version: 2 6 0 - built against R version: 3-1 2--66913 - running linked to R version: R version 3 1 2 (2014-10-31) /scratch/opt/python-2 7 9/lib/python2 7/site-packages/rpy2-2 6 0-py2 7-linux-x86_64 egg/rpy2/robjects/lib/ggplot2 py:59: UserWarning: This was designed againt ggplot2 version 1 0 1 but you have 1 0 0 warnings warn('This was designed againt ggplot2 version %s but you have %s' % (TARGET_VERSION ggplot2 __version__)) /tmp/tmp05nvfc py:17: UserWarning: ri baseenv['eval'](ri parse(rcode)) python: symbol lookup error: /usr/lib64/RRO-8 0 2/R-3 1 2/lib64/R/lib/libmkl_gnu_thread so: undefined symbol: omp_get_num_procs ```` I have the full Installation Log stored here: <a href="https://bitbucket org/Tamaki_Sakura/labscript/src/4cf05da1e19fca5b539c0ffb96c4334c6afe850d/stackoverflowtemp txt?at=default" rel="nofollow">https://bitbucket org/Tamaki_Sakura/labscript/src/4cf05da1e19fca5b539c0ffb96c4334c6afe850d/stackoverflowtemp txt?at=default</a> This one is kind of related to my old question here: <a href="http://stackoverflow com/questions/30968865/could-not-install-rpy2-correctly">Could not install rpy2 correctly</a> However they are not the same It happens on different machines and the one I have here now does have R built as a library | Issue is likely related to openmp and /or Intel's MKL in relation with the way R was compiled (and this is different when you are running rpy2) There are likely environment variables to be set |
Java Producer Stompy Python Consumer ActiveMQ I have a java ActiveMQ producer which produces Integer messages into an ObjectMessage instance On the python side I use stomp python for listening on the queue However I receive empty message body although all the headers are received right Moreover if I change the message type to TextMessage on the java side I get correct message on python-consumer side I have also tried with PyactiveMQ but with the same effect Any suggestions will be appreciated!!! <strong>EDIT</strong>: Here is a boilerplate java producer code and python subscriber code which i wrote to test stomp on python ````public class App { Connection conn; Session session; MessageProducer producer; public void registerPublisher(String queueName String url) throws JMSException { ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("system" "manager" url); conn = cf createConnection(); conn start(); session = conn createSession(false Session AUTO_ACKNOWLEDGE); Destination destination = session createQueue(queueName); producer = session createProducer(destination); producer setDeliveryMode(DeliveryMode PERSISTENT); } public void send(int c) { for (int i=0; i<c; i) { try { TextMessage tm = session createTextMessage(new Integer(i) toString()); // ObjectMessage tm = session createObjectMessage(); producer send(tm); } catch (JMSException e) { e printStackTrace(); } } } public static void main(String []arg) { App app = new App(); try { app registerPublisher(arg[0] arg[1]); System out println(app session); } catch (JMSException e) { e printStackTrace(); } app send(1000); } } ```` And Python Stomp listener ````import time import sys import logging import stomp from stomp import ConnectionListener queuename = sys argv[1] logging basicConfig( level=logging DEBUG) class MyListener(ConnectionListener): def on_error(self headers message): print 'received an error %s' % message def onMessage(self headers message): print headers print str(message) print type(message) print 'received a message %s ' % message conn = stomp Connection([('localhost' 61613)]) conn set_listener('' MyListener()) conn start() conn connect() conn subscribe(destination='/queue/'+queuename ack='auto') while 1: time sleep(2) ```` | In order to send an receive ObjectMessage types over Stomp you need to use the message <a href="http://activemq apache org/stomp html" rel="nofollow">transformation feature</a> of ActiveMQ to have the object payload delivered in a form a STOMP client can understand ActiveMQ provides XML and JSON transformation support out of the box however you can add your own transformer to get whatever format you want on the content |
django-admin bad interpreter: Permission Denied I am trying to use django on a Suse server to use it in production with apache and mod_python but I am finding some problems I have installed python 2 7 9 (the default version was 2 6 4) and django 1 7 I had some problem with the installation but they are now solved My current problem is that when I try to execute django-admin I get this error: -bash: /usr/local/bin/django-admin: : bad interpreter: Permission denied I have searched through the web but I have not found a solution I have tried to make the file executable: sudo chmod x django-admin and the problem remains equal Any idea? Thanking you in advance | It sounds like the python interpreter is what you do not have permission for Do you have permission to run python? |
Download Google Spreadsheet and save as xls Am trying to write python procedure to download a spreadsheet from google spreedsheets and save it as xls here is my code ````import os import sys from getpass import getpass import gdata docs service import gdata spreadsheet service ''' get user information from the command line argument and pass it to the download method ''' def get_gdoc_information(): email ="mygmailaccount" password ="mypassword" gdoc_id = ['google_id1' 'googleid2' 'googleidn'] for doc_id in gdoc_id: try: download(doc_id email password) except Exception e: raise e #python gdoc py 1m5F5TXAQ1ayVbDmUCyzXbpMQSYrP429K1FZigfD3bvk#gid=0 def download(doc_id email password download_path=None ): print "Downloading the XLS file with id %s" % doc_id gd_client = gdata docs service DocsService() #auth using ClientLogin gs_client = gdata spreadsheet service SpreadsheetsService() gs_client ClientLogin(email password) #getting the key(resource id and tab id from the ID) resource = doc_id split('#')[0] tab = doc_id split('#')[1] split('=')[1] resource_id = 'spreadsheet:'+resource if download_path is None: download_path = os path abspath(os path dirname(__file__)) file_name = os path join(download_path '%s xls' % (doc_id)) print 'Downloading spreadsheet to %s ' % file_name docs_token = gd_client GetClientLoginToken() gd_client SetClientLoginToken(gs_client GetClientLoginToken()) gd_client Export(resource_id file_name gid=tab) gd_client SetClientLoginToken(docs_token) print "Download Completed!" if __name__=='__main__': get_gdoc_information() ```` Whenever I try to run it i get a gdata error below ````gdata service RequestError: {'status': 401 'body': '<HTML>\n<HEAD>\n<TITLE>Unauthorized</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Unauthorized</H1>\n<H2>Error 401</H2>\n</BODY>\n</HTML>\n' 'reason': 'Unauthorized'} ```` Am using gdata library I have been struggling with this whole day and cannot seem to figure out what is happening Can anyone please figure out and assit? Any other minimal script that can achieve my purpose as described above is will be much appreciated Thank you | your error does suggest an login problem Maybe you need to change your settings in your google account or try another way of a login Try looking here: <a href="http://stackoverflow com/questions/2925985/syntaxerror-using-gdata-python-client-to-access-google-book-search-data-api/3013945#3013945">SyntaxError using gdata-python-client to access Google Book Search Data API</a> or here: <a href="http://stackoverflow com/questions/3287651/download-a-spreadsheet-from-google-docs-using-python">Download a spreadsheet from Google Docs using Python</a> I am sorry to post this as an answer but I cannot post comments yet Regards |
Django form re-validation for null/blank fields I have a model and two fields and either fields are set to accept null and blank values Now I want my modelForm to be posted only when one of them fields is validated or filled I already have an answer with jquery but i wanted to know if its possible with django Here Is my model: ````class Post(models Model): content = models TextField(default=None blank=True null=True) image = models FileField(upload_to="static/pic" blank=True null=True) ```` | You can override the clean method in modelform like this: ````def clean(self): if self cleaned_data['image'] is not None or self cleaned_data['content'] != '' : return super() clean() #For python 3 #return super(YourForm self) clean() // for python 2 raise ValidationError('Some Error') ```` |
Accessing self from outside of a class I am attempting to implement a decorator on certain methods in a class so that if the value has NOT been calculated yet the method will calculate the value otherwise it will just return the precomputed value which is stored in an instance `defaultdict` I cannot seem to figure out how to access the instance `defaultdict` from inside of a decorator declared outside of the class Any ideas on how to implement this? Here are the imports (for a working example): ````from collections import defaultdict from math import sqrt ```` Here is my decorator: ````class CalcOrPass: def __init__(self func): self f = func #if the value is already in the instance dict from SimpleData #do not recalculate the values instead return the value from the dict def __call__(self *args **kwargs): # cannot figure out how to access/pass dict_from_SimpleData to here :( res = dict_from_SimpleData[self f __name__] if not res: res = self f(*args **kwargs) dict_from_SimpleData[self f__name__] = res return res ```` And here is the SimpleData class with decorated methods: ````class SimpleData: def __init__(self data): self data = data self stats = defaultdict() #here is the dict I am trying to access @CalcOrPass def mean(self): return sum(self data)/float(len(self data)) @CalcOrPass def se(self): return [i - self mean() for i in self data] @CalcOrPass def variance(self): return sum(i**2 for i in self se()) / float(len(self data) - 1) @CalcOrPass def stdev(self): return sqrt(self variance()) ```` So far I have tried declaring the decorator <them>inside</them> of SimpleData trying to pass multiple arguments with the decorator(apparently you cannot do this) and spinning around in my swivel chair while trying to toss paper airplanes into my scorpion tank Any help would be appreciated! | The way you define your decorator the target object information is lost Use a function wrapper instead: ````def CalcOrPass(func): @wraps(func) def result(self *args **kwargs): res = self stats[func __name__] if not res: res = func(self *args **kwargs) self stats[func __name__] = res return res return result ```` `wraps` is from `functools` and not strictly necessary here but very convenient <hr> Side note: `defaultdict` takes a factory function argument: ````defaultdict(lambda: None) ```` But since you are testing for the existence of the key anyway you should prefer a simple `dict` |
how to prevent editing of any entered record in django model I have a condition where I wish to prevent editing of any entered record in certain django models in my application At the same time I wish to allow add permission for the same and also allow permission to view the existing records of the model I am aware of the readonly_fields option in the ModelAdmin But I am looking for a generic option so that it can be inherited for some of the models ````class ReadOnlyAdmin(admin ModelAdmin): readonly_fields = [] def get_readonly_fields(self request obj=None): return list(self readonly_fields) \ [field name for field in obj _meta fields] def has_add_permission(self request obj=None): return True #False originally def has_delete_permission(self request obj=None): return False class CompanyAdmin(ReadOnlyAdmin): list_display = ('name' 'website') ```` <blockquote> The error if return True for has_add_permission: ````AttributeError at /admin/tracker/company/add/ 'NoneType' object has no attribute '_meta' Request Method: GET Request URL: http://myhost:8000/admin/tracker/company/add/ Django Version: 1 6 5 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute '_meta' ```` </blockquote> | I suppose overriding the read only method is the obvious route: ````class ReadOnlyAdmin(admin ModelAdmin): def get_readonly_fields(self request obj=None): # your logic class YourAdmin(ReadOnlyAdmin): pass ```` |
Setup PyYaml with pyenv on Mac OS X; file not found: python exe I am having trouble installing python packets using pip in a virtualenv After some investigations it turns out there seems to be a problem with PyYaml I downloaded the last version and tried to build it When using the "system" python there is no problem However when I try to run the same command (python setup py install) after activating my virtualenv I get the following error: ````gcc -bundle -bundle_loader python exe -L/usr/local/opt/readline/lib -L/usr/local/opt/readline/lib - L/Users/a/ pyenv/versions/2 7 7/lib build/temp macosx-10 10-x86_64-2 7/ext/_yaml o -lyaml -o build/lib macosx-10 10-x86_64-2 7/_yaml so ld: file not found: python exe clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 ```` I have no idea where it comes from Any clue? | I ran into the same issue using pyenv The dirty way I got it to install was using ````CC=/path/to/virtualenv_dir/bin/python2 7 /path/to/virtualenv_dir/bin/pip install pyyaml ```` If you are using pyenv you can also use ````CC=$(which python) pip install pyyaml ```` |
Simultaneous replace functionality I have already converted user input of DNA code `(A T G C)` into RNA code`(A YOU G C)` This was fairly easy ````RNA_Code=DNA_Code replace('T' 'YOU') ```` Now the next thing I need to do is convert the RNA_Code into it is compliment strand This means I need to replace A with YOU YOU with A G with C and C with G but all simultaneously if I say ````RNA_Code replace('A' 'YOU') RNA_Code replace('YOU' 'A') ```` it converts all the As into Us then all the Us into As but I am left with all As for both I need it to take something like `AUUUGCGGCAAA` and convert it to `UAAACGCCGUUU` Any ideas on how to get this done?(3 3) | Use a translation table: ````RNA_compliment = { ord('A'): 'YOU' ord('YOU'): 'A' ord('G'): 'C' ord('C'): 'G'} RNA_Code translate(RNA_compliment) ```` The <a href="http://docs python org/3/library/stdtypes html#str translate" rel="nofollow">`str translate()` method</a> takes a mapping from codepoint (a number) to replacement character The <a href="http://docs python org/3/library/functions html#ord" rel="nofollow">`ord()` function</a> gives us a codepoint for a given character making it easy to build your map Demo: ````>>> RNA_compliment = {ord('A'): 'YOU' ord('YOU'): 'A' ord('G'): 'C' ord('C'): 'G'} >>> 'AUUUGCGGCAAA' translate(RNA_compliment) 'UAAACGCCGUUU' ```` |
get all parents of xml node using python for this xml ````<Departments orgID="123" name="xmllist"> <Department> <orgID>124</orgID> <name>A</name> <type>type a</type> <status>Active</status> <Department> <orgID>125</orgID> <name>B</name> <type>type b</type> <status>Active</status> <Department> <orgID>126</orgID> <name>C</name> <type>type c</type> <status>Active</status> </Department> </Department> </Department> <Department> <orgID>109449</orgID> <name>D</name> <type>type d</type> <status>Active</status> </Department> </Departments> ```` How i can get all parents of a node using `lxml` `etree` in python Expected output : Input orgid=126 it will return all the parents like ````{'A':124 'B':125 'C':126} ```` | Using `lxml` and XPath: ````>>> s = ''' <Departments orgID="123" name="xmllist"> <Department> <orgID>124</orgID> <name>A</name> <type>type a</type> <status>Active</status> <Department> <orgID>125</orgID> <name>B</name> <type>type b</type> <status>Active</status> <Department> <orgID>126</orgID> <name>C</name> <type>type c</type> <status>Active</status> </Department> </Department> </Department> <Department> <orgID>109449</orgID> <name>D</name> <type>type d</type> <status>Active</status> </Department> </Departments> ''' ```` <hr> Using `ancestor-or-self` axis you can find the node itself parent grandparent ````>>> import lxml etree as ET >>> root = ET fromstring(s) >>> for target in root xpath(' //Department/orgID[text()="126"]'): d = { dept find('name') text: int(dept find('orgID') text) for dept in target xpath('ancestor-or-self::Department') } print(d) {'A': 124 'C': 126 'B': 125} ```` |
how do i adjust this turtle graphics drawing to draw around a circle? with the current code <a href="http://imgur com/fGGiFkS png" rel="nofollow">this is the result</a> but I am trying to get it to look <a href="http://imgur com/91DKww9 png" rel="nofollow">like this</a> but not sure what to tweak ````#circle circle import turtle turtle colormode(255) window=turtle Screen() draw=turtle Turtle() draw pensize(2) window screensize(1200 1200) draw speed('fastest') red green blue= 255 255 0 for shape in range(30): for circle in range(1): draw circle(200) draw penup() draw forward(30) draw pendown() draw left(20) green=green-5 blue=blue+6 draw color(red green blue) window mainloop() ```` | If you notice your two images the one you want has the circles drawn outside the center while the wrong one draws them around the center Try changing `draw left(20)` to `draw right(20)` and adjust your values from there to get the sizes you want The change keeps the turtle outside of the circle just drawn which is what you are looking for |
Django creating user with add user permission I have gone through a strange behavior while creating a user using Django admin interface I have to create a user which can add other users but for that Django requires two permissions i e add user and change user But when I gave user the change permission its even able to change the superuser of the site What I want is to create a user which can only create other users Please suggest Thanks in advance | This is not supported by default in Django You could subclass the normal UserAdmin and make your own that disables the "superuser"-checkbox for non-superusers: ````from django contrib auth admin import UserAdmin from django contrib auth models import User from django contrib import admin class MyUserAdmin(UserAdmin): def formfield_for_dbfield(self db_field **kwargs): field = super(MyUserAdmin self) formfield_for_dbfield(db_field **kwargs) user = kwargs['request'] user if not user is_superuser: if db_field name == 'is_superuser': field widget attrs = {'disabled': 'disabled'} return field admin site unregister(User) admin site register(User MyUserAdmin) ```` |
skip an element in zip I have two files that are `zipped` with something like the following: ````for line in zip(open(file1) open(file2)): # do-something ```` Unfortunately now file2 has changed and there is an additional line at the beginning Yes I could get rid of that manually (or with an additional script/program) but since the actual number of involved files is huge I would prefer to solve the problem at this level So what I want is something like the following (which would be valid if open(file) were subscriptable): ````for line in zip(open(file1) open(file2)[1:]): # do-something ```` | Take a look at <a href="http://docs python org/library/itertools html" rel="nofollow">itertools</a>: ````for line in itertools izip( open(file1) itertools islice(open(file2) 1 None) ): # do something ```` <strong>Edit:</strong> changed from zip to the itertools izip function |
adding a row to a MultiIndex DataFrame/Series I was wondering if there is an equivalent way to add a row to a Series or DataFrame with a MultiIndex as there is with a single index i e using ix or loc? I thought the natural way would be something like ````row_to_add = pd MultiIndex from_tuples() df ix[row_to_add] = my_row ```` but that raises a KeyError I know I can use append() but I would find it much neater to use ix[] or loc[] here an example: ````>>> df = pd DataFrame({'Time': [dt datetime(2013 2 3 9 0 1) dt datetime(2013 2 3 9 0 1)] 'hsec': [1 25] 'vals': [45 46]}) >>> df Time hsec vals 0 2013-02-03 09:00:01 1 45 1 2013-02-03 09:00:01 25 46 [2 rows x 3 columns] >>> df set_index(['Time' 'hsec'] inplace=True) >>> ind = pd MultiIndex from_tuples([(dt datetime(2013 2 3 9 0 2) 0)] names=['Time' 'hsec']) >>> df ix[ind] = 5 Traceback (most recent call last): File "<pyshell#201>" line 1 in <module> df ix[ind] = 5 File "C:\Program Files\Python27\lib\site-packages\pandas\core\indexing py" line 96 in __setitem__ indexer = self _convert_to_indexer(key is_setter=True) File "C:\Program Files\Python27\lib\site-packages\pandas\core\indexing py" line 967 in _convert_to_indexer raise KeyError('%s not in index' % objarr[mask]) KeyError: "[(Timestamp('2013-02-03 09:00:02' tz=None) 0L)] not in index" ```` | You have to specify a tuple for the multi-indexing to work (AND you have to fully specify all axes e g the `:` is necessary) ````In [26]: df ix[(dt datetime(2013 2 3 9 0 2) 0) :] = 5 In [27]: df Out[27]: vals Time hsec 2013-02-03 09:00:01 1 45 25 46 2013-02-03 09:00:02 0 5 ```` Easier to reindex and/or concat/append a new dataframe though Generally setting (with this kind of enlargement) only makes sense if you are doing it with a small number of values As this makes a copy when you do this |
Is it possible to use 'else' in a python list comprehension? Here is the code I was trying to turn into a list comprehension: ````table = '' for index in xrange(256): if index in ords_to_keep: table = chr(index) else: table = replace_with ```` Is there a way to add the else statement to this comprehension? ````table = '' join(chr(index) for index in xrange(15) if index in ords_to_keep) ```` | If you want an `else` you do not want to filter the list comprehension you want it to iterate over every value You can use `true-value if cond else false-value` as the statement instead and remove the filter from the end: ````table = '' join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15)) ```` |
Not checking previous parameter I am trying just starting out with python and I am trying to write a basic program that checks if a word is a palindrome There is a `while` loop within a `while` loop but the program is not backing out to check if the first loop is still applicable ````while n <= half_word_length: while word[n] == word[word_length - 1 - n]: n = 1 if word[n] != word[word_length - n]: print('This word is not a palindrome ') break else: print('This word is a palindrome ') ```` Regardless of if the input word is a palindrome or not the error message is `"list index out of range"` I thought it was because it was not checking outside of the loop but then a non-palindrome should not because the program to crash Apologies if this is hard to understand tell me and I will try fix it up a bit :) | First of all with Python you can use negative indexes: ````mystr = "hello world" mystr[0] # "h" mystr[-1] # "d" mystr[-2] # "r" ```` Do not hesitate to use them! ````for i in range(0 len(word)): if word[i] != s[-1 - i]: return False return True ```` Then as I said in my previous comment there are some <them>pythonic ways</them> of doing such things For instance you can reverse a string in a single instruction: ````mystr = "hello world" mystr[::-1] # "dlrow olleh" ```` So in a single line: ````is_palyndrom = (mystr == mystr[::-1]) ```` |
How to raise a numpy matrix to non-integer power? The `**` operator for `numpy matrix` does not support non-integer power: ````>>> m matrix([[ 1 0 ] [ 0 5 0 5]]) >>> m ** 2 5 TypeError: exponent must be an integer ```` What I want is ````octave:14> [1 0; 5 5] ^ 2 5 ans = 1 00000 0 00000 0 82322 0 17678 ```` Can I do this with `numpy` or `scipy`? <h3>Note:</h3> this is NOT an element-wise operation It is an matrix (in linear algebra) raised to some power as talked in <a href="http://math stackexchange com/questions/16739/arbitrary-non-integer-power-of-a-matrix">this post</a> | From this <a href="http://math stackexchange com/questions/364613/can-you-raise-a-matrix-to-a-non-integer-number">question</a> you can see that the power of a matrix can be rewritten as: <a href="http://i stack imgur com/DOFqN gif"><img src="http://i stack imgur com/DOFqN gif" alt="enter image description here"></a> This code making use of scipy linalg gives as a result the same as Octave: ````import numpy as np from scipy linalg import logm expm M = np matrix([[ 1 0 ] [ 0 5 0 5]]) x = 2 5 A = logm(M)*x P = expm(A) ```` This is the output for P: ````Out[19]: array([[ 1 -0 ] [ 0 8232233 0 1767767]]) ```` |
The Supreme court has power to set jurisdiction of what? | null |
Python - Can I import specific classes when importing all from a package I have a package set up with a tree structure like ````pkg\ __init__ py module1 py Class11 Class12 module2 py Class21 function21 ```` I want specific classes and functions to be in the global namespace such that when I start my script with ````from pkg import * ```` I will be able to directly use say Class11 Class12 and function21 Is this possible? The motivation behind it is to allow for quick and light usages in small scripts or interactive mode It is implicitly known that with longer scripts one would not use import all and traverse the package structure properly EDIT: I could import Class11 Class12 and function21 in pkg's `__init__ py` but in this way when I do the regular `import pkg` I will still be able to access Class11 by `pkg Class11` instead of the proper `pkg module1 Class11` Preferably I want `pkg module1 Class11` to be the only way if I am not doing `import *` | Sure The `*` means "everything" <sup>*</sup> If you do not want everything but instead want a specific list of names just use those names: ````from pkg import Class11 Class21 function21 ```` <hr> Of course this assumes that `pkg` already imports those names from its submodules But if that were not true your `*` import would not work either If that is not true but you want to know how to make it true you just do something similar in `pkg/__init__ py`: ````from module1 import Class11 Class12 from module2 import Class21 function21 ```` Or maybe: ````from module1 import __all__ as _all1 from module2 import __all__ as _all2 from module1 import * from module2 import * __all__ = _all1 _all2 ```` <hr> <sub>* Well not quite "everything" If there is an `__all__` it means "every name in `__all__`"; if not it means "every name that does not start with `_`" But close enough for our purposes </sub> |
create dylib in mac import in python Hi i know how to make Library (dll) in windows with visual studio 2012 with c++ and import in python with ctypes work great here small example lib cpp ````#define DLLEXPORT extern "C" __declspec(dllexport) DLLEXPORT int sum(int a int b) { return (a+b); } ```` lib h ````int sum(int int); ```` test py ````from ctypes import * mydll=cdll LoadLibrary('lib dll') print mydll sum(2 2) ```` i try run same code in mac with xcode 4 4 version when i buld in xcode i get warring message ````__declspec attribute 'dllexport' is not supported ```` and when import lib dylib in python i get error ````AttributeError: dlsym(0x101afba30 sum): symbol not found ```` what i do wrong ? can some one write simple code how i can make a dylib in mac with xcode correct to import with Ctypes in python 2 6 4 OR the are is better way to import libaries in python in both system for mac and win ? basic i like to write code in windows with visual studio 2012 make dll i and then simple compiler in mac with xcode and import in python | Your problem was that you already had the dylib loaded into your Python interpreter Just rebuilding it will not affect what you have loaded into memory Just doing another `LoadLibrary` may or may not re-load the library and there is no way to force it to do so There is also no way to unload and reload libraries in `ctypes` The main reason is that there is no safe way to do so on all platformsâin fact before 10 4 OS X itself was such a platform (And Python still has <a href="http://hg python org/cpython/file/6a1ce1fd1fc0/Modules/_ctypes/darwin" rel="nofollow">current source code in the tree</a> to support pre-10 4 OS X in `ctypes` ) But also trying to come up with a model that does things the safe way on every platform is not exactly trivial So `ctypes` does not try If you really need to do it the `_ctypes` module underneath `ctypes` generally exports the necessary functions into Python If you know the names for your platform you can find them with `help(_ctypes)` or by looking at <a href="http://hg python org/cpython/file/6a1ce1fd1fc0/Modules/_ctypes/callproc c" rel="nofollow">the source</a> Briefly on most modern POSIX platforms (including OS X 10 5+) it is `_ctypes dlclose(mydll _handle)` while on Win32 it is `_ctypes FreeLibrary(mydll _handle)` In either case if you ever use `mydll` again (or any functions or values that you were referencing from it) you should pray for a segfault You may also segfault on exit And on Windows it may not actually free the library when you ask it to and in some cases you have to ask the library if it is ready to unload before you can do so and there are threading complexities and⦠well just read the <a href="http://msdn microsoft com/en-us/library/windows/desktop/ms683152%28v=vs 85%29 aspx" rel="nofollow">`FreeLibrary`</a> docs on MSDN and of course the manpage for <a href="https://developer apple com/library/mac/documentation/Darwin/Reference/ManPages/man3/dlclose 3 html" rel="nofollow">`dlclose(3)`</a> on every POSIX system you care about In general it is a much better idea to just start up a new interpreter process instead |
trying to get many-to-many related data in Django I am building a website in Django where messages have tags Below you can see my models py ````class Message(models Model): message_id = models BigIntegerField(primary_key=True) user = models ForeignKey(User) title = models CharField(max_length=50) tags = models ManyToManyField(Tag blank=True null=True) date_created = models DateTimeField(auto_now_add=True) def get_tags(self tag_id): return self message filter(tags__tag_id=tag_id) class Tag(models Model): tag_id = models BigIntegerField(primary_key=True) tag_name = models CharField(max_length=100) date_created = models DateTimeField(auto_now_add=True) ```` Here is my views py as well ````popular_tags = Tag objects filter(messages__date_created__gt=now) annotate(num=Count('messages')) order_by('-num')[:25] ```` What I am trying to do here is that I want to show tags with the most number of messages After I do that I want the tags to show which messages have that tag So I know I cannot do query filtering in template and that is why I added get_tags under the Message model So with that I have tried writing the right template but I am not sure what went wrong with it ````{% for q in popular_tags %} <tr> <td align="left"><h5>{{ q tag_name }}</h5> </td> {% for m in message get_tags %} <td align="left"><h5>{{ m title }} </h5></td> {% endfor %} </tr> {% endfor %} ```` I am not getting any errors it is just that no messages are being shown while the tags are correctly displayed Any ideas how and where I should fix? | You should add a function within `Tag` rather than `Message`: ````class Tag(models Model): tag_id = models BigIntegerField(primary_key=True) tag_name = models CharField(max_length=100) date_created = models DateTimeField(auto_now_add=True) def get_msgs(self): return Message objects filter(tags__tag_id=tag_id) ```` Hence the template should be: ````{% for q in popular_tags %} <tr> <td align="left"><h5>{{ q tag_name }}</h5> </td> {% for m in q get_msgs %} <td align="left"><h5>{{ m title }} </h5></td> {% endfor %} </tr> {% endfor %} ```` |
Why declare unicode by string in python? I am still learning python and I have a doubt: In python 2 6 x I usually declare encoding in the file header like this (as in <a href="http://www python org/dev/peps/pep-0263/">PEP 0263</a>) ````# -*- coding: utf-8 -*- ```` After that my strings are written as usual: ````a = "A normal string without declared Unicode" ```` But everytime I see a python project code the encoding is not declared at the header Instead it is declared at every string like this: ````a = you"A string with declared Unicode" ```` What is the difference? What is the purpose of this? I know Python 2 6 x sets ASCII encoding by default but it can be overriden by the header declaration so what is the point of per string declaration? <strong>Addendum:</strong> Seems that I have mixed up file encoding with string encoding Thanks for explaining it :) | That does not set the format of the string; it sets the format of the file Even with that header `"hello"` is a byte string not a Unicode string To make it Unicode you are going to have to use `you"hello"` everywhere The header is just a hint of what format to use when reading the ` py` file |
Problems basing enemy stats off of player stats in text based rpg So I am making a text based rpg and I have come up with a weird syntax error that I cannot seem to fix on the line: ````max_hp = randint((player level * 0 75) * 50 player level * 50) ```` in class Enemy Any help would be greatly appreciated :) ````from random import randint import math class Character(object): def __init__(self hp max_hp strength level exp): self level = level self exp = exp self hp = hp self max_hp = max_hp self strength = strength class Player(Character): def __init__(self): exp = 0 level = 1 max_hp = 100 hp = max_hp strength = level * 0 5 print max_hp hp strength def Level(level current_exp): if current_exp >= level * 100: level = 1 else: pass class Enemy(Character): def __init__(self): player = Player() level = randint(player level math ciel((player level * 75) 1) max_hp = randint((player level * 0 75) * 50 player level * 50) hp = max_hp strength = randint(player level 1 player level 3) print max_hp strength player = Player() enemy = Enemy() ```` | you are missing a closing parenthesis on the line above |
What is also a fruit? | pipa |
What are best practices for developing consistent libraries? I am working on developing a pair of libraries to work with a REST API Because I need to be able to use the API in very different settings I am currently planning to have a version in PHP (for web applications) and a second version in Python (for desktop applications and long running processes) Are there any best practices to follow in the development of the libraries to help maintain my own sanity? | Well the obvious one would be to keep your naming consistent Functions and classes should be named similarly (if not identically) in both implementations This usually happens naturally whenever you implement an API separately in two different languages The big ticket item though (at least in my book) is to follow language-specific idioms For example let us assume that I were implementing a REST API in two languages I am more familiar with: Ruby and Scala The Ruby version might have a class `MyCompany::Foo` which contains method `bar_baz()` Conversely the Scala version of the same API would have a class `com mycompany rest Foo` with a method `barBaz()` It is just naming conventions but I find it goes a long way to helping your API to feel "at home" in a particular language even when the design was created elsewhere Beyond that I have only one piece of advise: document document document That is easily the best way to keep your sanity when dealing with a multi-implementation API spec |
GUI freezes when executing def function Use threads? I have made a small program which has 2 buttons and each does certain thing Here is a simplified version of the code Thing is it works fine except that the button freezes and stays in a clicked position and whole GUI freezes until the command is completed As far as I know threads would be best to use in this situation but I have no idea how to implement it in this example I use glade and pygtk for gui ```` def do1: t = 2 #do something time sleep(t) #do something time sleep(t) def do2: t = 3 #do something time sleep(t) #do something time sleep(t) class we: wTree = None def __init__( self ): self wTree = gtk glade XML( "ui glade" ) dic = { "on_buttonSone" : self sone "on_buttonStwo" : self stwo } self wTree signal_autoconnect( dic ) gtk main() def sone(self widget): i = 0 while i < 3: t = 1 #do something i = 1 time sleep(t) self wTree get_widget("entryResult") set_text("Done ") def stwo(self widget): start = time clock() array = ['A' 'B'] adict = {'A':do1 'B':do2} for f in array: adict[f]() end = time clock() elapsed = end - start gg = round(elapsed 2) self wTree get_widget("entryResult") set_text(str(gg)) go=we() ```` | <a href="http://faq pygtk org/index py?req=all#20 1" rel="nofollow">pyGTK has a whole section of there FAQ devoted to threading</a> 20 6 seems like a good minimal example |
run python script with an ini file i would like to run a python script with different ini files I put some variable's in an ini py and than i would like to run my program py with this inifile I tried something like: in batch-> program py ini ````sys argv[1] from sys argv[1] import * ```` and ````eval('from '+sys argv[1]+' import *') ```` but this does not work now I wrote: ````import sys f = open('outp py' 'w') f write("from "+sys argv[1]+" import *\n") f write("print x\n") with open('program py' 'r') as content_file: content = content_file read() f write(content) f close() execfile( "outp py") ```` basicly rewriting my program file with an extra import statment there is an easier way i hope?! (not neccesarely in batch) thanks | You can use the `__import__` function ````my_module=__import__('os') #basically the same as `import os as my_module` ```` Of course you cannot do `from blah import *` with this but many people would argue that you should not use that idiom in production code anyway However if you just want to set a few variables you should instead consider a commandline parsing utility or a config file parser (`configparser` `argparse` and `optparse` all come to mind -- all in the standard library) as this will prevent users from running untrusted code |
python: print i for i in list When I printed a list I got a syntax error when using this method: ````print i for i in [1 2 3] ```` I knew this is ok when using this method: ````for i in [1 2 3]: print i ```` and I knew that ````(i for i in [1 2 3]) ```` is a generator object but I just do not get it that why ````print i for i in [1 2 3] ```` does't work Can anyone give me a clue? | The list comprehension syntax `x for x in ` <them>requires</them> brackets around it That is a syntactic rule of Python just like requiring indentation or requiring a colon after `if` or whatever `i for i in [1 2 3]` by itself is not valid syntax You need either `[i for i in [1 2 3]]` (for a list comprehension) or `(i for i in [1 2 3])` (for a generator comprehension) |
Where does the Glounthaune Rail system that departs from Kent Station connect to? | null |
Date comparion/consecutive date grouping I Am trying to write a function which identifies groups of dates and measures the size of the group The function will take a list of elements (the elements are individual lines from a CSV file with dates in) which have been sorted in date order The list may be 0 to n elements long I wish to write the list as it was inputted with the addition of the size of the date-group for example the list ````Bill 01/01/2011 Bill 02/01/2011 Bill 03/01/2011 Bill 05/01/2011 Bill 07/01/2011 ```` should be output (ideally printed to a file) as ````Bill 01/01/2011 3 Bill 02/01/2011 3 Bill 03/01/2011 3 Bill 05/01/2011 1 Bill 07/01/2011 1 ```` I have a function already called `isBeside(string1 string2)` which returns the delta between the two My attempt so far is this (an iterative mess i am sure python can be more elegant than this) Note `coll[i][1]` contains the date element of the CSV line ````def printSet(coll): setSize = len(coll) if setSize == 0: #do not need to do anything elif setSize == 1: for i in coll: print i 1 elif setSize > 1: printBuffer = [] ##new buffer list which will hold sequential dates until a non-sequential one is found printBuffer append(coll[0]) #add the first item print 'Adding ' str(coll[0]) for i in range(0 len(coll)-1): print 'Comparing ' coll[i][1] coll[i+1][1] isBeside(coll[i][1] coll[i+1][1]) if isBeside(coll[i][1] coll[i+1][1]) == 1: printBuffer append(coll[i+1]) print 'Adding ' str(coll[i+1]) else: for j in printBuffer: print j len(printBuffer) printBuffer = [] printBuffer append(coll[i]) return ```` | Something like this? ````from datetime import date timedelta coll = [['Bill' date(2011 1 1)] ['Bill' date(2011 1 2)] ['Bill' date(2011 1 3)] ['Bill' date(2011 1 5)] ['Bill' date(2011 1 7)]] res = [] group = [coll[0]] i = 1 while i < len(coll): row = coll[i] last_in_group = group[-1] # use your isBeside() function here if row[1] - last_in_group[1] == timedelta(days=1): # consecutive append to current group group append(row) else: # not consecutive start new group res append(group) group = [row] i = 1 res append(group) for group in res: for row in group: for item in row: print item print len(group) ```` It prints: ````Bill 2011-01-01 3 Bill 2011-01-02 3 Bill 2011-01-03 3 Bill 2011-01-05 1 Bill 2011-01-07 1 ```` |
Scrapy and submitting a javascript form I am learning scrapy and I have run into a snag attempting to submit a form that is controlled by javascript I have tried experimenting with a number of things found here on Stack Overflow including Selenium but having no luck (for a number of reasons) The page I need to scrape is <a href="http://agmarknet nic in/" rel="nofollow">http://agmarknet nic in/</a> and do a commodities search When I inspect elements it appears to have a form "m" with a filed "cmm" needing a commodity value ````<form name="m" method="post"> ( ) <input type="text" name="cmm" onchange="return validateName(document m cmm value);" size="13"> ( ) <input type="button" value="Go" name="Go3" style="color: #000080; font-size: 8pt; font-family: Arial; font-weight: bold" onclick="search1();"></td> ```` Any advice gratefully accepted! UPDATE: I have tried this with selenium but it does not find or populate the field I also would not mind being able to do this without popping up a firefox window ```` CrawlSpider __init__(self) self verificationErrors = [] from selenium import webdriver from selenium webdriver common keys import Keys driver = webdriver Firefox() driver get("http://agmarknet nic in/") time sleep(4) elem = driver find_element_by_name("cmm") elem send_keys("banana") time sleep(5) elem send_keys(Keys RETURN) driver close() ```` UPDATE: I have also tried various iterations of the following but with no luck When I submit the search from the web page fiddler2 tells me it is post'ing the string "cmm=banana&mkt=&search=" but when I use the code below fiddler tells me nothing is being posted ````class Agmarknet(Spider): name = "agmarknet" start_urls = ["http://agmarknet nic in/SearchCmmMkt asp"] def parse(self response): return [FormRequest from_response( response #formname = "cmm1" formdata={ 'method':'post' 'cmm': 'banana' 'mkt': '' 'search':''} callback=self after_search)] def after_search(self): print response body ```` OUTPUT FROM ABOVE: ````{'download_timeout': 180 'download_latency': 13 44700002670288 'proxy': 'http://127 0 0 1:8888' 'download_slot': 'agmarknet nic in'} Spider error processing <GET http://agmarknet nic in/SearchCmmMkt asp> Traceback (most recent call last): File "Z:\WinPython-32bit-2 7 6 2\python-2 7 6\lib\site-packages\twisted\internet\base py" line 1201 in mainLoop self runUntilCurrent() File "Z:\WinPython-32bit-2 7 6 2\python-2 7 6\lib\site-packages\twisted\internet\base py" line 824 in runUntilCurrent call func(*call args **call kw) File "Z:\WinPython-32bit-2 7 6 2\python-2 7 6\lib\site-packages\twisted\internet\defer py" line 382 in callback self _startRunCallbacks(result) File "Z:\WinPython-32bit-2 7 6 2\python-2 7 6\lib\site-packages\twisted\internet\defer py" line 490 in _startRunCallbacks self _runCallbacks() --- <exception caught here> --- File "Z:\WinPython-32bit-2 7 6 2\python-2 7 6\lib\site-packages\twisted\internet\defer py" line 577 in _runCallbacks current result = callback(current result *args **kw) File "Z:\WindowsDocuments\eclipseworkspaces\BioCom\manoliagro-agmarknetscraper\src\bin\agmarknetscraper\spiders\agmarknet py" line 34 in parse callback=self after_search)] File "Z:\WinPython-32bit-2 7 6 2\python-2 7 6\lib\site-packages\scrapy-0 22 0-py2 7 egg\scrapy\http\request\form py" line 36 in from_response form = _get_form(response formname formnumber formxpath) File "Z:\WinPython-32bit-2 7 6 2\python-2 7 6\lib\site-packages\scrapy-0 22 0-py2 7 egg\scrapy\http\request\form py" line 59 in _get_form raise ValueError("No <form> element found in %s" % response) exceptions ValueError: No <form> element found in <200 http://agmarknet nic in/SearchCmmMkt asp> SpiderRun done ```` | What will make your life easier especially with javascript is <a href="http://docs seleniumhq org/projects/ide/" rel="nofollow">Selenium IDE</a> It is a firefox-plugin able to record what you click & type in firefox and afterwards showing you the code for certain elements you need to put in your python-script Was very useful for me not only with forms :-) Try it out! |
missing attribute error when trying to set cell color in xlwt using python I am trying to change the color of my excel spreadsheet to color code data using python's xlwt package Here is my current code: ````from xlrd import open_workbook from tempfile import Temporary File from xlwt import sys import csv #Some other code style = xlwt XFStyle() #this is the line throwing the error pattern = xlwt Pattern() pattern pattern = xlwt Pattern SOLID_PATTERN pattern pattern_fore_colour = xlwt Style colour_map['red'] pattern pattern_fore_colour = xlwt Style colour_map['red'] newSheet write(row col values[row - 1][col] pattern) #Some other code ```` Other code sections are there because it is a longer script than shown but those sections of code are not related to this problem I get the following stack trace when it runs: ````Traceback (most recent call last): File "excel-procesor py" line 85 in <module> newSheet write(row col values[row - 1][col] pattern) File "/usr/local/lib/python2 7/dist-packages/xlwt/Worksheet py" line 1030 in write self row(r) write(c label style) File "/usr/local/lib/python2 7/dist-packages/xlwt/Row py" line 234 in write self __adjust_height(style) File "/usr/local/lib/python2 7/dist-packages/xlwt/Row py" line 64 in __adjust_height twip = style font height AttributeError: 'Pattern' object has no attribute 'font' ```` I am using <a href="http://stackoverflow com/questions/10532367/how-to-change-background-color-of-excel-cell-with-python-xlwt-library">How to change background color of excel cell with python xlwt library?</a> and <a href="http://stackoverflow com/questions/7746837/python-xlwt-set-custom-background-colour-of-a-cell">python xlwt set custom background colour of a cell</a> as guides | According to the source code: ````xlwt Worksheet write(self are c label='' style=<xlwt Style XFStyle object at 0x053AEA10>) ```` `write` should receive the `style` as argument and not directly the `Pattern` object You should try to put your pattern object into `style` and pass `style` as argument: ````style pattern = pattern newSheet write(row col values[row - 1][col] style) ```` Some <a href="http://www youlikeprogramming com/2011/04/examples-generating-excel-documents-using-pythons-xlwt/" rel="nofollow">examples</a> I found useful how to use `xlwt` including how to set the style |
Maltparser giving error in NLTK My COde is ````from nltk parse import malt mp = malt MaltParser(working_dir="/other/apps/maltparser-1 8 1" mco="engmalt poly-1 7 mco" additional_java_args=['-Xmx1024m']) print mp raw_parse("Hello World") ```` And the error is ```` Traceback (most recent call last): File "malt py" line 13 in <module> print mp raw_parse("Hello World") File "/usr/local/lib/python2 7/dist-packages/nltk/parse/malt py" line 139 in raw_parse return self parse(words verbose) File "/usr/local/lib/python2 7/dist-packages/nltk/parse/malt py" line 126 in parse return self parse_sents([sentence] verbose)[0] File "/usr/local/lib/python2 7/dist-packages/nltk/parse/malt py" line 114 in parse_sents return self tagged_parse_sents(tagged_sentences verbose) File "/usr/local/lib/python2 7/dist-packages/nltk/parse/malt py" line 194 in tagged_parse_sents "code %d" % (' ' join(cmd) ret)) Exception: MaltParser parsing (java -Xmx1024m -jar /usr/local/bin/malt jar -w /other/apps/maltparser-1 8 1 -c engmalt poly-1 7 mco -i /other/apps/maltparser-1 8 1/malt_input conlljOba1P -o /other/apps/maltparser-1 8 1/malt_output conllPLcoTu -m parse) failed with exit code 1 ```` | The MaltParser API in NLTK just had <a href="https://github com/nltk/nltk/pull/944" rel="nofollow">a patch</a> that fixes and stabilizes the problems that it used to have: - <a href="http://stackoverflow com/questions/14009330/how-to-use-malt-parser-in-python-nltk">How to use malt parser in python nltk</a> - <a href="http://stackoverflow com/questions/20091698/malt-parser-throwing-class-not-found-exception">Malt Parser throwing class not found exception</a> - <a href="http://stackoverflow com/questions/29513187/maltparser-not-working-in-python-nltk">MaltParser Not Working in Python NLTK</a> Here is an example of how to use MaltParser API in NLTK: ````# Upgrade your NLTK alvas@ubi:~$ cd ~ alvas@ubi:~$ pip install -YOU nltk # Get the latest MaltParser and model alvas@ubi:~$ wget http://maltparser org/dist/maltparser-1 8 1 zip alvas@ubi:~$ unzip maltparser-1 8 1 zip alvas@ubi:~$ wget http://www maltparser org/mco/english_parser/engmalt poly-1 7 mco # In python now you can do this: alvas@ubi:~$ python >>> from nltk parse malt import MaltParser >>> mp = MaltParser('/home/alvas/maltparser-1 8 1' '/home/alvas/engmalt poly-1 7 mco') >>> sent1 = 'I shot an elephant in my pajamas ' split() >>> print(mp parse_one(sent1) tree()) (shot I (elephant an (in (pajamas my))) ) ```` (See <a href="https://github com/nltk/nltk/blob/develop/nltk/parse/malt py#L284" rel="nofollow">here</a> for more demo code or <a href="https://github com/nltk/nltk/blob/f4c16c2f9c46cc42c9b68ae746832b622581c6b5/nltk/parse/malt py#L354" rel="nofollow">here</a> for a more elaborated demo code) <hr> Note that you can also use the export features and you can escape the usage of full path when initializing the `MaltParser` object But you have to still tell the object what is the name of the parser directory and model filename to look for e g ````alvas@ubi:~$ export MALT_PARSER='/home/$UID/maltparser-1 8 1/' alvas@ubi:~$ export MALT_MODEL='/home/$UID/engmalt poly-1 7 mco' alvas@ubi:~$ python >>> from nltk parse malt import MaltParser >>> mp = MaltParser('maltparser-1 8 1' 'engmalt poly-1 7 mco') >>> sent1 = 'I shot an elephant in my pajamas ' split() >>> print(mp parse_one(sent1) tree()) (shot I (elephant an (in (pajamas my))) ) ```` |
Who encouraged conversions in order to make more revenue? | null |
pyschools topic 3 ex 9 I have made already 3 posts today about pyschools com exercises i hope that is not too much Anyway the exercise asks me to write a function to convert the time to 24 hour format Here is an example: >>> time24hr('12:34am') '0034hr' My function which works fine in my IDLE: ````def time24hr(tstr): am_or_pm = tstr[-2:] first_numbers = tstr[0:2] last_numbers = tstr[3:5] if am_or_pm == "am": if first_numbers == '12': first_in_am12 = '00' return first_in_am12 last_numbers am_or_pm else: return first_numbers last_numbers am_or_pm if am_or_pm == "pm": if first_numbers == '12': return first_numbers last_numbers am_or_pm elif int(first_numbers) > 9: ok = repr(int(first_numbers) 12) return ok last_numbers am_or_pm elif int(first_numbers) <= 9: ok = repr(int(tstr[1]) 12) return ok last_numbers am_or_pm ```` However in the pyschools website when i run the code it gives me the following error : ValueError: invalid literal for int() with base 10: '1:' What does this mean ? | Actually your code is incorrect and you are not testing with full scale of test cases Consider the following scenarios ````>>> time24hr('2:34pm') Traceback (most recent call last): File "<pyshell#855>" line 1 in <module> time24hr('2:34pm') File "<pyshell#849>" line 14 in time24hr elif int(first_numbers) > 9: ValueError: invalid literal for int() with base 10: '2:' >>> time24hr('2:34am') '2:4aam' >>> time24hr('0:34am') '0:4aam' >>> time24hr('12am') '00mam' >>> ```` And you will see weird results The reason is because you have assumed that the input would always be in the format HH:MM[am|pm] You should make your code flexible to accept other formats Try to use `split(':')` instead of `first_numbers = tstr[0:2]` and `last_numbers = tstr[3:5] ` |
Python Finite Automata library What would be the most complete finite automata library for Python which is able to do the basic manipulations such as: - Minimization - Determinization of Nondeterministic Finite automata - Union Intersection and Product of the languages generated by these automata etc All the libraries that I am finding are either incomplete or do not work plug-and-play-wise | <a href="http://code google com/p/python-automata/" rel="nofollow">`python-automata`</a> seems to be able to do all the things you are asking - What is it missing? - Perhaps you would want to contribute a missing feature yourself? |
Python catch specific exceptions I have a python script that is being used to automate GPG/PGP file encryption (among a few other tasks) and I am having an issue catching errors being thrown by gunpg from within the script The overall setup is that I am configuring the variables in a database table and pulling them into the script to encrypt files So I am looking at catching the errors related to the encryption process failing (such as an incorrectly typed key in the database) When I execute the encryption with a bad key from the python she will I get the following error: ````<gnupg Crypt object at 0x7f49d0c51b50> ```` I am attempting to catch that error and send the info to a log file so that I can better debug any issues when setting this up Here is the code from the script that relates to this: ````try: gpg encrypt_file(open_file pub_key always_trust=True output=enc_file) except: logger error('ERROR: check the keystore and/or public key') ```` This just gets skipped over and I find out later down in my script that the encryption process failed when I attempt to validate if the encrypted file exists Any help is much appreciated Thanks! | `<gnupg Crypt object at 0x7f49d0c51b50>` is the return value from `gpg encrypt_file()` not an exception The Python console is simply displaying it for you because you did not assign it to a variable Note that the <a href="https://pythonhosted org/python-gnupg/#encryption" rel="nofollow">docs</a> for `encrypt_file()` state: <blockquote> Any public key provided for encryption should be trusted otherwise encryption fails but without any warning <strong>This is because gpg just prints a message to the console but does not provide a specific error indication that the Python wrapper can use </strong> </blockquote> Presumably this also applies in the case when the key does not exist in the keystore |
Getting attachment's hash for message files Right now I have code that does the following - Gets emails from inbox - Downloads emails - Goes through every email that was downloaded and extracts the attachments - Saves the attachment - Gets the hash for the file that was saved But instead of saving the attachment is it possible to just get the hash for the attachment and skipping the save? ````attachments = message Attachments for attachment in attachments: if attachment FileName endswith(" message"): attachment SaveASFile( os path dirname(os path abspath(__file__)) '/attachments/' str( time time()) "-" message subject "-" attachment FileName) ```` EDIT: This is what I have tried: ````def get_attachments(message): attachments = message Attachments for attachment in attachments: data_array = message PropertyAccessor GetProperty("http://schemas microsoft com/mapi/proptag/0x37010102") print len(data_array) ```` This is the error I am getting: ````pywintypes com_error: (-2147352567 'Exception occurred ' (4096 you'Microsoft Outlook' you'The property "http://schemas microsoft com/mapi/proptag/0x37010102" is unknown or cannot be found ' None 0 -2147221233) None) Process finished with exit code 1 ```` | Yes it is possible You need to use the <a href="https://msdn microsoft com/en-us/library/microsoft office interop outlook attachment propertyaccessor aspx" rel="nofollow">PropertyAccessor</a> property of the Attachment class to get an instance of the corresponding class It returns a <a href="https://msdn microsoft com/en-us/library/office/ff863046 aspx" rel="nofollow">PropertyAccessor</a> object that supports creating getting setting and deleting properties of the parent Attachment object So you can use the GetProperty method of the PropertyAccessor class to get a value of the PR_ATTACH_DATA_BIN property (the DASL name is `http://schemas microsoft com/mapi/proptag/0x37010102`) which returns a byte array which represents the attached file |
Who felt threatened by the Fujiware attempt to validate estate records? | null |
How to temporarily move a django site into a subdirectory (for testing)? I am in the process of deploying a new Django site to replace a current Wordpress blog As I get it setup I want to test everything in the domain's subdirectory before I switch things to the root and "go live" For example: `http://example com/django/` Editing my ` htaccess` file allows me to redirect things without a hitch (I can see the Django site and my wordpress site still works) however I am not sure how to tell Django to view `http://example com/django/` as the BASE URL (rather than just `http://example com/`) I tried setting my SITE domain but that did not help Currently all my pages get a 404 response - they they are not matching any url patterns (because none of my url patterns start with `django/`) I looked for a way to set a `BASE_URL` but cannot find any Ideas? I only want to do this for a couple hours while I test everything to make sure it is working and then swap the settings in the ` htaccess` file and run it on the main site | Set the following in your Apache directive: ```` PythonOption django root /django ```` Then django will trim `/django` off the front of every URL request |
How did City Council decide to paint the A? | red, white and blue |
How do I upload multiple files using Kivy (on android)? I have got a Kivy app that does what I need it to with one problem I have an event handler button that does this: ````def upload_files(self): s = requests Session() while self selected_files: filename = self selected_files pop() with open(filename 'rb') as f: s post('http://example com/upload' files={'file': f}) self upload_queue item_strings = [os path basename(_) for _ in self selected_files] ```` This uploads the file a-OK However when this runs on my Android it completely locks up the system Is there a correct way of uploading files with Kivy? Searching for `python kivy file upload` did not turn up anything useful The closest thing I have found was <a href="https://kivy org/docs/api-kivy network urlrequest html" rel="nofollow">https://kivy org/docs/api-kivy network urlrequest html</a> but it does not show how to upload a file Is there an example somewhere for uploading files in Kivy without blocking on Android? | Do your blocking operation in a thread |
why does this happen with lists in python When I assign one list to another I see that upon changing one of the elements in one list the other element is automatically assigned with that value What is the reason for this behavior? ````>>> a = [1 2 3] # create a list >>> b = a >>> b [1 2 3] >>> id(a) 40307408 >>> id(b) 40307408 >>> a[2] = 5 >>> b [1 2 5] >>> b[1] = 10 >>> a [1 10 5] ```` | Because objects `a` and `b` reference the same object (as you have observed by checking both objects' `id`s) If you change a value in one the other will change as well It is like `b` is a clone of `a` but will continue being a clone To avoid this behaviour you can do: ````b = a[:] ```` Which assigns `b` a copy of `a` Or: ````b = list(a) ```` Or: ````import copy b = copy copy(a) # The copy module can be useful for nested lists ```` |
How to convert * mha file to * nii file in Python (without using MedPy) or C? I want to process `* mha` file in `Python` But it requires the `MedPy` package which depends on `ITK` package I am currently having problems installing `ITK` package I was thinking of whether there is a way to convert `* mha` file to `* nii` file (using some other way may be `C++`) because I can then use `Python` to read `* nii` file Any pointers related are most welcome | Another route to solving this problem is installing sci-kit image and simpleitk This requires no building from source or wrapping of ITK and allows reading of MHA files and writing to NIFTI format ````pip install scikit-image pip install SimpleITK or easy_install -YOU SimpleITK ```` With these installed if you run the following code this should work ````import skimage io as io path = 'C:/test mha' #path to your MHA file outpath = 'C:/test nii' img = io imread(path plugin='simpleitk') io imsave('outpath' img plugin='simpleitk') ```` |
Boto Credential Error with Python on Windows I have been working on trying to sign in on Boto via python for the last few hours and cannot seem to solve the problem Python keep returning the error that: ```` No handler was ready to authenticate 1 handlers were checked ['HmacAuthV1Handler'] Check your Credentials ```` According to the logger: ```` boto set_stream_logger('boto') ```` The problem is: "[DEBUG]: Retrieving credentials from metadata server " This must mean my credentials file cannot be found and while I am not sure exactly where to place my file "mycreds boto" with my access and security key I have copied it to several location in the boto directory within my site-packages I have searched extensively and am unsure where to place this file Given the fact that: ```` s3 = boto connect_s3() ```` I am unsure how I would specify the path to my file "mycreds boto" if it was not in the "correct" location Seeing as how moving the file around did not work I have created an environmental variable "BOTO_CONFIG" with a value equal to the path to a "boto config" file that stores the same credentials as my "mycreds boto" file This unfortunately did not solve any issues Finally I have tried logging in using this code: ```` s3 = boto connect_s3(<aws access> <aws secret key>) ```` This returned the following from the logger: "[DEBUG]:Using access key provided by client " and "[DEBUG]:Using secret key provided by client " It did not return any other errors but when I tried to access my buckets online I was unable to connect I have tried restarting my Command windows and computer multiple times and I am not sure what else to try I have basically run out of ideas so any help would be appreciated I am running Windows 7 and Python 2 7 7 | By default boto looks for credentials in `/etc/boto cfg` and in `~/ boto` It uses `os path expanduser` to try to expand `~/ boto` into the appropriate path on your system For Windows platforms this relies on the environment variables `HOME` and `USERPROFILE` If neither of these variables are set in your environment it probably will not find the boto config file You have a couple of options You could make sure that `HOME` is set in your environment to the directory in which your ` boto` file is stored Or you could set the environment variable `BOTO_CONFIG` to point directly to your config file wherever it is on your file system If you take this option it should be set to the fully qualified path to your boto config file I am not sure why supplying the credentials directly did not work for you Could you provide more information about how it is failing? Are you getting an error message? If so what? |
Need help to compute derivative and integral using Numpy I need help to compute derivative and integral of function using finite difference method and Numpy without using loops The whole task: Tabulate Gauss function f(x) = (1 /(sqrt(2 *pi)*s))*e**(-0 5*((x-m)/s)**2) on the interval [-10 10] for m = 0 and s=[0 5 5] Compute derivative and integral of the function using finite difference method without using loops Create plots of the function and its derivative Use Numpy and Matplotlib Here is the beginning of the programm: def f(x s m): ````return (1 /(sqrt(2 *pi)*s))*e**(-0 5*((x-m)/s)**2) ```` def main(): ````m = 0 s = np linspace(0 5 5 3) x = np linspace(-10 10 20) for i in range(3): print('s = ' s[i]) for j in range(20): f(x[j] s[i] m) print('x = ' x[j] ' y = ' f(x[j] s[i] m)) ```` | By using the numpy arrays you can apply that operation directly with algebraic notation: ````result = (1 /(np sqrt(2 *np pi)*s))*np exp(-0 5*((x-m)/s)**2) ```` |
Exceptions in django stop the flow? in my view I am executing this piece of code: ````try: activeterm = LeaseTerm objects get(lease=lease is_active = True) except LeaseTenant DoesNotExist: activeterm = None ```` And I expected there will be no value in `LeaseTerm` I will get exception but I am getting an error: <blockquote> LeaseTerm matching query does not exist </blockquote> But I expected that I have handled the exception and flow should continue What is my miss understanding? | Please retry with: ````try: activeterm = LeaseTerm objects get(lease=lease is_active = True) except LeaseTerm DoesNotExist: # LeaseTerm activeterm = None ```` |
Creating Word Cloud in Python --- Making Words Different Sizes? I am trying to create a word cloud in python using <a href="https://pypi python org/pypi/pytagcloud/" rel="nofollow">pytagcloud</a> With my current cloud I can generate a cloud but the words all are the same size How can I alter the code so that my words' sizes appear in relation to their frequency? My text file already has the words with their respective frequency counts already in it the format is like "George 44" newline "Harold 77" newline "Andrew 22" newline etc However when it displays the word it also displays the frequency with it ````with open ("MyText txt" "r") as file: Data =file read() replace('\n' '') tags = make_tags(get_tag_counts(Data) maxsize=150) create_tag_image(tags 'Sample png' size=(1200 1200) background=(0 0 0 255) fontname='Lobstero' rectangular=True) import webbrowser webbrowser open('Sample png') ```` | You need to cast the result into a tuple Using your question as input text we get the expected result: ````from pytagcloud import create_tag_image make_tags from pytagcloud lang counter import get_tag_counts TEXT = '''I am trying to create a word cloud in python With my current cloud I can generate a cloud but the words all are the same size How can I alter the code so that my words' sizes appear in relation to their frequency?''' counts = get_tag_counts(TEXT) tags = make_tags(counts maxsize=120) create_tag_image(tags 'cloud_large png' size=(900 600) fontname='Lobster') ```` <img src="http://i stack imgur com/nlaGG png" alt="enter image description here"> It is worth looking at the variable `counts`: ````[('cloud' 3) ('words' 2) ('code' 1) ('word' 1) ('appear' 1) ```` which is simply a list of tuples Since your input text file contains a list of tuples you simply need to pass that information into `make_tags` <strong>Edit:</strong> You can read a file like this ````counts = [] with open("tag_file txt") as FIN: for line in FIN: # Assume lines look like: word number word n = line strip() split() word = word replace(' ' '') counts append([word int(n)]) ```` |
Regular expression for coordinates in Python I do not have much experience with regexps so need to ask the question here I am uploading a database for a learning algorithm There are five variables: iteration label vector of pixel intensities vector of coordinates and bounding box cordinates I have uploaded vector of pixels this way: ````with open(tracked_cow 'r+') as f: elif line % 5 == 2: # regular expression string_this_obs = [float(val) for val in re findall(r"[\d ]+" vs)] mean_intensities append(string_this_obs) ```` to get a list of intensities for each observation in floats which is exactly what I need Coordinates for each observation are in format `[(v1 v2) (v3 v4) ]` and I would like to get something like `['(v1 v2)' '(v3 v4)' ]` where each input is a string EDIT: here is the raw data from the file : ````10 3 [0 11198258 0 24691357 0 17487293 0 46013072 0 20174292 0 16528684 0 20348585 0 15991287 0 3205519 0 16397965 0 54306459 0 10878723 0 035439365 0 11387073 0 8691358 0 27843139 0 090777054 0 065649971 0 1697894 0 12941177 0 2556282 0 10762528 0 26187363 0 10312274 0 26550472 0 069571532 0 23805377 0 10036311 0 18707335 0 15976763 0 1828613 0 38010171 0 094262883 0 39157587 0 35410312 0 093827158 0 10777052 0 10777051 0 10079884 0 20130719 0 1029775 0 20275964 0 57981122 0 26056644 0 16180103 0 21089324 0 18445896 0 15323168 0 070007272 0 14989108 0 22716051 0 58344227 0 69876546 0 13478577 0 17037037 0 17893973 0 16092958 0 98155409 0 2771242 0 0824982 0 29092228 0 089034133 0 11314452 0 07392884 0 07770516 0 074074082 0 27102399 0 10442992 0 19419028 0 20116195 0 16325344 0 10617284 0 84647787 0 5863471 0 088017434 0 16891794 0 070007272 0 088598408 0 13493101 0 18997823 0 98779958 0 071895428 0 17748728 0 19680466 0 15700799 0 49513438 0 068409592 0 96920842 0 09440814 0 90515625 0 2878722 0 03267974 0 22120552 0 26753813 0 070007272 0 11372551 0 11532317 0 29019612 0 21161947 0 37400147] [(366 732) (269 759) (318 739) (326 790) (369 771) (384 775) (376 744) (312 739) (366 737) (304 736) (359 758) (333 773) (266 728) (362 728) (313 767) (343 759) (381 777) (268 731) (290 751) (287 740) (266 760) (334 745) (276 728) (313 751) (382 766) (265 751) (328 755) (310 748) (349 730) (374 759) (350 743) (360 756) (375 782) (354 754) (349 738) (345 747) (296 789) (355 790) (356 778) (363 730) (346 772) (278 753) (314 765) (383 723) (303 734) (374 778) (361 770) (299 733) (368 732) (286 737) (268 762) (287 769) (306 770) (323 748) (346 787) (294 757) (340 751) (283 771) (333 738) (266 737) (326 740) (382 772) (325 751) (267 741) (366 759) (266 732) (270 758) (307 782) (357 781) (325 755) (304 733) (320 780) (362 749) (283 775) (379 773) (374 730) (368 732) (265 748) (338 767) (317 736) (340 784) (316 788) (272 728) (360 770) (292 762) (359 756) (343 778) (306 767) (321 784) (340 725) (288 724) (366 789) (378 735) (339 735) (383 753) (305 780) (326 773) (366 750) (312 729) (339 738)] Bbox(x0=723 0 y0=263 0 x1=794 0 y1=389 0) ```` | Does this do what you are looking for? ````re findall(r'(\(\d+ \d+\))' coord_string) ```` |
Cookie not accepted on IE when authenticating with Graph API (oauth) - iframe app I started playing with the new graph api with the python sdk I am trying to use the python-sdk in an iframe app to make the authentication (I successfully did it with JS - although the popup is blocked on IE and chrome by default) I am following this example: <a href="http://github com/facebook/python-sdk/blob/master/examples/oauth/facebookoauth py" rel="nofollow">http://github com/facebook/python-sdk/blob/master/examples/oauth/facebookoauth py</a> It works on chrome and firefox but in safari and IE it only works if I set the cookie permissions in the browser to the lowest possible (which is impractical for average users) Any ideas ? Ze | <strong>IE</strong> Make sure the <a href="http://www w3 org/P3P/" rel="nofollow">P3P</a> header is set on all responses served through the iframe <strong>Safari</strong> Do not know <a href="http://stackoverflow com/questions/408582/setting-cross-domain-cookies-in-safari">Some</a> indicate that there is no better way than what you have already figured out |
Optimize Function - use array as input I am playing with SciPy today and I wanted to test least square fitting The function malo(time) works perfectly in returning me calculated concentrations if I put it in a loop which iterates over an array of timesteps (in the code "time") Now I want to compare my calculated concentrations with my measured ones I created a residuals function which calculates the difference between measured concentration (in the script an array called conc) and the modelled concentration with malo(time) With `optimize leastsq` I want to fit the parameter PD to fit both curves as good as possible I do not see a mistake in my code malo(time) performs well but whenever I want to run the `optimize leastsq` command Python says "only length-1 arrays can be converted to Python scalars" If I set the timedt array to a single value the code runs without any error Do you see any chance to convince Python to use my array of timesteps in the loop? ````import pylab as p import math as m import numpy as np from scipy import optimize Q = 0 02114 M = 7500 0 dt = 30 0 PD = 0 020242215 tom = 26 0 #Minuten tos = tom * 60 0 #Sekunden timedt = np array([30 60 90]) conc= np array([ 2 7096 2 258 1 3548 0 9032 0 9032]) def malo(time): M1 = M/Q M2 = 1/(tos*m sqrt(4*m pi*PD*((time/tos)**3))) M3a = (1 - time/tos)**2 M3b = 4*PD*(time/tos) M3 = m exp(-1*(M3a/M3b)) out = M1 * M2 * M3 return out def residuals(p y time): PD = p err = y - malo(timedt) return err p0 = 0 05 p1 = optimize leastsq(residuals p0 args=(conc timedt)) ```` | Notice that you are working here with arrays defined in NumPy module Eg ````timedt = np array([30 60 90]) conc= np array([ 2 7096 2 258 1 3548 0 9032 0 9032]) ```` Now those arrays are not part of standard Python (which is a general purpose language) The problem is that you are mixing arrays with regular operations from the `math` module which <strong>is</strong> part of the standard Python and only meant to work on scalars So for example: ````M2 = 1/(tos*m sqrt(4*m pi*PD*((time/tos)**3))) ```` will work if you use `np sqrt` instead which is designed to work on arrays: ````M2 = 1/(tos*np sqrt(4*m pi*PD*((time/tos)**3))) ```` And so on NB: SciPy and other modules meant for numeric/scientific programming know about NumPy and are built on top of it so those functions should all work on arrays Just do not use `math` when working with them NumPy comes with replicas of all those functions (`sqrt` `cos` `exp` ) to work with your arrays |
Replace all occurrences of all chars within a string with another chars without interfering one with eachother I started learning some cryptography from a book and now I have an exercise that wants me to find out the frequencies of each character from a string: Something like this: ````import collections my_coded_string = """NTCGPDOPANFLHJINTOOFITOVJHJCTMMHIHEMTCPFDWTSOFSHTOGFWTE TTJJTBTOOFSZOVEOCHCVCHPJHOCGTOHNQMTOCNTCGPDCGFCSTQMFBTO FBGFSFBCTSHJCGTQMFHJCTYCXHCGFAHYTDDHAATSTJCBGFSFBCTSHJC GTBHQGTSCTYCCGHONTCGPDQSTOTSWTOCGTMTCCTSASTRVTJBZHJCGTQ MFHJCTYCFJDOPPJTBFJOTFSBGAPSCGTQMFHJCTYCASPNFIHWTJBHQGT SCTYCEZBPNQFSHJICGTASTRVTJBZPATFBGMTCCTSFIFHJOCCGTLJPXJ BPNNPJASTRVTJBZHJCGTVJDTSMZHJIMFJIVFIT""" letters = collections defaultdict(float) for letter in my_coded_string: letters[letter] = 1 d_descending = OrderedDict(sorted(letters items() key=lambda x: x[-1] reverse=True)) print d_descending ```` This will return a dictionary of type `float` with all the keys and their frequencies (in decreased order) So far so good nothing scary <strong>Output:</strong> ````([ ('T' 57 0) ('C' 40 0) ('J' 29 0) ('F' 27 0) ('H' 26 0) ('S' 23 0) ('G' 22 0) ('OF 20 0) ('B' 16 0) ('P' 15 0) ('M' 12 0) ('A' 10 0) ('N' 10 0) ('I' 9 0) ('Q' 9 0) ( WOULD' 8 0) ('V' 8 0) ('Y' 6 0) ('Z' 6 0) ('E' 4 0) ('W' 4 0) ('R' 3 0) ('L' 2 0) ('X' 2 0) ]) ```` Now they say that in order to decode this string I have to compare these frequencies with the ones they provide which seems to be the expected frequency of each character in the English language <a href="http://i stack imgur com/yRP8y png" rel="nofollow"><img src="http://i stack imgur com/yRP8y png" alt="enter image description here"></a> Now the problem that I have is: how can I replace all occurences of letter `T` which is most frequent with letter `E` which is the first frequent letter of English alphabet then `C` with `T` and so on ? At some point when I will replace `T` with `E` I will have 57 `E`s but I will also have the remaining `e`s Any ideas ? | If you also create an `OrderedDict` for your mapping of expected english language (decreasing order) you will be able create a second `dict` that can be used to translate `my_coded_string` in one iteration Let us say the expected english mapping is called `freqs`: <pre class="lang-py prettyprint-override">`translate_table = dict(zip(d_descending freqs)) my_string = '' join([translate_table[c] for c in my_coded_string]) ```` Assuming you will also want to handle <them>newlines</them> (`\n`) here is a full working code: <pre class="lang-py prettyprint-override">`import collections import itertools freqs = collections OrderedDict([ ('e' 12 702) ('t' 9 056) ('a' 8 167) ('of 7 507) ('i' 6 749) ('n' 6 749) ('s' 6 327) ('h' 6 094) ('r' 5 987) ( would' 4 253) ('l' 4 052) ('c' 2 782) ('you' 2 758) ('m' 2 406) ('w' 2 360) ('f' 2 228) ('g' 2 015) ('y' 1 974) ('p' 1 929) ('b' 1 492) ('v' 0 978) ('k' 0 772) ('j' 0 153) ('x' 0 150) ('q' 0 095) ('z' 0 074)]) my_coded_string = """NTCGPDOPANFLHJINTOOFITOVJHJCTMMHIHEMTCPFDWTSOFSHTOGFWTE TTJJTBTOOFSZOVEOCHCVCHPJHOCGTOHNQMTOCNTCGPDCGFCSTQMFBTO FBGFSFBCTSHJCGTQMFHJCTYCXHCGFAHYTDDHAATSTJCBGFSFBCTSHJC GTBHQGTSCTYCCGHONTCGPDQSTOTSWTOCGTMTCCTSASTRVTJBZHJCGTQ MFHJCTYCFJDOPPJTBFJOTFSBGAPSCGTQMFHJCTYCASPNFIHWTJBHQGT SCTYCEZBPNQFSHJICGTASTRVTJBZPATFBGMTCCTSFIFHJOCCGTLJPXJ BPNNPJASTRVTJBZHJCGTVJDTSMZHJIMFJIVFIT""" def translate(coded): coded_lines = coded split('\n') letters = collections defaultdict(float) for letter in itertools chain(*coded_lines): letters[letter] = 1 mapping = dict(zip( (i[0] for i in sorted(letters items() key=lambda x: x[-1] reverse=True)) freqs keys())) return '\n' join('' join(mapping[letter] for letter in line) for line in coded_lines) print(translate(my_coded_string)) ```` |
What is one way you could group pesticides? | application method |
What did post-punk artists use in their music? | critical theory, cinema, performance art and modernist literature |
Generic object "watcher" proxy to wrap collection objects to log state-changes (add/del) I want to add "watchers" to some variables used by a library They are of type `collections deque` `dict` `weakref WeakSet` and `list` Anytime that an item is added/appended or popped to/from them I would like to generate a log message I would like to minimize the changes to the original code: - I do not want to add log messages in all of the places where the variables are accessed and modified - I do not want to create my own classes that inherit from the original classes (e g `class InstrumentedDeque(collections deque): `) Instead and this is the question is it possible to create a single generic class (or wrapper/decorator) that works for all of the collection objects above so that the only place where changes are needed is where the objects are originally created If this is the original code with 2 vars to "watch": `self scheduled` and `self ready` ````def __init__(self): self scheduled = [] self ready = collections deque() ```` then the only changes required would be something like ````def __init__(self): self scheduled = MyLogger([] var_name='scheduled') self ready = MyLogger(collections deque() var_name='ready') ```` <h1>without instrumentation</h1> ````test = Test() test add(1) test add(2) test pop() ```` <h1>after instrumentation changes</h1> ````test = Test() test add(1) ***instrumentation output scheduled: [1] ***instrumentation output ready: deque([1]) test add(2) ***instrumentation output scheduled: [1 2] ***instrumentation output ready = deque([1 2]) test pop() ***instrumentation output scheduled: [2] ***instrumentation output ready: deque([2]) ```` where the example `add()` and `pop()` would look something like this ```` def add(self val): heapq heappush(self scheduled val) self ready append(val) def pop(self): heapq heappop(self scheduled) self ready popleft() ```` I have tried creating a "wrapper" class and played with `__new__` `__init__` `__getattr__` but have not been able to get this to work Something like this ````class MyLooger: def __new__(cls): # what to do? def __init__(self): # what to do? def __getattr__(self name): # what to do? ```` Any help is greatly appreciated | <strong>Note:</strong> the following abstraction <them>does not</them> work with C extension code that goes directly into the low-level internals of the wrapped object (such as `heapq heappush` both on CPython as well as PyPy); there is nothing that can be done to alleviate that at the Python level You <them>might</them> see if you can "patch the leak" at the C level but then you will have to get your hands dirty with writing C and a Python extension <strong>Solution:</strong> You do not need to go as far as `__new__` The following will work generically on all objects It will also make `isinstance` work on the wrapper as if it were called on the wrapped object ````from functools import wraps class Logged(object): def __init__(self obj obj_name): self obj = obj self obj_name = obj_name def __getattribute__(self attr_name): obj = object __getattribute__(self 'obj') obj_name = object __getattribute__(self 'obj_name') attr = getattr(obj attr_name) # this is not 100% generic mathematically speaking # but covers all methods and the `__class__` attribute: if not callable(attr) or isinstance(attr type): return attr @wraps(attr) def fn(*args **kwargs): print "%s called on %s with: %s and %s" % (attr_name obj_name args kwargs) return attr(*args **kwargs) return fn def __repr__(self): return repr(object __getattribute__(self 'obj')) ```` And then just: ````>>> scheduled = Logged([] obj_name="scheduled") >>> scheduled append <function append> >>> scheduled append(3) append called on scheduled with: (3 ) and {} >>> scheduled extend([1 2]) extend called on scheduled with: ([1 2] ) and {} >>> isinstance(scheduled list) True >>> scheduled [3 1 2] ```` |
Django settings for standalone I asked this before but I am still stuck This script will end up being run as a cron job Previous question : <a href="http://stackoverflow com/questions/17979597/importing-csv-to-django-and-settings-not-recognised">Importing CSV to Django and settings not recognised</a> I have skipped the actual code that imports the csvs as that is not the problem ````import urllib2 import csv import requests from django core management import setup_environ from django db import models from gmbl import settings settings configure( DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django db backends sqlite3' # Add 'postgresql_psycopg2' 'mysql' 'sqlite3' or 'oracle' 'NAME': '/Users/c/Dropbox/Django/mysite/mysite/db db' # Or path to database file if using sqlite3 # The following settings are not used with sqlite3: 'USER': '' 'PASSWORD': '' 'HOST': '' # Empty for localhost through domain sockets or '127 0 0 1' for localhost through TCP 'PORT': '' # Set to empty string for default } } ) # from sys import path sys path append("/Users/chris/Dropbox/Django/mysite/gmbl") from django conf import settings ```` This gives me the traceback: `django core exceptions ImproperlyConfigured: Requested setting DATABASES but settings are not configured You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings configure() before accessing settings logout` So I tried switching it around and put settings configure etc before the `from django db import models` line but then it just said `"settings not defined"` I have tried adding the ````from django core management import setup_environ from django db import models from yoursite import settings setup_environ(settings) ```` code suggested in the answer but it still errors out on the from django db import models section What am I missing aside from something that seems super obvious to everyone else? | ````import os os environ['DJANGO_SETTINGS_MODULE'] = 'project settings' ```` |
How to login to a web application using python when it is using salt validation? I am having a tough time to login to a website that is protected by site so far I am using the following code to accomplish my task: ````res = requests get('http://domain com') salt_value = re search('name="salt" *value="( *)"' res) group(1) payload = { 'username': 'test' 'password': 'test12345678' 'salt':'%s'%salt_value } res=requests post('http://domain com' data=payload) print res text ```` I am not getting the expected response Please help | First analyze connection between browser and server - for example using `Firebug` in Firefox Maybe you have to `GET`t page to get cookies before you use `POST` Maybe you have to send more data in `POST` - data from hidden fields Maybe you need correct `user-aget` Or maybe you use too greedy rexeg and your salt is incorrect Better use `lxml` or `BeautifulSoup` to get element from HTML |
In Pygame i cannot make my sprite move?? is it my code? my sprite does not move when i use the arrow key?? i have looked at my code and i cannot for the life of me work out what is wrong with it?? any help would be apreciated massively thanks in advance!!:D ```` bif="cloud jpg" mif="reddwarf png" import pygame sys from pygame locals import * pygame init() DISPLAYSURF=screen=pygame display set_mode((813 555) 32 0) background=pygame image load(bif) convert() mouse_c=pygame image load(mif) convert_alpha() x y=0 0 movex movey=0 0 while True: for event in pygame event get(): if event type == QUIT: pygame quit() sys exit() if event type ==KEYDOWN: if event key==K_LEFT: movex=-1 elif event key==KEY_RIGHT: movex=+1 elif event key==K_UP: movey=-1 elif event key==K_DOWN: movey=+1 if event type==KEYUP: if event key==K_LEFT: movex=0 elif event key==KEY_RIGHT: movex=0 elif event key==K_UP: movey=0 elif event key==K_DOWN: movey=0 x+=movex y+=movey screen blit(background (0 0)) screen blit(mouse_c (x y)) pygame display update() ```` | Check your indentation It looks like your for loop which checks your events is not inside your while loop and neither is your code which moves your sprite or updates your screens |
Why does my script stop at parse_args() if -h argument is passed? I tried to run the following script to know what is inside the namespace returned by `command parse_args()` ````#!/usr/bin/python3 import argparse command = argparse ArgumentParser() command add_argument("test") print("test1") args = command parse_args() print("test2") print(args) ```` If I run a "complete" command (like ` /test py 1`) everything is ok and the Namespace is displayed But if I do something like ` /test py -h` it fails and stops at `args = command parse_args()` `print("Test2")` is not called I got no error But the rest of the script is not interpreted Why? Is there some kind of error this way? Is ` /test py -h` invalid for some reason (Even if it seems to work fine)? Does `args = command parse_args()` because an exit before the script's end? | By default <a href="https://docs python org/3/library/argparse html#add-help" rel="nofollow">help options are added</a> to the argument parser Then when the help argument is passed the help action is invoked which will print the help and then end the program execution If you donât want that to happen you need to set the `add_help` argument to `False` but that will also stop the argument parser from providing a help functionality The exit behavior is pretty obvious if you actually look at the help text that is printed: ````-h --help show this help message and exit ```` |
What is the French term for "fowl?" | null |
What can be said of these works compared to his work in other years even though the quantity was less? | more refined than many of his earlier compositions |
Is there a pythonic way of assigning values to variables when passed in from the command line? I have written to following code but it feels very clunky and I was wondering if there was a pythonic way of writing the following code: <pre class="lang-python prettyprint-override">`import argparse foo = 0 bar = 1 parser = argparse ArgumentParser() parser add_argument("-a" "--foo" type=int help="foo") parser add_argument("-b" "--bar" type=int help="bar") args = parser parse_args() if args foo: # This is the bit that I think is clunky foo = args foo # if args bar: # bar = args bar # ```` In my code I have about 7 different arguments and having a list of `if` statements does not seem like the best method Is there a better way of writing this section? | In `argsparse` there are `default` and `required` fields that can help you reduce the amount of `if`'s you have Example: ````parser = argparse ArgumentParser() parser add_argument("-a" "--foo" type=int required=True help="foo") parser add_argument("-b" "--bar" type=int default=42 help="bar") ```` You can also return the args object and accessing the args at a later point |
One single page to create a Parent object and its associated child objects This is my very first post on this awesome site from which I have been finding answers to a handful of challenging questions Kudos to the community! I am new to the Django world so am hoping to find help from some Django experts here Thanks in advance <hr> Item model: ````class Item(models Model): name = models CharField(max_length=50) ```` ItemImage model: ````class ItemImage(models Model): image = models ImageField(upload_to=get_unique_filename) item = models ForeignKey(Item related_name='images') ```` As you can tell from the model definitions above every Item object can have many ItemImage objects <hr> My requirements are as followings: - A single web page that allows users to create a new Item while uploading the images associated with the Item The Item and the ItemImages objects should be created in the database all together when the "Save" button on the page is clicked - I have created a variable in a custom config file called <strong>NUMBER_OF_IMAGES_PER_ITEM</strong> It is based on this variable that the system generates the number of image fields per item <hr> Questions: - What should the forms and the template be like? Can ModelForm be used to achieve the requirements? - For the view function what do I need to watch out other than making sure to save Item before ItemImage objects? | Considering that you are using file upload fields I am not sure that it is a right approach for web application What if Item name validation fails? If you re-display the form again all file upload fields become empty and user has to fill them again Re technical side - ModelForm will do for the Item model but you should also use model formset for ItemImage's See <a href="http://docs djangoproject com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view" rel="nofollow">http://docs djangoproject com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view</a> for details |
What much the primary effect of a law neither advance or inhibit? | religion |
Is it possible to name a variable 'in' in python? I am making a unit converter for a homework assignment and I am using abbreviations for the various units of measurement as variable names but when I try to define 'in' as a variable it thinks I mean to use the word 'in' as if I wanted to say 'for x in y' or something like that and I get the following error: ```` File "unit_converter-v1 py" line 13 in = 12 ^ SyntaxError: invalid syntax ```` Is there any way to get around this? I know I could just use the word 'inch' or 'inches' but then I would have to type 'inch' or 'inches' into the program every time I needed to convert inches and I want to make the process as efficient as possible (I am a senior in highschool and my phisics teacher will allow us to use unit converters on tests and quizzes if we write the code ourselves The point is that time is valuable and I need to be as time-efficient as possible) | `in` is a python keyword so no you cannot use it as a variable or function or class name See <a href="https://docs python org/2/reference/lexical_analysis html#keywords" rel="nofollow">https://docs python org/2/reference/lexical_analysis html#keywords</a> for the list of keywords in Python 2 7 12 |
Implementation of Port scan in Python I have a program that scans for open ports on remote host It will take long time to complete the scan I want to make it work fast Here is my code: <h1>Port Scan</h1> ````import socket import subprocess host = input("Enter a remote host to scan: ") hostIP = socket gethostbyname(host) print("Please wait scanning remote host" hostIP) try: for port in range(1 1024): sock = socket socket(socket AF_INET socket SOCK_STREAM) result = sock connect_ex((hostIP port)) if result == 0: print("Port: \t Open" format(port)) sock close() ```` Could one of you Python wizards help me with this Advance Thanks | This program became too simple It monitors only one port at once and it takes long time on one port to see if it is listening So try reducing the time to listen if it cannot connect deem it to be closed by setting a recursion limit for that number under the "expect:" in run() As in like this ```` try: # connect to the given host:port result = sock connect_ex((hostIP port)) if result == 0: print "%s:%d Open" % (hostIP port) sock close() except: #pass sock recurse = 1 if sock recurse < sock limit: sock run() else: print "%s:%d Closed" % (hostIP port) ```` There is other way to make it much more efficient by importing threading() module which can be used to keep an eye on a large number of sockets at once Here is the document on threading Refer this <a href="https://docs python org/2/library/threading html#" rel="nofollow">https://docs python org/2/library/threading html#</a> Hope that helped you All the best |
How to get the spline basis used by scipy interpolate splev I need to evaluate b-splines in python To do so i wrote the code below which works very well ````import numpy as np import scipy interpolate as si def scipy_bspline(cv n degree): """ bspline basis function c = list of control points n = number of points on the curve degree = curve degree """ # Create a range of you values c = len(cv) kv = np array([0]*degree range(c-degree+1) [c-degree]*degree dtype='int') you = np linspace(0 c-degree n) # Calculate result arange = np arange(n) points = np zeros((n cv shape[1])) for i in xrange(cv shape[1]): points[arange i] = si splev(you (kv cv[: i] degree)) return points ```` Giving it 6 control points and asking it to evaluate 100k points on curve is a breeze: ````# Control points cv = np array([[ 50 25 0 ] [ 59 12 0 ] [ 50 10 0 ] [ 57 2 0 ] [ 40 4 0 ] [ 40 14 0 ]]) n = 100000 # 100k Points degree = 3 # Curve degree points_scipy = scipy_bspline(cv n degree) #cProfile clocks this at 0 012 seconds ```` Here is a plot of "points_scipy": <a href="http://i stack imgur com/vVHwW png" rel="nofollow"><img src="http://i stack imgur com/vVHwW png" alt="enter image description here"></a> Now to make this faster i could compute a basis for all 100k points on the curve store that in memory and when i need to draw a curve all i would need to do is multiply the new control point positions with the stored basis to get the new curve To prove my point i wrote a function that uses <a href="https://en wikipedia org/wiki/De_Boor%27s_algorithm" rel="nofollow">DeBoor's algorithm</a> to compute my basis: ````def basis(c n degree): """ bspline basis function c = number of control points n = number of points on the curve degree = curve degree """ # Create knot vector and a range of samples on the curve kv = np array([0]*degree range(c-degree+1) [c-degree]*degree dtype='int') # knot vector you = np linspace(0 c-degree n) # samples range # Cox - DeBoor recursive function to calculate basis def coxDeBoor(you k d): # Test for end conditions if (d == 0): if (kv[k] <= you and you < kv[k+1]): return 1 return 0 Den1 = kv[k+d] - kv[k] Den2 = 0 Eq1 = 0 Eq2 = 0 if Den1 > 0: Eq1 = ((you-kv[k]) / Den1) * coxDeBoor(you k (d-1)) try: Den2 = kv[k+d+1] - kv[k+1] if Den2 > 0: Eq2 = ((kv[k+d+1]-you) / Den2) * coxDeBoor(you (k+1) (d-1)) except: pass return Eq1 Eq2 # Compute basis for each point b = np zeros((n c)) for i in xrange(n): for k in xrange(c): b[i][k%c] = coxDeBoor(you[i] k degree) b[n-1][-1] = 1 return b ```` Now let us use this to compute a new basis multiply that by the control points and confirm that we are getting the same results as splev: ````b = basis(len(cv) n degree) #5600011 function calls (600011 primitive calls) in 10 975 seconds points_basis = np dot(b cv) #3 function calls in 0 002 seconds print np allclose(points_basis points_scipy) # Returns True ```` My extremely slow function returned 100k basis values in 11 seconds but since these values only need to be computed once calculating the points on curve ended up being 6 times faster this way than doing it via splev The fact that I was able to get the exact same results from both my method and splev leads me to believe that internally splev probably calculates a basis like i do except much faster So my goal is to find out how to calculate my basis fast store it in memory and just use np dot() to compute the new points on curve and my question is: Is it possible to use spicy interpolate to get the basis values that (i presume) splev uses to compute it is result? And if so how? <h1>[ADDENDUM]</h1> Following unutbu's and ev-br's very useful insight on how scipy calculates a spline's basis I looked up the fortran code and wrote a equivalent to the best of my abilities: ````def fitpack_basis(c n=100 d=3 rMinOffset=0 rMaxOffset=0): """ fitpack's spline basis function c = number of control points n = number of points on the curve d = curve degree """ # Create knot vector kv = np array([0]*d range(c-d+1) [c-d]*d dtype='int') # Create sample range you = np linspace(rMinOffset rMaxOffset c - d n) # samples range # Create buffers b = np zeros((n c)) # basis bb = np zeros((n c)) # basis buffer left = np clip(np floor(you) 0 c-d-1) astype(int) # left knot vector indices right = left+d+1 # right knot vector indices # Go! nrange = np arange(n) b[nrange left] = 1 0 for j in xrange(1 d+1): crange = np arange(j)[: None] bb[nrange left+crange] = b[nrange left+crange] b[nrange left] = 0 0 for i in xrange(j): f = bb[nrange left+i] / (kv[right+i] - kv[right+i-j]) b[nrange left+i] = b[nrange left+i] f * (kv[right+i] - you) b[nrange left+i+1] = f * (you - kv[right+i-j]) return b ```` Testing against unutbu's version of my original basis function: ````fb = fitpack_basis(c n d) #22 function calls in 0 044 seconds b = basis(c n d) #81 function calls (45 primitive calls) in 0 013 seconds ~5 times faster print np allclose(b fb) # Returns True ```` My function is 5 times slower but still relatively fast What I like about it is that it let us me use sample ranges that go beyond the boundaries which is something of use in my application For example: ````print fitpack_basis(c 5 d rMinOffset=-0 1 rMaxOffset= 2) [[ 1 331 -0 3468 0 0159 -0 0002 0 0 ] [ 0 0208 0 4766 0 4391 0 0635 0 0 ] [ 0 0 0228 0 4398 0 4959 0 0416 0 ] [ 0 0 0 0407 0 3621 0 5444 0 0527] [ 0 0 -0 0013 0 0673 -0 794 1 728 ]] ```` So for that reason I will probably use fitpack_basis since it is relatively fast But i would love suggestions for improving its performance and hopefully get closer to unutbu's version of the original basis function i wrote | Here is a version of `coxDeBoor` which is (on my machine) 840x faster than the original ````In [102]: %timeit basis(len(cv) 10**5 degree) 1 loops best of 3: 24 5 s per loop In [104]: %timeit bspline_basis(len(cv) 10**5 degree) 10 loops best of 3: 29 1 ms per loop ```` <hr> ````import numpy as np import scipy interpolate as si def scipy_bspline(cv n degree): """ bspline basis function c = list of control points n = number of points on the curve degree = curve degree """ # Create a range of you values c = len(cv) kv = np array( [0] * degree range(c - degree 1) [c - degree] * degree dtype='int') you = np linspace(0 c - degree n) # Calculate result arange = np arange(n) points = np zeros((n cv shape[1])) for i in xrange(cv shape[1]): points[arange i] = si splev(you (kv cv[: i] degree)) return points def memo(f): # Peter Norvig's """Memoize the return value for each call to f(args) Then when called again with same args we can just look it up """ cache = {} def _f(*args): try: return cache[args] except KeyError: cache[args] = result = f(*args) return result except TypeError: # some element of args cannot be a dict key return f(*args) _f cache = cache return _f def bspline_basis(c n degree): """ bspline basis function c = number of control points n = number of points on the curve degree = curve degree """ # Create knot vector and a range of samples on the curve kv = np array([0] * degree range(c - degree 1) [c - degree] * degree dtype='int') # knot vector you = np linspace(0 c - degree n) # samples range # Cox - DeBoor recursive function to calculate basis @memo def coxDeBoor(k d): # Test for end conditions if (d == 0): return ((you - kv[k] >= 0) & (you - kv[k 1] < 0)) astype(int) denom1 = kv[k d] - kv[k] term1 = 0 if denom1 > 0: term1 = ((you - kv[k]) / denom1) * coxDeBoor(k d - 1) denom2 = kv[k d 1] - kv[k 1] term2 = 0 if denom2 > 0: term2 = ((-(you - kv[k d 1]) / denom2) * coxDeBoor(k 1 d - 1)) return term1 term2 # Compute basis for each point b = np column_stack([coxDeBoor(k degree) for k in xrange(c)]) b[n - 1][-1] = 1 return b # Control points cv = np array([[50 25 0 ] [59 12 0 ] [50 10 0 ] [57 2 0 ] [40 4 0 ] [40 14 0 ]]) n = 10 ** 6 degree = 3 # Curve degree points_scipy = scipy_bspline(cv n degree) b = bspline_basis(len(cv) n degree) points_basis = np dot(b cv) print np allclose(points_basis points_scipy) ```` <hr> The majority of the speedup is achieved by making coxDeBoor compute a vector of results instead of a single value at a time Notice that `you` is removed from the arguments passed to `coxDeBoor` Instead the new `coxDeBoor(k d)` calculates what was before `np array([coxDeBoor(you[i] k d) for i in xrange(n)])` Since NumPy array arithmetic has the same syntax as scalar arithmetic very little code needed to change The only syntactic change was in the end condition: ````if (d == 0): return ((you - kv[k] >= 0) & (you - kv[k 1] < 0)) astype(int) ```` `(you - kv[k] >= 0)` and `(you - kv[k 1] < 0)` are boolean arrays `astype` changes the array values to 0 and 1 So whereas before a single 0 or 1 was returned now a whole array of 0s and 1s are returned -- one for each value in `you` <a href="https://en wikipedia org/wiki/Memoization" rel="nofollow">Memoization</a> can also improve performance since the recurrence relations causes `coxDeBoor(k d)` to be called for the same values of `k` and `d` more than once The decorator syntax ````@memo def coxDeBoor(k d): ```` is equivalent to ````def coxDeBoor(k d): coxDeBoor = memo(coxDeBoor) ```` and the `memo` decorator causes `coxDeBoor` to record in a `cache` a mapping from `(k d)` pairs of arguments to returned values If `coxDeBoor(k d)` is called again then value from the `cache` will be returned instead of re-computing the value <hr> `scipy_bspline` is still faster but at least `bspline_basis` plus `np dot` is in the ballpark and may be useful if you want to re-use `b` with many control points `cv` ````In [109]: %timeit scipy_bspline(cv 10**5 degree) 100 loops best of 3: 17 2 ms per loop In [104]: %timeit b = bspline_basis(len(cv) 10**5 degree) 10 loops best of 3: 29 1 ms per loop In [111]: %timeit points_basis = np dot(b cv) 100 loops best of 3: 2 46 ms per loop ```` |
Django TypeError 'QueryDict' object is not callable I have looked for posts that have endured the same problem that I am currently facing But I have not found a solution What my problem is: I have a list of tags Generated by `{% for tag in all_tags %}` Each tag has a tagstatus form When a user selects an option from a drop down the form submits and is supposed to save the TagStatus object (Tags are foreignKey'd to TagStatus) However what returns is this: ````Exception Type: TypeError Exception Value: 'QueryDict' object is not callable ```` <strong>html:</strong> ````<form class="nice" id="status-form" method="POST" action=""> {% csrf_token %} <input type="hidden" name="status_check" /> <input type='hidden' name="tag" value="{{ tag }}" /> <select name="select" id="positionSelect" class="input-text category" onchange="this form submit()"> <option name="all" value="0">Your Status</option> <option name="investing" value="1">Status 1</option> <option name="selling" value="2">Status 2</option> <option name="interested" value="3">Status 3</option> </select> </form> ```` <strong>views py:</strong> ````@login_required def tags(request): all_tags = Tag objects all() context = base_context(request) if request method == 'POST': if 'status_check' in request POST: status = request GET('status') tag = request GET('tag') user = request user tag_status created = TagStatus objects get_or_create(status=len(status) tag=tag user=user) save() response = simplejson dumps({"status": "Successfully changed status"}) else: response = simplejson dumps({"status": "Error"}) return HttpResponse (response mimetype='application/json') context['all_tags'] = all_tags return render_to_response('tags/tag html' context context_instance=RequestContext(request)) ```` <strong>models py</strong> (if its relevant): ````class TagStatus(models Model): user = models ForeignKey(User null=True unique=True) status = models CharField(max_length=2 choices=tag_statuses) tag = models ForeignKey(Tag null=True blank=True) def __unicode__(self): return self status def save(self *args **kwargs): super(TagStatus self) save(*args **kwargs) ```` From what I gather it has something to do with the status not being a number But when I convert it to a int I get the same error Please help me Why is this happening? And what is the fix? I am not quite sure how to solve this problem Thank you for your help in advance | I believe the error you are encountering is in these lines: ````status = request GET('status') tag = request GET('tag') ```` request GET is a QueryDict and adding () after it attempts to "call" a non-callable object It appears the syntax you are looking for is dictionary lookup syntax instead: ````status = request GET['status'] tag = request GET['tag'] ```` |
Why are the presence of certain enzymes a sign of good health? | null |
What else is Sentinel Peak also known as? | "A Mountain" |
Trouble sending an uploaded file using the Python requests library I am trying to modify the <a href="http://docs python-requests org/en/latest/user/quickstart/#post-a-multipart-encoded-file" rel="nofollow">example</a> in the requests library documentation to include a file uploaded from a user (to an appengine app) I have tried the following: ````from libs import requests file_data = self request POST['file_to_upload'] the_file = file_data send_url = "http://httpbin org/post" values = { 'user_id' : '1234' 'file_name' : 'some_file pdf' } are = requests post(send_url files=the_file) logging info(r content) ```` However this returns ```` { "origin": "81 178 201 22" "files": {} "form": {} "url": "http://httpbin org/post" "args": {} "headers": { "Content-Length": "0" "Accept-Encoding": "identity deflate compress gzip" "Connection": "keep-alive" "Accept": "*/*" "User-Agent": "python-requests/0 11 1 AppEngine-Google; (+http://code google com/appengine)" "Host": "httpbin org" "Content-Type": "" } "json": null "data": "" } ```` i e there is no file received I have also tried sending the_file as ````file_data file file_data file read() ```` however these also fail Ultimately I want to include both teh "values" and the file in the same post request so something like: ````are = requests post(send_url data=values files=the_file) ```` However this is not working either - I guess I need to fix the above code first Any idea as to what I am doing wrong? | Could you provide an HTML code for displaying the upload form? Sometime form upload fails because it lacks some HTML attributes |
Collecting Data from Database functions vs classes I searched around and could not really find any information on this Basically i have a database "A" and a database "B" What i want to do is create a python script (that will likely run as a cron job) that will collect data from database "A" via sql perform an action on it and then input that data into database "B" I have written it using functions something along the lines of: - Function 1 gets the date the script was last run - Function 2 Gets the data from Database "A" based on function 1 - Function 3-5 Perform the needed actions - Function 6 Inserts data into Database "B" My question is it was mentioned to me that i should use a Class to do this rather than just functions The only problem is I am honestly a bit hazy on Classes and when to use them Would a Class be better for this? Or is writing this out as functions that feed into each other better? If i would use a Class could you tell me how it would look? | <blockquote> Would a Class be better for this? </blockquote> Probably not Classes are useful when you have multiple stateful instances that have shared methods Nothing in your problem description matches those criteria There is nothing wrong with having a script with a handful of functions to perform simple data transfers (extract transform store) |
What method didn't Avicenna criticize as not leading to absolute certainty? | null |
Celery Tasks Not Being Processed I am trying to process some tasks using celery and I am not having too much luck I am running celeryd and celerybeat as daemons I have a `tasks py` file that look like this with a simple app and task defined: ````from celery import Celery app = Celery('tasks' broker='amqp://user:pass@hostname:5672/vhostname') @app task def process_file(f): # do some stuff # and log results ```` And this file is referenced from another file `process py` I use to monitor for file changes that looks like: ````from tasks import process_file file_name = '/file/to/process' result = process_file delay(file_name) result get() ```` And with that little code celery is unable to see tasks and process them I can execute similar code in the python interpreter and celery processes them: ````py >>> from tasks import process_file py >>> process_file delay('/file/to/process') <AsyncResult: 8af23a4e-3f26-469c-8eee-e646b9d28c7b> ```` When I run the tasks from the interpreter however `beat log` and `worker1 log` do not show any indication that the tasks were received but using `logging` I can confirm the task code was executed There are also no obvious errors in the ` log` files Any ideas what could be causing this problem? My `/etc/default/celerybeat` looks like: ````CELERY_BIN="/usr/local/bin/celery" CELERYBEAT_CHDIR="/opt/dirwithpyfiles" CELERYBEAT_OPTS="--schedule=/var/run/celery/celerybeat-schedule" ```` And `/etc/default/celeryd`: ````CELERYD_NODES="worker1" CELERY_BIN="/usr/local/bin/celery" CELERYD_CHDIR="/opt/dirwithpyfiles" CELERYD_OPTS="--time-limit=300 --concurrency=8" CELERYD_USER="celery" CELERYD_GROUP="celery" CELERYD_LOG_FILE="/var/log/celery/%N log" CELERYD_PID_FILE="/var/run/celery/%N pid" CELERY_CREATE_DIRS=1 ```` | So I figure out my issue here by running celery from the cli instead of as a daemon enabling me to see more detailed output of errors that happened I did this by running: ````user@hostname /opt/dirwithpyfiles $ su celery celery@hostname /opt/dirwithpyfiles $ celery -A tasks worker --loglevel=info ```` There I could see that a permissions issue was happening as the `celery` user that did not happen when I ran the commands from the python interpreter as my normal user I fixed this by changing the permissions of `/file/to/process` so that both users could read from it |