End of line anchor $ match even there is extra trailing \n in matched string, so we use \Z instead of $
For example
^\w+$ will match the string abcd\n but ^\w+\Z is not
How about \A and when to use?
I've got a class like this:
class Image (models.Model):
...
sizes = ((90,90), (300,250))
def resize_image(self):
for size in sizes:
...
and another class like this:
class SomeClassWithAnImage (models.Model):
...
an_image = models.ForeignKey(Image)
what i'd like to do with that class is this:
class SomeClassWithAnImage (models.Model):
...
an_image = models.ForeignKey(Image, sizes=((90,90), (150, 120)))
where i'm can specify the sizes that i want the Image class to use to resize itself as a argument rather than being hard coded on the class. I realise I could pass these in when calling resize_image if that was called directly but the idea is that the resize_image method is called automatically when the object is persisted to the db.
if I try to pass arguments through the foreign key declaration like this i get an error straight away. is there an easy / better way to do this before I begin hacking down into django?
I just made a fresh copy of eclipse and installed pydev.
In my first trial to use pydev with eclipse, I created 2 module under the src package(the default one)
FirstModule.py:
'''
Created on 18.06.2009
@author: Lars Vogel
'''
def add(a,b):
return a+b
def addFixedValue(a):
y = 5
return y +a
print "123"
run.py:
'''
Created on Jun 20, 2011
@author: Raymond.Yeung
'''
from FirstModule import add
print add(1,2)
print "Helloword"
When I pull out the pull down menu of the run button, and click "ProjectName run.py", here is the result:
123
3
Helloword
Apparantly both module ran, why? Is this the default setting?
I've implemented my servers in the following way:
def makeServer(application, port):
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
internet.TCPServer(port, factory).setServiceParent(application)
application = service.Application("chatserver")
server1 = makeServer(application, port=1025)
server2 = makeServer(application, port=1026)
server3 = makeServer(application, port=1027)
Note that MyChat is an event handling class that has a "receiveMessage" action:
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.transport.write(message + '\n')
I want server1 to be able to pass messages to server2. Rather, I want server1 to be treated as a client of server2. If server1 receives the message "hi" then I want it to send that same exact message to server2.
How can I accomplish this?
Hi,
I'm trying to implement a shuttle control in wxPython but there doesn't seem to be one. I've decided to use two listbox controls. The shuttle control looks like this:
I've got two listboxes — one's populated, one's not. Could someone show me how to add a selected item to the second list box when it is double clicked? It should be removed from the first. When it is double clicked in the second, it should be added to the first and removed from the second. The shuttle control implements these by default but it's a pity it isn't there.
Thank you.
I have a dictionary called number_devices I'm passing to a template, the dictionary keys are the ids of a list of objects I'm also passing to the template (called implementations). I'm iterating over the list of objects and then trying to use the object.id to get a value out of the dict like so:
{% for implementation in implementations %}
{{ number_devices.implementation.id }}
{% endfor %}
Unfortunately number_devices.implementation is evaluated first, then the result.id is evaluated obviously returning and displaying nothing. I can't use parentheses like:
{{ number_devices.(implementation.id) }}
because I get a parse error. How do I get around this annoyance in Django templates?
Thanks for any help!
What is the best way to touch two following values in an numpy array?
example:
npdata = np.array([13,15,20,25])
for i in range( len(npdata) ):
print npdata[i] - npdata[i+1]
this looks really messed up and additionally needs exception code for the last iteration of the loop.
any ideas?
Thanks!
I am building a tree for a spell checker with suggestions. Each node contains a key (a letter) and a value (array of letters down that path).
So assume the following sub-trie in my big trie:
W
/ \
a e
| |
k k
| |
is word--> e e
|
...
This is just a subpath of a sub-trie. W is a node and a and e are two nodes in its value array etc...
At each node, I check if the next letter in the word is a value of the node. I am trying to support mistyped vowels for now. So 'weke' will yield 'wake' as a suggestion. Here's my searchWord function in my trie:
def searchWord(self, word, path=""):
if len(word) > 0:
key = word[0]
word = word[1:]
if self.values.has_key(key):
path = path + key
nextNode = self.values[key]
return nextNode.searchWord(word, path)
else:
# check here if key is a vowel. If it is, check for other vowel substitutes
else:
if self.isWord:
return path # this is the word found
else:
return None
Given 'weke', at the end when word is of length zero and path is 'weke', my code will hit the second big else block. weke is not marked as a word and so it will return with None. This will return out of searchWord with None.
To avoid this, at each stack unwind or recursion backtrack, I need to check if a letter is a vowel and if it is, do the checking again.
I changed the if self.values.has_key(key) loop to the following:
if self.values.has_key(key):
path = path + key
nextNode = self.values[key]
ret = nextNode.searchWord(word, path)
if ret == None:
# check if key == vowel and replace path
# return nextNode.searchWord(...
return ret
What am I doing wrong here? What can I do when backtracking to achieve what I'm trying to do?
I have the following code which searches all the directory in the current directory and then takes data from those files to plot the graph. The data is read correctly as verified by printing but there are no points plotted on graph.
import argparse
import os
import matplotlib.pyplot as plt
#find the present working directory
pwd=os.path.dirname(os.path.abspath(__file__))
#find all the folders in the present working directory.
dirs = [f for f in os.listdir('.') if os.path.isdir(f)]
plt.figure()
plt.xlim(0, 20000)
plt.ylim(0, 1)
for directory in dirs:
os.chdir(os.path.join(pwd, directory));
chd_dir = os.path.dirname(os.path.abspath(__file__))
files = [ fl for fl in os.listdir('.') if os.path.isfile(fl) ]
print files
for f in files:
f_obj = open(os.path.join(chd_dir, f), 'r')
list_x = []
list_y = []
for i in xrange(0,4):
f_obj.next()
for line in f_obj:
temp_list = line.split()
print temp_list
list_y.append(temp_list[0])
list_x.append(temp_list[1])
print 'final_lsit'
print list_x
print list_y
plt.plot(list_x, list_y, 'r.')
f_obj.close()
os.chdir(pwd)
plt.savefig("test.jpg")
The input files look like the following:
5
865 14709 15573
14709 1.32667e-06
664 0.815601
14719 1.55333e-06
674 0.813277
14729 1.82667e-06
684 0.810185
14739 1.4e-06
694 0.808459
Can anybody help me with why this is happening? Being new I would like to know some tutorial where I can get help with kind of plotting as the tutorial I was following made me end up here.
Any help appreciated.
Given a string named line whose raw version has this value:
\rRAWSTRING
how can I detect if it has the escape character \r? What I've tried is:
if repr(line).startswith('\r'):
blah...
but it doesn't catch it. I also tried find, such as:
if repr(line).find('\r') != -1:
blah
doesn't work either. What am I missing?
thx!
Hello, I chose this way to get linux distro name:
ls /etc/*release
And now I have to parse it for name:
/etc/<name>-release
def checkDistro():
p = Popen('ls /etc/*release' , shell = True, stdout = PIPE)
distroRelease = p.stdout.read()
distroName = re.search( ur"\/etc\/(.*)\-release", distroRelease).group()
print distroName
But this prints the same string that is in distroRelease.
I'm running an application from supervisord and I have to set up an environment for it. There are about 30 environment variables that need to be set. I've tried putting all on one big
environment=
line and that doesn't seem to work. I've also tried multiple enviroment= lines, and that doesn't seem to work either. I've also tried both with and without ' around the env value.
What's the best way to set up my environment such that it remains intact under supervisord control? Should I be calling my actual program (tornado, fwiw) from a shell script with the environment preloaded there? Ideally, I'd like to put all of the enviroment variables into an include file and load them with supervisor, but I'm open to doing it another way.
I have a django queryset in my views whose values I pack before passing to my template. There is a problem when the queryset returns none since associated values are not unpacked. the quersyet is called comments.
Here is my views.py
def forums(request ):
post_list = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0').order_by('postDate'))
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
newpostform = PostForm(request.POST)
deletepostform = PostDeleteForm(request.POST)
DelPostFormSet = modelformset_factory(forum, exclude=('child','postSubject','postBody','postPoster','postDate','childParentId'))
readform = ReadForumForm(request.POST)
comments =list( forum.objects.filter(deleted='0').filter(child='1').order_by('childParentId').values('childParentId').annotate(y=Count('childParentId')))
if request.user.is_staff== True :
staff = 1
else:
staff = 0
staffis = 1
if newpostform.is_valid():
topic = request.POST['postSubject']
poster = request.POST['postPoster']
newpostform.save()
return HttpResponseRedirect('/forums')
else:
newpostform = PostForm(initial = {'postPoster':user.id})
if request.GET:
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
post_list = list((forum.objects.filter(child='0')&forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)))or(forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)).values('childParentId')))
if request.method == 'POST':
delpostformset = DelPostFormSet(request.POST)
if delpostformset.is_valid():
delpostformset.save()
return HttpResponseRedirect('/forums')
else:
delpostformset = DelPostFormSet(queryset=forum.objects.filter(child='0', deleted='0'))
"""if readform.is_valid():
user=get_object_or_404(UserProfile.objects.all())
readform.save()
else:
readform = ReadForumForm()"""
post= zip( post_list,comments, delpostformset.forms)
paginator = Paginator(post, 10) # Show 10 contacts per page
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
post = paginator.page(page)
except (EmptyPage, InvalidPage):
post = paginator.page(paginator.num_pages)
return render_to_response('forum.html', {'post':post, 'newpostform': newpostform,'delpost':delpostformset, 'username':user.username, 'comments':comments, 'user':user, },context_instance = RequestContext( request ))
My question is about hosting Django and Wordpress under one domain, but two physical machines (actually, they are VMs but same diff).
Let's say I have a Django webapp at example.com. I'd like to start a Wordpress blog about my webapp, so any blog page rank mojo flows back to my webapp, I'd like the blog address t be example.com/blog. My understanding is blog.example.com would not transfer said page rank mojo.
Because I'm worried about Wordpress security flaws compromising my Django webapp, I want to host Django and Wordpress on two physically separate machines.
Given all that, is it possible using re-write rules or a reverse proxy server to do this? I know the easy way is to make my Wordpress blog a subdomain, but I really don't want to do that.
Has anyone done this in the past, is it stable? If I need a third server to be a dedicated reverse proxy, that's totally fine.
Thanks!
Hi all,
I wanna show a gtk.Window under a gtk.widget.
But I don't know how to retrieve the gtk.widget's coordinates for my gtk.window.
Anyone knows ?
Thanks.
write a script that takes two optional boolean arguments,"--verbose‚" and ‚"--live", and two required string arguments, "base"and "pattern". Please set up the command line processing using argparse.
This is the code I have so far for the question, I know I am getting close but something is not quite right. Any help is much appreciated.Thanks for all the quick useful feedback.
def main():
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('base', type=str)
parser.add_arguemnt('--verbose', action='store_true')
parser.add_argument('pattern', type=str)
parser.add_arguemnt('--live', action='store_true')
args = parser.parse_args()
print(args.base(args.pattern))
Hello,
I am trying to build a list of lists using the following code:
list=3*[[]]
Now I am trying to append a string to the list in position 0:
list[0].append("hello")
However, instead of receiving the list
[ ["hello"] , [], [] ]
I am receiving the list:
[ ["hello"] ,["hello"] , ["hello"] ]
Am I missing something?
Thanks,
Joel
What I'm trying to do is query the datastore for a model where the key is not the key of an object I already have. Here's some code:
class User(db.Model):
partner = db.SelfReferenceProperty()
def text_message(self, msg):
user = User.get_or_insert(msg.sender)
if not user.partner:
# user doesn't have a partner, find them one
# BUG: this line returns 'user' himself... :(
other = db.Query(User).filter('partner =', None).get()
if other:
# connect users
else:
# no one to connect to!
The idea is to find another User who doesn't have a partner, that isn't the User we already know.
I've tried filter('key !=, user.key()), filter('__key__ !=, user.key()) and a couple others, and nothing returns another User who doesn't have a partner.
filter('foo !=, user.key()) also returns nothing, for the record.
I am attempting to add functionality to my Django app: when a new post is approved, I want to update the corresponding Facebook Page's status with a message and a link to the post automatically. Basic status update.
I have downloaded and installed pyfacebook - and I have read through the tutorial from Facebook. I have also seen this suggestion here on SO:
import facebook
fb = facebook.Facebook('YOUR_API_KEY', 'YOUR_SECRET_KEY')
fb.auth.createToken()
fb.login() # THIS IS AS FAR AS I CAN GET
fb.auth.getSession()
fb.set_status('Checking out StackOverFlow.com')
When I get to the login() call, however, pyfacebook tries to open lynx so I can login to Facebook 'via the web' -- this is, obviously, not going to work for me because the system is supposed to be automated ...
I've been looking, but can't find out how I can keep this all working with the script and not having to login via a web browser.
Any ideas?
I am trying to generate tree with fasta file input and Alignment with MuscleCommandline
import sys,os, subprocess
from Bio import AlignIO
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(input="c:\Python26\opuntia.fasta")
child= subprocess.Popen(str(cline),
stdout = subprocess.PIPE,
stderr=subprocess.PIPE,
shell=(sys.platform!="win32"))
align=AlignIO.read(child.stdout,"fasta")
outfile=open('c:\Python26\opuntia.phy','w')
AlignIO.write([align],outfile,'phylip')
outfile.close()
I always encounter with these problems
Traceback (most recent call last):
File "", line 244, in run_nodebug
File "C:\Python26\muscleIO.py", line 11, in
align=AlignIO.read(child.stdout,"fasta")
File "C:\Python26\Lib\site-packages\Bio\AlignIO_init_.py", line 423, in read
raise ValueError("No records found in handle")
ValueError: No records found in handle
I have the following django test case that is giving me errors:
class MyTesting(unittest.TestCase):
def setUp(self):
self.u1 = User.objects.create(username='user1')
self.up1 = UserProfile.objects.create(user=self.u1)
def testA(self):
...
def testB(self):
...
When I run my tests, testA will pass sucessfully but before testB starts, I get the following error:
IntegrityError: column username is not unique
It's clear that it is trying to create self.u1 before each test case and finding that it already exists in the Database. How do I get it to properly clean up after each test case so that subsequent cases run correctly?
I have a function that attempts to take a list of usernames, look each one up in a user table, and then add them to a membership table. If even one username is invalid, I want the entire list to be rolled back, including any users that have already been processed. I thought that using sessions was the best way to do this but I'm running into a DetachedInstanceError:
DetachedInstanceError: Instance <Organization at 0x7fc35cb5df90> is not bound to a Session; attribute refresh operation cannot proceed
Full stack trace is here.
The error seems to trigger when I attempt to access the user (model) object that is returned by the query. From my reading I understand that it has something to do with there being multiple sessions, but none of the suggestions I saw on other threads worked for me. Code is below:
def add_members_in_bulk(organization_eid, users):
"""Add users to an organization in bulk - helper function for add_member()"""
"""Returns "success" on success and id of first failed student on failure"""
session = query_session.get_session()
session.begin_nested()
users = users.split('\n')
for u in users:
try:
user = user_lookup.by_student_id(u)
except ObjectNotFoundError:
session.rollback()
return u
if user:
membership.add_user_to_organization(
user.entity_id,
organization_eid,
'',
[]
)
session.flush()
session.commit()
return 'success'
here's the membership.add_user_to_organization:
def add_user_to_organization(user_eid, organization_eid, title, tag_ids):
"""Add a User to an Organization with the given title"""
user = user_lookup.by_eid(user_eid)
organization = organization_lookup.by_eid(organization_eid)
new_membership = OrganizationMembership(
organization_eid=organization.entity_id,
user_eid=user.entity_id,
title=title)
new_membership.tags = [get_tag_by_id(tag_id) for tag_id in tag_ids]
crud.add(new_membership)
and here is the lookup by ID query:
def by_student_id(student_id, include_disabled=False):
"""Get User by RIN"""
try:
return get_query_set(include_disabled).filter(User.student_id == student_id).one()
except NoResultFound:
raise ObjectNotFoundError("User with RIN %s does not exist." % student_id)
I don't think i fully understand character sets so i was wondering if anyone would be kind enough to explain it in layman's terms with examples ( for Dummies).I know there is utf8, latin1, ascii ect
The more answers the better really.
Thank you in advance;-)
I'm having a attribute on my model to allow the user to order the objects. I have to update the element's order depending on a list, that contains the object's ids in the new order; right now I'm iterating over the whole queryset and set one objects after the other. What would be the easiest/fastest way to do the same with the whole queryset?
def update_ordering(model, order):
""" order is in the form [id,id,id,id] for example: [8,4,5,1,3] """
id_to_order = dict((order[i], i) for i in range(len(order)))
for x in model.objects.all():
x.order = id_to_order[x.id]
x.save()