Hi all
i wish make little gui with pyqt4 that show the output of "dir c:\windows\" line by line
I'm looking for QlistView but i don't understand how do it.
Can anyone help me?
First of all thanks for your attention. My question is how to reduce the execution time of my code.
Here is the relevant code. The below code is called in iteration from the main.
def call_prism(prism_input_file,random_length):
prism_output_file = "path.txt"
cmd = "prism %s -simpath %d %s" % (prism_input_file,random_length,prism_output_file)
p = os.popen(cmd)
p.close()
return prism_output_file
def main(prism_input_file, number_of_strings):
...
for n in range(number_of_strings):
prism_output_file = call_prism(prism_input_file,z[n])
...
return
I used statistics from the "profile statistics browser" when I profiled my code. The "file close" system command took the maximum time (14.546 seconds). The call_prism routine is called 10 times. But the number_of_strings is usually in thousands, so, my program takes lot of time to complete.
Let me know if you need more information. By the way I tried with subprocess, too. Thanks.
Looking for a way to simulate nested loops (or a cartesian product) i came across the itertools.product function.
i need a function or piece of code that receive a list of integers as input and returns a specific generator.
example:
input = [3,2,4] - gen = product(xrange(3),xrange(2),xrange(4))
or
input = [2,4,5,6] - gen = product(xrange(2),xrange(4),xrange(5),xrange(6))
as the size of the lists varies i am very confused in how to do that without the need of a lot of precoding based on a crazy amount of ifs and the size of the list.
also is there a difference in calling product(range(3)) or product(xrange(3))?
My doubt is that if the len(list) calculates the length of the list everytime it is called or it returns the value of the builtin counter.I have a context where i need to check the length of list everytime in a loop, likelistData = []
for value in ioread():
if len(listData)=25:
processlistdata()
clearlistdata()
listData.append(value)
Should I check len(listData) every iteration, or can I have a counter for the length of the list.
Alright, here's my problem.
I have a thread that creates another thread in a pool, applies async so I can work with the returned data, which is working GREAT. But I need the current thread to WAIT until the result is returned.
Here is the simplified code, as the current script is over 300 lines. I'm sure i've included everything for you to make sense of what I'm attempting:
from multiprocessing.pool import ThreadPool
import threading
pool = ThreadPool(processes=1)
class MyStreamer(TwythonStreamer):
#[...]
def on_success(self, data): #### Everytime data comes in, this is called
#[...]
#<Pseudocode>
if score >= limit
if list exists: Do stuff
elif list does not exist:
#</Pseudocode>
dic = []
dic.append([k1, v1])
did = dict(dic)
async_result = pool.apply_async(self.list_step, args=(did))
return_val = async_result.get()
slug = return_val[0]
idd = return_val[1]
#[...]
def list_step(self, *args):
## CREATE LIST
## RETURN 2 VALUES
class threadStream (threading.Thread):
def __init__(self, auth):
threading.Thread.__init__(self)
self.auth = auth
def run(self):
stream = MyStreamer(auth = auth[0], *auth[0])
stream.statuses.filter(track=auth[1])
t = threadStream(auth=AuthMe)
t.start()
I receive the results as intended, which is great, but how do I make it so this thread t waits for the async_result to come in?? My problem is everytime new data comes in, it seems that the ## CREATE LIST function is called multiple times if similar data comes in quickly enough. So I'm ending up with many lists of the same name when I have code in place to ensure that a list will never be created if the name already exists.
So to reiterate: How do I make this thread wait on the function to complete before accepting new data / continuing. I don't think time.sleep() works because on_success is called when data enters the stream. I don't think Thread.Join() will work either since I have to use a ThreadPool.apply_async to receive the data I need. Is there a hack I can make in the MyStreamer class somehow? I'm kind of at a loss here. Am I over complicating things and can this be simplified to do what I want?
Hi,
I wish to compare two lists. Generally this is not a problem as I usually use a nested for loop and append the intersection to a new list. In this case, I need to delete the intersection of A and B from A.
A = [['ab', 'cd', 'ef', '0', '567'], ['ghy5'], ['pop', 'eye']]
B = [['ab'], ['hi'], ['op'], ['ej']]
My objective is to compare A and B and delete A intersection B from A, i.e., delete A[0][0] in this case.
I tried:
def match():
for i in A:
for j in i:
for k in B:
for v in k:
if j == v:
A.remove(j)
list.remove(x) throws a ValueError.
Something I wrote throws a lot of AttributeErrors when using time.strptime() inside a thread. This only seems to happen on Windows (not on Linux), but whatever…. Upon a'Googling, it seems that time.strptime() isn't considered thread-safe.
Is there a better way to create a datetime object from a string? Current code looks like:
val = DateFromTicks(mktime(strptime(val, '%B %d, %Y')))
But, that yields the AttributeErrors as its run inside a thread.
Thanks!
I wish to get a list of connections to a manager. I can get last_accepted from the servers' listener, but I want all connections. There HAS to be a method I am missing somewhere to return all connections to a server or manager
Please help!!
Note: I am cross-posting this from App Engine group because I got no answers there.
As part of my site about Japan, I have a feature where the user can
get a large PNG for use as desktop background that shows the user's
name in Japanese. After switching my site hosting entirely to App
Engine, I removed this particular feature because I could not find any
way to render text to a PNG using the image API.
In other words, how would you go about outputting an unicode string on
top of an image of known dimensions (1024x768 for example), so that
the text will be as large as possible horizontally, and centered
vertically? Is there a way to do this is App Engine, or is there some
external service besides App Engine that could make this easier for
me, that you could recommend (besides running ImageMagick on your own
server)?
I could use some help assigning to a global C variable in DLL using ctypes.
The following is an example of what I'm trying:
test.c contains the following
#include <stdio.h>
char name[60];
void test(void) {
printf("Name is %s\n", name);
}
On windows (cygwin) I build a DLL (Test.dll) as follows:
gcc -g -c -Wall test.c
gcc -Wall -mrtd -mno-cygwin -shared -W1,--add-stdcall-alias -o Test.dll test.o
When trying to modify the name variable and then calling the C test function using the ctypes interface I get the following...
>>> from ctypes import *
>>> dll = windll.Test
>>> dll
<WinDLL 'Test', handle ... at ...>
>>> f = c_char_p.in_dll(dll, 'name')
>>> f
c_char_p(None)
>>> f.value = 'foo'
>>> f
c_char_p('foo')
>>> dll.test()
Name is Name is 48+?
13
Why does the test function print garbage in this case?
I have a file called main.py and a file called classes.py
main.py contains the application and what's happening while class.py contains some classes.
main.py has the following code
main.py
import classes
def addItem(text):
print text
myClass = classes.ExampleClass()
And then we have classes.py
classes.py
class ExampleClass (object):
def __init__(self):
addItem('bob')
Surprisingly enough that's not the actual code I am using because I've stripped out anything that'd get in the way of you seeing what I want to do. I want to be able to call a method that's defined in main.py from a class within classes.py. How do I do this?
Thanks in advance
Which is preferred ("." indicating whitespace)?
A)
def foo():
x = 1
y = 2
....
if True:
bar()
B)
def foo():
x = 1
y = 2
if True:
bar()
My intuition would be B (that's also what vim does for me), but I see people using A) all the time. Is it just because most of the editors out there are broken?
>>> class Abcd:
... a = ''
... menu = ['a', 'b', 'c']
...
>>> a = Abcd()
>>> b = Abcd()
>>> a.a = 'a'
>>> b.a = 'b'
>>> a.a
'a'
>>> b.a
'b'
It's all correct and each object has own 'a', but...
>>> a.menu.pop()
'c'
>>> a.menu
['a', 'b']
>>> b.menu
['a', 'b']
How could this happen?
And how to use list as class attribute?
I cannot figure out what is wrong with the XPATH when trying to extract a value from a webpage table. The method seems correct as I can extract the page title and other attributes, but I cannot extract the third value, it always returns an empty list?
from lxml import html
import requests
test_url = 'SC312226'
page = ('https://www.opencompany.co.uk/company/'+test_url)
print 'Now searching URL: '+page
data = requests.get(page)
tree = html.fromstring(data.text)
print tree.xpath('//title/text()') # Get page title
print tree.xpath('//a/@href') # Get href attribute of all links
print tree.xpath('//*[@id="financial"]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[1]/div[2]/text()')
Unless i'm missing something, it would appear the XPATH is correct:
Chrome screenshot
I checked Chrome console, appears ok! So i'm at a loss
$x ('//*[@id="financial"]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[1]/div[2]/text()')
[
"£432,272"
]
I'm trying to run this script:
import re, os
def build_pool(cwd):
global xtn_pool, file_pool
xtn, xtn_pool = re.compile('\\.[0-9a-zA-Z]{1,4}$'), []
file_pool = [files for files in os.listdir(cwd) if os.path.isfile(files) and xtn.search(files)]
# Lists all the file extension in the folder
for file in file_pool:
if not xtn_pool.__contains__(xtn.search(file).group()):
xtn_pool.append(xtn.search(file).group())
return xtn_pool.sort(), file_pool
if __name__ == '__main__':
import sys
#if path is given, change working directory to path
if len(sys.argv) >= 2:
os.chdir(sys.argv[1])
build_pool(os.getcwd())
#if no path is given when running, do renaming in current folder
else:
build_pool(os.getcwd())
print('The folder contains the following extensions: ')
for i in range(0, len(xtn_pool)):
print(repr(i+1) + '. ' + xtn_pool[i][1:])
opt = int(input('Which one would you like to replace? '))
xtn_pick = xtn_pool[opt-1]
# Lists all the file with the chosen extension
xtn_file_pool = [file for file in file_pool if file.endswith(xtn_pick)]
print('There are {0} files with the {1} extension.'.format(len(xtn_file_pool), xtn_pick))
xtn_new = input('Input replacement extension: ')
# The actual renaming process
for file in xtn_file_pool:
os.rename(file, file[:-len(xtn_pick)+1] + xtn_new)
directly from my file browser (Nautilus), but for some reason it's not working. When I run it from terminal (python3 scriptname.py) it works fine as intended. But when I just click the script file in Nautilus, choose 'Run in Terminal', it always stops after asking 'Input replacement extension: '.
How can I make this script run without using the terminal?
I have this code:
a=[['a','b','c'],['a','f','c'],['a','c','d']]
for x in a:
for y in x:
if 'a' in x:
x.replace('a','*')`
but the result is:
a=[['a','b','c'],['a','f','c'],['a','c','d']]
and bot a=[['b','c'],['f','c'],['c','d']]
What should I do so the changes will last?
What I need is to hash a string. It doesn't really have to be secure because its just going to be a hidden pharse in the text file (simply it doesn't have to be recognizable for a human-eye).
It should not be just a random string because when user will be typing the string I would like to hash it and compare it with already hashed one (in the text file).
What would be the best for this purpose? Can it be done with the own class?
How would I check if the remote host is up without having a port number? Is there any other way I could check other then using regular ping.
There is a possibility that the remote host might drop ping packets
Hello all. I have a script running on a remote machine. db info is stored in a configuration file. I want to be able to encrypt the password in the conf text so that no one can just read the file and gain access to the database. This is my current set up:
My conf file sensitive info is encoded with base64 module. The main script then decodes the info. I have compiled the script using py2exe to make it a bit harder to see the code.
My question is:
Is there a better way of doing this? I know that base64 is not a very safe way of encrypting. Is there a way to encode using a key? I also know that py2exe can be reversed engineered very easily and the key could be found. Any other thoughts?
I am also running this script on a windows machine, so any modules that are suggested should be able to run in a windows environment with ease. I know there are several other posts on this topic but I have not found one with a windows solution, or at least one that is will explained.
I have a text file containing data in rows and columns (~17000 rows in total). Each column is a uniform number of characters long, with the 'unused' characters filled in by spaces. For example, the first column is 11 characters long, but the last four characters in that column are always spaces (so that it appears to be a nice column when viewed with a text editor). Sometimes it's more than four if the entry is less than 7 characters.
The columns are not otherwise separated by commas, tabs, or spaces. They are also not all the same number of characters (the first two are 11, the next two are 8 and the last one is 5 - but again, some are spaces).
What I want to do is import the entires (which are numbers) in the last two columns if the second column contains the string 'OW' somewhere in it. Any help would be greatly appreciated.
Hi, I have some text coming from the web as such:
£6.49
Obviously I would like this to be displayed as:
£6.49
I have tried the following so far:
s = url['title']
s = s.encode('utf8')
s = s.replace(u'Â','')
And a few variants on this (after finding it on this very same forum)
But still no luck as I keep getting:
UnicodeDecodeError: 'ascii' codec
can't decode byte 0xc3 in position
100: ordinal not in range(128)
Could anyone help me getting this right?
UPDATE:
Adding the reppr examples and content type
u'Star Trek XI £3.99'
u'Oscar Winners Best Pictures Box Set \xc2\xa36.49'
Content-Type: text/html; charset=utf-8
Thanks in advance