How do I find out if a connection has been broken using the httplib library? Seems like something so basic yet I can't find the answer on here or google.
I have a simple for loop problem, when i run the code below it prints out series of 'blue green' sequences then a series of 'green' sequences. I want the output to be; if row[4] is equal to 1 to print blue else print green.
for row in rows:
for i in `row[4]`:
if i ==`1`:
print 'blue '
else:
print 'green '
Any help would be grateful
thanks
Yas
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 a directory structure:
example.py
templates/
__init__.py
a.py
b.py
a.py and b.py have only one class, named the same as the file (because they are cheetah templates). For purely style reasons, I want to be able to import and use these classes in example.py like so:
import templates
t = templates.a()
Right now I do that by having this in the template folder's __init__.py:
__all__ = ["a", "b"]
from . import *
However, this seems pretty poor (and maybe superfluous), and doesn't even do what I want, as I have to use the classes like this:
t = templates.a.a()
Thoughts?
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?
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]
I need to open multiple files (2 input and 2 output files), do complex manipulations on the lines from input files and then append results at the end of 2 output files. I am currently using the following approach:
in_1 = open(input_1)
in_2 = open(input_2)
out_1 = open(output_1, "w")
out_2 = open(output_2, "w")
# Read one line from each 'in_' file
# Do many operations on the DNA sequences included in the input files
# Append one line to each 'out_' file
in_1.close()
in_2.close()
out_1.close()
out_2.close()
The files are huge (each potentially approaching 1Go, that is why I am reading through these input files one at a time. I am guessing that this is not a very Pythonic way to do things. :) Would using the following form good?
with open("file1") as f1:
with open("file2") as f2: # etc.
If yes, could I do it while avoiding the highly indented code that would result? Thanks for the insights!
I have an HTML table that I'd like to be able to export to an Excel file. I already have an option to export the table into an IQY file, but I'd prefer something that didn't allow the user to refresh the data via Excel. I just want a feature that takes a snapshot of the table at the time the user clicks the link/button.
I'd prefer it if the feature was a link/button on the HTML page that allows the user to save the query results displayed in the table. Is there a way to do this at all? Or, something I can modify with the IQY?
I can try to provide more details if needed. Thanks in advance.
i am using XML as my backend for the application...
LXML is used to parse the xml.
How can i encrypt this xml file to make sure that the data is protected......
thanks in advance.
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 need to sort string, and I came up with the following function.
def mysort(comb_):
str = []
size = len(comb_)
for c in comb_:
str.append(c)
str.sort()
return ''.join(str)
Is there any way to make it compact?
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
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
I know that wasn't clear. Here's what I'm doing specifically. I have my list of dictionaries here:
dict = [{int=0, value=A}, {int=1, value=B}, ... n]
and I want to take them in combinations, so I used itertools and it gave me a tuple (Well, okay it gave me a memory object that I then used enumerate on so I could loop over it and enumerate gave ma tuple):
for (index, tuple) in enumerate(combinations(dict, 2)):
and this is where I have my problem. I want to identify which of the two items in the combination has the bigger 'int' value and which has the smaller value and assign them to variables (I'm actually using more than 2 in the combination so I can't just say if tuple[0]['int'] tuple[1]['int'] and do the assignment because I'd have to list this out a bunch of times and that's hard to manage).
I was going to assign each 'int' value to a variable, sort it in a list, index the 'int' value in the list by 1, 2, 3, 4, 5 ... etc., then go back and access the dictionary I wanted by the int value and then assign the dictionary to a variable so I knew which was bigger. But I have a big list and lists and variable assignments are resource intensive and this is taking a long time (I had only a little bit of that written and it was taking forever to run).
So I was hoping someone knew a fast way to do this. I actually could list out every possible combination of assignmnets using the if/thens but it's just like 5 pages of if/thens and assignments and is hard to read and manage when I want to change it.
You've probably gathered this, but I"m new at programming. thx
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 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?
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?
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 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
Hello,
I am trying to understand the advantages of the module Multiprocessing over Threading. I know that Multiprocessing get's around the Global Interpreter Lock, but what other advantages are there, and can threading not do the same thing?
I know it's a really simple question, but I have no idea how to google it.
how can I do
print '<a href="%s">%s</a>' % (my_url)
So that my_url is used twice? I assume I have to "name" the %s and then use a dict in the params, but I'm not sure of the proper syntax?
just FYI, I'm aware I can just use my_url twice in the params, but that's not the point :)
Code first:
'''this is main structure of my program'''
from twisted.web import http
from twisted.protocols import basic
import threading
threadstop = False #thread trigger,to be done
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def run(self):
while True:
if threadstop:
return
dosomething()
'''def some function'''
if __name__ == '__main__':
from twisted.internet import reactor
t = MyThread()
reactor.listenTCP(serverport,myHttpFactory())
reactor.run()
As my first multithread program,I feel happy that it works as expected.But now I find I cannot control it.If I run it on front,Control+C can only stop the main process,and I can still find it in processlist;if I run it in background,I have to use kill -9 pid to stop it.And I wonder if there's a way to control the subthread process by a trigger variale,or a better way to stop the whole process other than kill -9.Thanks.
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 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.