I want my regex to catch:
monday mon thursday thu ...
So it's possible to write something like this:
(?P<day>monday|mon|thursday|thu ...
But I guess that there should be a more elegant solution.
I have the following issue with Selenium Webdriver. There are two dropdown menus on a page i am testing "brand" and "items". The options of "items" depend on which brand you choose. I am trying to iterate through all possible choices and print brand-item pairs. I use two possible ways to pick an option from each dropdown menu
Using Select():
def retryingSelectOption(name,n):
result=False
attempts=0
while attempts<5:
try:
element=Select(driver.find_element_by_name(name))
element.select_by_index(n)
print element.all_selected_options[0].text
result=True
break
except StaleElementReferenceException:
pass
attempts+=1
return result
And using .click():
def retryingClickOption(name,n):
result=False
attempts=0
while attempts<5:
try:
driver.find_element_by_name(name).find_elements_by_tag_name("option")[n].click()
result=True
break
except StaleElementReferenceException:
pass
attempts+=1
return result
My problem is that at ,what seem to me as random moments (sometimes it works sometimes it does not), even though the above functions return True and printing out the selected option shows me the correct answer, the browser still displays the previous option. So basically Selenium tells me i have picked the right option but the browser displays the previous one.No idea what is wrong.
n=[['dgd','sd','gsg'],['fsdsdf','sds','sdf']]
>>> n.remove('sd')
if i have a nested list like above and want to remove 'sd'.how can i doing the above thing is giving an error??
I want to do something like this. The _print_attr function is designed to be called lazily, so I don't want to evaluate it in the init and set the value to attr. I would like to make attr a property that computes _print_attr only when accessed:
class Base(object):
def __init__(self):
for attr in self._edl_uniform_attrs:
setattr(self, attr, property(lambda self: self._print_attr(attr)))
def _print_attr(self, attr):
print attr
class Child(Base):
_edl_uniform_attrs = ['foo', 'bar']
me = Child()
me.foo
me.bar
#output:
#"foo"
#"bar"
I have xml of the format:
<channel>
<games>
<game slot='1'>
<id>Bric A Bloc</id>
<title-text>BricABloc Hoorah</title-text>
<link>Fruit Splat</link>
</game>
</games>
</channel>
I've parsed this xml using lxml.objectify, via:
tree = objectify.parse(file)
There will potentially be a number of <game>s underneath <games>.
I understand that I can generate a list of <game> objects via:
[ tree.games[0].game[0:4] ]
My question is, what class are those objects and is there a function to print any object of whatever class these objects belong to?
I'd like to know if there is a class available, either in the standard library or in pypi, that fits this description.
The constructor would take an iterator.
It would implement the container protocol (ie _getitem_, _len_, etc), so that slices, length, etc., would work. In doing so, it would iterate and retain just enough values from its constructor argument to provide whatever information was requested.
So if jitlist[6] was requested, it would call self.source.next() 7 times, save those elements in its list, and return the last one.
This would allow downstream code to use it as a list, but avoid unnecessarily instantiating a list for cases where list functionality was not needed, and avoid allocating memory for the entire list if only a few members ended up being requested.
It seems like a pretty easy one to write, but it also seems useful enough that it's likely that someone would have already made it available in a module.
Hello,
I am writing website and i`d like to implement profile managment. Basic thing
would be to edit some of user details by themself, like first and last name
etc. Now, i had to extend User model to add my own stuff, and email address.
I am having troubles with displaying form. Example will describe better what i
would like achieve.
This is mine extended user model.
class UserExtended(models.Model):
user = models.ForeignKey(User, unique=True)
kod_pocztowy = models.CharField(max_length=6,blank=True)
email = models.EmailField()
This is how my form looks like.
class UserCreationFormExtended(UserCreationForm):
def __init__(self, *args, **kwargs):
super(UserCreationFormExtended, self).__init__(*args, **kwargs)
self.fields['email'].required = True
self.fields['first_name'].required = False
self.fields['last_name'].required = False
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email')
It works fine when registering, as i need allow users to put username and email but when it goes to editing profile it displays too many fields. I would not like them to be able to edit username and email. How could i disable fields in form?
Thanks for help.
Does map() iterate through the list like "for" would? Is there a value in using map vs for?
If so, right now my code looks like this:
for item in items:
item.my_func()
If it makes sense, I would like to make it map(). Is that possible? What is an example like?
I have models that belong to some 'group' (Company class). I want to add users, who will also belong to a one group and should be able to edit/manage/add objects with membership in associated group.
something like:
class Company()
class Something()
company = ForeignKey(Company)
user Microsoft_admin
company = ForeignKey(Company)
and this user should only see and edit objects belonging to associated Company in the Admin Interface.
How to acomplish that?
I have a long string and a set of <end-index, string> list like the following:
long_sentence = "This is a long long long long sentence"
indices = [[6, "is"], [8, "is a"], [18, "long"], [23, "long"]]
An element 6, "is" indicates that 6 is the end index of the word "is" in the string. I want to get the following string in the end:
>> print long_sentence
This .... long ......... long sentence"
I tried an approach like this:
temp = long_sentence
for i in indices:
temp = temp[:int(i[0]) - len(i[1])] + '.'*(len(i[1])+1) + temp[i[0]+1:]
While this seems to be working, it is taking exceptionally long time (more than 6 hours on 5000 strings inside a 300 MB file). Is there a way to speed this up?
My code is:
print os.urandom(64)
which outputs:
> "D:\Python25\pythonw.exe" "D:\zjm_code\a.py"
\xd0\xc8=<\xdbD'
\xdf\xf0\xb3>\xfc\xf2\x99\x93
=S\xb2\xcd'\xdbD\x8d\xd0\\xbc{&YkD[\xdd\x8b\xbd\x82\x9e\xad\xd5\x90\x90\xdcD9\xbf9.\xeb\x9b>\xef#n\x84
which isn't readable, so I tried this:
print os.urandom(64).decode("utf-8")
but then I get:
> "D:\Python25\pythonw.exe" "D:\zjm_code\a.py"
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 17, in <module>
print os.urandom(64).decode("utf-8")
File "D:\Python25\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-3: invalid data
What should I do to get human-readable output?
can anyone see why this wouldn't be working. Fairly new to django so any help would be much appreciated
actual url:
http://127.0.0.1:8000/2010/may/12/my-second-blog-post/
urls.py:
(r'(?P<year>d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-w]+)/$', 'object_detail', dict(info_dict, slug_field='slug',template_name='blog/detail.html')),
i have a programm that generate the list and then i ask them to tell me what they want to do from the menu and this is where my problem start i was able to get the input form the user to different function but when i try to use the if else condition it doesn't check, below are my code
def menu(x,l):
print (x)
if x == 1:
return make_table(l)
if x == 2:
y= input("enter a row (as a number) or a column (as an uppercase letter")
if y in [ "1",'2','3']:
print("Minmum is:",minimum(y,l))
if x== 3:
print ('bye')
def main():
bad_filename = True
l =[]
while bad_filename == True:
try:
filename = input("Enter the filename: ")
fp = open(filename, "r")
for f_line in fp:
f_str=f_line.strip()
f_str=f_str.split(',')
for unit_str in f_str:
unit=float(unit_str)
l.append(unit)
bad_filename = False
except IOError:
print("Error: The file was not found: ", filename)
#print(l)
condition=True
while condition==True:
print('1- open\n','2- maximum')
x=input("Enter the choice")
menu(x,l)
main()
from the bottom function i can get list and i can get the user input and i can get the data and move it in second function but it wont work after that.thank you
i am getting
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 104: ordinal not in range(128)
i am using intgereproparty,stringproparty,datetimeproparty
How can I obtain the (IPv4) addresses for all network interfaces using only proc? After some extensive investigation I've discovered the following:
ifconfig makes use of SIOCGIFADDR, which requires open sockets and advance knowledge of all the interface names. It also isn't documented in any manual pages on Linux.
proc contains /proc/net/dev, but this is a list of interface statistics.
proc contains /proc/net/if_inet6, which is exactly what I need but for IPv6.
Generally interfaces are easy to find in proc, but actual addresses are very rarely used except where explicitly part of some connection.
There's a system call called getifaddrs, which is very much a "magical" function you'd expect to see in Windows. It's also implemented on BSD. However it's not very text-oriented, which makes it difficult to use from non-C languages.
import math
def gen_caller(a):
for z in a:
x,y=z
if x==1:
x=2
if y>=x and y-x<=100000:
for i in range(x,y+1):
flag=0
for j in range(2,(long(math.sqrt(i))+1)):
if(i%j==0):
flag=1
break
if flag==0:
print i
print ""
n=(int(raw_input()))
gen_caller([[(long(raw_input())) for j in range(0,2)] for i in range(0,n) if n<=10])
I have the following code in the urls.py in mysite project.
/mysite/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^gallery/$', include('mysite.gallery.urls')),
)
This results in a 404 page when I try to access a url set in gallery/urls.py.
/mysite/gallery/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^gallery/browse/$', 'mysite.gallery.views.browse'),
(r'^gallery/photo/$', 'mysite.gallery.views.photo'),
)
404 error
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^gallery/$
The current URL, gallery/browse/, didn't match any of these.
Also, the site is hosted on a media temple (dv) server and using mod_wsgi
def process_dialect_translation_rules():
# Read in lines from the text file specified in sys.argv[1], stripping away
# excess whitespace and discarding comments (lines that start with '##').
f_lines = [line.strip() for line in open(sys.argv[1], 'r').readlines()]
f_lines = filter(lambda line: not re.match(r'##', line), f_lines)
# Remove any occurances of the pattern '\s*<=>\s*'. This leaves us with a
# list of lists. Each 2nd level list has two elements: the value to be
# translated from and the value to be translated to. Use the sub function
# from the re module to get rid of those pesky asterisks.
f_lines = [re.split(r'\s*<=>\s*', line) for line in f_lines]
f_lines = [re.sub(r'"', '', elem) for elem in line for line in f_lines]
This function should take the lines from a file and perform some operations on the lines, such as removing any lines that begin with ##. Another operation that I wish to perform is to remove the quotation marks around the words in the line. However, when the final line of this script runs, f_lines becomes an empty lines. What happened?
Requested lines of original file:
## English-Geek Reversible Translation File #1
## (Moderate Geek)
## Created by Todd WAreham, October 2009
"TV show" <=> "STAR TREK"
"food" <=> "pizza"
"drink" <=> "Red Bull"
"computer" <=> "TRS 80"
"girlfriend" <=> "significant other"
can we use elif in list comprehension?
example :
l = [1, 2, 3, 4, 5]
for values in l:
if values==1:
print 'yes'
elif values==2:
print 'no'
else:
print 'idle'
can we use list comprehension for such 2 if conditions and one else condition?
foe example answer like :
['yes', 'no', 'idle', 'idle', 'idle']
I have done till now only if else in list comprehension.
I have remote objects which talk each others with RPCs, using Twisted Spread.
I want that objects authenticate messages, before using them, with digital signatures, but I don't know where to start to implement this.
In my head, the Root object must have a public/private key pair, and the Client too. When a message is sent, a digital signature of the hash is added, and when it is received, the signature is checked. Is the Protocol part where I need to add these adds and checks?
Thank you
Suppose I have a numpy array x = [5, 2, 3, 1, 4, 5], y = ['f', 'o', 'o', 'b', 'a', 'r']. I want to select the elements in y corresponding to elements in x that are greater than 1 and less than 5.
I tried
x = array([5, 2, 3, 1, 4, 5])
y = array(['f','o','o','b','a','r'])
output = y[x > 1 & x < 5] # desired output is ['o','o','b','a']
but this doesn't work. How would I do this?
I've written a script that installs several printers for a new user.
I want to change the settings on some of these so that they can print on both sides of the page.
I BELIEVE this involves modifying an attribute with printui, however it might need VB script or possibly another .NET language (I'd either use VB, C# or IronPython).
I can add a comment to a given printer, but how do I select preferences and modify them?
Pseudocode would look like this:
printui.exe /n printername /??? [how to change quality desired]
OR calls to the relevant Windows API.
Here is my problem. I want the following class to have a bunch of property attributes. I could either write them all out like foo and bar, or based on some other examples I've seen, it looks like I could use a class decorator, a metaclass, or override the __new__ method to set the properties automagically. I'm just not sure what the "right" way to do it would be.
class Test(object):
def calculate_attr(self, attr):
# do calculaty stuff
return attr
@property
def foo(self):
return self.calculate_attr('foo')
@property
def bar(self):
return self.calculate_attr('bar')
I have an interface created with Glade. It contains a DrawingArea and buttons.
I tried to create a Thread to refresh every X time my Canva. After a few seconds, I get error messages like:
"X Window Server 0.0", "Fatal Error IO 11"
Here is my code :
import pygtk
pygtk.require("2.0")
import gtk
import Canvas
import threading as T
import time
import Map
gtk.gdk.threads_init()
class Interface(object):
class ThreadCanvas(T.Thread):
"""Thread to display the map"""
def __init__(self, interface):
T.Thread.__init__(self)
self.interface = interface
self.started = True
self.start()
def run(self):
while self.started:
time.sleep(2)
self.interface.on_canvas_expose_event()
def stop(self):
self.started = False
def __init__(self):
self.interface = gtk.Builder()
self.interface.add_from_file("interface.glade")
#Map
self.map = Map.Map(2,2)
#Canva
self.canvas = Canvas.MyCanvas(self.interface.get_object("canvas"),self.game)
self.interface.connect_signals(self)
#Thread Canvas
self.render = self.ThreadCanvas(self)
def on_btnChange_clicked(self, widget):
#Change map
self.map.change()
def on_interface_destroy(self, widget):
self.render.stop()
self.render.join()
self.render._Thread__stop()
gtk.main_quit()
def on_canvas_expose_event(self):
st = time.time()
self.canvas.update(self.map)
et = time.time()
print "Canvas refresh in : %f times" %(et-st)
def main(self):
gtk.main()
How can i fix these errors ?