i have two tables, and its a one-to-one relationship. is there a way to make it generate a row for table b automatically, when saving for table a? or do i have to be explicit everytime?
class LocationLog(models.Model):
user = models.ForeignKey(User)
utm = models.GeometryField(spatial_index=True)
This is my database model. I would like to insert a row.
I want to insert a circle at point -55, 333. With a radius of 10. How can I put this circle into the geometry field?
Of course, then I would want to check which circles overlap a given circle. (my select statement)
"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
I'm doing a programming challenge where i need to parse this sequence into my sudoku script.
Need to get the above sequence into 8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8.........
I tried re but without success, help is appreciated, thanks.
Trying to subclass mechanize.Browser class:
from mechanize import Browser
class LLManager(Browser, object):
IS_AUTHORIZED = False
def __init__(self, login = "", passw = "", *args, **kwargs):
super(LLManager, self).__init__(*args, **kwargs)
self.set_handle_robots(False)
But when I make something like this:
lm["Widget[LinksList]_link_1_title"] = anc
then I get an error:
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
lm["Widget[LinksList]_link_1_title"] = anc
TypeError: 'LLManager' object does not support item assignment
Browser class have overridden method __getattr__ as shown:
def __getattr__(self, name):
# pass through _form.HTMLForm methods and attributes
form = self.__dict__.get("form")
if form is None:
raise AttributeError(
"%s instance has no attribute %s (perhaps you forgot to "
".select_form()?)" % (self.__class__, name))
return getattr(form, name)
Why my class or instance don't get this method as in parent class?
Hi,
I am able to override multiple config parameters using nose-testconfig plugin only if i pass the overriding parameters on commandline.
e.g. nosetests -c nose.cfg -s --tc=jack.env1:asl --tc=server2.env2:abc
But when I define the same thing inside nose.cfg, than only the value for last parameter is modified.
e.g.
tc = server2.env2:abc
tc = jack.env1:asl
I checked the plugin code. It looks fine to me. I am pasting the part of plugin code below:
parser.add_option(
"--tc", action="append",
dest="overrides",
default = [],
help="Option:Value specific overrides.")
configure:
if options.overrides:
self.overrides = []
overrides = tolist(options.overrides)
for override in overrides:
keys, val = override.split(":")
if options.exact:
config[keys] = val
else:
ns = ''.join(['["%s"]' % i for i in keys.split(".") ])
# BUG: Breaks if the config value you're overriding is not
# defined in the configuration file already. TBD
exec('config%s = "%s"' % (ns, val))
Let me know if any one has any clue.
I am trying to get a login form I have in django to only allow three login attempts before redirecting to a "login help" page. I am currently using the builtin "django.contrib.auth.views.login" view with a custom template. How do I force it to redirect to another page after n failed login attempts?
Okay this is probably a really dumb question, however its really starting to hurt. I have a numpy matrix, and basically i print it out row by row. However i want to make each row be formatted and separated properly.
>>> arr = numpy.matrix([[x for x in range(5)] for y in range(5)])
>>> arr
matrix([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Lets say i want to print the first row, and add a '|' between each element:
>>> '|'.join(map(str, arr[0,]))
'[[0 1 2 3 4]]'
Err...
>>> '|'.join(map(lambda x: str(x[0]), arr[0]))
'[[0 1 2 3 4]]'
I am really confused by this behavior why does it do this?
Hey,
Im trying to write a program that would be listening for data (simple text messages) on some port (say tcp 6666) and then pass them to one or more different protocols - irc, xmpp and so on. I've tried many approaches and digged the Internet, but I cant find easy and working solution for such task.
The code I am currently fighting with is here: http://pastebin.com/ri7caXih
I would like to know how to from object like:
ircf = ircFactory('asdfasdf', '#asdf666')
get access to self protocol methods, because this:
self.protocol.dupa1(msg)
returns error about self not being passed to active protocol object. Or maybe there is other, better, easier and more kosher way to create single reactor with multiple protocols and have actions triggeres when a message arrives on any of them, and then pass that message to other protocols for handling/processing/sending?
Any help will be highly appreciated!
When is exception handling more preferable than condition checking? There are many situations where I can choose using one or the other.
For example, this is a summing function which uses a custom exception:
# module mylibrary
class WrongSummand(Exception):
pass
def sum_(a, b):
""" returns the sum of two summands of the same type """
if type(a) != type(b):
raise WrongSummand("given arguments are not of the same type")
return a + b
# module application using mylibrary
from mylibrary import sum_, WrongSummand
try:
print sum_("A", 5)
except WrongSummand:
print "wrong arguments"
And this is the same function, which avoids using exceptions
# module mylibrary
def sum_(a, b):
""" returns the sum of two summands if they are both of the same type """
if type(a) == type(b):
return a + b
# module application using mylibrary
from mylibrary import sum_
c = sum_("A", 5)
if c is not None:
print c
else:
print "wrong arguments"
I think that using conditions is always more readable and manageable. Or am I wrong? What are the proper cases for defining APIs which raise exceptions and why?
Hi All,
I am experimenting with the Google App Engine and have a question.
For the sake of simplicity, let's say my app is modeling a computer network (a fairly large corporate network with 10,000 nodes). I am trying to model my Node class as follows:
class Node(db.Model):
name = db.StringProperty()
neighbors = db.SelfReferenceProperty()
Let's suppose, for a minute, that I cannot use a ListProperty(). Based on my experiments to date, I can assign only a single entity to 'neighbors' - and I cannot use the "virtual" collection (node_set) to access the list of Node neighbors.
So... my questions are:
Does SelfReferenceProperty limit you to a single entity that you can reference?
If I instead use a ListProperty, I believe I am limited to 5,000 keys, which I need to exceed.
Thoughts?
Thanks,
John
APNG is backwards compatible with PNG. I opened up an apng and png file in a hex editor and the first few bytes look identical. So if a user uploads either of these formats, how do I detect what the format really is? I've seen this done on some sites that block apng.
I'm guessing the ImageMagick library makes this easy, but what if I were to do the detect without the use of an image processing library (for learning purposes)? Can I look for specific bytes that tell me if the file is apng?
Solutions in any language is welcome.
I'm doing a batch script to connect to a tcp server and then exiting.
My problem is that I can't stop the reactor, for example:
cmd = raw_input("Command: ")
# custom factory, the protocol just send a line
reactor.connectTCP(HOST,PORT, CommandClientFactory(cmd)
d = defer.Deferred()
d.addCallback(lambda x: reactor.stop())
reactor.callWhenRunning(d.callback,None)
reactor.run()
In this code the reactor stops before that the tcp connection is done and the cmd is passed.
How can I stop the reactor after that all the operation are finished?
I'm using the nice feature in QMessageBox to optionally show detailed text to the user. However, the window after expansion is still fairly small, and one immediately tries to resize the window so more of the details are visible. Even after setting what I think are the proper settings it won't allow resizing.
Here's the relevant snippet of PyQt4 code:
mb = QMessageBox()
mb.setText("Results written to '%s'" % filename)
mb.setDetailedText(str(myData))
mb.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
mb.setSizeGripEnabled(True)
Am I missing a step and/or is this at all possible?
i find this: http://aralbalkan.com/1784
but it is :
Gaebar is an easy-to-use, standalone Django application that you can plug in to your existing Google App Engine Django or app-engine-patch-based Django applications on Google App Engine to give them datastore backup and restore functionality.
my app is not based on django,so
did you know any tools esay to do this .
thanks
Hi,
I'm working on my first Django application. In short, what it needs to do is to display a list of film titles, and allow users to give a rating (out of 10) to each film. I've been able to use the {{ form }} and {{ formset }} syntax in a template to produce a form which lets you rate one film at a time, which corresponds to one row in a MySQL table, but how do I produce a form that iterates over all the movie titles in the database and produces a form that lets you rate lots of them at once?
At first, I thought this was what formsets were for, but I can't see any way to automatically iterate over the contents of a database table to produce items to go in the form, if you see what I mean.
Currently, my views.py has this code:
def survey(request):
ScoreFormSet = formset_factory(ScoreForm)
if request.method == 'POST':
formset = ScoreFormSet(request.POST, request.FILES)
if formset.is_valid():
return HttpResponseRedirect('/')
else:
formset = ScoreFormSet()
return render_to_response('cf/survey.html', {
'formset':formset,
})
And my survey.html has this:
<form action="/survey/" method="POST">
<table>
{{ formset }}
</table>
<input type = "submit" value = "Submit">
</form>
Oh, and the definition of ScoreForm and Score from models.py are:
class Score(models.Model):
movie = models.ForeignKey(Movie)
score = models.IntegerField()
user = models.ForeignKey(User)
class ScoreForm(ModelForm):
class Meta:
model = Score
So, in case the above is not clear, what I'm aiming to produce is a form which has one row per movie, and each row shows a title, and has a box to allow the user to enter their score.
If anyone can point me at the right sort of approach to this, I'd be most grateful.
Thanks,
Ben
I'm trying to find a way to cause sqlalchemy to generate sql of the following form:
select * from t where (a,b) in ((a1,b1),(a2,b2));
Is this possible?
If not, any suggestions on a way to emulate it?
Thanks kindly!
I'm using matplotlib to plot log-normalized images but I would like the original raw image data to be represented in the colorbar rather than the [0-1] interval. I get the feeling there's a more matplotlib'y way of doing this by using some sort of normalization object and not transforming the data beforehand... in any case, there could be negative values in the raw image.
import matplotlib.pyplot as plt
import numpy as np
def log_transform(im):
'''returns log(image) scaled to the interval [0,1]'''
try:
(min, max) = (im[im > 0].min(), im.max())
if (max > min) and (max > 0):
return (np.log(im.clip(min, max)) - np.log(min)) / (np.log(max) - np.log(min))
except:
pass
return im
a = np.ones((100,100))
for i in range(100): a[i] = i
f = plt.figure()
ax = f.add_subplot(111)
res = ax.imshow(log_transform(a))
# the colorbar drawn shows [0-1], but I want to see [0-99]
cb = f.colorbar(res)
I've tried using cb.set_array, but that didn't appear to do anything, and cb.set_clim, but that rescales the colors completely.
Thanks in advance for any help :)
Is that possible to define a function without referencing to self this way?
def myfunc(var_a,var_b)
But so that it could also get sender data, like if I defined it like this:
def myfunc(self, var_a,var_b)
That self is always the same so it looks a little redundant here always to run a function this way: myfunc(self,'data_a','data_b'). Then I would like to get its data in the function like this sender.fields.
UPDATE:
Here is some code to understand better what I mean.
The class below is used to show a page based on Jinja2 templates engine for users to sign up.
class SignupHandler(webapp.RequestHandler):
def get(self, *args, **kwargs):
utils.render_template(self, 'signup.html')
And this code below is a render_template that I created as wrapper to Jinja2 functions to use it more conveniently in my project:
def render_template(response, template_name, vars=dict(), is_string=False):
template_dirs = [os.path.join(root(), 'templates')]
logging.info(template_dirs[0])
env = Environment(loader=FileSystemLoader(template_dirs))
try:
template = env.get_template(template_name)
except TemplateNotFound:
raise TemplateNotFound(template_name)
content = template.render(vars)
if is_string:
return content
else:
response.response.out.write(content)
As I use this function render_template very often in my project and usually the same way, just with different template files, I wondered if there was a way to get rid of having to call it like I do it now, with self as the first argument but still having access to that object.
I'm trying to use boto as a downloaded library, rather than installing it globally on my machine. I'm able to import boto, but when I run boto.connect_dynamodb() I get an error:
ImportError: No module named dynamodb.layer2
Here's my file structure:
project/
project/
__init__.py
libraries/
__init__.py
flask/
boto/
views/
....
modules/
__init__.py
db.py
....
templates/
....
static/
....
runserver.py
And the contents of the relevant files as follows:
project/project/modules/db.py
from project.libraries import boto
conn = boto.connect_dynamodb(
aws_access_key_id='<YOUR_AWS_KEY_ID>',
aws_secret_access_key='<YOUR_AWS_SECRET_KEY>')
What am I doing wrong? Thanks in advance.
My simple GAE app is not redirecting to the /static directory for requests when url is multiple levels.
Dir structure:
/app/static/css/main.css
App:
I have two handlers one for /app and one for /app/new
app.yaml:
handlers:
- url: /static
static_dir: static
- url: /app/static/(.*)
static_dir: static\1
- url: /app/.*
script: app.py
login: required
HTML:
Description:
When page is loaded from /app HTTP request for main.css is successful
GET /static/css/main.css
But when page is loaded from /app/new I see the following request:
GET /app/static/css/main.cs
That's when I tried adding the /app/static/(.*) in the app.yaml but it is not having any effect.
Is there way to initialize a numpy array of a shape and add to it? I will explain what I need with a list example. If I want to create a list of objects generated in a loop, I can do:
a = []
for i in range(5):
a.append(i)
I want to do something similar with a numpy array. I know about vstack, concatenate etc. However, it seems these require two numpy arrays as inputs. What I need is:
big_array # Initially empty. This is where I don't know what to specify
for i in range(5):
array i of shape = (2,4) created.
add to big_array
The big_array should have a shape (10,4). How to do this? Thanks for your help.
import wx
class MainFrame(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self, parent, title=title, size=(640,480))
self.mainPanel=DoubleBufferTest(self,-1)
self.Show(True)
class DoubleBufferTest(wx.Panel):
def __init__(self,parent=None,id=-1):
wx.Panel.__init__(self,parent,id,style=wx.FULL_REPAINT_ON_RESIZE)
self.SetBackgroundColour("#FFFFFF")
self.timer = wx.Timer(self)
self.timer.Start(100)
self.Bind(wx.EVT_TIMER, self.update, self.timer)
self.Bind(wx.EVT_PAINT,self.onPaint)
def onPaint(self,event):
event.Skip()
dc = wx.MemoryDC()
dc.SelectObject(wx.EmptyBitmap(640, 480))
gc = wx.GraphicsContext.Create(dc)
gc.PushState()
gc.SetBrush(wx.Brush("#CFCFCF"))
bgRect=gc.CreatePath()
bgRect.AddRectangle(0,0,640,480)
gc.FillPath(bgRect)
gc.PopState()
dc2=wx.PaintDC(self)
dc2.Blit(0,0,640,480,dc,0,0)
def update(self,event):
self.Refresh()
app = wx.App(False)
f=MainFrame(None,"Test")
app.MainLoop()
I've come up with this code to draw double buffered GraphicsContext content onto a panel, but there's a constant flickering across the window. I've tried different kinds of paths, like lines and curves but it's still there and I don't know what's causing it.