what is the current state of user authentication? is it good to go with openid or another alternative, or we still have to write our own user/password?
class MyWriter:
def __init__(self, stdout):
self.stdout = stdout
self.dumps = []
def write(self, text):
self.stdout.write(smart_unicode(text).encode('cp1251'))
self.dumps.append(text)
def close(self):
self.stdout.close()
writer = MyWriter(sys.stdout)
save = sys.stdout
sys.stdout = writer
I use self.dumps list to store geted data from prints. Is it exists more convinient object for storing string lines in memory? ideally i want dump it to one big string. I can get it like this "\n".join(self.dumps) from code above. Mb it's better to just concat strings - self.dumps += text ?
I have created an array thusly:
import numpy as np
data = np.zeros( (512,512,3), dtype=np.uint8)
data[256,256] = [255,0,0]
What I want this to do is display a single red dot in the center of a 512x512 image. (At least to begin with... I think I can figure out the rest from there)
How can I list the numbers 01 to 12 (one for each of the 12 months) in such a way so that the current month always comes last where the oldest one is first. In other words, if the number is grater than the current month, it's from the previous year.
e.g. 02 is Feb, 2011 (the current month right now), 03 is March, 2010 and 09 is Sep, 2010 but 01 is Jan, 2011. In this case, I'd like to have [09, 03, 01, 02]. This is what I'm doing to determine the year:
for inFile in os.listdir('.'):
if inFile.isdigit():
month = months[int(inFile)]
if int(inFile) <= int(strftime("%m")):
year = strftime("%Y")
else:
year = int(strftime("%Y"))-1
mnYear = month + ", " + str(year)
I don't have a clue what to do next. What should I do here?
Is it possible to get the name of a node using minidom?
for example i have a node:
<heading><![CDATA[5 year]]></heading>
what i'm trying to do is store the value heading so that i can use it as a key in a dictionary,
the closest i can get is something like
[<DOM Element: heading at 0x11e6d28>]
i'm sure i'm overlooking something very simple here, thanks!
If I'm using a canvas to display data and I want the user to be able to click on various items on the canvas in order to get more information or interact with it in some way, whats the best way of going about this?
Searching online I can find information about how to bind events to tags but that seems to be more indirect then what I want. I don't want to group items with tags, but rather have specific function calls when the user clicks specific items on the canvas.
info = {'phone_number': '123456', 'personal_detail': {'foo':foo, 'bar':bar}, 'is_active': 1, 'document_detail': {'baz':baz, 'saz':saz}, 'is_admin': 1, 'email': '[email protected]'}
return HttpResponse(simplejson.dumps({'success':'True', 'result':info}), mimetype='application/javascript')
if(data["success"] === "True") {
alert(data[**here I want to display personal_detail and document_details**]);
}
How can I do this?
I'm trying to dynamically load a class from a specific module (called 'commands') and the code runs totally cool on my local setup running from a local Django server. This bombs out though when I deploy to Google App Engine. I've tried adding the commands module's parent module to the import as well with no avail (on either setup in that case). Here's the code:
mod = __import__('commands.%s' % command, globals(), locals(), [command])
return getattr(mod, command)
App Engine just throws an ImportError whenever it hits this.
And the clarify, it doesn't bomb out on the commands module. If I have a command like 'commands.cat' it can't find 'cat'.
I originally had the variable cpanel named url and the code would not return anything. Any idea why? It doesn't seem to be used by anything else, but there's gotta be something I'm overlooking.
import urllib2
cpanel = 'http://www.tas-tech.com/cpanel'
req = urllib2.Request(cpanel)
try:
handle = urllib2.urlopen(req)
except IOError, e:
if hasattr(e, 'code'):
if e.code != 401:
print 'We got another error'
print e.code
else:
print e.headers
print e.headers['www-authenticate']
Currently it takes about 3 minutes to run through a single 53 page word document. Hopefully you all have some advice about speeding up the process.
Code:
import win32com.client as win32
from glob import glob
import io
import re
from collections import namedtuple
from collections import defaultdict
import pprint
raw_files = glob('*.docx')
word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible = False
oFile = io.open("rawsort.txt", "w+", encoding = "utf-8")#text dump
doccat= list()
for f in raw_files:
word.Documents.Open(f)
doc = word.ActiveDocument #whichever document is active at the time
doc.ConvertNumbersToText()
print doc.Paragraphs.Count
for x in xrange(1, doc.Paragraphs.Count+1):#for loop to print through paragraphs
oText = doc.Paragraphs(x)
if not oText.Range.Tables.Count >0 :
results = re.match('(?P<number>(([1-3]*[A-D]*[0-9]*)(.[1-3]*[0-9])+))', oText.Range.Text)
stylematch = re.match('Heading \d', oText.Style.NameLocal)
if results!= None and oText.Style != None and stylematch != None:
doccat.append((oText.Style.NameLocal, oText.Range.Text[:len(results.group('number'))],oText.Range.Text[len(results.group('number')):]))
style = oText.Style.NameLocal
else:
if oText.Range.Font.Bold == True :
doccat.append(style, oText)
oFile.write(unicode(doccat))
oFile.close()
The for Paragraph loop obviously takes the most amount of time. Is there some way of identifying and appending it without going through every Paragraph?
I have an application in Django 1.2.
Language is selectable (I18N and Locale = True)
When I select the english lang. in the site, the admin works OK. But when I change to any other language this is what happens with date inputs (spanish example):
Correctly, the input accepts the spanish format %d/%m/%Y (Even selecting from the calendar, the date inserts as expected). But when I save the form and load it again, the date shows in the english form: %Y-%m-%d
The real problem is that when I load the form to change any other text field and try to save it I get an error telling me to enter a valid date, so I have to write all dates again or change the language in the site to use the admin.
I haven't specified anything for DATE_INPUT_FORMATS in settings nor have I overridden forms or models.
Surely I am missing something but I can't find it. Can anybody give me a hint?
I have an app I was working on to learn more about wxPython( I have been primarily been a scripter ). I forgot about it now I am opening it back up. It's a screen scraper, and I have it working almost the way I want it, going to build a regex parser to strip out the links in every scrape that I don't need. The questions I have are this. In it current state, if I check more than one site, it goes out and scrapes, and returns it in separate windows, the for:each section in the Clicked function. I want to put them in a frame, in the window, altogether. I also want to know if I can take the list they are read into and send it to a checklist, so someone could check off separate items, I want to build a save function and keep certain ones. In regards to a save function, I want to keep saved checks, are there calls to the widgets to save their states? I know it's a lot, but thanks for the help.
Hello!
To empty database table, I use this SQL Query:
TRUNCATE TABLE `books`
How to I Truncate table using Django models and orm?
I've tried this, but it doesn't work:
Book.objects.truncate()
how can i control the number of retries of the "opener.open"?
for example, in the following code, it will send about 6 "GET" HTTP requests (i saw it in the Wireshark sniffer) before it goes to the " except urllib.error.URLError" success/no-success lines.
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None,url, username, password)
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
opener = urllib.request.build_opener(handler)
try:
resp = opener.open(url,None,1)
except urllib.error.URLError as e:
print ("no success")
else:
print ("success!")
I want to make Waf generate a beep when it finishes the execution of any command that took more than 10 seconds.
I don't know how do add this and assure that the code executes when Waf exits.
This should run for any Waf command not only build.
I checked the Waf book but I wasn't able to find any indication about how should I do this.
Hi folks,
I'm trying to compute the average of a field over various subsets of a queryset.
Player.objects.order_by('-score').filter(sex='male').aggregate(Avg('level'))
This works perfectly!
But... if I try to compute it for the top 50 players it does not work.
Player.objects.order_by('-score').filter(sex='male')[:50].aggregate(Avg('level'))
This last one returns the exact same result as the query above it, which is wrong.
What am I doing wrong?
Help would be very much appreciated!
I've got a GUI script with all my wxPython code in it, and a separate testSequences module that has a bunch of tasks that I run based on input from the GUI. The tasks take a long time to complete (from 20 seconds to 3 minutes), so I want to thread them, otherwise the GUI locks up while they're running. I also need them to run one after another, since they all use the same hardware. (My rationale behind threading is simply to prevent the GUI from locking up.) I'd like to have a "Running" message (with varying number of periods after it, i.e. "Running", "Running.", "Running..", etc.) so the user knows that progress is occurring, even though it isn't visible. I'd like this script to run the test sequences in separate threads, but sequentially, so that the second thread won't be created and run until the first is complete. Since this is kind of the opposite of the purpose of threads, I can't really find any information on how to do this... Any help would be greatly appreciated.
Thanks in advance!
gui.py
import testSequences
from threading import Thread
#wxPython code for setting everything up here...
for j in range(5):
testThread = Thread(target=testSequences.test1)
testThread.start()
while testThread.isAlive():
#wait until the previous thread is complete
time.sleep(0.5)
i = (i+1) % 4
self.status.SetStatusText("Running"+'.'*i)
testSequences.py
import time
def test1():
for i in range(10):
print i
time.sleep(1)
(Obviously this isn't the actual test code, but the idea is the same.)
Hello,
I have the following table in the model with a recursive structure (a page can have children pages)
class DynamicPage(models.Model):
name = models.CharField("Titre",max_length=200)
parent = models.ForeignKey('self',null=True,blank=True)
I want to create another table with manytomany relation with this one:
class UserMessage(models.Model):
name = models.CharField("Nom", max_length=100)
page = models.ManyToManyField(DynamicPage)
The generated SQL creates the following constraint:
ALTER TABLE `website_dynamicpage` ADD CONSTRAINT `parent_id_refs_id_29c58e1b` FOREIGN KEY (`parent_id`) REFERENCES `website_dynamicpage` (`id`);
I would like to have the ManyToMany with the page itself (the id) and not with the parent field.
How to modify the model to make the constraint using the id and not the parent?
Thanks in advance
Suppose my template has in it something like {% block subject %}my subject{% endblock %} and I load this template with tmpl = loader.get_template('mytemplate.html'), how can I extract "my subject"?
I've been searching here and there, and based on this answer I've put together what you see below.
It works, but I need to put some stuff in the user's session, right there inside authenticate.
How would I store acme_token in the user's session, so that it will get cleared if they logged out?
class AcmeUserBackend(object):
# Create a User object if not already in the database?
create_unknown_user = False
def get_user(self, username):
return AcmeUser(id=username)
def authenticate(self, username=None, password=None):
""" Check the username/password and return an AcmeUser. """
acme_token = ask_another_site_about_creds(username, password)
if acme_token:
return AcmeUser(id=username)
return None
##################
from django.contrib.auth.models import User
class AcmeUser(User):
objects = None # we cannot really use this w/o local DB
def save(self):
"""saving to DB disabled"""
pass
def get_group_permissions(self):
"""If you don't make your own permissions module,
the default also will use the DB. Throw it away"""
return [] # likewise with the other permission defs
def get_and_delete_messages(self):
"""Messages are stored in the DB. Darn!"""
return []
Hi.
First of all, my question is similar to this one
But it's a little bit different.
What we have is a series of environments, with the same set of services.
For some environments (the local ones) we can get access to the wsdl, and thus generating the suds client.
For external environment, we cannot access the wsdl. But being the same, I was hoping I can change just the URL without regenerating the client.
I've tried cloning the client, but it doesn't work.
Using the local dev server, I can use ';' in urls, but as soon as I try the live version hosted by Google, it looks like the ';' and everything afterward is stripped (at least according to request.path_qs).
(I would prefer not to encode them if possible, it's much less user friendly if the url cannot be constructed by copy-pasting, especially since other characters works fine, e.g. ':').