How can I do this with Firefox?
ie = win32com.client.Dispatch('InternetExplorer.Application')
ie.visible = 1
ie.navigate('http://google.com')
Is there a way to do it?
say ive got a matrix that looks like:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
how can i make it on seperate lines:
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
and then remove commas etc:
0 0 0 0 0
And also to make it blank instead of 0's, so that numbers can be put in later, so in the end it will be like:
_ 1 2 _ 1 _ 1
(spaces not underscores)
thanks
Hi All,
I have following:
temp = "aaaab123xyz@+"
lists = ["abc", "123.35", "xyz", "AND+"]
for list in lists
if re.match(list, temp, re.I):
print "The %s is within %s." % (list,temp)
The re.match is only match the beginning of the string, How to I match substring in between too.
Having a class like this:
class Spam(object):
def __init__(self, name=''):
self.name = name
eggs = Spam('systempuntoout')
using dis, is it possible to see how an instance of a class and the respective hex Identity are created?
query = "SELECT * FROM mytable WHERE time=%s", (mytime)
Then, I want to add a limit %s to it. How can I do that without messing up the %s in mytime?
Edit: I want to concat query2, which has "LIMIT %s, %s"
Hi folks,
is there a similar library to simplejson, which would enable quick serialization of data to and from XML.
e.g. json.loads('{vol:'III', title:'Magical Unicorn'}')
e.g. json.dumps([1,2,3,4,5])
Any ideas?
I have this xml model.
link text
So I have to add some node (see the text commented) to this file.
How I can do it?
I have writed this partial code but it doesn't work:
xmldoc=minidom.parse(directory)
child = xmldoc.createElement("map")
for node in xmldoc.getElementsByTagName("Environment"):
node.appendChild(child)
Thanks in advance.
I had to do heavy I/o bound operation, i.e Parsing large files and converting from one format to other format. Initially I used to do it serially, i.e parsing one after another..! Performance was very poor ( it used take 90+ seconds). So I decided to use threading to improve the performance. I created one thread for each file. ( 4 threads)
for file in file_list:
t=threading.Thread(target = self.convertfile,args = file)
t.start()
ts.append(t)
for t in ts:
t.join()
But for my astonishment, there is no performance improvement whatsoever. Now also it takes around 90+ seconds to complete the task. As this is I/o bound operation , I had expected to improve the performance. What am I doing wrong?
I have this small script that sorts the content of a text file
# The built-in function `open` opens a file and returns a file object.
# Read mode opens a file for reading only.
try:
f = open("tracks.txt", "r")
try:
# Read the entire contents of a file at once.
# string = f.read()
# OR read one line at a time.
#line = f.readline()
# OR read all the lines into a list.
lines = f.readlines()
lines.sort()
f = open('tracks.txt', 'w')
f.writelines(lines) # Write a sequence of strings to a file
finally:
f.close()
except IOError:
pass
the only problem is that the text is displayed at the bottom of the text file everytime it's sortened...
I assume it also sorts the blank lines...anybody knows why?
thanks in advance
Suppose I have a list of lists of elements which are all the same (i'll use ints in this example)
[range(100)[::4], range(100)[::3], range(100)[::2], range(100)[::1]]
What would be a nice and/or efficient way to take the intersection of these lists (so you would get every element that is in each of the lists)?
For the example that would be:
[0, 12, 24, 36, 48, 60, 72, 84, 96]
Hey guys, new programmer here. I have an assignment for class and I'm stuck... What I need to do is a create a GUI that gives someone a basic arithmetic problem in one box, asks the person to answer it, evaluates it, and tells you if you're right or wrong...
Basically, what I have is this:
[code]
class Lesson(Frame):
def init (self, parent=None):
Frame.init(self, parent)
self.pack()
Lesson.make_widgets(self)
def make_widgets(self):
Label(self, text="").pack(side=TOP)
ent = Entry(self)
self.a = randrange(1,10)
self.b = randrange(1,10)
self.expr = choice(["+","-"])
ent.insert(END, str(self.a) + str(self.expr) + str(self.a))
[/code]
I've broken this down into many little steps and basically, what I'm trying to do right now is insert a default random expression into the first entry widget. When I run this code, I just get a blank Label. Why is that? How can I put a something like "7+7" into the box? If you absolutely need background to the problem, it's question #3 on this link.
http://reed.cs.depaul.edu/lperkovic/csc242/homeworks/Homework8.html
-Thanks for all help in advance.
I have a file that is about 100Mb that looks like this:
#meta data 1
skadjflaskdjfasljdfalskdjfl
sdkfjhasdlkgjhsdlkjghlaskdj
asdhfk
#meta data 2
jflaksdjflaksjdflkjasdlfjas
ldaksjflkdsajlkdfj
#meta data 3
alsdkjflasdjkfglalaskdjf
This file contains one row of meta data that corresponds to several, variable length data containing only alpha-numeric characters. What is the best way to read this data into a simple list like this:
data = [[#meta data 1, skadjflaskdjfasljdfalskdjflsdkfjhasdlkgjhsdlkjghlaskdjasdhfk],
[#meta data 2, jflaksdjflaksjdflkjasdlfjasldaksjflkdsajlkdfj],
[#meta data 3, alsdkjflasdjkfglalaskdjf]]
My initial idea was to use the read() method to read the whole file into memory and then use regular expressions to parse the data into the desired format. Is there a better more pythonic way? All metadata lines start with an octothorpe and all data lines are all alpha-numeric. Thanks!
Can someone explain how to do nested dict comprehensions?
>> l = [set([1, 2, 3]), set([4, 5, 6])]
>> j = dict((a, i) for a in s for i, s in enumerate(l))
>> NameError: name 's' is not defined
I would have liked:
>> j
>> {1:0, 2:0, 3:0, 4: 1, 5: 1, 6: 1}
I just asked a previous question about a simpler dict comprehension where the parentheses in the generator function were reduced. How come the s in the leftmost comprehension is not recognized?
I was unsuccessful browsing web for a solution for the following simple question:
How to draw 3D polygon (say a filled rectangle or triangle) using vertices values?
I have tried many ideas but all failed, see:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
x = [0,1,1,0]
y = [0,0,1,1]
z = [0,1,0,1]
verts = [zip(x, y,z)]
ax.add_collection3d(PolyCollection(verts),zs=z)
plt.show()
I appreciate in advance any idea/comment.
Updates based on the accepted answer:
import mpl_toolkits.mplot3d as a3
import matplotlib.colors as colors
import pylab as pl
import scipy as sp
ax = a3.Axes3D(pl.figure())
for i in range(10000):
vtx = sp.rand(3,3)
tri = a3.art3d.Poly3DCollection([vtx])
tri.set_color(colors.rgb2hex(sp.rand(3)))
tri.set_edgecolor('k')
ax.add_collection3d(tri)
pl.show()
Here is the result:
I am creating a 'Euromillions Lottery generator' just for fun and I keep getting the same numbers printing out. How can I make it so that I get random numbers and never get the same number popping up:
from random import randint
numbers = randint(1,50)
stars = randint(1,11)
print "Your lucky numbers are: ", numbers, numbers, numbers, numbers, numbers
print "Your lucky stars are: " , stars, stars
The output is just:
>>> Your lucky numbers are: 41 41 41 41 41
>>> Your lucky stars are: 8 8
>>> Good bye!
How can I fix this?
Regards
Here's the code, I don't quite understand, how does it work. Could anyone tell, is that an expected behavior?
$ipython
In [1]: 1 in [1] == True
Out[1]: False
In [2]: (1 in [1]) == True
Out[2]: True
In [3]: 1 in ([1] == True)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/dmedvinsky/projects/condo/condo/<ipython console> in <module>()
TypeError: argument of type 'bool' is not iterable
In [4]: from sys import version_info
In [5]: version_info
Out[5]: (2, 6, 4, 'final', 0)
I have a dictionary of the following form
a = {'100':12,'6':5,'88':3,'test':34, '67':7,'1':64 }
I want to sort this dictionary with respect to key as following
a = {'1':64,'6':5,'67':7,'88':3, '100':12,'test':34 }
Please help
I understand the gist of the code, that it forms permutations; however, I was wondering if someone could explain exactly what is going on in the return statement.
def perm(l):
sz = len(l)
print (l)
if sz <= 1:
print ('sz <= 1')
return [l]
return [p[:i]+[l[0]]+p[i:] for i in range(sz) for p in perm(l[1:])]
Is it possible to get reference to class B in this example?
class A(object): pass
class B(A):
def test(self):
test2()
class C(B): pass
import inspect
def test2():
frame = inspect.currentframe().f_back
cls = frame.[?something here?]
# cls here should == B (class)
c = C()
c.test()
Basically, C is child of B, B is child of A. Then we create c of type C. Then the call to c.test() actually calls B.test() (via inheritance), which calls to test2().
test2() can get the parent frame frame; code reference to method via frame.f_code;
self via frame.f_locals['self']; but type(frame.f_locals['self']) is C (of course), but not B, where method is defined.
Any way to get B?
Currently I am stuck trying to find the intersection of three sets. Now these sets are really lists that I am converting into sets, and then trying to find the intersection of.
Here's what I have so far:
for list1 in masterlist:
list1=thingList1
for list2 in masterlist:
list2=thingList2
for list3 in masterlist:
list3=thingList3
d3=[set(thingList1), set(thingList2), set(thingList3)] setmatches c=
set.intersection(*map(set,d3)) print setmatches
and I'm getting
set([])
Script terminated.
I know there's a much simpler and better way to do this, but I can't find one...
I'm sure this is simple but I can't figure it out. I have a list of strings like this(after using sorted on it):
Season 2, Episode 1: A Flight to Remember
Season 2, Episode 20: Anthology of Interest I
Season 2, Episode 2: Mars University
Season 2, Episode 3: When Aliens Attack
....
Season 3, Episode 10: The Luck of the Fryrish
Season 3, Episode 11: The Cyber House Rules
Season 3, Episode 12: Insane in the Mainframe
Season 3, Episode 1: The Honking
Season 3, Episode 2: War Is the H-Word
How can I make them sort out properly? (by episode #, ascending)
I'm trying to make a test for checking whether a sys.argv input matches the regex for an IP address...
As a simple test, I have the following...
import re
pat = re.compile("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")
test = pat.match(hostIP)
if test:
print "Acceptable ip address"
else:
print "Unacceptable ip address"
However when I pass random values into it, it returns "Acceptable ip address" in most cases, except when I have an "address" that is basically equivalent to \d+
Any thoughts welcome.
Cheers
Matt
I have this code:
filenames=["file1","FILE2","file3","fiLe4"]
def alignfilenames():
#build a string that can be used to add labels to the R variables.
#format goal: suffixes=c(".fileA",".fileB")
filestring='suffixes=c(".'
for filename in filenames:
filestring=filestring+str(filename)+'",".'
print filestring[:-3]
#now delete the extra characters
filestring=filestring[-1:-4]
filestring=filestring+')'
print "New String"
print str(filestring)
alignfilenames()
I'm trying to get the string variable to look like this format: suffixes=c(".fileA",".fileB".....) but adding on the final parenthesis is not working. When I run this code as is, I get:
suffixes=c(".file1",".FILE2",".file3",".fiLe4"
New String
)
Any idea what's going on or how to fix it?
Is there a cleaner way to write this:
for w in [w for w in words if w != '']:
I want to loop over a dictionary words, but only words that aren't whitespace. Thanks!