I noticed that this recipe seems to use __rlshift__, __ror__ like operators. But, they aren't in the documentation! Can anyone explain these and perhaps point to some docs?
for example at first you have to find hwnd of skype
hwnd = win32gui.FindWindow(None, 'skype')
and than all his child windows and their titles
child = ???
any idea?
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.
Hi all,
I need to make a variable with similar behaviour like in C lanquage.
I need byte or unsigned char with range 0-255.
This variable should overflow, that means...
myVar = 255
myVar += 1
print myVar #!!myVar = 0!!
I am writing an app to do a file conversion and part of that is replacing old account numbers with a new account numbers.
Right now I have a CSV file mapping the old and new account numbers with around 30K records. I read this in and store it as dict and when writing the new file grab the new account from the dict by key.
My question is what is the best way to do this if the CSV file increases to 100K+ records?
Would it be more efficient to convert the account mappings from a CSV to a sqlite database rather than storing them as a dict in memory?
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)?
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.
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?
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
I want to count how many members of an iterable meet a given condition. I'd like to do it in a way that is clear and simple and preferably reasonably optimal.
My current best ideas are:
sum(meets_condition(x) for x in my_list)
and
len([x for x in my_list if meets_condition(x)])
The first one being iterator based is presumably faster for big lists. And it's the same form as you'd use for testing any and all. However it depends on the fact that int(True) == 1, which is somewhat ugly.
The second one seems easier to read to me, but it is different from the any and all forms.
Does anyone have any better suggestions? is there a library function somewhere that I am missing?
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 two large lists that are filled with dictionaries. I need to combine the entries if a value from dict2==dict1 and place the newly combined matches somewhere else. I'm having trouble explaining it.
List one contains:
{'keyword':value, 'keyword2':value2}
List two:
{'keyword2':value2, 'keyword3':value3}
I want a new list with dictionaries including keyword1, keyword2, and keyword3 if both lists share the same 'keyword2' value. What's the best way to do this? When I try, I only come up with tons of nested for loops. Thanks
>>> 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?
If I want a list initialized to 5 zeroes, that's very nice and easy:
[0] * 5
However if I change my code to put a more complicated data structure, like a list of zeroes:
[[0]] * 5
will not work as intended, since it'll be 10 copies of the same list. I have to do:
[[0] for i in xrange(5)]
that feels bulky and uses a variable so sometimes I even do:
[[0] for _ in " "]
But then if i want a list of lists of zeros it gets uglier:
[[[0] for _ in " "] for _ in " "]
all this instead of what I want to do:
[[[0]]*5]*5
Has anyone found an elegant way to deal with this "problem"?
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.
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?
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!!
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
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?
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"
]
This is working fine, but I'm looking for any feedback on how to do it better. Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension. Any suggestions are welcome.
day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n in range(day_count)) if d <= end_date]:
print strftime("%Y-%m-%d", single_date.timetuple())
Notes:
I'm not actually using this to print; that's just for demo purposes.
The variables start_date and end_date are datetime.date objects, because I don't need the timestamps (they're going to be used to generate a report).
I checked the StackOverflow questions which were similar before posting this, but none were exactly the same.
Sample Output (for a start date of 2009-05-30 and an end date of 2009-06-09):
2009-05-30
2009-05-31
2009-06-01
2009-06-02
2009-06-03
2009-06-04
2009-06-05
2009-06-06
2009-06-07
2009-06-08
2009-06-09
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?
If I have a string
"this is a string"
How can I shorten it so that I only have one space between the words rather than multiple? (The number of white spaces is random)
"this is a string"