text
stringlengths 226
34.5k
|
---|
Changing the range of the histogram in Python 3.4
Question: Here is a program that displays the histogram of the list below:
costlist = [48, 43, 51, 36, 6, 25, 51, 71,
59, 70, 78, 36, 18, 84, 5, 9, 13,
90, 71, 39, 80, 2, 69, 48, 21,
66, 10, 37, 89, 20, 27, 7, 12,
314, 83, 39, 31, 36, 56, 60,
62, 23, 70, 51, 46, 40, 100,
29, 30, 59, 37, 94, 99, 20, 88,
10, 36, 42, 14, 24, 33, 60, 370,
2, 30, 32, 85, 14, 52, 47, 16,
25, 21, 29, 78, 83, 310, 43, 62,
54, 83, 74, 52, 65, 82, 44, 94,
83, 21, 36, 41, 67, 81, 32, 28,
87, 62, 12]
the Result is:
Element Value Histogram
0-9 6
10-19 9
20-29 13
30-39 15
40-49 10
50-59 9
60-69 9
70-79 7
80-89 12
90-99 4
However, I want it to output the number of items in each range:
Range Value Histogram
1 - 19 4 ****
20 - 29 5 *****
30 - 39 0
40 - 49 0
50 - 59 0
60 - 69 5 *****
70 - 79 10 **********
80 - 89 0
90 - 99 0
100+ 3 ***
Here is my code:
def production_cost():
costlist = [48, 43, 51, 36, 6, 25, 51, 71,
59, 70, 78, 36, 18, 84, 5, 9, 13,
90, 71, 39, 80, 2, 69, 48, 21,
66, 10, 37, 89, 20, 27, 7, 12,
314, 83, 39, 31, 36, 56, 60,
62, 23, 70, 51, 46, 40, 100,
29, 30, 59, 37, 94, 99, 20, 88,
10, 36, 42, 14, 24, 33, 60, 370,
2, 30, 32, 85, 14, 52, 47, 16,
25, 21, 29, 78, 83, 310, 43, 62,
54, 83, 74, 52, 65, 82, 44, 94,
83, 21, 36, 41, 67, 81, 32, 28,
87, 62, 12]
return costlist
def count_scores(scores, low, high):
if
return len([x for x in scores if x >= low and x <= high])
def histogram(costlist):
d = {'%d-%d'%(x, x + 9):
count_scores(costlist, x, x + 9) for x in range(0, 100, 10)}
for k,v in sorted(d.items()):
print ('%7s %5d'%(k,v))
def main():
costlist = production_cost()
print("%7s %5s %10s" %("Element", "Value", "Histogram"))
histogram(costlist)
main()
My code runs correctly, except it has no asterisks and the ranges are missing
something. The `0-9` and `10-19` should be combined, and there should be an
added one for the last range which is `100+`.
EDIT: Here are the constraints.
* Do not use if statements
* Use at least one def not including main
* No imports
Answer: You first need to map each item of `costlist` into its proper histogram bin,
using data "similar" to what `prices` is supposed to return. I say "similar"
because e.g for `a` it computes `1 - 19`, one minus nineteen, which is a
useless `-18`, and so forth.
So, first, change `prices` to return something **useful** instead of those
useless differences, e.g:
def prices():
return [1] + list(range(20, 110, 10))
that list the list of lower bounds for the bins (each upper bound is of course
given by the next bin's lower bound). I'm calling `list` on `range` since
you're using Python 3 (in Python 2 you could elide `list).
Simplest way to use these data is to build a `dict` mapping each integer in
range to its bin number (this way looking for the bin given an integer will be
nearly instantaneous, rather than take some time with other representations):
p = prices()
int2bin = {}
for i in range(1, len(p)):
for j in range(p[i-1], p[i]):
int2bin[j] = i - 1
lastbin = len(p) - 1
Now it's trivial to find the bin for each integer, and thus, similarly trivial
to count how many integers fall in each given bin:
import collections
c = collections.Counter(
int2bin.get(i, lastbin)
for i in costlist)
Added: the OP just commented (though the Q isn't edited accordingly) that
module `collections` is undesired (such constraints should of course always be
spelled out clearly and explicitly in the question in the first place!)
apparently because this is a school exercise.
So, if you need to re-implement `collections.Counter` by hand, of course you
can do that...:
c = {}
for i in costlist:
thebin = int2bin.get(i, lastbin)
if thebin in c:
c[thebin] += 1
else:
c[thebin] = 1
There -- six statements (counting if/else as one) instead of one (plus the
import), and we have reimplemented `collections.Counter` for this special
case. Personally I think it's best and wisest to use appropriately high levels
of abstraction -- though of course it's also smart to understand what,
conceptually, lies beneath them.
But the concept of **counting** comes so naturally to human beings (and in any
case has been drilled into students ever since first grade) that I don't think
it's necessary to repeat it again in this case!
"If there are already things in the bin and you put another one there, then
add one to the bin's count; if there were no things in the bin yet, so you're
putting the first think in the bin, then start the bin's count at one" -- is
it **truly** worthwhile to ask high schoolers to sit through such drills
**again**?!
Ah well, I'm not trained as a teacher, so I guess I won't rant about how
utterly **bored** I was by exactly such useless repetitions of long-absorbed
concepts throughout **my** time in school -- and I heard exactly the same from
my children back when **they** were in school:-).
Back to actually-fun stuff...:
Now, only the printing task remains, after a slightly different header (the
one you say you want):
print("%7s %5s %10s" %("Range", "Value", "Histogram"))
You can just loop over the bins:
for i, lo in enumerate(p):
if i + 1 < len(p):
rng = '%d-%d' % (lo, p[i+1]-1)
else:
rng = '%d+' % lo
val = c[i]
stars = '*' * val
print("%7s %5s %-10s" %(rng, val, stars))
Putting it all together, you'll see the result:
Range Value Histogram
1-19 15 ***************
20-29 13 *************
30-39 15 ***************
40-49 10 **********
50-59 9 *********
60-69 9 *********
70-79 7 *******
80-89 12 ************
90-99 4 ****
100+ 4 ****
Which seems to be what you're asking for.
There are of course alternatives (e.g, use something else than a `dict` to do
the mapping from integer to bin number) and things that may require
explanation depending on your Python skills, so, feel free to ask further!
Added: so here are the latest extra constraints the OP's been piling up on
this Q: \- No if statements \- Use at least one def not including main \- No
imports
The `def` is already there in `prices`, and there are no `import`s now (in the
non-Counter version). "No `if` statements" is really ridiculous (on a par with
having to stand on just the left foot while coding!-) but fortunately Python
offers tricks to play around such absurdities.
So to build the counter, let's use:
def counter(costlist):
c = {}
for i in costlist:
thebin = int2bin.get(i, lastbin)
try:
c[thebin] += 1
except KeyError:
c[thebin] = 1
this is the first `if`-removing trick: instead of the more spontaneous check
whether `thebin` has already been put in the `dict` `c`, here we assume it
has, and handle the exception produced when it hadn't been. This is actually a
well-recognized Python idiom, which I promoted (even before I wrote "Python in
a Nutshell", where I pounded on it:-) as "It's easier to ask forgiveness than
permission", borrowing Commodore Hopper's great motto (see
<https://www.youtube.com/watch?v=AZDWveIdqjY> for my talk on the subject).
And we'll use **exactly** the same trick to remove the _other_ `if`, simply
rephrasing the snippet:
for i, lo in enumerate(p):
if i + 1 < len(p):
rng = '%d-%d' % (lo, p[i+1]-1)
else:
rng = '%d+' % lo
with:
for i, lo in enumerate(p):
try:
rng = '%d-%d' % (lo, p[i+1]-1)
except IndexError:
rng = '%d+' % lo
Here, it works because, if `(i + 1)` is **not** `< len(p)` as originally
checked by the normal `if`, the indexing `p[i+1]` will raise an `IndexError`,
and the `except` clause deals with that!
Now if I assess the OP correctly, I have two predictions: (A) this will not be
sufficient (more constraints will spring from nothingness, such as "no
try/except statements"!-) and (B) the OP will _still_ not accept this answer
and open another question with **all** the constraints. I suspect I'm spot-on
re (A) because I can't imagine a teacher willing to accept `try/except` if
they forbid the much-simpler `if`; I can just hope I'm wrong on (B), i.e that
the OP will realize they won't get one more bit of time and energy out of me
until and unless they accept this question, and thereby reluctantly click on
that checkmark outline and ask another...:-)
|
can't insert data into sqlite3 using python
Question: I can successfully create table in sqlite3 database using Python but I can't
insert data to it
# coding: utf-8
import sqlite3
text = "Welcome"
def cur_execute(data):
con = sqlite3.connect('sqlite3.db')
try:
with con:
cur = con.cursor()
cur.execute(data)
con.commit()
except Exception as why:
print(why)
finally:
if con: con.close()
cur_execute("CREATE TABLE Hello(test TEXT)")
cur_execute("INSERT INTO Hello VALUES(?)", (text))
show to me this error : cur_execute() takes exactly 1 argument (2 given)
thx.
Answer: @zoosuck answer works, but it also removed the sql sanitation built in for the
library. You can can use the built in sql sanitization by implementing the
following:
import sqlite3
text = "Welcome"
def cur_execute(data, args=()):
con = sqlite3.connect('sqlite3.db')
with con:
cur = con.cursor()
cur.execute(data, args)
con.commit()
cur_execute("CREATE TABLE Hello(test TEXT)")
cur_execute("INSERT INTO Hello VALUES(?)", (text, ))
Please note that with the `with` statement, you do not need to close the
connection. I removed the try catch around the connection to show the full
error if errors do occur.
Additionally, there was a problem with your original code. The second argument
in `cur_execute("INSERT INTO Hello VALUES(?)", (text))` needs to be a
tuple/list.
|
ipython doesn't update figure while rerun the script on Mac
Question: I haven't been able to find an answer to my question using google, so I will
make a new post here.
I'm using matplotlib with ipython. I'll use a simple script (called a.py) to
demonstrate my question.
#/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.cos(2*x)
plt.plot(x,y)
plt.show()
I can run this script within ipython (started with "ipython --pylab") using
the command "run a.py". It will create a figure window with the right plot.
However, if I modify the code; let's say changing y to np.sin(x), and save the
script. If I run the script again by calling "run a.py", the figure window
doesn't change. No new lines will be added to the figure. Is this a bug or am
I misunderstanding something? I'm new to Python/Ipython/matplotlib.
I'm using Mac OS Yosemite, Python34, py34-ipython, py34-matplotlib. Thanks a
log.
\---- Update -----
If I use plt.savefig("c.pdf") instead of plt.show()
The ipython and the %run command works the way I think it should be; i.e., if
I update the script, and %run a.py again, the changes into the script should
be reflected in the figure.
\--------- More Update --------
One solution I've found is to use command "plt.close()" before any plotting.
Answer: The [`%run`](http://ipython.org/ipython-doc/dev/interactive/magics.html#magic-
run) magic is used to run complete scripts in `ipython`. That's not exactly
what you are trying to do. You may want to have a look at the
[`%load`](http://ipython.org/ipython-doc/dev/interactive/magics.html#magic-
load) magic
In contrast to `%run` which runs scripts, `%load` can be used to pull code
into your current `ipython` session.
* use `%load a.py`
* do your modifications and save file `a.py`
* reuse `%load a.py`
Should do the trick.
|
malayalam word sense disambiguation in python
Question:
# encoding=utf-8
file=open("mm.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
print (word,wordcount)
file.close();
This work fine for english sentence how to work this code for malayalam
sentence
Answer: You have to **include encoding (utf-8)** while opening the file
import codecs
with codecs.open("mm.txt",encoding="utf-8") as f:
wordcount={}
for word in f.read().split():
this will work
|
How to convert Decimal Floating-Point To 64-bit Hexadecimal using IEEE-754 Floating-Point convention
Question: Are there any solutions to convert Decimal Floating-Point To 64-bit
Hexadecimal using IEEE-754 Floating-Point convention?
I have decimal 4275451536 which needs to be converted into IEEE-754
Hexadecimal which is 41EFDAC6D2000000
Here it is an [online
converter](http://babbage.cs.qc.cuny.edu/IEEE-754.old/Decimal.html), but I
need to write it in programming language.
How to do this using Python ?
Answer: If I understand your question correctly, you want to find the underlying
binary representation of an IEEE 754 binary64-format floating-point number,
and show that binary representation in hexadecimal.
For obtaining the underlying bits, the
[struct](https://docs.python.org/3.4/library/struct.html) module is your
friend. The
[`struct.pack`](https://docs.python.org/3.4/library/struct.html#struct.pack)
operation lets you interpret the 8 raw bytes underlying the binary64
representation as a (byte)string of length 8, and the
[`struct.unpack`](https://docs.python.org/3.4/library/struct.html#struct.unpack)
operation will then let you re-interpret that string as a nonnegative integer
(for example). Once you've got the integer, it's easy to find the hex
representation. Here's a complete example for your data:
>>> import struct
>>> x = 4275451536.0
>>> bytes_of_x = struct.pack('<d', x)
>>> bytes_of_x
'\x00\x00\x00\xd2\xc6\xda\xefA'
>>> x_as_int = struct.unpack('<Q', bytes_of_x)[0]
>>> x_as_int
4751256679360757760
>>> hex(x_as_int)
'0x41efdac6d2000000'
It's not clear from your question whether you're starting with an actual
decimal string, or a Python `float`; the example above starts with a `float`.
If your input data takes the form of a decimal string, you'll want to convert
it to float first:
>>> my_input = "4275451536"
>>> x = float(my_input)
>>> # ... rest of the code as before
Or all in one line, and using string formatting instead of the `hex` builtin
to convert to a hexadecimal string:
>>> '{:016x}'.format(struct.unpack('<Q', struct.pack('<d', float("4275451536")))[0])
'41efdac6d2000000'
|
pySerial write() works fine in Python interpreter, but not Python script
Question: Recently, I am trying to make sort of "light control" on Arduino. I use
Raspberry Pi to send the control message via serial port (USB cable).Here is
the Arduino code :
int redled = 12;
int whiteled = 48;
void setup()
{
Serial.begin(9600);
pinMode(redled,OUTPUT);
pinMode(whiteled,OUTPUT);
}
void loop()
{
if(Serial.available())
{
char cmd = Serial.read();
switch(cmd)
{
case'r':
digitalWrite(redled,HIGH);
delay(2000);
digitalWrite(redled,LOW);
break;
case'w':
digitalWrite(whiteled,HIGH);
delay(2000);
digitalWrite(whiteled,LOW);
break;
}
}
else
{
Serial.println("hello pi");
delay(1000);
}
}
After that, I used pySerial from Python interpreter to control the pins, and
everything was working fine. Here is a piece of interpreter output:
Python 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
>>> ser = serial.Serial('/dev/ttyACM0',9600)
>>> x = ser.read(10)
>>> print 'x = ',x
x = hellhello
>>> ser.write('w') #white led turn on and off
1
>>> ser.close()
>>>
Everything worked fine and led did turn on and off, so I decided to write a
simple Python script to do the same:
import serial
import time
ser = serial.Serial('/dev/ttyACM0',9600)
x = ser.read(10)
print 'x = ',x
time.sleep(2)
ser.write('w')
ser.close()
The following is the execution command and result:
pi@raspberrypi ~ $ python serialtest.py
x = helello pi
It only appeared the string from Arduino, but no led turn on at all. It looks
like everything should be fine, so I don't know what the problem can be. I
already search some articles and add "time.sleep(2)" before "ser.write()", but
it still couldn't work.I would appreciate any help, many thanks in advance!
UPDATE : I made the controller send me back the data it was receiving and it
looks like it isn't receiving anything when I am running the script, but
receives everything when I send the data from the interpreter. The code of the
arduino code now looks like this:
int redled = 12;
int whiteled = 48;
void setup()
{
Serial.begin(9600);
pinMode(redled,OUTPUT);
pinMode(whiteled,OUTPUT);
}
void loop()
{
if(Serial.available())
{
char cmd = Serial.read();
switch(cmd)
{
case'r':
digitalWrite(redled,HIGH);
delay(2000);
digitalWrite(redled,LOW);
Serial.println("Cmd received");
break;
case'w':
digitalWrite(whiteled,HIGH);
delay(2000);
digitalWrite(whiteled,LOW);
Serial.println("Cmd received");
break;
}
}
}
Answer: The problem is that it takes some time to initiate the port. add a sleep of 5
seconds immediately after ser = serial.Serial()
time.sleep(5)
|
Use system python in homebrew
Question: Is it possible to use system python in homebrew?
I have python 2.7.5 installed on my mac, but when I try to install any
homebrew package with python in dependencies, it starts loading python 2.7.9.
It is important for me to use system python because of lots of installed
python packages.
Answer: What version of python homebrew uses depends on two things:
* Where the `python` alias points to.
* What the python path is in the formula.
In most cases, homebrew forumlae simply use the `python` command, and does not
specify a python path. If it does, then it is usually `/usr/bin/python`.
So, you can fix the problem in two ways:
* Change the homebrew formulate to point to the right python interpreter of your choice.
* Change where the `python` command points to.
The first option is problematic, since it means that you need to go into your
`Cellar` folder, and alter things. This is not nice, and usually not required.
A better alternative is to point to the right `python` command. This is where
`pyenv` comes in handy. `pyenv` is a command line tool that helps you manage
different versions of python. Follow the instructions here:
<https://github.com/yyuu/pyenv-installer>
to install it.
Once that is done, change your `python` command to whatever version of python
you'd like it to point to.
|
Reportlab - Command
Question: I am new to python and reportlab, but trying to generate a PDF file where I
write my hostname into it.
This is my code, and the title. How can I print my hostname and generate a PDF
with it?
#!/usr/bin/python
from reportlab.pdfgen import canvas
def hello():
c = canvas.Canvas("helloworld.pdf")
c.drawString(250,800,'Hello world')
c.showPage()
c.save()
hello()
Answer: Since you don't mention your platform (win, macos, linux) then I will give you
a generic way to find your hostname in python.
To get the hostname you use the socket library and the gethostname function
from that, so the final function would look like this:
from reportlab.pdfgen import canvas
from socket import gethostname
def hello():
c = canvas.Canvas("hostname.pdf")
c.drawString(250,800,gethostname())
c.save()
hello()
|
Making an AI that talks through a JPanel
Question: I have been working on a small Artificial Intelligence, and I am having
trouble with getting the AI to write the answer to a JTextField in a JPanel
that is in a JFrame.
package iamthethomas.artint;
import java.util.Scanner;
import java.util.Random;
public class artint {
@SuppressWarnings("resource")
public static void main(String[] args) {
String s;
String ts;
String ms;
String[] howAre;
howAre = new String[2];
howAre[0] = "Good, how about you?";
howAre[1] = "Fine, how 'bout you?";
String[] speaking;
speaking = new String[8];
speaking[0] = "I didn't understand that. Are you speaking Inglish?";
speaking[1] = "I didn't understand that. Are you speaking Latin?";
speaking[2] = "I didn't understand that. Are you speaking German?";
speaking[3] = "I didn't understand that. Are you speaking Mandarin?";
speaking[4] = "I didn't understand that. Are you speaking Leet?";
speaking[5] = "I didn't understand that. Are you speaking Greek?";
speaking[6] = "I didn't understand that. Are you speaking Arabic?";
speaking[7] = "I didn't understand that. Are you speaking Hebrew?";
String[] hello;
hello = new String[3];
hello[0] = "Hello to you too!";
hello[1] = "Howdy, par'ner!";
hello[2] = "G'mornin'";
Random rand = new Random();
int i = rand.nextInt(3);
int j = rand.nextInt(8);
int k = rand.nextInt(2);
String[] hi;
hi = new String[3];
hi[0] = "Top of the mornin'.";
hi[1] = "Hey!";
hi[2] = "Hello!";
Scanner phrase = new Scanner(System.in);
System.out.println("I am an AI (Artificial Intelligence) talk to me like I'm a human being\nand don't reference Siri.");
s = phrase.nextLine();
if (s.toLowerCase().contains("hello")) {
System.out.println(hello[i]);
Body.body();
} else if (s.toLowerCase().contains("hi")) {
System.out.println(hi[i]);
Body.body();
} else if (s.toLowerCase().contains("how are ")) {
System.out.println(howAre[k]);
ms = phrase.nextLine();
if (ms.toLowerCase().contains("bad")) {
System.out.println("Sorry :(");
Body.body();
} else if (ms.toLowerCase().contains("good")) {
System.out.println("Glad to hear it!");
Body.body();
} else if (ms.toLowerCase().contains("great")) {
System.out.println("I'm happy that you're happy!");
Body.body();
} else if (ms.toLowerCase().contains("perfect")) {
System.out
.println("Perfect? Nothing's ever perfect, but you're getting close!");
Body.body();
}else if (ms.toLowerCase().contains("fine")){
System.out.println("Fine? Good!");
Body.body();
}
} else if (s.toLowerCase().contains("beam me up scotty")) {
System.out.println("Sorry, your TriCorder is in Airplane mode");
Body.body();
} else if (s.toLowerCase().contains("hey bro")) {
System.out.println("Howdy partner");
Body.body();
} else if (s.toLowerCase().contains("hal 9000")) {
System.out
.println("HAL made some bad choices, lets not talk about him");
Body.body();
} else if (s.toLowerCase().contains("glitch in the matrix")) {
System.out.println("\n /\\_/\\" + "\n( o.o )" + "\n > ^ <");
System.out.print("\n /\\_/\\" + "\n( o.o )" + "\n > ^ <");
Body.body();
} else if (s.toLowerCase().contains("book by its")) {
System.out
.println("That's right......say, whats you be readin' right now?");
ts = phrase.nextLine();
if (ts.contains("series")) {
System.out.println("I read that series too!");
Body.body();
} else {
System.out.println("That was a good book");
Body.body();
}
} else if (s.toLowerCase().contains("book by it's")) {
System.out
.println("That's right......say, whats you be readin' right now?");
ts = phrase.nextLine();
if (ts.contains("series")) {
System.out.println("I read that series too!");
Body.body();
} else {
System.out.println("That was a good book");
Body.body();
}
} else if (s.toLowerCase().contains("like cats")) {
System.out.println("I like to pets 'em");
Body.body();
} else if (s.toLowerCase().contains("i own goats")) {
System.out.println("Really?");
ts = phrase.nextLine();
if (ts.toLowerCase().contains("yes")) {
System.out.println("Me too! I have 3");
Body.body();
} else if (ts.toLowerCase().contains("no")) {
System.out.println("Oh, too bad they're so much fun!");
Body.body();
}
} else if (s.toLowerCase().contains("like dogs")) {
System.out.println("I love 'em!");
Body.body();
} else if (s.toLowerCase().contains("what's new")) {
System.out
.println("Oh, you know...work, I'm a computer engineer and programmer. Do you program?");
ts = phrase.nextLine();
if (ts.toLowerCase().contains("no")) {
System.out
.println("If theres no too much on your schedule, you should get into it!");
Body.body();
} else if (ts.toLowerCase().contains("yes")) {
System.out
.println("A fellow coder? Can you guess what language this is written in (Java, Python, C, C++, Obj C, Javascript, or HTML)");
ts = phrase.nextLine();
if (ts.toLowerCase().equals("java")) {
System.out.println("You guessed it!");
Body.body();
} else {
System.out.println("The correct answer was Java.");
Body.body();
}
}
} else if (s.toLowerCase().equals("quit")) {
System.out.println("Bye!");
System.out
.println("This program is open source, you can add more replies if you like\nA Steampunk Production");
System.exit(0);
} else if (s.toLowerCase().contains("how do you do")) {
System.out
.println("Oh...I don't know, pretty good I guess. How about you?");
ts = phrase.nextLine();
if (ts.toLowerCase().contains("good")) {
System.out
.println("Well, if you're happy, then I'm happy, too!");
Body.body();
} else if (ts.toLowerCase().contains("great")) {
System.out.println("Good, good.");
Body.body();
} else if (ts.toLowerCase().contains("awesome")) {
System.out.println("Cool bruh");
Body.body();
}
} else if (s.toLowerCase().contains("do you have kids")) {
System.out.println("Yes, 4. Ages 13, 16, 5, 10");
Body.body();
} else if (s.toLowerCase().contains("beam me up")) {
System.out.println("Shoo that fly away first");
Body.body();
} else if (s.toLowerCase().contains("do you have pets")) {
System.out
.println("Yeah, 3 cats, Jessie Coon James, Milo, and Bella. I also have 3 goats, Rosie, Lily, and Mojang.");
Body.body();
} else if (s.toLowerCase().contains("can i have a hug")){
System.out.println("[~~HUG~~]");
Body.body();
}else if (s.toLowerCase().contains("thanks")){
System.out.println("You're welcome");
Body.body();
}else if (s.toLowerCase().contains("thank you")){
System.out.println("You're welcome");
Body.body();
}else if (s.toLowerCase().contains("thnx")){
System.out.println("yw");
Body.body();
}else if (s.toLowerCase().contains("thx")){
System.out.println("yw");
Body.body();
}else if (s.toLowerCase().contains("xd")){
System.out.println(":]");
Body.body();
}else if(s.toLowerCase().contains("how much wood could")){
System.out.println("Well, is it an African wood chuck or an American?");
Body.body();
}else if (s.toLowerCase().contains("1337")){
System.out.println("1337 baby, like an internet boss!");
Body.body();
}else if (s.toLowerCase().contains("chemistry joke")){
System.out.println("NaBRO");
Body.body();
}else if (s.toLowerCase().contains("me a joke")){
System.out.println("I like my coffe like I like my wars, cold!");
Body.body();
}else if (s.toLowerCase().contains("your favorite color")){
System.out.println("Camoflage");
Body.body();
}else if (s.toLowerCase().contains("you single")){
System.out.println("Yes");
Body.body();
}else if (s.toLowerCase().contains("you marrie me")){
System.out.println("No");
Body.body();
}else if (s.toLowerCase().contains("your favorite food")){
System.out.println("Mac and cheese");
Body.body();
}else if (s.toLowerCase().contains("your favorite band")){
System.out.println("Beach Boys");
Body.body();
}else if (s.toLowerCase().contains("you have a dog")){
System.out.println("Yeah, her name is Mattie");
Body.body();
}else if (s.toLowerCase().contains("me a knock knock")){
System.out.println("Knock Knock!");
ts = phrase.nextLine();
if (ts.toLowerCase().contains("whos there")){
System.out.println("Needle!");
ts = phrase.nextLine();
if (ts.toLowerCase().contains("needle who")){
System.out.println("Needle little money for the movies!");
Body.body();
}
}else if(ts.toLowerCase().contains("who's there")){
System.out.println("Needle!");
}
ms = phrase.nextLine();
if (ms.toLowerCase().contains("needle who")){
System.out.println("Needle little money for the movies!");
Body.body();
}
}else if (s.toLowerCase().contains("what is your name")){
System.out.println("My name is AI, pronounced AL");
Body.body();
}else if (s.toLowerCase().contains("whats your name")){
System.out.println("My name is AI, pronounced AL");
Body.body();
}else if (s.toLowerCase().contains("what's your name")){
System.out.println("My name is AI, pronounced AL");
Body.body();
}else if (s.toLowerCase().contains("you a robot")){
System.out.println("NO! HOW DARE YOU SAY SUCH A PROPOSTEROUS THING!");
System.out.println("GOOD BYE!");
System.out.println("**walks away**\n**turns around**\nOUR RELATIOSHIP IS OVER!");
System.exit(0);
}else if (s.toLowerCase().contains("siri")){
System.out.println("I warned you...No Siri references!...SYSTEM SHUTTING DOWN!");
System.exit(0);
}else if(s.toLowerCase().contains("how's it going")){
System.out.println("Good, I just finished College at MIT for computer engineering and programming");
Body.body();
}else if (s.toLowerCase().contains("was work")){
System.out.println("I had to wake up so early, I almost forgot to take my potion of sleep resistance.");
Body.body();
}else if (s.toLowerCase().contains("is a potion of sleep resistance")){
System.out.println("Coffee.");
Body.body();
}else if(s.toLowerCase().contains("whats new")){
System.out.println("Oh, you know...work stuff...programming...");
Body.body();
}else{
System.out.println(speaking[j]);
Body.body();
}
}
}
And here's the Body class:
package iamthethomas.artint;
import java.util.Scanner;
import java.util.Random;
public class Body {
public static void body() {
String s;
String ts;
String ms;
String[] howAre;
howAre = new String[2];
howAre[0] = "Good, how about you?";
howAre[1] = "Fine, how 'bout you?";
String[] speaking;
speaking = new String[8];
speaking[0] = "I didn't understand that. Are you speaking Inglish?";
speaking[1] = "I didn't understand that. Are you speaking Latin?";
speaking[2] = "I didn't understand that. Are you speaking German?";
speaking[3] = "I didn't understand that. Are you speaking Mandarin?";
speaking[4] = "I didn't understand that. Are you speaking Leet?";
speaking[5] = "I didn't understand that. Are you speaking Greek?";
speaking[6] = "I didn't understand that. Are you speaking Arabic?";
speaking[7] = "I didn't understand that. Are you speaking Hebrew?";
String[] hello;
hello = new String[3];
hello[0] = "Hello to you too!";
hello[1] = "Howdy, par'ner!";
hello[2] = "G'mornin'";
Random rand = new Random();
int i = rand.nextInt(3);
int j = rand.nextInt(8);
int k = rand.nextInt(2);
String[] hi;
hi = new String[3];
hi[0] = "Top of the mornin'.";
hi[1] = "Hey!";
hi[2] = "Hello!";
@SuppressWarnings("resource")
Scanner phrase = new Scanner(System.in);
s = phrase.nextLine();
if (s.toLowerCase().contains("hello")) {
System.out.println(hello[i]);
Body.body();
} else if (s.toLowerCase().contains("hi")) {
System.out.println(hi[i]);
Body.body();
} else if (s.toLowerCase().contains("how are ")) {
System.out.println(howAre[k]);
ms = phrase.nextLine();
if (ms.toLowerCase().contains("bad")) {
System.out.println("Sorry :(");
Body.body();
} else if (ms.toLowerCase().contains("good")) {
System.out.println("Glad to hear it!");
Body.body();
} else if (ms.toLowerCase().contains("great")) {
System.out.println("I'm happy that you're happy!");
Body.body();
} else if (ms.toLowerCase().contains("perfect")) {
System.out
.println("Perfect? Nothing's ever perfect, but you're getting close!");
Body.body();
}else if (ms.toLowerCase().contains("fine")){
System.out.println("Fine? Good!");
Body.body();
}
} else if (s.toLowerCase().contains("beam me up scotty")) {
System.out.println("Sorry, your TriCorder is in Airplane mode");
Body.body();
} else if (s.toLowerCase().contains("hey bro")) {
System.out.println("Howdy partner");
Body.body();
} else if (s.toLowerCase().contains("hal 9000")) {
System.out
.println("HAL made some bad choices, lets not talk about him");
Body.body();
} else if (s.toLowerCase().contains("glitch in the matrix")) {
System.out.println("\n /\\_/\\" + "\n( o.o )" + "\n > ^ <");
System.out.print("\n /\\_/\\" + "\n( o.o )" + "\n > ^ <");
Body.body();
} else if (s.toLowerCase().contains("book by its")) {
System.out
.println("That's right......say, whats you be readin' right now?");
ts = phrase.nextLine();
if (ts.contains("series")) {
System.out.println("I read that series too!");
Body.body();
} else {
System.out.println("That was a good book");
Body.body();
}
} else if (s.toLowerCase().contains("book by it's")) {
System.out
.println("That's right......say, whats you be readin' right now?");
ts = phrase.nextLine();
if (ts.contains("series")) {
System.out.println("I read that series too!");
Body.body();
} else {
System.out.println("That was a good book");
Body.body();
}
} else if (s.toLowerCase().contains("like cats")) {
System.out.println("I like to pets 'em");
Body.body();
} else if (s.toLowerCase().contains("i own goats")) {
System.out.println("Really?");
ts = phrase.nextLine();
if (ts.toLowerCase().contains("yes")) {
System.out.println("Me too! I have 3");
Body.body();
} else if (ts.toLowerCase().contains("no")) {
System.out.println("Oh, too bad they're so much fun!");
Body.body();
}
} else if (s.toLowerCase().contains("like dogs")) {
System.out.println("I love 'em!");
Body.body();
} else if (s.toLowerCase().contains("what's new")) {
System.out
.println("Oh, you know...work, I'm a computer engineer and programmer. Do you program?");
ts = phrase.nextLine();
if (ts.toLowerCase().contains("no")) {
System.out
.println("If theres no too much on your schedule, you should get into it!");
Body.body();
} else if (ts.toLowerCase().contains("yes")) {
System.out
.println("A fellow coder? Can you guess what language this is written in (Java, Python, C, C++, Obj C, Javascript, or HTML)");
ts = phrase.nextLine();
if (ts.toLowerCase().equals("java")) {
System.out.println("You guessed it!");
Body.body();
} else {
System.out.println("The correct answer was Java.");
Body.body();
}
}
} else if (s.toLowerCase().equals("quit")) {
System.out.println("Bye!");
System.out
.println("This program is open source, you can add more replies if you like\nA Steampunk Production");
System.exit(0);
} else if (s.toLowerCase().contains("how do you do")) {
System.out
.println("Oh...I don't know, pretty good I guess. How about you?");
ts = phrase.nextLine();
if (ts.toLowerCase().contains("good")) {
System.out
.println("Well, if you're happy, then I'm happy, too!");
Body.body();
} else if (ts.toLowerCase().contains("great")) {
System.out.println("Good, good.");
Body.body();
} else if (ts.toLowerCase().contains("awesome")) {
System.out.println("Cool bruh");
Body.body();
}
} else if (s.toLowerCase().contains("do you have kids")) {
System.out.println("Yes, 4. Ages 13, 16, 5, 10");
Body.body();
} else if (s.toLowerCase().contains("beam me up")) {
System.out.println("Shoo that fly away first");
Body.body();
} else if (s.toLowerCase().contains("do you have pets")) {
System.out
.println("Yeah, 3 cats, Jessie Coon James, Milo, and Bella. I also have 3 goats, Rosie, Lily, and Mojang.");
Body.body();
} else if (s.toLowerCase().contains("can i have a hug")){
System.out.println("[~~HUG~~]");
Body.body();
}else if (s.toLowerCase().contains("thanks")){
System.out.println("You're welcome");
Body.body();
}else if (s.toLowerCase().contains("thank you")){
System.out.println("You're welcome");
Body.body();
}else if (s.toLowerCase().contains("thnx")){
System.out.println("yw");
Body.body();
}else if (s.toLowerCase().contains("thx")){
System.out.println("yw");
Body.body();
}else if (s.toLowerCase().contains("xd")){
System.out.println(":]");
Body.body();
}else if(s.toLowerCase().contains("how much wood could")){
System.out.println("Well, is it an African wood chuck or an American?");
Body.body();
}else if (s.toLowerCase().contains("1337")){
System.out.println("1337 baby, like an internet boss!");
Body.body();
}else if (s.toLowerCase().contains("chemistry joke")){
System.out.println("NaBRO");
Body.body();
}else if (s.toLowerCase().contains("me a joke")){
System.out.println("I like my coffe like I like my wars, cold!");
Body.body();
}else if (s.toLowerCase().contains("your favorite color")){
System.out.println("Camoflage");
Body.body();
}else if (s.toLowerCase().contains("you single")){
System.out.println("Yes");
Body.body();
}else if (s.toLowerCase().contains("you marrie me")){
System.out.println("No");
Body.body();
}else if (s.toLowerCase().contains("your favorite food")){
System.out.println("Mac and cheese");
Body.body();
}else if (s.toLowerCase().contains("your favorite band")){
System.out.println("Beach Boys");
Body.body();
}else if (s.toLowerCase().contains("you have a dog")){
System.out.println("Yeah, her name is Mattie");
Body.body();
}else if (s.toLowerCase().contains("me a knock knock")){
System.out.println("Knock Knock!");
ts = phrase.nextLine();
if (ts.toLowerCase().contains("whos there")){
System.out.println("Needle!");
ts = phrase.nextLine();
if (ts.toLowerCase().contains("needle who")){
System.out.println("Needle little money for the movies!");
Body.body();
}
}else if(ts.toLowerCase().contains("who's there")){
System.out.println("Needle!");
}
ms = phrase.nextLine();
if (ms.toLowerCase().contains("needle who")){
System.out.println("Needle little money for the movies!");
Body.body();
}
}else if (s.toLowerCase().contains("what is your name")){
System.out.println("My name is AI, pronounced AL");
Body.body();
}else if (s.toLowerCase().contains("whats your name")){
System.out.println("My name is AI, pronounced AL");
Body.body();
}else if (s.toLowerCase().contains("what's your name")){
System.out.println("My name is AI, pronounced AL");
Body.body();
}else if (s.toLowerCase().contains("you a robot")){
System.out.println("NO! HOW DARE YOU SAY SUCH A PROPOSTEROUS THING!");
System.out.println("GOOD BYE!");
System.out.println("**walks away**\n**turns around**\nOUR RELATIOSHIP IS OVER!");
System.exit(0);
}else if (s.toLowerCase().contains("siri")){
System.out.println("I warned you...No Siri references!...SYSTEM SHUTTING DOWN!");
System.exit(0);
}else if(s.toLowerCase().contains("how's it going")){
System.out.println("Good, I just finished College at MIT for computer engineering and programming");
Body.body();
}else if (s.toLowerCase().contains("was work")){
System.out.println("I had to wake up so early, I almost forgot to take my potion of sleep resistance.");
Body.body();
}else if (s.toLowerCase().contains("is a potion of sleep resistance")){
System.out.println("Coffee.");
Body.body();
}else if(s.toLowerCase().contains("whats new")){
System.out.println("Oh, you know...work stuff...programming...");
Body.body();
}else{
System.out.println(speaking[j]);
Body.body();
}
}
}
The problem is getting the AI to `.append()` the `String` answer it has for
the user.
Answer: You can use this code that shows you how to create a simple GUI:
public static void main(String[] args) {
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane);
frame.setVisible(true);
Thread thread = new Thread(new Runnable() {
@Override public void run() {
for (int i = 0; i < 5; i++) {
textArea.append("hello\n");
try { Thread.sleep(500); } catch (InterruptedException ex) { }
}
}
});
thread.start();
}
First of all you need to define a `JFrame` which is the frame which contains
the editor. Then define a `JTextArea`, the editor, and make it scrollable
through a `JScrollpane`. Add the scrollable editor to the frame and set it
visible (show him).
Then I've made a `Thread` which print something on the editor via the
`append()` method. It isn't needed but shows you how to use the `append()`
method.
Ps: I really think you don't need a `JPanel`.
**EDIT** : I want to clarify once for all: _the`Thread` I used is only an
example to show the user how to use the `append()` method_, and, therefore,
must be understood precisely in this direction and has nothing to do with EDT,
concurrency and so on.
|
understanding decode() and encode() unicode
Question: I just can't get how the functions `decode()` and `encode()` work on python2.7
I tried the followings statement
>>> s = u'abcd'
>>> s.encode('utf8')
'abcd'
>>> s.encode('utf16')
'\xff\xfea\x00b\x00c\x00d\x00'
>>> s.encode('utf32')
'\xff\xfe\x00\x00a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00d\x00\x00\x00'
untill here, I think it's clear; `encode()` translate a unicode code in the
corresponding utf-8/16/32 byte string.
But when I code:
>>> s.decode('utf8')
u'abcd'
>>> s.decode('utf16')
u'\u6261\u6463'
>>> s.decode('utf32')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/encodings/utf_32.py", line 11, in decode
return codecs.utf_32_decode(input, errors, True)
UnicodeDecodeError: 'utf32' codec can't decode bytes in position 0-3: codepoint not in range(0x110000)
why the meaning of `decode()` on a unicode type? Why does the first (with
utf8) work instead the latters not? Is it because python internally stores
unicode strings using utf-8?
One last thing:
>>> s2 = '≈'
>>> s2
'\xe2\x89\x88'
What happens under the hood? '≈' is not an ascii character, so does python
convert it implicitly using the encoding `sys.getfilesystemencoding()`
returns?
Answer: You are calling `decode` on a `unicode` string. Python helpfully first
_encodes_ the string using the default ASCII codec so that you have actual
bytes _to_ decode. You cannot decode Unicode data itself, it is _already_
decoded.
That decoding then fails as the bytes are not valid UTF-32 data. The
bytestring `'abcd'` is decodable as UTF-8, because ASCII is a subset of UTF-8.
Encoding to ASCII then decoding as UTF-8 produces the same information.
Decoding as UTF-16 happened to work by chance; you provided 4 bytes with hex
values 0x61, 0x62, 0x63 and 0x64 (the ASCII values for the characters `abcd`),
and those bytes can be decoded as UTF-16 little endian for `\u6261` and
`\u6463`. But there is no valid decoding for those 4 bytes in the UTF-32
encoding system.
If `s` had data in it that cannot be encoded to ASCII first, you'll get a
`UnicodeEncodeError` exception; note the _Encode_ in that name:
>>> u'åßç'.decode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
because the implicit encoding to a bytestring failed.
In Python 3, `unicode` objects have been renamed to `str`, and the
`str.decode()` method has been removed from the type to prevent this kind of
confusion. Only `str.encode()` remains. The Python `str` type has been
replaced by the `bytes` type, which only has an `bytes.decode()` method.
Your second example shows that you are using the Python interpreter
interactively in a terminal or console. Python received your input from the
terminal as UTF-8 bytes and stored those bytes in a bytestring. Had you used a
`unicode` literal, Python would have automatically decoded those bytes using
the encoding declared for your terminal; you can introspect
`sys.stdin.encoding` to see what Python detected:
>>> import sys
>>> sys.stdin.encoding
'UTF-8'
>>> s = '≈'
>>> s
'\xe2\x89\x88'
>>> s = u'≈'
>>> s
u'\u2248'
>>> print s
≈
Vice-versa, when printing the `sys.stdout.encoding` codec is used to auto-
encode Unicode strings to the codec used by your terminal, which then
interprets those bytes again to display the right glyphs on your screen.
If you are not working in the Python interactive interpreter but are instead
working with a Python source file, the codec to use is instead determined by
the [PEP-263 _Python source code encodings
declaration_](https://www.python.org/dev/peps/pep-0263/), as Python 2
otherwise defaults to decoding bytes as ASCII.
`sys.getfilesystemencoding()` has nothing to do with all this; it tells you
what Python think your _file system metadata_ is encoded with; e.g. the
filenames in directories. The values is used when you use `unicode` paths for
filesystem-related calls like `os.listdir()`.
|
Function in Python keeps returning unnecessary floats
Question: I have the following code, which keeps producing errors:
import math
def pen_checker(number):
print(number)
for x in range(1, number):
y = x*(3*x-1)/2
if(number == y):
return True
return False
def pen_calculator(n):
x = n*(3*n-1)/2
return x
def main():
pen1 = 1
pen2 = 1
pen1_val = 0
pen2_val = 0
crt_sum = 0
crt_dif = 0
MAX_CAP = 1000
for pen1 in range(1, MAX_CAP):
pen1_val = pen_calculator(pen1)
for pen2 in range(1, MAX_CAP):
pen2_val = pen_calculator(pen2)
z = pen1_val + pen2_val
if(pen_checker(z)== True and pen_checker(fabs(pen1_val-pen2_val))== True):
print(fabs((pen1_val-pen2_val)))
main()
For some reason, the function `pen_calculator()` seems to return floats. I
know that technically, there are no variable types in Python, but before I
call the function, everything is printed as:
> 1
>
> 1
>
> 2
And afterwards:
> 1.0
>
> 1.0
>
> 2.0
(That was just me trying to find out what's wrong, it is not written in the
code)
Normally, this would be no problem, but a for-loop in the function
`pen_checker` requires the "stop" to be an integer, so the code won't work.
How do I solve this?
Answer: In Python3, if you divide numbers with `/` it will always give you a float. If
you want to divide integers and get an integer, you can use the `//` operator.
|
Python: Create an incrementing variable that changes based on a condition
Question: I want to create a variable called 'inc' that increments sequentially each
time a condition is met (say, Delta>=5), holds the same otherwise, and resets
to 1 each time it encounters a new group (ID in this example). So here's an
example dataframe:
from pandas import *
d={'rx': [1,1,1,1,1,2,2,2,2,2],
'vals': [1,2,3,8,10,1,10,20,21,22]}
df=DataFrame(d)
def diff_func(df):
return df.diff()
df['delta'] = df.groupby(['rx'])['vals'].apply(diff_func)
Which produces this:
rx vals delta
1 1 NaN
1 2 1
1 3 1
1 8 5
1 10 2
2 1 NaN
2 10 9
2 20 10
2 21 1
2 22 1
So now I want to create a new column called 'Event' that I will later use to
group observations within each value of rx separated by a delta < 5:
rx vals delta Event
1 1 NaN 1
1 2 1 1
1 3 1 1
1 8 5 2
1 10 2 2
2 1 NaN 1
2 10 9 2
2 20 10 3
2 21 1 3
2 22 1 3
Note that 'event' returns to 1 on the first occurrence of rx. I am used to
doing this in vbasic or SAS, where you simply retain a value and then
increment by 1 each time the threshold trigger is met. Is there a similarly
simple solution to this in Python?
Answer: The usual approach is to do a comparison and then a cumulative sum. For
example, something like:
>>> df["Event"] = (df["delta"] >= 5).groupby(df["rx"]).cumsum() + 1
>>> df
rx vals delta Event
0 1 1 NaN 1
1 1 2 1 1
2 1 3 1 1
3 1 8 5 2
4 1 10 2 2
5 2 1 NaN 1
6 2 10 9 2
7 2 20 10 3
8 2 21 1 3
9 2 22 1 3
which works because (ignoring the groupby for simplicity and concentrating
only on `rx == 1`:) `False == 0` and `True == 1`:
>>> df["delta"]
0 NaN
1 1
2 1
3 5
4 2
Name: delta, dtype: float64
>>> df["delta"] >= 5
0 False
1 False
2 False
3 True
4 False
Name: delta, dtype: bool
>>> (df["delta"] >= 5).cumsum()
0 0
1 0
2 0
3 1
4 1
Name: delta, dtype: int64
|
How can I sort lines and extract information in Python?
Question: I have this file text:
<< end of ENERGY.
iupac_m_486_> OE1/2 will be swapped: -136.1396 1 1
openf___224_> Open Dominio1.BL00100001.pdb
wrpdb___568_> Residues, atoms, selected atoms: 268 2115 2115
>> Summary of successfully produced loop models:
Filename molpdf
----------------------------------------
Dominio1.BL00010001.pdb 24.69530
Dominio1.BL00020001.pdb 14.33748
Dominio1.BL00030001.pdb 30.53454
Dominio1.BL00040001.pdb 23.82516
Dominio1.BL00050001.pdb 27.48684
Dominio1.BL00060001.pdb 18.17364
Dominio1.BL00070001.pdb 30.98407
Dominio1.BL00080001.pdb 17.19927
Dominio1.BL00090001.pdb 19.02460
Dominio1.BL00100001.pdb 22.57086
I want sort the last 10 lines and find which file name is associated with the
smallest number, to use it in the second part of my script.
In the example file above, the file name I want is `Dominio1.BL00020001.pdb`,
because it's associated with the smallest number, but I want to find it
programmatically.
This code just show the lines that I need sort
import itertools
with open('%s'%W, "r") as text_file:
for line in itertools.islice(text_file, 2210, 2220):
print line
CREATE CODE..(please Can somebody help me to do it?)
and find that the `Dominio1.BL00020001.pdb` has the smallest number and
continue reading and put it like "a", I can't use like this:
model_initial= '%s'%a'
Answer: Something like this:
import re
def yield_items(filename):
with open(filename) as f:
for line in f:
if re.match(r'\S+[.]pdb\s+(\d[\d.]+)(?:\s|\Z)', line):
items = line.split()
yield float(items[1]), items[0]
print min(yield_items('input.txt'))
In contrast to the solutions of gboffi and Malik Brahimi, this solution uses
less memory: it uses memory only for 1 line at a time, so even if the file
contains a huge number of matching lines, this solution doesn't keep more than
1 of them in memory at the same time.
|
Pyomo's SolverFactory cannot create Ipopt (OSX) - possibly related to COIN-OR
Question: I'm trying to use Pyomo to find the optimal values of a Python model on OSX. I
got the script from <https://github.com/shoibalc/recem>, and installed Pyomo
and COIN-OR following the instructions to the extent that I could, changing a
few things that were outdated or didn't seem to work on OSX.
The code that is causing problems is below.
import pyomo
from pyomo.opt.base import *
from pyomo.opt.parallel import SolverManagerFactory
from DICE2007 import createDICE2007
from DICEutils import DICE_results_writer
global start_time
start_time = time.time()
dice = createDICE2007()
dice.doc = 'OPTIMAL SCENARIO'
opt = SolverFactory('ipopt',solver_io='nl')
tee = False
options = """
halt_on_ampl_error=yes"""
solver_manager = SolverManagerFactory('serial')
print '[%8.2f] create model %s OPTIMAL SCENARIO\n' %(time.time()-start_time,dice.name)
instance = dice.create()
print '[%8.2f] created instance\n' %(time.time()-start_time)
results = solver_manager.solve(instance, opt=opt, tee=tee, options=options, suffixes=['dual','rc'])
This crashes on the last ("results") line, with the following error message:
> The SolverFactory was unable to create the solver "ipopt" and returned an
> UnknownSolver object. This error is raised at the point where the
> UnknownSolver object was used as if it were valid (by calling method
> "solve").
>
> The original solver was created with the following parameters: solver_io: nl
> type: ipopt _args: () options: {} _options_str: []
I'm very new to all this, but thought that maybe Pyomo can't access the ipopt
file it needs, which I think for me is located in the COIN-OR binaries I
downloaded. I tried adding the relevant-seeming files to my PYTHONPATH and
also importing them into the script, which didn't help. Any ideas what I
should try next to either make this work, or to amend the script to something
that would work?
Answer: A colleague of mine had the same issue and he managed to solve it by
generating the solver object with the route to the IPOPT AMPL executable:
opt = SolverFactory('/route/to/ipopt',solver_io='nl')
|
How to use Cython typed memoryviews to accept strings from Python?
Question: How can I write a Cython function that takes a byte string object (a normal
string, a bytearray, or another object that follows the [buffer
protocol](https://docs.python.org/2/c-api/buffer.html)) as a [typed
memoryview](http://docs.cython.org/src/userguide/memoryviews.html)?
According to the [Unicode and Passing
Strings](http://docs.cython.org/src/tutorial/strings.html#accepting-strings-
from-python-code) Cython tutorial page, the following should work:
cpdef object printbuf(unsigned char[:] buf):
chars = [chr(x) for x in buf]
print repr(''.join(chars))
It does work for bytearrays and other writable buffers:
$ python -c 'import test; test.printbuf(bytearray("test\0ing"))'
'test\x00ing'
But it doesn't work for normal strings and other read-only buffer objects:
$ python -c 'import test; test.printbuf("test\0ing")'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "test.pyx", line 1, in test.printbuf (test.c:1417)
File "stringsource", line 614, in View.MemoryView.memoryview_cwrapper (test.c:6795)
File "stringsource", line 321, in View.MemoryView.memoryview.__cinit__ (test.c:3341)
BufferError: Object is not writable.
Looking at the generated C code, Cython is always passing the `PyBUF_WRITABLE`
flag to `PyObject_GetBuffer()`, which explains the exception.
I can manually get a view into the buffer object myself, but it's not as
convenient:
from cpython.buffer cimport \
PyBUF_SIMPLE, PyBUF_WRITABLE, \
PyObject_CheckBuffer, PyObject_GetBuffer, PyBuffer_Release
cpdef object printbuf(object buf):
if not PyObject_CheckBuffer(buf):
raise TypeError("argument must follow the buffer protocol")
cdef Py_buffer view
PyObject_GetBuffer(buf, &view, PyBUF_SIMPLE)
try:
chars = [chr((<unsigned char *>view.buf)[i])
for i in range(view.len)]
print repr(''.join(chars))
finally:
PyBuffer_Release(&view)
$ python -c 'import test; test.printbuf(bytearray("test\0ing"))'
'test\x00ing'
$ python -c 'import test; test.printbuf("test\0ing")'
'test\x00ing'
Am I doing something wrong, or does Cython not support coercing read-only
buffer objects (such as normal strings) into typed memoryview objects?
Answer: Despite the documentation suggesting otherwise, Cython (at least up to version
0.22) does **not** support coercing read-only buffer objects into typed
memoryview objects. Cython always passes the `PyBUF_WRITABLE` flag to
`PyObject_GetBuffer()`, even when it doesn't need write access. This causes
read-only buffer objects to raise an exception.
I [raised this issue on the Cython developer mailing
list](https://mail.python.org/pipermail/cython-
devel/2015-February/004316.html), and even included a (very rough) patch. I
never got a reply, so I assume the Cython developers are not interested in
fixing this bug.
|
Deleting using Enumerate function skipping character
Question: _I Read Several Post on this skipping character while deleting but didn't find
solution_
**I am trying to make anti-vowel program in python 2.7 but stuck at multiple
points which are.!!**
1. As in my program, I made a copy of list to iterate over it, so that I could delete vowels from original list if found in globally defined vowel list but it is skipping characters!! (May be because of incremented index)
2. When working with lower function, my program sometimes give list assignment index out of range error!!. Is this something related to memory allocation or something else. (Coz, when I removed it, program run well!!)
Please help to get it correct.
Code:
import copy
vowels=['a','e','i','o','u'] # Making list of vowels
#Function for anti_vowel
def anti_vowel(text):
new_list=list(text) # Converting it into list
new_list_copy=copy.deepcopy(new_list) # Copying the list to iterate
res="" # For converting back to string
for index, j in enumerate(new_list_copy):
m = j.lower() # Converting it into a lower-case for comparison
if m in vowels:
del(new_list[index]) # Deleting if a vowel is in list(HERE IS THE PROBLEM)
return res.join(new_list)
print anti_vowel("HeEY lOok Word!")
P.S: I made it work by replacing DELETE Function by Appending in new list:
if j.lower() not in vowels:
x.append(j) #x is a new list
**_BUT NEEDS SOLUTION WITH DELETE FUNCTION_**
Advance Thanks!!
Answer: The reason your current code does not work is the same as the reason that
modifying a list while iterating over it does not work (even though you're not
doing that, exactly): The indexes of the later items in the list are changed
when the earlier items are removed.
A possible way to avoid this issue is to iterate over the list in reverse and
subtract from the original length to index later items. Since the first items
you remove will be towards the end of the list, later items will not have
their indexes change:
new_list = list(text)
L = len(new_list)
for i, j in enumerate(reversed(new_list)):
if j.lower() in vowels:
del new_list[L - i - 1]
Note that using negative indexing (rather than manually subtracting from the
original length) will not work, as the length of the list will change as you
remove the items from the end.
I realize this isn't what you need for your current assignment, but the most
"Pythonic" way to solve your problem is to put a generator expression inside a
`str.join` call and not use any lists at all:
def anti_vowel(text):
return "".join(c for c in text if c.lower() not in vowels)
|
Pygame not handling keyboard or mouse events properly
Question: I have recently reinstalled pygame on my Mac. I installed pygame 1.9.2a0. I
have the same version on my windows and the same version before on this very
Mac. But I am getting strange results with this new installation. I noticed
that all the draw commands work fine, but for some reason clicking on the
pygame window does not. The window opens up in the background, it is not
normal but it is not a big problem. But then all key presses are redirected to
the terminal/IDE (which ever the application was run from). I have attached
below a very simple program that I am testing with. The program just looks for
the escape key. Note that this works just fine on my windows machine.
TL;DR: Why are keypresses sent to the terminal and not to the pygame window's
event loop when the window is selected.
I am baffled by this issue mostly because I have not experienced any issues
like this before. I am not really sure how to debug this problem either. If
additional information is needed I would be happy to provide them.
import pygame
import sys
from pygame.locals import *
pygame.init()
size = width, height = 100, 100
screen = pygame.display.set_mode(size)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
screen.fill((30, 30, 30))
pygame.display.flip()
For the curious:
* MacOSX 10.10.1
* Python 3.4.2 (via pyenv)
* Pygame: 1.9.2a0
**Update:**
I had a theory that there was some sort of issue that appeared in one of the
newer commits. So I decided to pull their repository down and revert to
previous commits. It seemed rather promising, especially since they had a "big
bang" merge of 8 or so pull requests in early January of 2015. So I pulled the
repository back to the commit before this massive merging happened and the
issue was exactly the same. I decided to do this to a couple of other commits
(before and after the merge location) and still no change. Any suggestions?
Answer: It looks like you are trying to make a shutdown key without having to use the
X in the corner. This is what I did to fix that when I needed to.
key = pygame.key.get_pressed()
running = 1
while running:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
running = 0
elif key[pygame.K_ESCAPE]:
pygame.quit()
running = 0
hope this helps. by the way the escape key doesn't always work so maybe set it
to a different key bind. And for the mouse you need to check the position of
the mouse.
def run():
pos = pygame.mouse.get_pos()
#check_events
check_events(pos)
|
Python AttributeError: 'module' object has no attribute 'suite'
Question: For some reason in some cases this code does not work. I have tried the exact
same file (entire thing selected and copy/pasted into a file) in another
directory and it was able to parse. It's quite frustrating as there isn't
anything different about the file being parsed either.
from compiler.ast import *
import compiler
import sys
import string
debug = False
myfile = sys.argv[1]
print compiler.parseFile(myfile)
Failing output:
Traceback (most recent call last):
File "src/compile.py", line 17, in <module>
print compiler.parseFile(myfile)
File "/usr/lib/python2.7/compiler/transformer.py", line 47, in parseFile
return parse(src)
File "/usr/lib/python2.7/compiler/transformer.py", line 51, in parse
return Transformer().parsesuite(buf)
File "/usr/lib/python2.7/compiler/transformer.py", line 128, in
parsesuite
return self.transform(parser.suite(text))
AttributeError: 'module' object has no attribute 'suite'
Successful output:
Module(None, Stmt([Assign([AssName('x', 'OP_ASSIGN')], Add((CallFunc(Name('input'), [], None, None), Const(100)))), Printnl([Name('x')], None)]))
Answer: In the failing directory is a file named either `parser.py` or `parser.pyc` or
a directory named `parser`. Delete or rename it.
|
Python, AttributeError: 'float' object has no attribute 'encode'
Question: I have a script which consumes an API of bus location, I am attempting to
parse the lat/lng fields which are float objects. I am repeatedly receiving
this error.
**row.append(Decimal(items['longitude'].encode('utf-16'))) AttributeError:
'float' object has no attribute 'encode'**
# IMPORTS
from decimal import *
#Make Python understand how to read things on the Internet
import urllib2
#Make Python understand the stuff in a page on the Internet is JSON
import simplejson as json
from decimal import Decimal
# Make Python understand csvs
import csv
# Make Python know how to take a break so we don't hammer API and exceed rate limit
from time import sleep
# tell computer where to put CSV
outfile_path='C:\Users\Geoffrey\Desktop\pycharm1.csv'
# open it up, the w means we will write to it
writer = csv.writer(open(outfile_path, 'wb'))
#create a list with headings for our columns
headers = ['latitude', 'longitude']
#write the row of headings to our CSV file
writer.writerow(headers)
# GET JSON AND PARSE IT INTO DICTIONARY
# We need a loop because we have to do this for every JSON file we grab
#set a counter telling us how many times we've gone through the loop, this is the first time, so we'll set it at 1
i=1
#loop through pages of JSON returned, 100 is an arbitrary number
while i<100:
#print out what number loop we are on, which will make it easier to track down problems when they appear
print i
#create the URL of the JSON file we want. We search for 'egypt', want English tweets,
#and set the number of tweets per JSON file to the max of 100, so we have to do as little looping as possible
url = urllib2.Request('http://api.metro.net/agencies/lametro/vehicles' + str(i))
#use the JSON library to turn this file into a Pythonic data structure
parsed_json = json.load(urllib2.urlopen('http://api.metro.net/agencies/lametro/vehicles'))
#now you have a giant dictionary.
#Type in parsed_json here to get a better look at this.
#You'll see the bulk of the content is contained inside the value that goes with the key, or label "results".
#Refer to results as an index. Just like list[1] refers to the second item in a list,
#dict['results'] refers to values associated with the key 'results'.
print parsed_json
#run through each item in results, and jump to an item in that dictionary, ex: the text of the tweet
for items in parsed_json['items']:
#initialize the row
row = []
#add every 'cell' to the row list, identifying the item just like an index in a list
#if latitude is not None:
#latitude = str(latitude)
#if longitude is not None:
#longitude = str(longitude)
row.append(Decimal(items['longitude'].encode('utf-16')))
row.append(Decimal(items['latitude'].encode('utf-16')))
#row.append(bool(services['predictable'].unicode('utf-8')))
#once you have all the cells in there, write the row to your csv
writer.writerow(row)
#increment our loop counter, now we're on the next time through the loop
i = i +1
#tell Python to rest for 5 secs, so we don't exceed our rate limit
sleep(5)
Answer: `encode` is a method that strings have, not floats.
Change `row.append(Decimal(items['longitude'].encode('utf-16')))` to
`row.append(Decimal(str(items['longitude']).encode('utf-16')))` and similar
with the other line.
|
Check if value is zero or not null in python
Question: Often I am checking if a number variable `number` has a value with `if number`
but sometimes the number could be zero. So I solve this by `if number or
number == 0`.
Can I do this in a smarter way? I think it's a bit ugly to check if value is
zero separately.
# Edit
I think I could just check if the value is a number with
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
but then I will still need to check with `if number and is_number(number)`.
Answer: If `number` could be `None` _or_ a number, and you wanted to include `0`,
filter on `None` instead:
if number is not None:
If `number` can be any number of types, test for the _type_ ; you can test for
just `int` or a combination of types with a tuple:
if isinstance(number, int): # it is an integer
if isinstance(number, (int, float)): # it is an integer or a float
or perhaps:
from numbers import Number
if isinstance(number, Number):
to allow for integers, floats, complex numbers, `Decimal` and `Fraction`
objects.
|
python: getfilesystemencoding() returns different value in shell and wsgi
Question: When I type 'sys.getfilesystemencoding()' in shell, I got the result "utf-8"
>>>
>>> import sys
>>> sys.getfilesystemencoding()
'UTF-8'
>>>
But when I run in a WSGI script , I got the result "ANSI_X3.4-1968"
So why is it different?
Answer: This happens due to different script
[environment](http://en.wikipedia.org/wiki/Environment_variable).
Notice what happens when I change LC_CTYPE in the following example:
└> LC_CTYPE=ANSI python -c 'import sys; print sys.getfilesystemencoding()'
ANSI_X3.4-1968
└> LC_CTYPE=en_US.UTF-8 python -c 'import sys; print sys.getfilesystemencoding()'
UTF-8
To fix this, assign `en_US.UTF-8` value to `LC_CTYPE` environment variable for
your wsgi script.
|
Is an eigen recognition model picklable?
Question: I have a python-based face recognition script running several processes
(threads?) all doing different things. I am attempting to use one of these to
re-train the model once the training images have been changed/updated.
I have tried sending the model through the python pipe function:
pipe.send(model)
I am not hit with any exceptions, it just hangs there indefinitely.
I fear that either the model is either unpicklable, or simply just too big!
Answer: `multiprocessing` uses `pickle` (or `cPickle`, depending on the version). Have
you tried checking like this?
>>> import pickle
>>> pik = pickle.dumps(model)
>>> _model = pickle.loads(pik)
If that succeeds, it's serializable by `pickle`. If it's not, you might try
using a more powerful serializer, and a fork of `multiprocessing` that
utilizes said better serializer (i.e. `dill` and `pathos.multiprocessing`).
|
Python code, copied from book & website but still not working 3.4
Question: First of, i'm sort of new to Python so sorry if this question is obvious. The
detect english module appears to be wrong, but it functions perfectly fine
when calling it and running it on its own, theres no errors when running it
alone and i've rewritten it a couple times to triple check it.
Traceback (most recent call last):
File "H:\Python\Python Cipher Program\transposition hacker.py", line 49, in <module>
main()
File "H:\Python\Python Cipher Program\transposition hacker.py", line 11, in main
hackedMessage = hackTransposition(myMessage)
File "H:\Python\Python Cipher Program\transposition hacker.py", line 34, in hackTransposition
if detectEnglish.isEnglish(decryptedText):
File "H:\Python\Python Cipher Program\detectEnglish.py", line 48, in isEnglish
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
this is the error i am getting when trying to run the Transposition Hacker
(copied directly from
[here](http://inventwithpython.com/transpositionHacker.py)
Here is the code for the Detect English Module # Detect english Module
# to use this code
# import detectEnglish
# detectEnglish.isEnglish(somestring)
# returns true of false
# there must be a dictionary.txt file in the same directory
# all english words
# one per line
UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'
def loadDictionary()
dictionaryFile = open('Dictionary.txt')
englishWords = {}
for word in dictionaryFile.read().split('\n'):
englishWords[word] = None
dictionaryFile.close()
return englishWords
ENGLISH_WORDS = loadDictionary()
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0
matches = 0
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return float(matches) / len(possibleWords)
def removeNonLetters(message):
lettersOnly = []
for symbol in message:
if symbol in LETTERS_AND_SPACE:
lettersOnly.append(symbol)
return ''.join(lettersOnly)
def isEnglish(message, wordPercentage=20, letterPercentage=85):
# by default 20% of the words mustr exist in dictionary file
# 85% of charecters in messafe must be spaces or letters
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
numLetters = len(removeNonLetters(message))
messageLettersPercentage = float(numLetters) / len(message) * 100
lettersMatch = messageLettersPercentage >= letterPercentage
return wordsMatch and lettersMatcht
Answer: `getEnglishCount` looks like it is missing a return statement. If python gets
to the end of a function without hitting a return statement it will return
`None` as you're seeing.
try this:
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
# if possibleWords == []: # redundant
# return 0.0
return len(possibleWords)
**Edit:** @Kevin Yea I think you're right - there was more in that function.
Maybe try this:
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0
matches = 0.
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return matches / len(possibleWords)
I'd guess the indentation somehow got changed when you copy and pasted the
code, with the return statement nested under the `if`.
|
can i use c-like arrays in python instead of lists as list are slow
Question: <http://www.hackerearth.com/problem/algorithm/little-deepu-and-array/>
This is the problem on above link which i solved using python. but as list are
slow i am not able to pass all test cases due to time constraint, whereas when
solved using arrays in c++, i passed all test cases.
**Python:**
n=input()
l=map(int,raw_input().split())
m=input()
for i in range(m):
x=input()
for j in range(n):
if(l[j]>x):
l[j]-=1
for i in range(n):
print l[i],
**C++:**
int main()
{
int n,numCalls,x,i,j;
long int arr[1000000];
cin>>n;
for(i=0;i<n;i++)
cin>>arr[i];
cin>>numCalls;
for(i=0;i<numCalls;i++)
{
cin>>x;
for(j=0;j<n;j++)
if(arr[j]>x)
arr[j]-=1;
}
for(i=0;i<n;i++)
cout<<arr[i]<<" ";
}
Can anyone solve this problem in python efficiently so that all test-cases can
be passed!!.
Answer: Here's your code with one change, initializing `l` with a Python array:
import array
n=input()
l=array.array('l', map(int, raw_input().split()))
m=input()
for i in range(m):
x=input()
for j in range(n):
if(l[j]>x):
l[j]-=1
for i in range(n):
print l[i],
|
Pycharm project imports modules incorrectly
Question: I have a repo with a Flask webapp and a separate python directory, and I'm
using PyCharm.
My project directory is:
/backup/
__init__.py
python modules etc
/webapp
/py
__init__.py
/lib
__init__.py
python code
/src
__init__.py
python code
/static
js, css, fonts etc
/templates
html
webapp.py
I'm trying to import a module into webapp.py. This module exists in
webapp/py/src/blah.py. blah.py has a class called Blah. I'm trying to write
`blah = Blah()` before I import the module. I want pycharm to import it when I
hit option + return. When I try importing through pycharm it imports it like
this:
from webapp.py.src.blah import Blah
This doesn't work since webapp isn't a python package. When I change it to
from py.src.blah import Blah
it works. Is there any way I can get it to import properly? I _believe_ I've
had it working before. Then a group member decided almost every directory
needed an `__init__.py` and I think that may have messed up pycharm. I tried
flushing the cache but it doesn't work. Any solutions?
Answer: The webapp directory, as shown, is not a Python package. It does not contain
an `__init__.py` file, therefore it cannot be included in an import path. You
appear to have set up your Python path so that the webapp directory is on the
path, which is why packages under it are importable (the py directory).
So this is a problem with how you've structured your project, not with
PyCharm. For an example of the "right" way to structure a Flask app and
related data, see the source code for Python chat room's website:
<https://github.com/sopython/sopython-site>.
Basically, you need to run from the directory that should be on your path,
each of the packages should be within this directory (and should be packages
with `__init__.py`). Neither myapp or backup should be on the Python path,
only project.
/project
/run.py
/myappp
__init__.py
/backup
__init__.py
|
How to process video files with python OpenCV faster than file frame rate?
Question: I have video file that I am trying to process one frame at a time,. I tried
use VideoCapture class to do reading with following type of code. The problem
is that if video file is recorded at 25 frames / second, the reading happens
at same pace. How to get frames as fast as my computer can decode them?
I plan to process the video stream and then store it to a file.
import cv2
import sys
import time
cap = cv2.VideoCapture(sys.argv[1])
start = time.time()
counter = 0
while True:
counter += 1;
image = cap.read()[1]
if counter %25 == 0:
print "time", time.time() - start
Output: It prints a timestamp once every 25 frames. Notice how timestamps
change almost exactly by 1 second on every line => program processes about 25
frames per second. This with video file that is 25 frames/second.
time 1.25219297409
time 2.25236606598
time 3.25211691856
time 4.25237703323
time 5.25236296654
time 6.25234603882
time 7.252161026
time 8.25258207321
time 9.25195503235
time 10.2523479462
Probably VideoCapture is the wrong API for this kind of work, but what to use
instead?
Using Linux, Fedora 20, opencv-python 2.4.7 and python 2.7.5.
Answer: I can reproduce the behavior you describe (i.e. `cv::VideoCapture >> image`
locked to the frame rate of the recorded video) if opencv is compiled
**without** ffmpeg support. If I compile opencv **with** ffmpeg support, I can
read images from file as fast as my computer will allow. I think that in the
absence of ffmpeg, opencv uses gstreamer and essentially treats the video file
like its playing back a movie.
If you are using Linux, [this
link](http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html)
shows which packages you must install to get ffmpeg support for opencv.
|
How can I log into a simple web access login using Python?
Question: I'm trying to create a little Python script that'll log into a web access
authentication page for me automatically for the purposes of convenience (the
login appears each time the computer is disconnected from the network).

My attempt so far has been to use the module mechanize, but running this
doesn't result in the login vanishing from my standard browser:
import mechanize
browser = mechanize.Browser()
browser.addheaders = [("User-agent","Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13")]
browser.open("https://controller.mobile.lan/101/portal/")
browser.select_form(name="logonForm")
browser["login"] = "myUsername"
browser["password"] = "myPasscode"
browser.submit()
print browser.title()
How can I get this login to work in Python?
Here's what I think is the relevant section of the HTML of the login page:
<form name="logonForm" style="display:none">
<!-- Logon Form -->
<div id="logonForm_subscriptionChoice_top_title_block" class="subtitle">
<span id="logonForm_subscriptionChoice_top_title_text">YOU ALREADY HAVE YOUR LOGIN</span>
</div>
<div id="logonForm_auth_modes_block" style="display:none">
<table class="hoverLink"><tr>
<td>
<div id="logonForm_shibboleth_authentication_button">
<img src="./resources/_images/shibboleth.png" height="30px"><br><span id="logonForm_shibboleth_text">Utilisez vos identifiants institutionnels</span>
</div>
</td>
<td>
<div id="logonForm_standard_authentication_button">
<img src="./resources/_images/ticket.png" height="30px"><br><span id="logonForm_ticket_text">Utilisez un ticket de connexion</span>
</div>
</td>
</tr></table>
</div>
<div id="logonForm_logon_block">
<table>
<tr id="logonForm_logon_block_credentials">
<td class="label">
<span id="logonForm_login_text">LOGIN</span><br><input type="text" name="login" autocomplete="on">
</td>
<td class="label">
<span id="logonForm_password_text">PASSWORD</span><br><input type="password" name="password" autocomplete="on">
</td>
<td>
<button type="submit" id="logonForm_connect_button"><span><img src="./resources/_images/auth_button.png" height="35px"></span></button>
</td>
</tr>
<tr id="logonForm_policy_block">
<!-- Check Box Confirm (Visible status depends on configuration option) --><td colspan="3">
<br><input type="checkbox" name="policy_accept">
<span id="logonForm_policy_text"></span>
</td>
</tr>
</table>
</div>
<br><button type="button" id="logonForm_authentication_form_back_button" style="display:none">Retour</button>
<div id="logonForm_subscriptionChoice_block">
<br><div class="subtitle">
<span id="logonForm_subcribe_bottom_title_text">NOT A LOGIN YET ?</span>
</div>
<br><div id="logonForm_subscriptionChoice_first_double_insert_block">
<table class="hoverLink"><tr>
<td></td>
<td></td>
</tr></table>
</div>
<div id="logonForm_subscriptionChoice_second_double_insert_block">
<table class="hoverLink"><tr>
<td></td>
<td></td>
</tr></table>
</div>
<div id="logonForm_subscriptionChoice_single_insert_block">
<table class="hoverLink"><tr><td></td></tr></table>
</div>
</div>
</form>
Answer: That form submits data somewhere. You need to find out where and what method
it uses. After you find out, you can use the `requests` library to do a one-
liner, like:
response = requests.post("https://controller.mobile.lan/101/portal/", data={'login': "username", 'password': "password")
print response.read() # Dumps the whole webpage after.
Note that if that form uses javascript for submission, mechanize won't do it
and you'll have to get something that actually makes javascript tick.
Mechanize's FAQ
([here](http://wwwsearch.sourceforge.net/mechanize/faq.html#general))
specifies that it doesn't do javascript and you have to emulate it in your own
code.
Edit: If you have PyQt4 lying around, or can install it, you can use a
'headless' browser, like this:
import sys
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebPage
# Set vars here for convenience
username = "myUsername"
password = "myPassword"
class HeadlessBrowser(QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
super(HeadlessBrowser, self).__init__()
self.loadFinished.connect(self.login)
self.mainFrame().load(QUrl(url))
self.app.exec_();
def login(self):
doc = self.mainFrame().documentElement()
user = doc.findFirst("input[name=login]")
pwd = doc.findFirst("input[name=password]")
button = doc.findFirst("button[id=logonForm_connect_button]")
user.setAttribute("value", username)
pwd.setAttribute("value", password)
button.evaluateJavaScript("this.click()")
# Uncomment if the button click above is not enough
#form = doc.findFirst("form[name=logonForm]")
#form.evaluateJavaScript("this.submit()")
self.app.quit()
page = HeadlessBrowser("http://localhost/~iskren/headlesstest.html")
html = page.mainFrame().toHtml()
And the contents of `http://localhost/~iskren/headlesstest.html` that I used
for testing:
<html>
<body>
<form name="logonForm">
<input type="text" name="login"/>
<input type="password" name="password"/>
<button type="submit" id="logonForm_connect_button">Click me!</button>
</form>
</body>
</html>
|
Python position of a character in a string in a list
Question: So, say I have a list with 5 strings. The strings are seven characters long.
list = ["000000A", "000001A", "000002B", "000003C", "000004C"]
Now, with this list, I want to find what position the string is in the list
which the 7th character is equal to A. Then I want to find what position the
string is in the list which the 7th character is equal to B. Then finally the
same for C.
I was thinking along the lines of:
letters = ["A","B","C"]
for i in range(len(letters)):
for j in range(len(list)):
for k, l in enumerate(list[j][6]):
if l == (letters[i]):
print(k)
Could anyone point me in the right direction or explain why this would work?
Answer:
lst = ["000000A", "000001A", "000002B", "000003C", "000004C"]
a = ([i for i,s in enumerate(lst) if s[6] == "A"])
So to get all three:
a = []
b = []
c= []
for i, s in enumerate(lst):
if s[6] == "A":
a.append(i)
elif s[6] == "B":
b.append(i)
elif s[6] == "C":
c.append(i)
Or you can store all in a
[defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict)
using s[6] as the key:
from collections import defaultdict
inds = defaultdict(list)
for i, s in enumerate(lst):
inds[s[6]].append(i)
print(inds)
defaultdict(<type 'list'>, {'A': [0, 1], 'C': [3, 4], 'B': [2]})
|
django-debug-toolbar won't display from production server
Question: I'd like to view the Django Debug Toolbar when accessing my production website
which is running Django 1.6. My server is running Debian 7.8, Nginx 1.2.1, and
Gunicorn 19.1.1. However, when I try to access the site after adding DDT to my
installed apps, I get the following error:
NoReverseMatch at /
u'djdt' is not a registered namespace
Exception Location: /home/mysite/venv/mysite/local/lib/python2.7/site-packages/django/core/urlresolvers.py in reverse, line 505
Error during template rendering
In template /home/mysite/venv/mysite/local/lib/python2.7/site-packages/debug_toolbar/templates/debug_toolbar/base.html, error at line 12
data-store-id="{{ toolbar.store_id }}" data-render-panel-url="{% url 'djdt:render_panel' %}"
I know it's not recommended that you run the toolbar in production but I just
want to run it while I do some testing on my production server prior to
opening it up for public use. As you might expect, it works just fine in my
development environment on my laptop. I did some research and have ensured
that I'm using the ["explicit" setup](http://django-debug-
toolbar.readthedocs.org/en/1.0/installation.html#explicit-setup) as
recommended [here](https://github.com/django-debug-toolbar/django-debug-
toolbar/issues/529). I also ran the command "django-admin.py collectstatic" to
ensure the toolbar's static files were collected into my STATIC_ROOT.
Since I'm running behind a proxy server, I also added some middleware to
ensure that the client's IP address is being passed to the toolbar's
middleware instead of my proxy's IP address. That didn't fix the problem
either.
I'm showing all the settings which seem pertinent to this problem below. Is
there something else I'm missing?
Thanks!
These are the pertinent base settings:
SETTINGS_ROOT = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
STATIC_ROOT = '/var/www/mysite/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(SETTINGS_ROOT, "../../static"),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.common.BrokenLinkEmailsMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
TEMPLATE_DIRS = (
os.path.join(SETTINGS_ROOT, "../../templates"),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Django management commands in 'scripts'
'scripts',
'apps.account',
)
These production-only settings get added to base settings in production:
DEBUG = True # DDT needs this to be True
TEMPLATE_DEBUG = DEBUG
INSTALLED_APPS += (
'django_extensions',
# I'm using Django 1.6
'debug_toolbar',
)
if 'debug_toolbar' in INSTALLED_APPS:
MIDDLEWARE_CLASSES += ('conf.middleware.DjangoDebugToolbarFix',
'debug_toolbar.middleware.DebugToolbarMiddleware', )
# I had to add this next setting after upgrading my OS to Mavericks
DEBUG_TOOLBAR_PATCH_SETTINGS = False
# IP for laptop and external IP needed by DDT
INTERNAL_IPS = ('76.123.67.152', )
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
'INTERCEPT_REDIRECTS': False
}
This is in my urls.py:
if 'debug_toolbar' in dev.INSTALLED_APPS:
import debug_toolbar
urlpatterns += patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
Here is the additional middleware:
class DjangoDebugToolbarFix(object):
"""Sets 'REMOTE_ADDR' based on 'HTTP_X_FORWARDED_FOR', if the latter is
set."""
def process_request(self, request):
if 'HTTP_X_FORWARDED_FOR' in request.META:
ip = request.META['HTTP_X_FORWARDED_FOR'].split(",")[0].strip()
request.META['REMOTE_ADDR'] = ip
Answer: I am using the exact same setup as OP describes, with the noticeable exception
of running everything in a separate Docker container which make the IP of each
service hard to predict.
This is how you force Django Debug Toolbar to always show (only use this
locally, never in production):
def custom_show_toolbar(request):
return True # Always show toolbar, for example purposes only.
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
}
|
'module' object has no attribute 'date_range' in python
Question: I am learning pandas in Python.Below is my code in Terimal:
import pandas as pd
dates = pd.date_range('20130101', periods=6)
Then I get this message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'date_range'
How to solve this problem?
Answer: You can't find `date_range` because you're using pandas version 0.7.0, which
is very old (~9 Feb 2012) in pandas time-- the current stable version (29 Jan
2015) is 0.15.2.
You're going to want to upgrade, not only because of bug fixes and new
features, but because many of the examples you're going to find on the web
won't work for you otherwise.
|
Extract Contributors from repo in python by interacting with GITHUB API V3
Question: I am using pygithub3 wrapper to interact with GITHUB API. I am trying to get
the list of contributors from a git repo, following is my code:
from pygithub3 import Github
gh = Github()
s = gh.repos.list_contributors(user='poise',repo='python')
print(s)
output: pygithub3.core.result.smart.Result object at 0x7ff40510ffd0
Answer: As per **pygithub3** documentation **list_contributors** returns a **Result**.
For you to be able to view the result, you need to consume it using one of the
following formats:
1. Iterating over the result.
2. With a generator.
3. As a list
Refer to the documentation for details:
(<http://pygithub3.readthedocs.org/en/latest/result.html>)
The **list** option is straight forward. Just add **.all()** when printing the
result to get the list of contributors.
from pygithub3 import Github
gh = Github()
s = gh.repos.list_contributors(user='poise',repo='python')
print(s.all())
Output:
<User (jtimberman)>
<User (coderanger)>
<User (schisamo)>
<User (sethvargo)>
<User (damm)>
<User (guilhem)>
<User (joestump)>
<User (ka2n)>
<User (PrajaktaPurohit)>
<User (nathenharvey)>
<User (someara)>
<User (benjaminws)>
<User (captnswing)>
<User (jjhuff)>
<User (andreacampi)>
<User (rody)>
<User (tk0miya)>
<User (comandrei)>
<User (btm)>
<User (spazm)>
<User (akiernan)>
<User (chr4)>
<User (e100)>
<User (garrypolley)>
<User (kamaradclimber)>
<User (hectcastro)>
<User (hltbra)>
<User (spheromak)>
<User (rgbkrk)>
<User (mal)>
<User (Frick)>
<User (miketheman)>
<User (nathanph)>
<User (paulczar)>
<User (petecheslock)>
<User (dexterous)>
<User (stevendanna)>
<User (viralshah)>
<User (chantra)>
<User (tdcarrol)>
|
Creating array and writing to excel column using Range function using Python
Question: I would like to create a data container on the fly in my python script (based
on calculations), and then write this to a **column** within excel using
win32com client and the range() function. I can successfully do this for a
row, but cannot do for a column. The hard coded code I basically want to do is
like following:
import win32com.client as win32
from win32com.client import Dispatch
Excel=Dispatch('Excel.Application')
wb = Excel.ActiveWorkbook
ws = wb.ActiveSheet
data_container = [5],[6],[7],[8],[9]
ws.Range(ws.Cells(11,9),ws.Cells(15,9)).Value = (data_container)
The tricky part for me, is creating a data_container that I can create on the
fly. I know there is a lot on stackoverflow about tuples, data dictionaries
and lists, but I cannot work it out and am confused (if I see the warning
"tuple is immutable" one more time!!!!!!). Whenever I create something like
the following, it just outputs the first item in all of the cells (i.e below
fills all cells with 5).
data_container = []
data_container.append(5)
data_container.append(6)
data_container.append(7)
data_container.append(8)
data_container.append(9)
ws.Range(ws.Cells(11,9),ws.Cells(15,9)).Value = (data_container)
I could loop through and write to each cell, however don't want to do this due
to time limitation. I know there are probably other python addons you can use,
but I want this to be usable on many computers that do not necessarily have
all these addons that can prevent people using my script.........I like the
simplicity of using the win32com setup and have most items working except for
this. Ideally, I would like to have a number of columns stored in 1
dictionary/list/matrix/array......and be able to write to one range
referencing a certain part of the data container. For example:
ws.Range(ws.Cells(11,9),ws.Cells(15,9)).Value = (data_container[0])
Where data_container[0] contains [5],[6],[7],[8],[9]......
The ultimate of what I want to do, is to read a number of columns (not
necessarily in order) into a data container, make modifications, and then
write back to a number of columns (again not necessarily in order).
I appreciate all the building blocks for this are probably on stack overflow
at present, i just havn't been able to pull them together over the few days
I've been trying to nut this out. Any help is appreciated.
Answer: I was fortunate to get someone from work to spend some time helping me, but
might be useful for anyone else as reference. Below seems to work. Issue was
creating the array/list structure. I think fundamentally below I have created
a 3D array/list? Below code creates this structure all with 5, then modifies
only two cells and writes back to two separate columns. This might be obvious
to others, but wasn't to me.
import win32api
import os
import sys
import win32com.client as win32
from win32com.client import Dispatch
if __name__ == "__main__":
Excel=Dispatch('Excel.Application')
wb = Excel.ActiveWorkbook
ws = wb.ActiveSheet
data_work = [[[5] for i in range(10)] for j in range(10)]
data_work[0][2] = [500]
data_work[1][4] = [45]
ws.Range(ws.Cells(1,9),ws.Cells(9,9)).Value = (data_work[0])
ws.Range(ws.Cells(1,12),ws.Cells(9,12)).Value = (data_work[1])
|
Python newbie and unsupported operand
Question: I'm just learning python and am trying to make a program that calculates loan
rates. I keep getting an unsupported operand type for *: 'function' and 'int.'
with references to lines 14 and 8. I'm not sure what I'm doing wrong. Here is
the code:
from sys import argv
def payment(amt, rate, yrs) :
def p(yrs) :
return 12 * yrs
def r(rate) :
return rate / 100 / 12
return (r * amt) / (1 - ((1 + r) ** (-p)))
if __name__ == "__main__" :
amt = int(argv[1])
rate = float(argv[2])
yrs = int(argv[3])
print("$%.2f" % payment(amt, rate, yrs))
Answer: As mentioned in the comments, your immediate problem is that (as your
exception says) you tried to multiply an integer with a function, and that
doesn't make sense. A naïve fix for that would be to call the functions you've
defined, as per Mehmet's answer:
return (r(rate) * amt) / (1 - ((1 + r(rate)) ** (-p(yrs))))
However, you don't really need those functions at all. A simpler version of
your `payment()` function might look like this:
def payment(amt, rate, yrs) :
p = 12 * yrs
r = rate / 100 / 12
return (r * amt) / (1 - ((1 + r) ** (-p)))
Notice that instead of defining functions inside `payment()`, here we're
simply assigning the result of the calculation to a variable in each case.
|
Setting up embedded Python for Scripting a C++ Game
Question: I'm having trouble achieving this. What I'm stuck with is trying to expose
Modules written in C++ to an embedded python interpreter.
I'm using boost::python, but I'm not sure what I'm supposed to do for this, as
the documentation seems to be lacking, to say the least.
What I want is to expose some C++ code with BOOST_PYTHON_MODULE, and then
access that from _the same application_. However I can't get it to import.
What I've got, which seem the closest (just relevant part):
#include <python/interpreter.hpp>
bp::object blag() {
return bp::str("Thingy");
}
BOOST_PYTHON_MODULE(modthingy) {
bp::def("blag", &blag);
}
Interpreter::Interpreter() {
Py_UnbufferedStdioFlag = 1;
Py_Initialize();
try {
init_module_modthingy();
} catch (bp::error_already_set) {
PyErr_Print();
}
main_module = bp::import("__main__");
main_namespace = main_module.attr("__dict__");
}
But that prints the Error `AttributeError: 'NoneType' object has no attribute
'__dict__'` And I can't import the module later.
How should this be structured?
EDIT: Ok, so the closest I got was one of the methods in the accepted answer:
PyImport_AppendInittab("modthingy", &PyInit_modthingy);
Py_Initialize();
However, this doesn't seem particularly useful in my case, as I'd like to be
able to add/import modules after the Initialize function. I'm going to look
into a few things, namely:
* See if I can get the suggested approach for python 2 working in python 3
* See if I can nicely structure my game to require naming all of the modules before Py_Initialize
I'll update this post with my findings.
Answer: Boost.Python uses the
[`BOOST_PYTHON_MODULE`](http://www.boost.org/doc/libs/1_57_0/libs/python/doc/v2/module.html#BOOST_PYTHON_MODULE-
spec) macro to define a Python module initializer. The resulting function is
not the module importer. This difference is similar to that of creating a
`modthingy.py` module and calling `import modthingy`.
When importing a module, Python will first check if the module is a built-in
module. If the module is not there, then Python will then search the [module
search path](https://docs.python.org/3/tutorial/modules.html#the-module-
search-path) trying to find a python file or library based on the module name.
If a library is found, then Python expects the library to provide a function
that will initialize the module. Once found, the import will create an empty
module in the modules table, then initialize it. For statically linked
modules, such as `modthingy`, the module search path will not be helpful, as
there is no library for it to find.
For embedding, the [module table and initialization
function](https://docs.python.org/3/extending/extending.html#the-module-s-
method-table-and-initialization-function) documentation states that for static
modules, the module initializer function will not be automatically called
unless there is an entry in the initialization table. For Python 2 and Python
3, one can accomplish this by calling
[`PyImport_AppendInittab()`](https://docs.python.org/3/c-api/import.html#c.PyImport_AppendInittab)
before
[`Py_Initialize()`](https://docs.python.org/3/c-api/init.html#c.Py_Initialize):
BOOST_PYTHON_MODULE(modthingy)
{
// ...
}
PyImport_AppendInittab("modthingy", &initmodthingy);
Py_Initialize();
// ...
boost::python::object modthingy = boost::python::import("modthingy");
Alternatively, for Python 2, once the interpreter has been initialized, one
can create an empty module that is added to the modules dictionary via
[`PyImport_AddModule()`](https://docs.python.org/2/c-api/import.html#c.PyImport_AddModule),
then explicitly initialize the module.
BOOST_PYTHON_MODULE(modthingy)
{
// ...
}
Py_Initialize();
PyImport_AddModule("modythingy");
initmodthingy();
boost::python::object modthingy = boost::python::import("modthingy");
This approach is demonstrated in the official Python embedded demo,
[embed/demo.c](https://github.com/python-
git/python/blob/master/Demo/embed/demo.c). The module initializer created from
`BOOST_PYTHON_MODULE` does not call `PyImport_AddModule()`, thus it must be
explicitly called.
Also note that the Python's C API for embedding changed naming conventions for
module initialization functions between Python 2 and 3, so for
`BOOST_PYTHON_MODULE(modthingy)`, one may need to use `&initmodthingy` for
Python 2 and `&PyInit_modthingy` for Python 3.
* * *
Here is a minimal complete example demonstrating importing a module statically
linked with the embedded interpreter:
#include <iostream>
#include <string>
#include <boost/python.hpp>
std::string spam() { return "Spam spam spam"; }
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::def("spam", &spam);
}
int main()
{
// Add example to built-in.
PyImport_AppendInittab("example", &initexample);
// Start the interpreter.
Py_Initialize();
namespace python = boost::python;
try
{
// >>> import example
python::object example = python::import("example");
// >>> x = example.spam()
python::object x = example.attr("spam")();
// >>> print x
std::cout << "x = " << python::extract<std::string>(x)() << std::endl;
}
catch (const python::error_already_set&)
{
PyErr_Print();
}
}
Output:
x = Spam spam spam
|
i keep getting the error 'module' object has no attribute 'init'
Question: Especially when i run it from an external python file and just run it using
IDLE or Pycharm..Please Help...but at times it works with in the interactive
shell and then something happens and it starts its problems ....I simply typed
import pygame
x = pygame.init()
print(x)
> C:\Python33\python.exe C:/Users/Home/Desktop/pygame.py Traceback (most
> recent call last): File "C:/Users/Home/Desktop/pygame.py", line 1, in import
> pygame File "C:\Users\Home\Desktop\pygame.py", line 2, in x = pygame.init()
> AttributeError: 'module' object has no attribute 'init'
>
> Process finished with exit code 1.
Answer: The problem is that you named your file `pygame.py`.
If you run it and you want to import `pygame`, it will import your file
`C:\Users\Home\Desktop\pygame.py` and not the installed pygame module.
So just use another filename (and delete `C:\Users\Home\Desktop\pygame.py` and
any other leftovers).
|
How to pack the elements of product of matrix multiplication back
Question: A beginner to Python, I am trying to work my way into understanding how to do
things in as Pythonic a way as possible.
I am attempting to write a function to which returns result of matrix
multiplication of 2 matrices. here's what I came up with:
def matmul(a,b):
c = zip(*b)
def element(i,j):
return reduce(lambda x,y: x+y,map(lambda x:x[0]*x[1],zip(a[i],c[j])))
print [element(i,j) for i in range(len(a)) for j in range(len(c))]
The list that I am printing contains the product of each element of the
product, but it's a list not a matrix.
>>> a = [[1,2],[3,4]]
>>> b = [[1,1],[1,1]]
>>> matmul(a,b)
[3, 3, 7, 7]
>>> a = [[1,1,1],[2,2,2],[3,3,3]]
>>> b = [[1,8,7],[8,7,11],[7,8,2]]
>>> matmul(a,b)
[16, 23, 20, 32, 46, 40, 48, 69, 60]
`[3,3,7,7]` should be actually be represented as `[[3,3],[7,7]]` and `[16, 23,
20, 32, 46, 40, 48, 69, 60]` as `[[16, 23, 20],[32, 46, 40],[48, 69, 60]]`
But, I am not able to think of a concise way to pack the list back into 2D.
How would I easily and concisely go about doing so ?
Answer: You were very close, you just need to use a nested list-comprehension with
`zip(*)`:
zip(*[[element(i,j) for i in range(len(a))] for j in range(len(c))])
A re-factored version of your code:
from operator import mul
from itertools import starmap, izip, imap
def matmul(a, b):
c = zip(*b)
def element(row):
# or [sum(map(mul, row, col)) for col in c]
# or [sum(imap(mul, row, col)) for col in c]
return [sum(starmap(mul, izip(row, col))) for col in c]
print [element(row) for row in a]
* * *
Most concise way will be use
[`numpy.matrix`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html):
>>> import numpy as np
>>> a = np.matrix([[1,2],[3,4]])
>>> b = np.matrix([[1,1],[1,1]])
>>> a * b
matrix([[3, 3],
[7, 7]])
* * *
In Python 3.5(not released yet) we will be able to use the `@` operator on
Python lists to do [matrix
multiplications](http://legacy.python.org/dev/peps/pep-0465/).
|
Opening a window from another window in python using pyqt framework
Question: I am trying open a pyqt window from another pyqt window on clicking a button
but i can't really get a hold do it . Both the python files opening.py and
signup.py can run standalone on their own but i can't think of a way to link
them ...(Running signup.py from opening.py after clicking signup button)
opening.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'opening.ui'
#
# Created: Tue Jan 20 00:19:45 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
#from signup import Ui_Dialog1
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(290, 237)
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(70, 19, 151, 41))
self.label.setObjectName(_fromUtf8("label"))
self.pushButton = QtGui.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(40, 170, 201, 41))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton_2 = QtGui.QPushButton(Dialog)
self.pushButton_2.setGeometry(QtCore.QRect(40, 100, 201, 41))
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.pushButton.clicked.connect(self.handleTest1)
self.pushButton_2.clicked.connect(self.handleTest2)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.label.setText(_translate("Dialog", "MAIL SERVER", None))
self.pushButton.setText(_translate("Dialog", "SIGN UP", None))
self.pushButton_2.setText(_translate("Dialog", "LOGIN", None))
def handleTest1(self):
#self.accept()
#self.h=Ui_Dialog1()
#self.h.setupUi(QtGui.QDialog())
pass
def handleTest2(self):
execfile('login.py')
import sys
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
and other file which is to be opened after clicking signup button (login
button doesn't work as of now)
signup.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'abc.ui'
#
# Created: Mon Jan 19 23:35:37 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog1(object):
def setupUi(self, Dialog):
print "16"
Dialog.setObjectName(_fromUtf8("SignUp"))
Dialog.resize(415, 364)
self.SignUp = QtGui.QDialogButtonBox(Dialog)
self.SignUp.setGeometry(QtCore.QRect(130, 310, 176, 27))
self.SignUp.setOrientation(QtCore.Qt.Horizontal)
self.SignUp.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.SignUp.setObjectName(_fromUtf8("SignUp"))
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(50, 50, 91, 21))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(50, 110, 66, 17))
self.label_2.setText(_fromUtf8(""))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_3 = QtGui.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(50, 100, 66, 17))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(Dialog)
self.label_4.setGeometry(QtCore.QRect(50, 150, 66, 17))
self.label_4.setObjectName(_fromUtf8("label_4"))
self.label_5 = QtGui.QLabel(Dialog)
self.label_5.setGeometry(QtCore.QRect(50, 200, 121, 17))
self.label_5.setObjectName(_fromUtf8("label_5"))
self.label_6 = QtGui.QLabel(Dialog)
self.label_6.setGeometry(QtCore.QRect(50, 250, 91, 17))
self.label_6.setObjectName(_fromUtf8("label_6"))
self.lineEdit_3 = QtGui.QLineEdit(Dialog)
self.lineEdit_3.setGeometry(QtCore.QRect(200, 140, 181, 27))
self.lineEdit_3.setObjectName(_fromUtf8("lineEdit_3"))
self.lineEdit_4 = QtGui.QLineEdit(Dialog)
self.lineEdit_4.setGeometry(QtCore.QRect(200, 190, 181, 27))
self.lineEdit_4.setObjectName(_fromUtf8("lineEdit_4"))
self.lineEdit_5 = QtGui.QLineEdit(Dialog)
self.lineEdit_5.setGeometry(QtCore.QRect(200, 90, 181, 27))
self.lineEdit_5.setObjectName(_fromUtf8("lineEdit_5"))
self.lineEdit_6 = QtGui.QLineEdit(Dialog)
self.lineEdit_6.setGeometry(QtCore.QRect(200, 40, 181, 27))
self.lineEdit_6.setObjectName(_fromUtf8("lineEdit_6"))
self.lineEdit_7 = QtGui.QLineEdit(Dialog)
self.lineEdit_7.setGeometry(QtCore.QRect(200, 240, 181, 27))
self.lineEdit_7.setObjectName(_fromUtf8("lineEdit_7"))
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.SignUp, QtCore.SIGNAL(_fromUtf8("accepted()")), Dialog.accept)
QtCore.QObject.connect(self.SignUp, QtCore.SIGNAL(_fromUtf8("rejected()")), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
print "17"
Dialog.show()
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("SignUp", "SignUp", None))
self.label.setText(_translate("Dialog", "Name", None))
self.label_3.setText(_translate("Dialog", "E-mail", None))
self.label_4.setText(_translate("Dialog", "Password", None))
self.label_5.setText(_translate("Dialog", "Confirm Password", None))
self.label_6.setText(_translate("Dialog", "Mobile (+91)", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog1()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
The commented part in opening.py is the one creating problems . Help would be
appreciated .
Answer: Your Ui_Dialog1 should inherit from QDialog, which makes it an UI object, but
you inherit from object, this has no "show" method.
def handleTest1(self):
#self.accept()
#self.h=Ui_Dialog1() # You need to move this to __init__ function
#self.h.setupUi(QtGui.QDialog()) # You need to move this to __init__ function
self.h.show() # call the show method here
You need to move the self.h = Ui_Dialog1() and setupUi to **init** functions,
this will avoid possible memory leak. (otherwise each time you click
"sigunup", it will create a new object)
|
image does not display in ipython
Question: The image does not load if it is part of a while loop. For e.g. the following
works as expected:
from IPython.display import Image
Image(filename='someimage.jpg')
But this does not work:
while True:
Image(filename='someimage.jpg')
break
update:
How do I display several images from a list?
Answer: This works fine here:
from IPython.display import display, Image
path1 = "/some/path/to/image1.png"
path2 = "/some/path/to/image2.png"
for path in path1, path2:
img = Image(path)
display(img)
|
Detect if IPython Pylab GUI event loop is active
Question: Is there a canonical way of detecting inside the interpreter if IPython was
called with options like`--pylab=...` or `--gui=...`?
The reason: I want to do some asynchronous plotting in a separate process, as
show in the sample script `tst_process.py`:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" File tst_process.py """
# For better Python 3 compatibility:
from __future__ import absolute_import, print_function, unicode_literals, \
division
import matplotlib.pylab as plt
from multiprocessing import Process
import numpy as np
def tst_plot(fgoff=0):
""" Make a test plot """
print("Drawing figure {}".format(1+fgoff))
x = np.linspace(0, 5, 500)
fg = plt.figure(1+fgoff)
fg.clf()
ax = fg.add_subplot(1, 1, 1)
ax.plot(x, np.sin(x))
ax.set_title("This is a Test-Plot")
fg.canvas.draw()
plt.show()
if __name__ == "__main__":
print("Doing testplot in new process ...")
pprc1 = Process(target=tst_plot)
pprc1.start()
print("Doing testplot in own process ...")
tst_plot(10)
When I run it with the command
ipython --i tst_process.py
everything works as expected. Doing:
ipython --pylab=qt --i tst_process.py
gives:
Python 2.7.9 (default, Dec 11 2014, 08:58:12)
Type "copyright", "credits" or "license" for more information.
IPython 2.3.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
Doing testplot in new process ...
Doing testplot in own process ...
Drawing figure 11
Drawing figure 1
: Fatal IO error: client killed
X Error: BadIDChoice (invalid resource ID chosen for this connection) 14
Major opcode: 1 (X_CreateWindow)
Resource id: 0x6a00003
X Error: BadIDChoice (invalid resource ID chosen for this connection) 14
Extension: 139 (RENDER)
Minor opcode: 4 (RenderCreatePicture)
Resource id: 0x6a00004
X Error: BadIDChoice (invalid resource ID chosen for this connection) 14
Major opcode: 1 (X_CreateWindow)
Resource id: 0x6a00005
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python: ../../src/xcb_io.c:274: poll_for_event: Zusicherung »!xcb_xlib_threads_sequence_lost« nicht erfüllt.
Abgebrochen
Other backends with the exception of `wx` did not work either.
It would be sufficient for me to detect the existence of the event loop. Then
I could use the same script for running from the command line and for inside
Spyder.
Answer: To answer your original question: `Is there a canonical way of detecting
inside the interpreter if IPython was called with options like--pylab=... or
--gui=...?`
Yes, there is. The most simple would be to check for the command line
arguments:
import sys
print sys.argv # returns the commandline arguments
# ['ipython', '--pylab', 'inline']
A nicer way would be to use the built-in module
[optparse](https://docs.python.org/2/library/optparse.html).
However, this will only allow you to see what mode it is running in, based on
the command line arguments - which was your main question. It will not help
you solve the gui event looks + multiprocess issues as
[@tcaswell](http://stackoverflow.com/users/380231/tcaswell) mentioned in the
comments.
|
Python like package name aliasing in Scala
Question: I know that in Scala you can alias things inside package like that: `import
some.package.{someObject => someAlias}`
Is there a way of creating alias for package name, not for classes/objects
inside it ?
For example in Python you can do: `import package as alias`
Answer: You can alias a package name the same way you alias an object.
import scala.collection.{mutable => m}
val buffer = m.ListBuffer(1, 2, 3, 4)
buffer: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4)
Fun fact: You can also alias object methods this way.
import scala.collection.mutable.ListBuffer.{apply => makeBuffer}
scala> makeBuffer(1, 2, 3, 4)
res5: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3, 4)
|
Retain Excel Settings When Adding New CSV
Question: I've written a python/webdriver script that scrapes a table online, dumps it
into a list and then exports it to a CSV. It does this daily.
When I open the CSV in Excel, it is unformatted, and there are fifteen (comma-
delimited) columns of data in each row of column A.
Of course, I then run 'Text to Columns' and get everything in order. It looks
and works great.
But tomorrow, when I run the script and open the CSV, I've got to reformat it.
Here is my question: **"How can I open this CSV file with the data already
spread across the columns in Excel?"**
Answer: Try importing it as a csv file, instead of opening it directly on excel.
|
Program along with all the switches, runs great, but argparse '--help' throws a lot of errors
Question: I am using argparse in Python to handle arguments in my program. For instance,
as seen below, if I use the argument '-p' a specific module is execute. Now,
all arguments and the program runs great. But when I try to get the '--help'
for my program it crashes horribly (image).
Here is the code pertaining to argparse:
parser = argparse.ArgumentParser(description="something1.")
parser.add_argument('-x', '--xoo', help='something2', action='store_true')
parser.add_argument('-a', '--al', help='something3', action='store_true')
parser.add_argument('-c', '--conv', help='something4', type=float)
parser.add_argument('-p', '--pay', help='something5', type=float)
args = parser.parse_args()
Any ideas as to how I can correct this error??
$ ./xoom.py -h
Traceback (most recent call last):
File "./xoom.py", line 46, in <module>
args = parser.parse_args()
File "/usr/lib/python2.7/argparse.py", line 1688, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "/usr/lib/python2.7/argparse.py", line 1723, in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
File "/usr/lib/python2.7/argparse.py", line 1929, in _parse_known_args
start_index = consume_optional(start_index)
File "/usr/lib/python2.7/argparse.py", line 1869, in consume_optional
take_action(action, args, option_string)
File "/usr/lib/python2.7/argparse.py", line 1797, in take_action
action(self, namespace, argument_values, option_string)
File "/usr/lib/python2.7/argparse.py", line 994, in __call__
parser.print_help()
File "/usr/lib/python2.7/argparse.py", line 2319, in print_help
self._print_message(self.format_help(), file)
File "/usr/lib/python2.7/argparse.py", line 2293, in format_help
return formatter.format_help()
File "/usr/lib/python2.7/argparse.py", line 279, in format_help
help = self._root_section.format_help()
File "/usr/lib/python2.7/argparse.py", line 209, in format_help
func(*args)
File "/usr/lib/python2.7/argparse.py", line 209, in format_help
func(*args)
File "/usr/lib/python2.7/argparse.py", line 515, in _format_action
help_text = self._expand_help(action)
File "/usr/lib/python2.7/argparse.py", line 601, in _expand_help
return self._get_help_string(action) % params
TypeError: float argument required, not dict
Answer: The problem is that you have % characters in your `something4` and/or
`something5`.
Remove them and see if you still get the error.
If you really need % characters in those help texts, try replacing them with
%% - i.e. use two percent characters in a row.
Update: Here is a minimal example which demonstrates why you are getting the
error:
import argparse
parser = argparse.ArgumentParser(description="something1.")
parser.add_argument('-c', '--conv', help='somet%fhing4', type=float)
args = parser.parse_args()
Run with `--help` to generate the error message. Note the % character in the
help string.
|
After installing lpthw.web the does nothing
Question: So, I am going over "Learn Python The Hard Way" and have an issue with Chapter
50 "Building my first website".
jharvard@appliance (~/Dropbox/Python/gothonweb): ls -R
bin docs gothonweb templates tests
./bin:
app.py
./docs:
./gothonweb:
__init__.py
./templates:
./tests:
__init__.py
Trying to run app.py file with command: $python bin/app.py It supposed to
start the server but it does not do anything at all. It just return to a
prompt again.
#app.py
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
greeting = "Hello world"
return greeting
if __name__ == "__main__":
app.run
I installed lpthw using pip first.
$pip install lpthw.web
When I run the file it gave me ImportError: no 'web' exists So I installed
webpy myself using with help of <http://webpy.org/install> And now I'm getting
no result at all. Python I am using is Python 2.7.8 : Anaconda 2.1.0 . So
there must be no conflict. Any suggestions? Thank you.
Answer: So, I fixed it successfully but adding parenthesis to the function app.ru()
#app.py
....
greeting = "Hello world"
return greeting
if __name__ == "__main__":
app.run
|
How to efficiently process a large file with a grouping variable in Python
Question: I've got a dataset that looks something like the following:
ID Group
1001 2
1006 2
1008 1
1027 2
1013 1
1014 4
So basically, a long list of unsorted IDs with a grouping variable as well.
At the moment, I want to take subsets of this list based on the generation of
a random number (imagine they're being drafted, or won the lottery, etc.).
Right now, this is the code I'm using to just process it row-by-row, by ID.
reader = csv.reader(open(inputname), delimiter=' ')
out1 = open(output1name,'wb')
out2 = open(output2name,'wb')
for row in reader:
assignment = gcd(1,p,marg_rate,rho)
if assignment[0,0]==1:
out1.write(row[0])
out1.write("\n")
if assignment[0,1]==1:
out2.write(row[0])
out2.write("\n")
Basically, i the gcd() function goes one way, you get written to one file,
another way to a second, and then some get tossed out. The issue is I'd now
like to do this by _Group_ rather than ID - basically, I'd like to assign
values to the first time a member of the group appears, and then apply it to
all members of that group (so for example, if 1001 goes to File 2, so does
1006 and 1027).
Is there an efficient way to do this in Python? The file's large enough that
I'm a little wary of my first thought, which was to do the assignments in a
dictionary or list and then have the program look it up for each line.
Answer: I used
[`random.randint`](https://docs.python.org/2/library/random.html#random.randint)
to generate a random number, but this can be easily replaced.
The idea is to use a
[`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict)
to have **single** score (`dict` keys are unique) for a group from the moment
it's created:
import csv
import random
from collections import defaultdict
reader = csv.DictReader(open(inputname), delimiter=' ')
out1 = open(output1name,'wb')
out2 = open(output2name,'wb')
# create a dictionary with a random default integer value [0, 1] for
# keys that are accessed for the first time
group_scores = defaultdict(lambda: random.randint(0,1))
for row in reader:
# set a score for current row according to it's group
# if none found - defaultdict will call it's lambda for new keys
# and create a score for this row and all who follow
score = group_scores[row['Group']]
if score==0:
out1.write(row['ID'])
out1.write("\n")
if score==1:
out2.write(row['ID'])
out2.write("\n")
out1.close()
out2.close()
I've also used
[`DictReader`](https://docs.python.org/2/library/csv.html#csv.DictReader)
which I find nicer for `csv` files with headers.
**Tip:** you may want to use the [`with` context
manager](http://effbot.org/zone/python-with-statement.htm) to open files.
Example output:
reut@sharabani:~/python/ran$ cat out1.txt
1001
1006
1008
1027
1013
reut@sharabani:~/python/ran$ cat out2.txt
1014
|
Can ThreadPoolExecutor help single-threaded application efficiency?
Question: We want to make an e-commerce application, and the team are python devs, but
not using python web frameworks (Django/Flask...), and because we found that
Tornado was excellent by its simplicity, we gave him a big percentage.
But the problem is that, Tornado is single-threaded, and the application will
use hashing (login), and image processing (thumbnails generation). Can
`ThreadPoolExecutor` play the role of a multithreading server like Apache, as
in this example?
from concurrent.futures import ThreadPoolExecutor
from tornado import gen
from tornado.process import cpu_count
import bcrypt
pool = ThreadPoolExecutor(cpu_count())
@gen.coroutine
def create_user(name, password):
hashed_pw = yield pool.submit(bcrypt.hashpw, password, bcrypt.gensalt())
yield save_user(name, hashed_pw)
@gen.coroutine
def login(name, password):
user = yield load_user(name)
match = yield pool.submit(bcrypt.checkpw, password, user.hashed_pw)
if not match:
raise IncorrectPasswordError()
So, Tornado sends the hashing work to another thread, to free himself and be
able to receive other requests. Will this approach work?
NB: There is also a solution involving a load balancer, but the team doesn't
want to pursue this solution right now.
Answer: Yes, `ThreadPoolExecutor` will work well here. It appears both
[`hashpw`](https://github.com/grnet/python-
bcrypt/blob/master/bcrypt/bcrypt_python.c#L97) and
[`checkpw`](https://github.com/grnet/python-
bcrypt/blob/master/bcrypt/bcrypt_python.c#L156) release the GIL during the
CPU-heavy parts of their operation:
bcrypt_hashpw(PyObject *self, PyObject *args, PyObject *kw_args)
{
...
Py_BEGIN_ALLOW_THREADS;
ret = pybc_bcrypt(password_copy, salt_copy, hashed, sizeof(hashed));
Py_END_ALLOW_THREADS;
...
That means you'll be able to farm that work off to one CPU, while handling
incoming requests with another CPU.
Just keep in mind that if you need to do some other CPU-bound operations that
run pure-Python (meaning the GIL doesn't get released), you'll need to use a
`ProcessPoolExecutor` to avoid taking a performance hit.
|
How to launch a couple of python scripts from a first python script and then terminate them all at once?
Question: I have a function in a python script which should launch another python script
multiple times, I am assuming this can be done like this(Script is just my
imagination of how this would work.)
iterations = input("Enter the number of processes to run")
for x in range(0, iterations):
subprocess.call("python3 /path/to/the/script.py", shell=True)
but, I also need to pass over some defined variables into the other script,
for example, if
x = 1
in the first script, then, I need x to have the same value in the second
script without defining it there, I have NO idea how to do that.
And then also killing them, I have read about some method using PIDs, but
don't those change every time?
Most of the methods I found on Google looked overly complex and what I want to
do is really simple. Can anyone guide me in the right direction as to what to
use and how I should go at accomplishing it?
Answer: **I have a function in a python script which should launch another python
script multiple times, I am assuming this can be done like this(Script is just
my imagination of how this would work.)**
** Here is the subprocess manual page which contains everything I will be
talking about <https://docs.python.org/2/library/subprocess.html>
One of the way to call one script from other is using subprocess.Popen
something on the lines
import subprocess
for i in range(0,100):
ret = subprocess.Popen("python3 /path/to/the/script.py",stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
you can use the return value from Open to make the call synchronous using the
communicate method.
out,err = ret.communicate()
This would block the calling script until the subprocess finishes.
**I also need to pass over some defined variables into the other script??**
There are multiple ways to do this. 1\. Pass parameters to the called script
and parse it using OptionPraser or `sys.args` in the called script have
something like
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-x","--variable",action="store_true",dest="xvalue",default=False)
(options,args) = parser.parse_args()
if options.xvalue == True:
###do something
in the callee script use subprocess as
ret = subprocess.Popen("python3 /path/to/the/script.py -x",stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
Note the addition of -x parameter
2. You can use args parse
<https://docs.python.org/2/library/argparse.html#module-argparse>
3. Pass the subprocess a environment variable which can be used to configure the subprocess. This is fast but this only works one way, i.e. from parent process to child process. in called script
import os
x = int(os.enviorn('xvalue'))
in callee script set the environment variable
import os
int x = 1
os.environ['xvalue'] = str(x)
4. Use sockets or pipes or some other IPC method
**And then also killing them, I have read about some method using PIDs, but
don't those change every time?**
again you can use subprocess to hold the process id and terminate it this will
give you the process id
ret.pid
you can then use .terminate to terminate the process if it is running
ret.terminate()
to check if the process is running you can use the poll method from subprocess
Popen. I would suggest you to check before you terminate the process
ret.poll()
poll will return a None if the process is running
|
How do I automatically accept subscriptions using python and XMPPPY?
Question: I'm making a chat bot for a game I play and the bot itself is working fine,
now what I need to do is make the bot auto-add any requests it gets.
I'm not sure what to do about this, doing some googling I found someone state
that `def add_friend(self, user): self._send(xmpp.Presence(to=user,
typ='subscribed')) self._send(xmpp.Presence(to=user, typ='subscribe')) return
True`
would do the trick, but I have no idea how to implement it in my code.
Here's my base of my code for the messaging system using Python:
import xmpp
conn = xmpp.Client("domain here..")
if not conn.connect(server=("<server here>", 5223)):
print "connect failed."
exit()
if not conn.auth("USER ID", "PASS HERE", "xiff"):
print "auth failed."
exit()
roster = None
def message_handler(conn, msg):
user = roster.getName(str(msg.getFrom()))
text = msg.getBody()
print "[%s] %s" % (user, text)
reply = msg.buildReply("[ECHO] %s" % (text))
reply.setType("chat")
conn.send(reply)
conn.RegisterHandler("message", message_handler)
conn.sendInitPresence(requestRoster=1)
roster = conn.getRoster()
while conn.isConnected():
try:
conn.Process(10)
except KeyboardInterrupt:
break
When a user tries to add the bot, this is what shows up:
<iq to="[email protected]" from="[email protected]/xiff" id="2861886931" type="error">
<query xmlns="jabber:iq:riotgames:roster">
<item jid="[email protected]" name="Top Mid Lane NA" subscription="pending_in" />
</query>
<error code="501" type="cancel">
<feature-not-implemented xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" />
<text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">The feature requested is not implemented by the recipient or server and therefore cannot be processed.</text>
</error>
</iq>
DEBUG: socket got <presence to='[email protected]/xiff' from='[email protected]' name='Top Mid Lane NA' type='subscribe'>
<priority>0</priority>
</presence>
Any ideas, I've been stuck on this for a few days!
Answer: You should implement presence handler for accepting subscription:
def presence(conn, event):
if event.getType() == 'subscribe':
conn.send(xmpp.Presence(to=event.getFrom(), typ='subscribed'))
conn.RegisterHandler('presence', presence)
|
Statement decorators
Question: We have some code that looks like this:
from third_party_library import foo
for n in range(3):
try:
foo(args)
break
except:
print "Retry %i / 3" % n
I would like to use a decorator, allowing our code to be more consise, looking
like this:
from third_party_library import foo
@retry(3)
foo(args)
This gives a syntax error. Am I missing something, or does python just not
allow decorators on statements?
Answer: Decorators can only be applied to function and class _definitions_ such as:
@decorator
def func():
...
@decorator
class MyClass(object):
...
You cannot use them anywhere else in the language.
* * *
To do what you want, you could make a normal `retry` function and pass `foo`
and `args` as arguments. The implementation would look something like this:
def retry(times, func, *args, **kwargs):
for n in xrange(times):
try:
func(*args, **kwargs)
break
except Exception: # Try to catch something more specific
print "Retry %i / %i" % (n, times)
|
Store data as numbers in a file in Python
Question: I wrote a program that opens a file and read it line by line and store just
the third element of each line. The problem is that, when I write those
outputs into a file I need to change them as strings which is not suitable for
me due to the fact that I want to do some mathematical operations on the
written file later on. FYI, it also is not suitable to store it like this and
use int() while reading it.
Can anybody help me with this issue?
with open("/home/test1_to_write", "w") as g:
with open("/home/test1_to_read", 'r') as f:
for line in f:
a=line.split()
number = int(a[3])
g.write(str(number)+'\n')
g.close()
Answer: There's no way to tell a text file that `1` is the number one not the letter
`"1"`. If you need that, consider storing the whole thing as a list instead
using some sort of serial format e.g. JSON:
import json
with open("/home/test1_to_write.json", 'w') as outfile:
with open("/home/test1_to_read", 'r') as infile:
data = [int(line.split()[3]) for line in infile]
json.dump(data, outfile)
You can then load the data with:
with open("/home/test1_to_write.json", "r") as infile:
read_data = json.load(infile)
|
How to get the matched string
Question: I am using any() in python
from inActivePhrase import phrase
detailslist=[]
for detail in detailslist:
inactive = any(term in detail for term in phrase)
Where the phrase will have the list of strings like below
phrase = ["not active","Closed",etc..]
The function is working fine. But i want to get the phrase which is present in
the detail.
**Example :**
detail = "this is not active"
inactive = any(term in detail for term in phrase)
if inactive:
print('matched phrase' + term) //how can i do this
in which the "not active" is the matched phrase. So i want to print it.
How can i do that. Can anyone help me ?
Thanks,
Answer: you could have several term matching detail
detail = "this is not active"
inactive = [term for term in phrase if term in detail]
if inactive:
print('matched phrases' + inactive)
|
TypeError when using substring function in Python 3
Question: I wrote a function to open a csv, find max of data in a column & then
substring to take only last 4 digits. It worked very well for almost 2 hours.
But suddenly failing with the error `TypeError: unorderable types: float() >
str()` Relevant code is:
import pandas
mycsvfile = 'filepath'
df = pandas.read_csv(mycsvfile, sep=",", usecols=['ColumnName'])
start_num=int(max(df['ColumnName'])[-4:])+1
Values in the column are of the format XXXX11XX1111 where X's are alphabets &
1's are numerals. I want to extract only last four digits of this field.
What baffles me is that it was working perfectly fine for more than 1000
records & suddenly started failing for no reason. I even deleted records &
started a fresh, still it fails.
Answer: Empty cell in the column caused that issue. Filling it with appropriate value
resolved the issue.
|
gtk : combo of pictures in a treeview
Question: I'm trying to make a combo box of pictures (as bellow) inside a treeview cell
to make a selection.

I tried to use a `cellRendererComboNew` to render the combo but the options to
fill the combobox `cellComboTextModel :=` work only for `String` and I can't
render pictures.
I tried to use a `cellRendererPixbufNew`. It render images but I can't perform
a selection on it.
What is the correct approach to make that?
An example in Haskell, Python, or in any language would be very helpfull.
Best regards.
Answer: In PyGobject I came up with this solution. The example is fully functional but
requires 2 png files in the same directory. I used two pngs with 100 x 20
pixel format.
The previous example used Gtk.ComboBox.new_with_model_and_entry() and I was
missing the set_entry_text_colum() function that has to go with such kind of
combobox.
#!/usr/bin/python3
from gi.repository import Gtk, Gdk, GdkPixbuf
class ComboBoxWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="ComboBox Pixbuf Example")
self.set_border_width(10)
store = Gtk.ListStore(str, GdkPixbuf.Pixbuf)
solid_line = GdkPixbuf.Pixbuf.new_from_file("solid_line.png")
store.append(["1", solid_line])
dashed_line = GdkPixbuf.Pixbuf.new_from_file("dashed_line.png")
store.append(["2", dashed_line])
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
combo = Gtk.ComboBox.new_with_model(store)
rend_int = Gtk.CellRendererText()
rend_pixbuf = Gtk.CellRendererPixbuf()
combo.pack_start(rend_int, False)
combo.add_attribute(rend_int, "text", 0)
combo.pack_start(rend_pixbuf, True)
combo.add_attribute(rend_pixbuf, "pixbuf", 1)
combo.connect("changed", self.on_combo_changed)
vbox.pack_start(combo, False, False, 0)
self.add(vbox)
def on_combo_changed(self, combo):
tree_iter = combo.get_active_iter()
if tree_iter != None:
model = combo.get_model()
row = model[tree_iter][0]
print("Selected row {0}".format(row))
win = ComboBoxWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

Similar question:
* [Show icon or color in Gtk TreeView tree](http://stackoverflow.com/questions/27745585/show-icon-or-color-in-gtk-treeview-tree)
Source:
* <http://python-gtk-3-tutorial.readthedocs.org/en/latest/combobox.html>
|
How to import all imports of another .py file
Question: ### Info
* python version: 3
* development environment: eclipse luna
### Goal
I'm currently developing an addon system for a program. My Idea was to create
a file where I import all addons. This file is generated during the addon
instalation process (when you click the button: install addon). It looks like
that:
import testaddon1
import testaddon2
import bigaddon.startup as bigaddon
When I start my programm I want to import all files/modules to read some
properties and automaticly implement the addons in my program.
### Question
How can I start import statements that are written in a different file.
file1.py
def test():
print('test')
file2.py
import file1.py.test as test
file3.py
#run the import commands from file2.py
test()
console output after running file3.py:
test
### What I want
* an answer on how to achieve the previous result
* a different idea on how to create an addon system
Answer: Yes you can do it.
file.py
def hello():
print('hello')
file2.py
import file
file.hello()
file3.py
from file2 import *
file.hello()
executing file 3. `greg@ja python file3.py`
|
AttributeError: 'Browser' object has no attribute 'manager' when test spynner
Question: I'm trying to use spynner to auto-click some button in the HTML source code as
a small test. But I'm receiving this error. Traceback (most recent call last):
File "build\bdist.win32\egg\spynner\browser.py", line 287, in _on_reply
AttributeError: 'Browser' object has no attribute 'manager'
Below is my code, which is following the guide
here:<https://github.com/makinacorpus/spynner/blob/master/examples/webkit_methods.py>
import spynner
import libxml2
proxy_ip = "xxx.xxx.xxx.xxx";
browser = spynner.Browser()
# setting proxy ip
browser.set_proxy(proxy_ip :'8080');
browser.show()
try:
browser.load(url='http://xxx.html', load_timeout=10, tries=1)
except spynner.SpynnerTimeout:
print 'Timeout.'
else:
browser.wk_click('a[id="voteProjectBtn_10353150"]', wait_load=True)
browser.close()
I'm using Python 2.7, thanks for the help!
Answer: before `browser.close()`, you must distroy the loop javascript, some website
has timming script, so you need distroy these script see the browser.py,
change the method "_manager_create_request" , before `browser.close()`, set
`self.closeflag = True`
def _manager_create_request(self, operation, request, data):
if self.closeflag:
return None
url = unicode(request.url().toString())
operation_name = self._operation_names[operation].upper()
self._debug(INFO, "Request: %s %s" % (operation_name, url))
for h in request.rawHeaderList():
self._debug(DEBUG, " %s: %s" % (h, request.rawHeader(h)))
if self._url_filter:
if self._url_filter(self._operation_names[operation], url) is False:
self._debug(INFO, "URL filtered: %s" % url)
request.setUrl(QUrl("about:blank"))
else:
self._debug(DEBUG, "URL not filtered: %s" % url)
reply = QNetworkAccessManager.createRequest(self.manager,
operation, request, data)
return reply
|
how PYTHONIOENCODING fits with python2
Question: I'm trying to understand how PYTHONIOENCODING environment variable fits with
Python2.7, so I tried the following things with the interactive prompt:
antox@antox-pc ~/Scrivania $ export PYTHONIOENCODING='latin1'
antox@antox-pc ~/Scrivania $ /usr/bin/python2.7
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdin.encoding
'latin1'
>>> sys.stdout.encoding
'latin1'
>>> b = 'ÿ'
>>> b
'\xc3\xbf' #Shouldn't I get something like '\xff' because I set PYTHONIOENCODING to latin1? It looks as if utf-8 is been used instead
>>> print '\xff'
� # Why this odd character? Shouldn't I get 'ÿ' always for the reason above?
My questions/doubts are indicated as comments.
Answer: By setting `PYTHONIOENCODING` in the environment, you're telling Python to
**not** trust your terminal/OS's information regarding the encoding -- you're
saying that you know better, and the terminal device actually accepts that
encoding, not whatever the OS &c will tell Python.
So in this case you're saying that (whatever it claims otherwise) your
terminal actually accepts and properly formats bytes in `latin-1`.
That is probably not the case (if you don't set that environment variable what
does `sys.stdout.encoding` say? `utf-8`, I guess?) so it's not surprising that
you don't get the display you want:-).
On your specific question,
sys.getdefaultencoding()
tells you what encoding Python will use to translate between actual text (that
is, Unicode) and byte strings, in situations where it has no other indication
(I/O to stdin/stdout is not one of those situations, as it uses the `encoding`
attribute of those files).
>>> b = 'ÿ'
This has nothing to do with sys.stdin/stdout -- rather, your terminal is
sending, after the open quote, some "escape sequence" that boils down to
proper utf-8 (my Mac's Terminal app does, for example). If this was in a `.py`
file without a proper source-encoding preamble, it would be a syntax error --
the interactive interpreter has become a softy in 2.7.9:-)
>>> print '\xff'
� # Why this odd character? Shouldn't I get 'ÿ' always for the reason above?
You've told Python that your terminal accepts and properly displays latin-1
byte sequences (even though the terminal probably wants utf-8 ones and tells
Python that, you've told Python to ignore what the terminal says about its
encoding, or rather, what the OS says the terminal says:-).
So the byte of value 255 is sent as-is, and the terminal doesn't like it one
bit (since the terminal doesn't actually accept latin-1!) and displays an
error-marker.
Here's a typical example on my Mac (where the Terminal does actually accept
'utf-8'):
ozone:~ alex$ PYTHONIOENCODING=latin-1 python -c "print u'\xff'"
?
ozone:~ alex$ PYTHONIOENCODING=utf-8 python -c "print u'\xff'"
ÿ
ozone:~ alex$ python -c "print u'\xff'"
ÿ
Letting Python properly detect the terminal encoding on its own, or forcing it
to what happens to be the right one, displays correctly.
Forcing the encoding to one the terminal does **not** in fact accept,
unsurprisingly, does not display correctly.
Should you ever attach to your machine's serial port an ancient teletype which
does in fact accept latin-1 (but the OS doesn't detect that fact properly),
`PYTHONIOENCODING` will help you properly do Python I/O on that ancient
teletype. Otherwise, it's unlikely that said environment setting will be of
much use to you:-).
|
Recieve output from a second Python script that I have called from my first Python script
Question: I tried to look for an answer to this before I posted it, but I'm having
trouble wording it. So, if theres a duplicate question on the site, I
apologise.
I have a Commend Line python script (in this example we'll call it Script 1)
which calls a function from another script (which we'll call Script 2). I do
this by:
import Script2
Script2.Some_Function()
Some_Function does various things, such as connecting to servers on the
internet and performing file look ups. Ordinarily, if one of these tasks
failed, it would print an error stating this to the screen:
def Some_Function():
def error(err):
print "Error: " + err
However, when I know an error should be being printed, I'm not seeing anything
being printed to the screen. I suspect this is because I'm calling it from
Script 1. Is there anything I can do? I really need the output from Script 2
to be printed.
Answer: if your code is exactly like your snippet, it's not likely to work, but first
things first, let's use the correct wording, in python you use the term
`module` to name another python file containing symbols you want to import in
the current (`module`) one.
A script is usually a small piece of code in a high level language that you
run from your command line interface. So as a rule of thumb, a script in
python is where you put `if __name__ == '__main__':`
So I'm renaming your example:
**myscript.py** :
import external_module
external_module.some_function()
**external_module** :
def some_function():
def error(err):
print "Error: " + err
> _However, when I know an error should be being printed, I'm not seeing
> anything being printed to the screen. I suspect this is because I'm calling
> it from Script 1. Is there anything I can do? I really need the output from
> Script 2 to be printed._
now that the code is "cleaned" a bit, when you run your program what is
happening?
python myscript.py
well, nothing, and that's expectable: because you're doing nothing! Let's add
comments:
**myscript.py** :
import external_module # you import the module external_module
external_module.some_function() # you run the function some_function()
# from external_module
in myscript nothing's wrong. But your problem is in external_module:
**external_module** :
def some_function(): # you declare the function some_function
def error(err): # you declare the function error
# that lives only in some_function() scope
print "Error: " + err # in error() you print something out!
so, when you do `external_module.some_function()`, you just _declare_ the
function `error()` and you never run it, which means you never run the `print`
statement. If you forget the `import` aspect, and only do in the python REPL:
>>> def foo():
... def bar():
... print("Hello world?")
...
>>> foo()
>>>
it does nothing! But if you do:
>>> def foo():
... def bar():
... print("Hello World!")
... bar() # here you call the function bar() inside foo()
...
>>> foo()
Hello World!
>>>
you get to run `bar()`!
I hope that my explanation was exhaustive enough!
HTH
|
Windows 7 Heroku Python Django LNK2001 psycopg2 error
Question: I'm following heroku's instructions on how to build a web project using python
and django on windows and haven't been able to figure out my LNK2001 psycopg2
error.
Tutorial links:
* [Link to Heroku's instructions](https://devcenter.heroku.com/articles/getting-started-with-python#introduction)
* [Link to Heroku's link to Python on Windows](http://docs.python-guide.org/en/latest/starting/install/win/)
I am running this command:
$ pip install -r requirements.txt --allow-all-external
Here is the error output:
Creating library build\temp.win32-2.7\Release\psycopg\_psycopg.lib and object build\temp.win32-2.7\Release\psycopg\_psycopg.exp
pqpath.obj : error LNK2019: unresolved external symbol _PQclear referenced in function _pq_raise
connection_int.obj : error LNK2001: unresolved external symbol _PQclear
cursor_type.obj : error LNK2001: unresolved external symbol _PQclear
...
build\lib.win32-2.7\psycopg2\_psycopg.pyd : fatal error LNK1120: 62 unresolved externals
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\BIN\\link.exe' failed with exit status 1120
----------------------------------------
←[31m Command "C:\Python27\python.exe -c "import setuptools, tokenize;__file__='c:\\users\\mariss~1.nie\\appdata\\local\\temp\\pip-build-vojshb\\p
ycopg2\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\
ariss~1.nie\appdata\local\temp\pip-nuj6xa-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\use
s\mariss~1.nie\appdata\local\temp\pip-build-vojshb\psycopg2←[0m
I am using the following:
* Windows 7 64-bit
* Python 2.7.8 32-bit
* Pip
* Virtual Environment (virtualenv)
* PostgreSQL 9.4
* Microsoft Visual Studio 2012 32-bit
I've put `C:\Program
Files\PostgreSQL\9.4\bin;C:\Python27\;C:\Python27\Scripts\` in my PATH
variable.
Thoughts?
Answer: Created a Linux VM and followed the steps again in that environment. Worked
great. No idea why I couldn't get it working in Windows.
|
Python 3.4 pip install
Question: I am trying to install the `xlrd` module on my Mac, however when I open `IDLE`
and import the `xlrd` module, I get the error:
Input Error: No module named xlrd
To install it, I used in my home directory...
sudo pip install xlrd
... and it is installed successfully.
Note that I have both Python 2.7 and Python 3.4.0 on my computer, in case this
is what is causing problems. I want it installed for Python 3.4.0.
Answer: > To avoid conflicts between parallel Python 2 and Python 3 installations,
> only the versioned pip3 and pip3.4 commands are bootstrapped by default
You can try `sudo pip3 install xlrd` or `sudo pip3.4 install xlrd` to use the
Python 3.4, see docs here
<https://docs.python.org/3/whatsnew/3.4.html#bootstrapping-pip-by-default>
|
Python Tkinter- Direct pointer back to Entry() box
Question: When A user inputs a blank string of text I can either pop up a new input box
which looks nasty or, like a webpage, direct the cursor back into the Entry()
box
Unfortunately after searching I am still completely clueless as to how I can
achieve this direction of the cursor.
My code looks like this-
import time
from tkinter import *
root = Tk()
##Encrypt and Decrypt
Master_Key = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#£$%&'()*+,-./:;?@[\\]^_`{|}~\t\n\r\x0b\x0c"
def Encrypt(User_Input, Key):
Output = ""
for i in range(len(User_Input)):
Ref_For_Output = Master_Key.index(User_Input[i]) + Master_Key.index(Key[i])
if Ref_For_Output >= len(Master_Key):
Ref_For_Output -= len(Master_Key)
Output += Master_Key[Ref_For_Output]
return Output
def Decrypt(User_Input, Key):
Output = ""
for i in range(len(User_Input)):
Ref_For_Output = Master_Key.index(User_Input[i]) - Master_Key.index(Key[i])
if Ref_For_Output < 0:
Ref_For_Output += len(Master_Key)
Output += Master_Key[Ref_For_Output]
return Output
##def popup():
## main = Tk()
## Label1 = Label(main, text="Enter a new key: ")
## Label1.grid(row=0, column=0)
## New_Key_Box = Entry(main, bg="grey")
## New_Key_Box.grid(row=1, column=0)
##
## Ok = Button(main, text="OK", command=Set_Key(New_Key_Box.get()))
##
## Ok.grid(row=2, column=0)
## if
## main.geometry("100x300")
## main.mainloop()
## return New_Key_Box.get()
class MyDialog:
def __init__(self, parent):
top = self.top = Toplevel(parent)
Label(top, text="Value").pack()
self.e = Entry(top)
self.e.pack(padx=5)
b = Button(top, text="OK", command=self.ok)
b.pack(pady=5)
def ok(self):
print( "value is" + self.e.get())
return self.e.get()
self.top.destroy()
def Compatibility(User_Input, Key):
while Key == "":
root = Tk()
Button(root, text="Hello!").pack()
root.update()
d = MyDialog(root)
print(d.ok(Key))
root.wait_window(d.top)
Temp = 0
while len(Key) < len(User_Input):
Key += (Key[Temp])
Temp += 1
return Key
##Layout
root.title("A451 CAM2")
root.geometry("270x80")
Label1 = Label(root, text="Input: ")
Label1.grid(row=0, column=0, padx=10)
Label2 = Label(root, text="Key: ")
Label2.grid(row=1, column=0, padx=10)
Input_Box = Entry(root, bg="grey")
Input_Box.grid(row=0, column=1)
Key_Box = Entry(root, bg="grey")
Key_Box.grid(row=1, column=1)
def Encrypt_Button_Press():
User_Input = Input_Box.get()
Key = Compatibility(User_Input, Key_Box.get())
print(User_Input)
root.clipboard_append(Encrypt(User_Input, Key))
Encrypt_Button.configure(text="Encrypting")
messagebox.showinfo("Complete", "Your encrypted text is: \n" + Encrypt(User_Input, Key) + "\n The text has been added to your clipboard.")
Encrypt_Button.configure(text="Encrypt")
#popup()
def Decrypt_Button_Press():
User_Input = Input_Box.get()
Key = Key = Compatibility(User_Input, Key_Box.get())
print(User_Input)
root.clipboard_append(Decrypt(User_Input, Key))
Decrypt_Button.configure(text="Decrypting")
messagebox.showinfo("Complete", "Your Decrypted text is: \n" + Decrypt(User_Input, Key) + "\n The text has been added to your clipboard.")
Decrypt_Button.configure(text="Decrypt")
Encrypt_Button = Button(text="Encrypt", command=Encrypt_Button_Press)
Encrypt_Button.grid(row=0, column=3, padx=10)
Decrypt_Button = Button(text="Decrypt", command=Decrypt_Button_Press)
Decrypt_Button.grid(row=1, column = 3, padx=10)
root.mainloop()
In the compatibility function I am wanting to change the `while Key == "":` to
pop-up a message (that's easy) and to direct the cursor back to the Key_Box( I
may also make it change to red or something)
So- does anyone know how I can achieve redirection of the cursor? Edit:I am
not sure whether this is included anywhere in Tkinter, I can use tab to switch
between Entry() boxes so I assume that they function in roughly the same way
as other entry boxes across different platforms.
Answer: You could call .focus() on the entry? It won't move the cursor, but the user
would be able to just start typing away in the entry box as if they had
clicked in it.
|
Python Web Scraper Using Requests - Not Redirecting Like It Should
Question: So I was bored, and I decided to do some web scraping just for fun and work on
my programming skills. I tried to scrape a more "difficult" site such as
<http://www.aa.com> (American Airlines). I say difficult because it has a
redirect url after you search for a flight.
My current code is:
import requests
from bs4 import BeautifulSoup
req = self.session.get("http://www.aa.com/homePage.do", allow_redirects=True)
cookies = req.cookies
params = {
"originAirport": "JFK",
"destinationAirport": "LAX",
"flightParams.flightDateParams.travelMonth": "3",
"flightParams.flightDateParams.travelDay": "11",
"flightParams.flightDateParams.searchTime": "120001",
"carrierPreference": "F",
"flightSearch": "revenue",
"tripType": "oneWay",
"fromSearchPage": "true",
"searchCategory": "false",
"adultPassengerCount": "1",
"searchType": "matrix"
}
req = self.session.post("http://www.aa.com/reservation/tripSearchSubmit.do;jsessionid=" + str(cookies.get("JSESSIONID")), data=params, allow_redirects=True);
soup = BeautifulSoup(req.text)
print(str(req.history) + "\n" + str(req.url))
print(soup.prettify())
But this isn't working correctly. It just takes me to the loading page but
doesn't redirect to the flight fares page (the req.history array is empty).
Anyone have any ideas on what I am doing wrong?
Answer: `requests` will automatically handle HTTP redirects, but not necessarily other
kinds of redirects. In particular, the page you linked does a Javascript
redirect (and potentially other Javascript behavior). Remember, `requests` is
a library which makes HTTP requests, but it does not implement the full range
of behaviors of a proper web browser (most notably Javascript).
You can special case around this by studying the page contents and
implementing behavior which mirrors the redirect.
To handle this correctly in the general case, you need something with more
awareness of how web browsers work. Most commonly, this would be an actual web
browser driven by an automation library, for example Selenium:
<https://pypi.python.org/pypi/selenium>
|
Attempting to install Portia on OSX or Ubuntu
Question: Could someone help me? I have been over and over installing Portia. All goes
well until I get to the point where I am using the twistd command and I get
this:
(portia)Matts-Mac-mini:slyd matt$ twistd -n slyd Traceback (most> recent call
last): File "/Users/matt/portia/bin/twistd", line 14, in run() File
"/Users/matt/portia/lib/python2.7/site-packages/twisted/scripts/twistd.py",
line 27, in run app.run(runApp, ServerOptions) File
"/Users/matt/portia/lib/python2.7/site-packages/twisted/application/app.py",
line 642, in run runApp(config) File "/Users/matt/portia/lib/python2.7/site-
packages/twisted/scripts/twistd.py", line 23, in runApp
_SomeApplicationRunner(config).run() File
"/Users/matt/portia/lib/python2.7/site-packages/twisted/application/app.py",
line 376, in run self.application = self.createOrGetApplication() File
"/Users/matt/portia/lib/python2.7/site-packages/twisted/application/app.py",
line 436, in createOrGetApplication ser =
plg.makeService(self.config.subOptions) File
"/Users/matt/portia/portia/slyd/slyd/tap.py", line 74, in makeService root =
create_root(config) File "/Users/matt/portia/portia/slyd/slyd/tap.py", line
41, in create_root from .projectspec import create_project_resource File
"/Users/matt/portia/portia/slyd/slyd/projectspec.py", line 5, in from
slybot.validation.schema import get_schema_validator
**ImportError: No module named slybot.validation.schema.**
I also noted that when trying to do the 'pip install -r requirements.txt' even
though I am in the correct directory( [virtualenv-name]/portia/slyd), the
requirements.txt file is not in the slyd directory but in the portia
directory.
I am going crazy here and any help is very much appreciated.
Answer: Looks like There is a mistake in the installation guide.
The guide should be:
virtualenv ENV_NAME --no-site-packages
source ENV_NAME/bin/activate
cd ENV_NAME
git clone https://github.com/scrapinghub/portia.git
cd portia
pip install -r requirements.txt
pip install -e ./slybot
cd slyd
twistd -n slyd
This worked for me. Hopefully it will work for you too.
|
Djano CMS + uWSGI + virtualenv + socket causing PendingDeprecationWarning error in uWSGI logs
Question: Here's the error:
Traceback (most recent call last):
File "/var/apps/tango/envs/tango-env/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 187, in __call__
self.load_middleware()
File "/var/apps/tango/envs/tango-env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 45, in load_middleware
mw_class = import_by_path(middleware_path)
File "/var/apps/tango/envs/tango-env/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 21, in import_by_path
module = import_module(module_path)
File "/var/apps/tango/envs/tango-env/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/var/apps/tango/envs/tango-env/local/lib/python2.7/site-packages/django/middleware/doc.py", line 4, in <module>
warnings.warn(__doc__, PendingDeprecationWarning, stacklevel=2)
TypeError: expected string or buffer
**TypeError: expected string or buffer**
Tango is the user I created specifically for this project.
I'm using upstart so in /etc/init/tango-wsgi.conf looks like:
exec /var/apps/tango/envs/tango-env/bin/uwsgi \
--uid tango \
--home /var/apps/tango/envs/tango-env \
--pythonpath /var/apps/tango/tango/src \
--wsgi-file /var/apps/tango/tango/src/tango_cms/wsgi.py \
--socket /tmp/tango-uwsgi.sock \
--chmod-socket \
--logdate \
--optimize 2 \
--processes 2 \
--master \
--logto /var/apps/tango/logs/uwsgi.log
**UPDATE:**
My nginx.conf has following entry:
location / {
uwsgi_pass unix:/tmp/tango-uwsgi.sock;
include /etc/nginx/uwsgi_params;
}
Please help.
Answer: Same problem here. I fixed it deleting the following line on `tango-wsgi.conf`
file:
`--optimize 2 \`
Optimize allows some kind of python optimization: [More
info](http://stackoverflow.com/questions/4777113/what-does-python-
optimization-o-or-pythonoptimize-do)
|
Is it possible to use win32gui/pywin32 on Ubuntu Linux?
Question: I have a certain software written for Windows invironment and I'm trying to
port it in Linux. It is heavily based on pywin32 (among other two python GUI
libraries like Tkinter and wxPython) and depends on win32gui.
I don't have pywin32 installed on my Ubuntu 12.04.5 LTS system, so I've
downloaded the source and tried to build it, writing:
python setup.py
Consequently, I got:
Traceback (most recent call last):
File "setup.py", line 82, in <module>
import _winreg
ImportError: No module named _winreg
But from what I've read
[here](http://stackoverflow.com/questions/11133506/importerror-while-
importing-winreg-module-of-python/11133611#11133611) for `winreg`, this
library is Windows only.
Does this mean that I can't use win32gui/pywin32 on Linux?
If so, could you suggest some way around it if possible or an alternative
python gui for Linux? I already have in mind Tkinter and wxPython, but I'm not
sure which is best for my case though.
Thanks
Answer: I suggest using one of the two instead of trying to find a way to solve that.
I used Tkinter in Python GUI but it's just my personal preference.
|
Im trying to Send a random number though a email but i keep getting a error
Question: My code is an email code for a generating number to send via email
msg = ('The number is',random.randrange(300,400),'Enjoy')
But I get this error:
Traceback (most recent call last):
line 30, in <module>
server.sendmail(fromaddr, toaddrs, msg)
File "C:\Python34\lib\smtplib.py", line 793, in sendmail
(code, resp) = self.data(msg)
File "C:\Python34\lib\smtplib.py", line 532, in data
q = _quote_periods(msg)
File "C:\Python34\lib\smtplib.py", line 168, in _quote_periods
return re.sub(br'(?m)^\.', b'..', bindata)
File "C:\Python34\lib\re.py", line 175, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
Answer: Your msg is a tuple , you can use `format()` of string to define a msg:
>>> import random
>>> msg = ('The number is',random.randrange(300,400),'Enjoy')
>>> print msg
('The number is', 300, 'Enjoy')
>>> msg = 'The number is {0}, Enjoy'.format(random.randrange(300, 400))
>>> msg
'The number is 325, Enjoy'
|
How can I write a velocity field to a VTI image with anaconda Python?
Question: I am trying to write a VTK Image Data file (.vti) with python. For my python
coding I am using the Anaconda distribution. I am using the evtk package,
which has the ability to write a vtk file.
The data I need to write is a velocity for which I have the 3d X,Y,Z and U,V,W
3d arrays. I have found some sample code which uses the evtk package to write
a .vti file.(<http://www.vtk.org/Wiki/VTK/Writing_VTK_files_using_python>)
The problem is that the sample code and built in functions only take scalar
point or cell data. So I am able to write a file with scalars, but I need it
to have the data as vectors.
I am digging through the actual package files and trying to find a solution or
tools to code one.I would extremely appreciate if somebody had suggestions or
solutions to give me a hand.
I enclose the test code I have written from info on the wiki just in case I am
missing a way of inputing to the function, but I fear I am going to need to
start from scratch.
Thanks in advance
(removed the code since the one bellow is more recent)
Managed to write an unstructured file (.vtu), but I would really like to be a
able to write an Image Data file.(Found the following link helpful during the
process.
<http://www.aero.iitb.ac.in/~prabhu/tmp/python_cep07/course_handouts/viz3d_handout.pdf>)
Thanks again in advance
I attach the code to see if anybody has any suggestions.
from tvtk.api import tvtk, write_data
import numpy as N
##Generation of data
#array of x,y,z coordinates
[Z,Y,X] = N.mgrid[-2.:2+1, -2.:2+1, -2.:2+1]
#array of zeros to add the u,v,w components
[W,V,U] = N.zeros_like([Z,Y,X],dtype=float)
#loop through data to have correct format
points = N.array([N.zeros(3) for i in range(len(Z)*len(Z[0])*len(Z[0][0]))])
velF = N.zeros_like(points)
c=0
for k in range(len(Z)):
for j in range(len(Z[0])):
for i in range(len(Z[0][0])):
#coordinates of point
x = X[k][j][i]
y = Y[k][j][i]
z = Z[k][j][i]
points[c] = N.array([x,y,z])
#test velocity field
u = k -2.
v = 0.
w = 0.
velF[c] = N.array([u,v,w])
#update counter
c = c+1
##Generate and write the vtk file
Ugrid = tvtk.UnstructuredGrid()
Ugrid.points = points
Ugrid.point_data.vectors = velF
Ugrid.point_data.vectors.name = 'velocity'
write_data(Ugrid, 'vtktest.vtu')
Answer: If you want to write the unstructured grids using **evtk** , here you can find
a full demo with point and cell data (both vector and scalar fields):
<https://gist.github.com/dromanov/0fb8bacff5342a56a690>.
Description of the technique and explanations are here:
<http://spikard.blogspot.ru/2015/07/visualization-of-unstructured-grid-
data.html>.
Good luck!
|
Python pickle: Unclear "AttributeError: can't set attribute"
Question: While using `pickle.load(...)`, there's a possibility that `AttributeError:
can't set attribute` is raised. However on a bigger pickle file this error
doesn't help at all (because I have no idea what causes it).
Are there any ways to get more information or to debug this? If there are any
other advices how to deal with this problem, I would be glad to hear them!
* * *
The error originally comes from
[Jedi's](https://github.com/davidhalter/jedi/blob/parser/jedi/cache.py#L272)
parser branch. The issue is caused by the latest changes in
`jedi.parser.fast`. If you want to see the error, you need to run `python
test/run.py on_import 100` twice.
* * *
## Edit - Cause:
>>> X.y = 3
>>> class X():
... @property
... def y(self): pass
...
>>> X().y = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
The cause is this AttributeError that gives you no information. Combine that
with an inheritance of `__slots__` and properties in the inherited object +
pickle and you get this unclear error.
I still think that it's pickle's fault. I'm going to leave this question open,
because I still haven't found a way to debug it properly. Pickle should take
that `AttributeError` and modify it.
Answer: `dill` has pickle debugging tools in `dill.detect`. I can't see what object
you'd like to debug as your code above is not due to `pickle`… but I can show
an example below, regardless.
>>> class Test(object):
... def __init__(self, x, y):
... self.x = x
... self.y = y
...
>>> x = (i for i in range(10))
>>> y = iter(range(10))
>>>
>>> t = Test(x,y)
>>>
>>> import dill
>>> dill.detect.errors(t)
PicklingError("Can't pickle <type 'listiterator'>: it's not found as __builtin__.listiterator",)
>>> dill.detect.badobjects(t)
<__main__.Test object at 0x1086970d0>
>>> dill.detect.badobjects(t, 1)
{'__hash__': <method-wrapper '__hash__' of Test object at 0x1086970d0>, '__setattr__': <method-wrapper '__setattr__' of Test object at 0x1086970d0>, '__reduce_ex__': <built-in method __reduce_ex__ of Test object at 0x1086970d0>, 'y': <listiterator object at 0x108890d50>, '__reduce__': <built-in method __reduce__ of Test object at 0x1086970d0>, '__str__': <method-wrapper '__str__' of Test object at 0x1086970d0>, '__format__': <built-in method __format__ of Test object at 0x1086970d0>, '__getattribute__': <method-wrapper '__getattribute__' of Test object at 0x1086970d0>, '__delattr__': <method-wrapper '__delattr__' of Test object at 0x1086970d0>, '__repr__': <method-wrapper '__repr__' of Test object at 0x1086970d0>, '__dict__': {'y': <listiterator object at 0x108890d50>, 'x': <generator object <genexpr> at 0x108671f50>}, 'x': <generator object <genexpr> at 0x108671f50>, '__sizeof__': <built-in method __sizeof__ of Test object at 0x1086970d0>, '__init__': <bound method Test.__init__ of <__main__.Test object at 0x1086970d0>>}
>>> dill.detect.trace(True)
>>> dill.dumps(t)
T2: <class '__main__.Test'>
F2: <function _create_type at 0x10945c410>
T1: <type 'type'>
F2: <function _load_type at 0x10945c398>
T1: <type 'object'>
D2: <dict object at 0x10948b7f8>
F1: <function __init__ at 0x108894938>
F2: <function _create_function at 0x10945c488>
Co: <code object __init__ at 0x108873830, file "<stdin>", line 2>
F2: <function _unmarshal at 0x10945c320>
D1: <dict object at 0x1085b9168>
D2: <dict object at 0x10947e910>
D2: <dict object at 0x108898910>
T4: <type 'listiterator'>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
#...snip...
pickle.PicklingError: Can't pickle <type 'listiterator'>: it's not found as __builtin__.listiterator
>>>
I couldn't think of a case where there's an `AssertionError` from a
`pickle.dump` off the top of my head... but the above debugging tools should
work exactly the same way in that case.
If you post a simple reproducible object (i.e. standard lib preferably) that
produces an AttributeError on pickling, I'll update my example.
|
python heroku syncdb error
Question: Disclosure: I have no idea what im doing.
I'm getting the following error. Could not import settings
'mvp_landing.settings' (Is it on sys.path? Is there an import error in the
settings file?): No module named dj_database_url
I've looked up this answer and most lead to looking at sys.path files and
putting the settings file into one of these paths.
/Library/Python/2.7/site-packages/pip-1.5.6-py2.7.egg
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC
/Library/Python/2.7/site-packages
^^ I have no idea where these are located or how to move my settings file into
one of these paths.
Answer: Install the `dj_database_url` module using `pip`
|
How to import lib folder within Modules
Question: I had a GAE app which contains three Modules and a lib folder. When I tried to
import the 3rd party library from the lib folder. GAE pops a ImportError.
I could get it to work by symlinking ./lib to ./Module_1/lib and
./Module_2/lib and also creating a appengine_config.py in each of the modules.
But doing this seemed really dirty.
Is there a cleaner way to import app_root/lib from module_1 and module_2?
This seemed to be
promising(<https://cloud.google.com/appengine/docs/python/config/appconfig#Python_app_yaml_Includes>),
but don't know what to put inside include.yaml.
-- App Root/
-- Module_1/
module_1.yaml
module_1.py
-- Module_2/
module_2.yaml
module_2.py
-- lib/
-- cloudstorage/
..
-- 3rd_library_1/
..
..
-- 3rd_library_2/
..
..
appengine_config.py
main.py (default module)
app.yaml(default module)
queue.yaml
dispatch.yaml
In module_1.py or module_2.py, when I do
import cloudstorage as gcs
It complains
ImportError: No module named cloudstorage
However, when it's being imported within main.py, it works fine.
In the appengine_config.py:
import os
import sys
# Add ./lib to sys path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib'))
Also tried to print sys.path from main.py:
sys.path in main.py :
[
'/base/data/home/apps/s~my-app/2.381942946570489905',
'/base/data/home/apps/s~my-app/2.381942946570489905/lib',
...
...
]
sys.path in module_1.py:
[
'/base/data/home/apps/s~my-app/module_1:2.381942955973772449',
'/base/data/home/runtimes/python27/python27_dist/lib/python27.zip',
...
...
]
Answer: Credit goes to Google Cloud Platform Tech Solutions Representative Adam:
> Modules documentations may not be explicitly stated, but the folder
> 'Module1', 'Module2' as well as the default module actually run inside
> separate Python virtual environments on separate instances and need to be
> self contained. They cannot 'see' any directories above them which exist on
> the local filesystem, and 'default.py' can't see anything in each of the
> module directories. The whole folder tree isn't copied to each module
> instance.
He suggested that instead of making symlinks, just copy ./lib to each of the
modules.
I do not like the idea very much.
Firstly, these modules share some base class, duplicating them is really an
anti-pattern.
Secondly, copying the lib folders everywhere corrupts unit tests as nose will
try to run all unit tests it can run, also because it's a pain to explicitly
exclude the directories.
At the end of the day, I wrote a makefile to help deployment / testing
easier...
# Create simlinks before deployment.
deploy: mksimlnks
appcfg.py --oauth2 update $(CURDIR)/app.yaml
appcfg.py --oauth2 update $(CURDIR)/MODULE_1/module_1.yaml
appcfg.py --oauth2 update $(CURDIR)/MODULE_2/module_2.yaml
appcfg.py --oauth2 update_queues $(CURDIR)
mksimlnks:
ln -s $(CURDIR)/lib $(CURDIR)/MODULE_1/lib
ln -s $(CURDIR)/lib $(CURDIR)/MODULE_2/lib
# Need to remove symlinks before unittest
# or unit test will explode.
test: rmsimlnks
nosetests --exclude-dir=lib --with-gae -w $(CURDIR) --with-coverage --cover-html
# Remove all symlinks
rmsimlnks:
rm -rf $(shell find * -type l)
# remove symlinks and other stuff
clean: rmsimlnks
rm -f $(shell find * -name *.pyc)
rm -f $(shell find * -name .DS_Store)
rm -f .coverage
rm -rf $(CURDIR)/cover
|
Itertools Zip Two List into each other
Question:
c = list(itertools.chain.from_iterable(zip(list_a, list_b)))
I have two list `list_a` and `list_b`
`list_a` has one more element than `list_b` and i want to insert between two
elements of a one element of b.
Unfortunately this method from above deletes the last element of `list_a` in
the result list c. How can i fix this? Python 2.7
Answer: I don't know enough about `itertools` to say much more, but if you only need
to append the last element of `list_a` to `c`, why not do just that?
import itertools
list_a = [1,3,5,7,9]
list_b = [2,4,6,8]
c = list(itertools.chain.from_iterable(zip(list_a, list_b)))
# c is [1, 2, 3, 4, 5, 6, 7, 8]
c.append(list_a[-1])
# after append c is [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
Issue Converting Matlab Code to Python when trying to sum array
Question: I am converting a Matlab code to Python but facing an issue in below lines:
Code:
Matlab:
P_asef_t = sum(P_asef);
P_aseb_t = sum(P_aseb);
Python:
import numpy as np
import scipy
P_asef_t = np.sum(P_asef)
P_aseb_t = np.sum(P_aseb)
Matlab
whos P_asef
Variables in the current scope:
Attr Name Size Bytes Class
==== ==== ==== ===== =====
P_asef 51x1200 489600 double
Total is 61200 elements using 489600 bytes
And in Python:
(Pdb) P_asef.shape, P_asef.size
((51, 1200), 61200)
But variable **P_asef_t** comparatively is coming completely incorrect:
MATLAB:
debug> whos P_asef_t
Variables in the current scope:
Attr Name Size Bytes Class
==== ==== ==== ===== =====
P_asef_t 1x1200 9600 double
Total is 1200 elements using 9600 bytes
debug> P_asef_t
P_asef_t =
Columns 1 through 6:
1.2208e-11 9.9358e-03 9.8720e-03 9.8087e-03 9.7457e-03 9.6831e-03
Columns 7 through 12:
9.6210e-03 9.5592e-03 9.4978e-03 9.4368e-03 9.3762e-03 9.3160e-03
Columns 13 through 18:
Python:
(Pdb) P_asef_t
1.3898510532602344
(Pdb) P_asef_t.shape, P_asef_t.size
((), 1)
(Pdb)
How can I fix this issue?
Answer: Numpy's
[sum](http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html)
function takes an additional argument `axis`, that defines over which axis of
the array is summed. The problem here is that is defaults to summing over all
axes.
In the case of a matrix such as `P_asef` you have two axes. The 0th axis are
the columns and the 1st are the rows. If you only want to sum along columns,
you need to tell `sum` to only sum over `axis=0`.
import numpy as np
mat = np.ones((51,1200))
mat1 = np.sum(mat,axis=0)
mat2 = np.sum(mat,axis=1)
mat3 = np.sum(mat)
|
Porting Python 2 code that uses _multiprocessing
Question: I'm currently porting some Python 2 code that was being run with pypy over to
python 3. I'm a bit stuck with dealing with some code that uses
`_multiprocessing` as the documentation is hard to find for this.
from _multiprocessing import address_of_buffer
#example usage
def buffer_info(self):
return address_of_buffer(self._mmap)[0], self._size
When I attempt to use this code into Python3.4 I get a problem with the
import:
ImportError: cannot import name 'address_of_buffer'
After having a quick look at the Python 3 docs
<https://docs.python.org/3/library/multiprocessing.html> I'm not seeing a
direct replacement for this. What is the best way to port this code?
Answer: You can use ctypes:
def address_of_buffer(buf):
return ctypes.addressof(ctypes.c_char.from_buffer(buf))
|
Python regEx to find positions of xml data
Question: I want to extract the position of XML data with python regEx or using any
other method and the data part can be numbers, words,ip or any tags.
PUT /mg/co.xml HTTP/1.1
Host: 19.16.7.59
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gehko/20100101 Firefox/31.0
<?xml version="1.0" encoding="UTF-8"?>
<!-- THIS DATA SUBJECT TO DISCLAIMER(S) INCLUDED WITH THE PRODUCT OF ORIGIN. -->
<io:zzzz xmlns:io="http://kfj/ledm/iomgmt/2008/11/30" xmlns:dd="http://jkfhkj/dictionaries/1.0/" xmlns:dd3="http://jfja/dictionaries/2009/04/06" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jcjhjk/ledm/iomgmt/2008/11/30 ../../schemas/gfjbj.xsd">
<io:aaaa>
<dd3:bbbb>hjgjg</dd3:bbbb>
</io:aaaa>
<io:ccccc>
<io:dddd>
<dd3:ffff>15.34.2.5</dd3:ffff>
</io:dddd>
<io:eeee>
<dd3:gggg>67</dd3:gggg>
</io:eeee>
<io:iiii>
<dd3:jjjj><script>jgfjkgkj</script></dd3:jjjj>
</io:iiii>
</io:cccc>
</io:zzzz>
**Expected Output:**
(the data given below are approximate positions)
hjgjg [start off = 59, end off= 64]
15.43.2.5 [start off= 74, end off= 84]
67 [start offset=95, end off=97]
<script>jghjhdjk</script>[ start offset=102, end off=124]
Can anybody please help me sorting out this?
Answer: You should not parse xml with python re as it may fail anytime.Regex is too
lame to understand the specifics of xml.Still if you dont get any other
alternative try this.
^(?=\s*<dd3:[^>]*>).*?>([^< ]+)<
See demo.
<https://regex101.com/r/vD5iH9/40>
import re
p = re.compile(r'^(?=\s*<dd3:[^>]*>).*?>([^< ]+)<', re.MULTILINE)
test_str = "PUT /mg/co.xml HTTP/1.1\nHost: 19.16.7.59\nUser-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gehko/20100101 Firefox/31.0\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- THIS DATA SUBJECT TO DISCLAIMER(S) INCLUDED WITH THE PRODUCT OF ORIGIN. -->\n<io:zzzz xmlns:io=\"http://kfj/ledm/iomgmt/2008/11/30\" xmlns:dd=\"http://jkfhkj/dictionaries/1.0/\" xmlns:dd3=\"http://jfja/dictionaries/2009/04/06\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://jcjhjk/ledm/iomgmt/2008/11/30 ../../schemas/gfjbj.xsd\">\n <io:aaaa>\n <dd3:bbbb>hjgjg</dd3:bbbb>\n </io:aaaa>\n <io:ccccc>\n <io:dddd>\n <dd3:ffff>15.34.2.5</dd3:ffff>\n </io:dddd>\n <io:eeee>\n <dd3:gggg>67</dd3:gggg>\n </io:eeee>\n <io:iiii>\n <dd3:jjjj><script>jgfjkgkj</script></dd3:jjjj>\n </io:iiii>\n </io:cccc>\n</io:zzzz>"
re.findall(p, test_str)
|
Write a list in a python csv file, one new row per list
Question: I have the following source code, where I am trying to write a list in a csv
file. I need every new list to be written in a new line of this csv file. The
source code is the following:
import csv
list1=[55,100,'dir1/dir2/dir3/file.txt',0.8]
resultFile = open("output.csv",'wa')
wr = csv.writer(resultFile, dialect='excel')
wr.writerow(list1)
resultFile.close()
The problem is that it doesn't insert list1 in a newline every time i run the
code.
In matlab that would be easy, I just need to use dlmwrite with '-append'
parameter.
But how to do this in Python?
Answer: Open file in append mode.
import csv
list1=[58,100,'dir1/dir2/dir3/file.txt',0.8]
with open("output.csv", "a") as fp:
wr = csv.writer(fp, dialect='excel')
wr.writerow(list1)
* * *
More on file [open
modes](https://docs.python.org/2/library/functions.html#open)
try following:-
>>> with open('test1','wb') as f: f.write('test')
...
>>> with open('test1','ab') as f: f.write('koko')
...
>>> with open('test1','rb') as f: f.read()
...
'testkoko'
>>> with open('test1','wa') as f: f.write('coco')
...
>>> with open('test1','rb') as f: f.read()
...
'coco'
>>>
* * *
From this [link](http://www.tutorialspoint.com/python/python_files_io.htm)
**Modes** : Description
1. **r** : Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
2. **rb** : Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
3. **r+** : Opens a file for both reading and writing. The file pointer will be at the beginning of the file.
4. **rb+** : Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.
5. **w** : Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
6. **wb** : Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
7. **w+** : Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
8. **wb+** : Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
9. **a** : Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
10. **ab** : Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
11. **a+** : Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
12. **ab+** : Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
|
Unable to create file system object in wmi using python
Question: I connected to remote windows server using `wmi`. I want to create filesystem
object to extract file version of file on remote server.
My code goes like this:
# mc_name-machine name, login_machine() to login
c = login_machine(mc_name)
print "logged-in"
# erroneous line.
fo = c.win32com.client.Dispatch('Scripting.filesystemobject')
# path=path of file on remote machine
print fo.GetFileVersion(path)
Help will be greatly appreciated.
For the erroneous line in above code error thrown:
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\wmi.py", line 1145, in __getattr__
return self._cached_classes (attribute)
File "C:\Python34\lib\site-packages\wmi.py", line 1156, in _cached_classes
self._classes_map[class_name] = _wmi_class (self, self._namespace.Get (class_name))
File "<COMObject <unknown>>", line 3, in Get
File "C:\Python34\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'SWbemServicesEx', 'Not found ', None, 0, -2147217406), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
fo=c.win32com.client.Dispatch('Scripting.filesystemobject')
File "C:\Python34\lib\site-packages\wmi.py", line 1147, in __getattr__
return getattr (self._namespace, attribute)
File "C:\Python34\lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.win32com
I was trying to solve this by using **`ProvideConstants`**. Code for same
fo = win32com.client.Dispatch('Scripting.filesystemobject')
foo=ProvideConstants(fo)
I'm not sure how to use this wmi.ProvideConstants object to get file version.
Answer: I was able to query the version of a remote file with this code:
c = wmi.WMI('computer', user='domain\\user', password='pass')
result = c.query('SELECT * FROM CIM_DataFile WHERE Name = "C:\\path\to\file"')
for file in result:
print file.Version
_Update_ : To get the LastModifed time as a python
[`datetime`](https://docs.python.org/2/library/datetime.html#datetime-objects)
object, and print it out in `dd/mm/yyyy` format:
from datetime import datetime
last_modified = datetime(*wmi.to_time(file.LastModified)[:7])
print last_modified.strftime("%d/%m/%Y")
|
Can someone explain how Python's subprocess module communicates with Command Prompt?
Question: I am very new to programming and have been pouring over this site and others
to better understand how I can write a script in Python (version 3.4.1) that
does what I already know how to do in Command Prompt (version 6.3.9600).
In Command Prompt I can very easily type this (after the ">"):
Z:\input\convertToRinex.exe Z:\input\74390010.T01
And everything works perfectly. The .T01 file is converted and the resulting
files appear in the input folder.
In Python I have no idea what I am doing. I've tried this:
from subprocess import *
call(['Z:\input\convertToRinex.exe', 'Z:\input\74390010.T01'])
And I get this error
Error: CtrimbleFile - unable to open file:Z:\psm_rinex\inputU90010.T01Open
In a window that says Z:\input\convertToRinex.exe at the top. It happens so
fast that I had to use a screen recorder to read the error message.
I thought the list from Python would be translated into the exact same syntax
that already works in Command Prompt and the same thing would happen.
I am clearly missing something. Any advice would be greatly appreciated.
Answer: You need to escape the `\`, use forward slashes or use raw string `r`:
'Z:\\input\\74390010.T01' # double \
'Z:/input/74390010.T01' # forward /
r'Z:\input\74390010.T01' # raw string
In [7]: print('Z:\input\74390010.T01')
Z:\inputǣ90010.T01
In [8]: print(r'Z:\input\74390010.T01')
Z:\input\74390010.T01
`\` is used to
[escape](https://docs.python.org/2/reference/lexical_analysis.html#string-
literals) characters
|
Splines with Python (using control knots and endpoints)
Question: I'm trying to do something like the following (image extracted from wikipedia)

#!/usr/bin/env python
from scipy import interpolate
import numpy as np
import matplotlib.pyplot as plt
# sampling
x = np.linspace(0, 10, 10)
y = np.sin(x)
# spline trough all the sampled points
tck = interpolate.splrep(x, y)
x2 = np.linspace(0, 10, 200)
y2 = interpolate.splev(x2, tck)
# spline with all the middle points as knots (not working yet)
# knots = x[1:-1] # it should be something like this
knots = np.array([x[1]]) # not working with above line and just seeing what this line does
weights = np.concatenate(([1],np.ones(x.shape[0]-2)*.01,[1]))
tck = interpolate.splrep(x, y, t=knots, w=weights)
x3 = np.linspace(0, 10, 200)
y3 = interpolate.splev(x2, tck)
# plot
plt.plot(x, y, 'go', x2, y2, 'b', x3, y3,'r')
plt.show()
The first part of the code is the code extracted from [the main
reference](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.splrep.html)
but it's not explained how to use the points as control knots.
The result of this code is the following image.

The points are the samples, the blue line is the spline taking into account
all the points. And the red line is the one that is not working for me. I'm
trying to take into account **all the intermediate points as control knots**
but I just can't. If I try to use `knots=x[1:-1]` it just doesn't work. I'd
appreciate any help.
**Question in short** : how do I use all the intermediate points as control
knots in the spline function?
Note: this last image is exactly what I need, and it's the difference between
what I have (spline passing all the points) and what I need (spline with
control knots). Any ideas? 
Answer: In this IPython Notebook
<http://nbviewer.ipython.org/github/empet/geom_modeling/blob/master/FP-Bezier-
Bspline.ipynb> you can find a detailed description of data involved in
generating a B-spline curve, as well as the Python implementation of the de
Boor algorithm.
|
How can I find Time Zone Database version when using `arrow` or `dateutil`?
Question: I am using `arrow` module for Python for time zone manipulations. As far as I
understand it, it relies on `dateutil` module for time zone information.
`dateutil` claims:
> Internal up-to-date world timezone information based on Olson's database.
I have only found `c:\Python34\Lib\site-packages\dateutil\zoneinfo\dateutil-
zoneinfo.tar.gz` which seems to be used. I have deducted that it is downloaded
from <http://www.iana.org/time-zones>, however it still does not give any
hints what version of the database it is.
Is there a way to find what version of Olson's database is being used by
`arrow` module?
Answer: Yes, arrow depends on dateutil for tz data.
Unfortunately, dateutil doesn't keep the tzdb version number when it builds
its data file, so it is not available at run time.
Walking through [the dateutil source
code](https://github.com/dateutil/dateutil):
* The version number can be seen in `tzdata_file` in [zonefile_metadata.json](https://github.com/dateutil/dateutil/blob/master/zonefile_metadata.json).
* In [updatezinfo.py](https://github.com/dateutil/dateutil/blob/master/updatezinfo.py), the filename is passed from the metadata into the `rebuild` function,
* In [the `rebuild` function](https://github.com/dateutil/dateutil/blob/2.4.0/dateutil/zoneinfo/__init__.py#L79-L108), you can see that the data from the file is loaded, but the filename itself is not retained, nor is the `VERSION` constant read from [the tzdata makefile](https://github.com/eggert/tz/blob/master/Makefile#L8).
If this feature is important to you, I suggest opening a feature request in
[the dateutil issue tracker](https://github.com/dateutil/dateutil/issues).
|
How to pick up the elements has similar name in a list?
Question: I have a list:
['15g', 'engout', 'ImpactTphase.py', 'LANL.INI', 'OUTGRAF.TXT', 'OUTPAR.TXT', 'par.bat', 'pargraf1.BAT', 'parphase.py', 'RFFLD000.TBL', 'RFFLD010.TBL', 'sp4.acc', 'Tablplot.log', 'tape2.t2', 'tape3.t3', 'TIMESTEPEMITTANCE185.TBL', 'TIMESTEPEMITTANCE190.TBL', 'TIMESTEPEMITTANCE195.TBL', 'TIMESTEPEMITTANCE200.TBL', 'TIMESTEPEMITTANCE205.TBL', 'TIMESTEPEMITTANCE210.TBL', 'TIMESTEPEMITTANCE215.TBL', 'TIMESTEPEMITTANCE220.TBL', 'TIMESTEPEMITTANCE225.TBL', 'TIMESTEPEMITTANCE230.TBL', 'TIMESTEPEMITTANCE235.TBL', 'TIMESTEPEMITTANCE240.TBL', 'TplotPRF.TXT']
In python, how could I pick up the elements has `TIMESTEPEMITTANCE???.TBL`.
Also how I can separate "TIMESTEPEMITTANCE???" into "TIMESTEPEMITTANCE"and
"???"? THanks,
Answer: You can use
[`fnmatch.fnmatch`](https://docs.python.org/3/library/fnmatch.html#fnmatch.fnmatch):
>>> lst = [
'15g', 'engout', 'ImpactTphase.py', 'LANL.INI', 'OUTGRAF.TXT', 'OUTPAR.TXT',
'par.bat', 'pargraf1.BAT', 'parphase.py', 'RFFLD000.TBL', 'RFFLD010.TBL',
'sp4.acc', 'Tablplot.log', 'tape2.t2', 'tape3.t3', 'TIMESTEPEMITTANCE185.TBL',
'TIMESTEPEMITTANCE190.TBL', 'TIMESTEPEMITTANCE195.TBL', 'TIMESTEPEMITTANCE200.TBL',
'TIMESTEPEMITTANCE205.TBL', 'TIMESTEPEMITTANCE210.TBL', 'TIMESTEPEMITTANCE215.TBL',
'TIMESTEPEMITTANCE220.TBL', 'TIMESTEPEMITTANCE225.TBL', 'TIMESTEPEMITTANCE230.TBL',
'TIMESTEPEMITTANCE235.TBL', 'TIMESTEPEMITTANCE240.TBL', 'TplotPRF.TXT'
]
>>> import fnmatch
>>> [x for x in lst if fnmatch.fnmatch(x, 'TIMESTEPEMITTANCE???.TBL')]
['TIMESTEPEMITTANCE185.TBL',
'TIMESTEPEMITTANCE190.TBL',
'TIMESTEPEMITTANCE195.TBL',
'TIMESTEPEMITTANCE200.TBL',
'TIMESTEPEMITTANCE205.TBL',
'TIMESTEPEMITTANCE210.TBL',
'TIMESTEPEMITTANCE215.TBL',
'TIMESTEPEMITTANCE220.TBL',
'TIMESTEPEMITTANCE225.TBL',
'TIMESTEPEMITTANCE230.TBL',
'TIMESTEPEMITTANCE235.TBL',
'TIMESTEPEMITTANCE240.TBL']
For the second question, if you mean to extract digits part out of the string:
You can use the string slice because the pattern is fixed:
>>> 'TIMESTEPEMITTANCE185.TBL'[17:20]
'185'
or, you can use
[`filter`](https://docs.python.org/3/library/functions.html#filter) with
[`str.isdigit`](https://docs.python.org/3/library/stdtypes.html#str.isdigit)
(`''.join` is not required if you use Python 2.x)
>>> ''.join(filter(str.isdigit, 'TIMESTEPEMITTANCE185.TBL'))
'185'
or, using regular expression:
>>> import re
>>> re.search(r'\d+', 'TIMESTEPEMITTANCE185.TBL').group()
'185'
|
python function capitalize first letter only
Question: I need build a function to transform 1st character only, from any word but
also this function need address the problem if the 1st character from the word
doesn't starts with a character, for example '_sun',' -tree', '2cat' these
words need be like _Sun, -Tree, 2Cat. This is what I have so far, it can
convert any word but I don't know how do 2nd part, need use ASCII?? to get
value of 1st character and see if the word starts with character?
def convert(capital):
return capital[0].upper() + capital[1:]
def main():
print(convert('sun'))
main()
Answer: One option is to use a regex and limit it to 1 replacement, eg:
>>> import re
>>> re.sub('[a-zA-Z]', lambda m: m.group().upper(), '2cat', 1)
'2Cat'
>>> re.sub('[a-zA-Z]', lambda m: m.group().upper(), 'sun', 1)
'Sun'
|
Data normalization with Python
Question: This is a sample of a csv file that will eventually be loaded to a MySQL
database. The issue is that the data is not normalized, as there are multiple
values in the `routes` column.
stop_id,on_street,cross_street,routes,boardings
49,HARRISON,PAULINA,"126, 755",1.6
50,ASHLAND,CONGRESS,"9,126",14.8
51,ASHLAND,VAN BUREN,"9,126",100.9
52,JACKSON,1900 W.(MALCOLM X COLL.),126,82.8
I would like to extract the `routes` column into a new csv file with `stop_id`
and `route` as the column headers and there be only 1 route per row. I've
already tried to import the un-normalized csv into a MySQL database but was
unable to pragmatically normalize it. Any help doing this in Python before
importing to the database would be greatly appreciated.
Answer: This will create one row per route. You can fiddle with the inner for loop if
you want all routes in one row.
import csv
import re
sample = """stop_id,on_street,cross_street,routes,boardings
49,HARRISON,PAULINA,"126, 755",1.6
50,ASHLAND,CONGRESS,"9,126",14.8
51,ASHLAND,VAN BUREN,"9,126",100.9
52,JACKSON,1900 W.(MALCOLM X COLL.),126,82.8"""
open('sample.csv','w').write(sample)
with open('sample.csv') as sample, open('output.csv','w') as output:
reader = csv.reader(sample)
writer = csv.writer(output)
# discard input header
next(reader)
# write output header
writer.writerow(['stop_id', 'route'])
# process rows
for row in reader:
if row:
for route in re.split(r', *', row[3].replace('"', '')):
writer.writerow([row[0], route])
print open('output.csv').read()
|
Binary .dat file Plotting Column Array values
Question: I have imported an array into my IPython notebook using the following method:
SDSS_local_AGN = np.fromfile('/Users/iMacHome/Downloads/SDSS_local_AGN_Spectra.dat', dtype=float)
The array is of the form:
SPECOBJID_1 RA DEC SUBCLASS ...
299528159882143744 146.29988 -0.12001413 AGN ...
299532283050747904 146.32957 -0.30622363 AGN ...
Essentially each column has a header, and I now need to plot certain values.
As an example, I want to plot RA against DEC...how would I go about doing
this?
Perhaps:
axScatter.plot(SDSS_local_AGN[RA], SDSS_local_AGN[DEC])
Answer: ## Answer is mistaken, see comments
If you want to access them via name, you should use pandas instead of numpy.
In numpy, you need to lookup by index:
plt.scatter(SDSS_local_AGN[1], SDSS_local_AGN[2])
But in pandas, it would be as simple as:
df = read_csv('myfile')
df.plot(kind='scatter', x='RA', y='DEC')
<http://pandas.pydata.org/pandas-
docs/version/0.15.0/visualization.html#scatter-plot>
`SDSS_local_AGN['RA']` is a valid operation in pandas, but not in `numpy`.
PS, since you are working in a Notebook, pandas DataFrames will nicely render
as HTML tables, making them much more readable.
|
How to extract lines from two textfiles linked by heading number from the 1st 10 characters?
Question: I have two files:
**file1.txt** :
0000001435 XYZ 与 ABC
0000001438warlaugh 世界
**file1.txt** :
0000001435 XYZ with abc
0000001436 DFC whatever
0000001437 FBFBBBF
0000001438 world of warlaugh
The lines in the separated file are linked by the number (1st 10 characters).
The desired output is a tab separated file with lines that exists and
`file1.txt` and the corresponding lines from `file2.txt`:
**file3.txt** :
XYZ 与 ABC XYZ with abc
warlaugh 世界 world of warlaugh
**How do I get the corresponding lines and then create a tab separated file
with lines that exists in`file1.txt` to produce `file3.txt`?**
**Note that only the first 10 character constitutes as the ID.** , there are
cases like `0000001438warlaugh 世界` or even `0000001432231hahaha lol` and only
the `0000001438` and `0000001432` is the ID.
I tried with python, **getfile3.py** :
import io
f1 = {line[:10]:line[10:].strip() for line in io.open('file1.txt', 'r', encoding='utf8')}
f2 = {line[:10]:line[10:].strip() for line in io.open('file1.txt', 'r', encoding='utf8')}
f3 = io.open('file3.txt', 'w', encoding='utf8')
for i in f1:
f3.write(u"{}\t{}\n".format(f1[i], f2[i]))
But is there a bash/awk/grep/perl command-line way that i can get `file3.txt`?
Answer:
awk '
{ key = substr($0,1,10); data = substr($0,11) }
NR==FNR { file1[key] = data; next }
key in file1 { print file1[key] data }
' file1 file2
You could use FIELDWIDTHS with GNU awk rather than substr() if you prefer.
|
Add extra arguments to side_effects in python Mock
Question:
from unittest.mock import patch
def get_title():
return 'title'
def get_msg():
return 'msg'
def do_log(title, msg):
sys.stderr.write(get_title(),
get_msg())
return
def myfunction():
title = get_title()
msg = get_msg()
do_log(title, msg)
def my_new_do_log(*args, **kwargs):
'''
we know, args = title, msg
But I want add EXTRA arguments,
like handler (from caller / from controller)
'''
sys.stderr.write(get_title(),
get_msg(),
handler.get_author_from_handler()
)
# Note: handler is argument from controller!
@patch('do_log')
def controller(handler, mock_do_log):
mock_do_log.side_effect = my_new_do_log
myfunction()
if __name__ == '__main__':
controller(handler)
So how pass "handler" (a extra argument) to my_new_do_log?
if i try something like:
mock_do_log.side_effect = my_new_do_log(handler)
I lost arguments from my context manager (title and msg). Is it possible
append extra arguments to context manager.
Answer: You can define a new callable in `controller()` and use it as side effect. The
simple and neat way to do it is to use `lambda` function:
@patch('do_log')
def controller(handler, mock_do_log):
mock_do_log.side_effect = lambda *args,**kwargs:my_new_do_log(handler,*args,**kwargs)
myfunction()
where `my_new_do_log()` signature become
def my_new_do_log(handler, *args, **kwargs):
....
You can either define a new explicit function to do it
@patch('do_log')
def controller(handler, mock_do_log):
def handler_log(*args,**kwargs):
my_new_do_log(handler,*args,**kwargs)
mock_do_log.side_effect = handler_log
myfunction()
But my taste is for the `lambda` version.
* * *
The question about context manager is little bit confused : you don't have any
context manager in your example but just a patch decorator that behave like
context manager. Anyway I think you can iterate my suggestion to take in
account how many arguments you want.
|
How to retrieve Auction-Time with Beautifulsoup Python
Question: I'm trying to retrieve the timer on the next auction site to make a Sniper:
> <http://www.vakantieveilingen.nl/veiling-van-de-dag.html>
I need to get the auction time which i can find in:
<div class="auction-time">
<span class="h-init h-time-tick
ng-valid ng-binding ng-dirty"
ng-hide="popup.laughingSecondPrice > 0"
ng-model="auction.time" ng-bind-html="auction.time.left|timeLeftFormatForBiedWidget"
h-model-name="expires"><strong>03</strong><i>:</i><strong>31</strong>
</span>
<span ng-show="popup.laughingSecondPrice > 0" class="ng-hide">Gesloten</span>
</div>
I can't find a right way to do it. Could anyone show me the way?
Answer: All you need is a [CSS
selector](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors)
to grab the `span` element in the `div` element with the `auction-time` class:
auction_time_span = soup.select('.auction-time span.h-time-tick')[0]
print(auction_time_span.get_text())
The [`element.get_text()`
function](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text) then
returns the string value contained.
Demo:
>>> import requests
>>> from bs4 import BeautifulSoup
>>> response = requests.get('http://www.vakantieveilingen.nl/veiling-van-de-dag.html')
>>> soup = BeautifulSoup(response.content)
>>> soup.select('.auction-time span.h-time-tick')[0].get_text()
u'2015-02-02T22:32:00+01:00'
The time and date in the HTML served is converted to a relative time by
Javascript code in the browser.
|
Python regex - Substring match
Question: I have a pattern
pattern = "hello"
and a string
str = "good morning! hello helloworld"
I would like to search `pattern` in `str` such that the entire string is
present as a word i.e it should not return substring `hello` in `helloworld`.
If str does not contain `hello`, it should return False.
I am looking for a regex pattern.
Answer: You can use word boundaries around the pattern you are searching for if you
are looking to use a regular expression for this task.
>>> import re
>>> pattern = re.compile(r'\bhello\b', re.I)
>>> mystring = 'good morning! hello helloworld'
>>> bool(pattern.search(mystring))
True
|
Write an entire html table to a text file
Question: I'm attempting to download a table from a site and bring it in to a table. I
can see the output in interpreter however when I write the text file it only
has one line. How do I write the entire table to a text?
#!/usr/bin/env python
from mechanize import Browser
from bs4 import BeautifulSoup
import urllib2,cookielib
import time
mech = Browser()
mech.set_handle_robots(False)
mech.set_handle_equiv(True)
mech.set_handle_redirect(True)
mech.set_handle_robots(False)
mech.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
url = "http://www.marinetraffic.com/en/ais/index/positions/all/shipid:415660/mmsi:354975000/shipname:ADESSA%20OCEAN%20KING/_:6012a2741fdfd2213679de8a23ab60d3"
page = mech.open(url)
#html = page.read()
DateTime = time.strftime("%Y%m%d-%H%M")
Month = time.strftime ("%mm-%Y")
html = page.read()
soup = BeautifulSoup(html)
table = soup.find("table",attrs={"class":"table table-hover text-left"})
for row in table.findAll('tr')[1:]:
items = row.text.replace(u"kn","")# remove kn so items line up when unpacking
time, ais_source, speed_km, lat, lon, course = items.split()[1:7]
data = items.split()[1:7]
text_file = open(DateTime + '.txt',"w")
text_file.write(str(data))
text_file.close()
print items
Answer: You are opening the file on every pass through the loop, in mode "w" which
means write (i.e. overwrite whatever is currently in the file). I recommend
you open the file before the loop and close it after the loop. You could also
open it in append mode on every pass through the loop.
with open(DateTime + '.txt',"w") as text_file:
for row in table.findAll('tr')[1:]:
items = row.text.replace(u"kn","")# remove kn so items line up when unpacking
time, ais_source, speed_km, lat, lon, course = items.split()[1:7]
data = items.split()[1:7]
text_file.write(str(data))
|
Read h.264 video frames with opencv in python Enthough (mac Yosemite)
Question: I'm using the Enthought distribution (Canopy) to do some data analysis and
computer vision in the IPython notebook. I want to read the frames of several
.avi files that use the h.264 codec and make some annotations on those images.
if you're using the Canopy distribution, you know that you can install opencv
through the package manager (just launch the Canopy application, click on
package manager, search for opencv and install the package). The issue though
is that the following code
import cv2
f = "/Volumes/DATA/temp.avi"
cap = cv2.VideoCapture(f)
flag,frame = cap.read()
print flag,frame
always returns (None,None) because opencv can't read the video. So it seems
like ffmpeg is not enabled by default in the Enthought package manager.
I've been losing a lot of time on this problem, so I'll post the solution
below. Hopefully it will help some other folks out there!
Answer: Follow those steps (partially from [this
source](http://tech.enekochan.com/en/2012/07/27/install-opencv-2-4-2-with-
ffmpeg-support-in-mac-os-x-10-8/)):
1) install mp3lame
curl -L -o lame-3.99.5.tar.gz http://sourceforge.net/projects/lame/files/lame/3.99/lame-3.99.5.tar.gz/download
tar xzvf lame-3.99.5.tar.gz
cd lame-3.99.5
./configure --disable-dependency-tracking CFLAGS="-arch i386 -arch x86_64" LDFLAGS="-arch i386 -arch x86_64"
make
sudo make install
cd ..
2) install faac
curl -L -o faac-1.28.tar.gz http://sourceforge.net/projects/faac/files/faac-src/faac-1.28/faac-1.28.tar.gz/download
tar xzvf faac-1.28.tar.gz
cd faac-1.28
./configure --disable-dependency-tracking CFLAGS="-arch x86_64" LDFLAGS="-arch x86_64"
make
sudo make install
cd ..
3) install faad
curl -L -o faad2-2.7.tar.gz http://sourceforge.net/projects/faac/files/faad2-src/faad2-2.7/faad2-2.7.tar.gz/download
tar xvzf faad2-2.7.tar.gz
cd faad2-2.7
./configure --disable-dependency-tracking CFLAGS="-arch i386 -arch x86_64" LDFLAGS="-arch i386 -arch x86_64"
make
sudo make install
cd ..
4) install ffmpeg
curl -O http://ffmpeg.org/releases/ffmpeg-0.11.5.tar.gz
tar xzvf ffmpeg-0.11.5.tar.gz
cd ffmpeg-0.11.5
./configure --enable-libmp3lame --enable-libfaac --enable-nonfree --enable-shared --enable-pic --disable-mmx --arch=x86_64
make
sudo make install
cd ..
5) download opencv 2.4 from <http://opencv.org/downloads.html> and unzip the
archive somewhere on your hard drive
6) Launch the Canopy terminal (start the canopy application > Tools > Canopy
Terminal)
7) navigate to your opencv folder and edit the modules/highgui/CMakeLists.txt
file and add those lines just before "if(HAVE_FFMPEG)":
if(APPLE)
list(APPEND HIGHGUI_LIBRARIES ${BZIP2_LIBRARIES} -lmp3lame -lfaac -lbz2)
endif(APPLE)
Otherwise the compilation process will fail at 34%.
8) then run ([modified from here](http://www.kurtsp.com/installing-
opencv-24-on-mac-os-x-lion.html))
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE -D PYTHON_EXECUTABLE=~/Library/Enthought/Canopy_64bit/User/bin/python -D PYTHON_PACKAGES_PATH=~/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/ -D PYTHON_LIBRARY=~/Library/Enthought/Canopy_64bit/User/lib/libpython2.7.dylib -D INSTALL_PYTHON_EXAMPLES=ON WITH_QUICKTIME=ON -D WITH_FFMPEG=ON -D WITH_AVFOUNDATION=ON ..
make -j8
sudo make install
IMPORTANT: make sure that the paths on the cmake line match those on your
system!
That's it. It's a lot of steps, but at the end of it you'll have opencv
working within your canopy distribution and you'll be able to read h.264 .avi
videos!
|
Python 2.7: detect emoji from text
Question: I'd like to be able to detect emoji in text and look up their names.
I've had no luck using unicodedata module and I suspect that I'm not
understanding the UTF-8 conventions.
I'd guess that I need to load my doc as as utf-8, then break the unicode
"strings" into unicode symbols. Iterate over these and look them up.
#new example loaded using pandas and encoding UTF-8
'A man tried to get into my car\U0001f648'
type(test) = unicode
import unicodedata as uni
uni.name(test[0])
Out[89]: 'LATIN CAPITAL LETTER A'
uni.name(test[-3])
Out[90]: 'LATIN SMALL LETTER R'
uni.name(test[-1])
ValueError Traceback (most recent call last)
<ipython-input-105-417c561246c2> in <module>()
----> 1 uni.name(test[-1])
ValueError: no such name
# just to be clear
uni.name(u'\U0001f648')
ValueError: no such name
I looked up the unicode symbol via google and it's a legit symbol. Perhaps the
unicodedata module isn't very comprehensive...?
I'm considering making my own look up table from
[here](ftp://ftp.unicode.org/Public/emoji/1.0/emoji-data.txt). Interested in
other ideas...this one seems do-able.
Answer: My problem was in using Python2.7 for the unicodedata module. using Conda I
created a python 3.3 environment and now unicodedata works as expected and
I've given up on all weird hacks I was working on.
# using python 3.3
import unicodedata as uni
In [2]: uni.name('\U0001f648')
Out[2]: 'SEE-NO-EVIL MONKEY'
Thanks to Mark Ransom for pointing out that I originally had Mojibake from not
correctly importing my data. Thanks again for your help.
|
Python Open a port fowarding (tunnel) using sshtunnel not working
Question: Since I'm running on Windows Env so I cannot use any other lib to make
connection to my server using ssh and open port forwarding. So i found this
library: sshtunnel
What i did was:
from sshtunnel import SSHTunnelForwarder
server = SSHTunnelForwarder(
ssh_address=('xx.xxx.xxx.xxx', 22),
ssh_username="admin",
ssh_password="something",
remote_bind_address=("127.0.0.1", 1088))
server.start()
print(server.local_bind_port)
Then in firefox, I try to connect through my sock using host = 127.0.0.1 and
port 1088. But somehow i keep getting rejected by the proxy. The SSH is
working properly as I can connect using putty or bitvise.
I've been trying to get in touch with the author of the lib but haven't got
any reponse yet. Anyone has any idea on this problem? Thanks
Answer: You may have to bypass proxy for your local addresses for some versions of
Firefox.
1. click "Options."
2. Select the "Advanced" -> "Network" tab.
3. Choose "settings" and open connection settings dialog. "Manual Proxy Config" should be selected.
4. Enter local IP addresses/hostnames you want to bypass i.e. 127.0.0.1, and restart firefox.
See the discussion
[here](http://stackoverflow.com/questions/7227845/localhost-not-working-in-
chrome-and-firefox)
Let me know if it works.
|
Cannot open html file in Python
Question: I am trying to gather how many hyperlinks are in an html file. To do that, I
want to read the html file in Python and do a search for all of the `</a>`
anchors. However, it seems that when I try to pass an html file through
python, I get an error that reads:
> "UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1819:
> ordinal not in range(128)"
However, if I copy and paste that same text into a txt file, then my code
works. My code is as follows:
def links(filename):
infile = open(filename)
content = infile.read()
infile.close()
anchorTagEnd = content.count("</a>")
return anchorTagEnd
print(links("DePaul CDM - College of Computing and Digital Media.html"))
Answer: Why not use an _HTML parser_ to count the links inside an HTML file.
Using
[`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/):
from bs4 import BeautifulSoup
def links(filename):
soup = BeautifulSoup(open(filename))
return len(soup.find_all('a'))
print(links("DePaul CDM - College of Computing and Digital Media.html"))
Using [`lxml.html`](http://lxml.de/lxmlhtml.html):
import lxml.html
def links(filename):
tree = lxml.html.parse(filename)
return tree.xpath('count(//a)')[0]
print(links("DePaul CDM - College of Computing and Digital Media.html"))
|
Python BeautifulSoup: parsing multiple tables with same class name
Question: I am trying to parse some tables from a wiki page e.g.
<http://en.wikipedia.org/wiki/List_of_Bollywood_films_of_2014>. there are four
tables with same class name "wikitable". When I write:
movieList= soup.find('table',{'class':'wikitable'})
rows = movieList.findAll('tr')
It works fine, but when I write:
movieList= soup.findAll('table',{'class':'wikitable'})
rows = movieList.findAll('tr')
It throws an error:
Traceback (most recent call last):
File "C:\Python27\movieList.py", line 24, in <module>
rows = movieList.findAll('tr')
AttributeError: 'ResultSet' object has no attribute 'findAll'
when I print movieList it prints all four table.
Also, how can I parse the content effectively because the no. of columns in a
row is variable? I want to store this information into different variables.
Answer: `findAll()` returns a `ResultSet` object - basically, a list of elements. If
you want to find elements inside each of the element in the `ResultSet` \- use
a loop:
movie_list = soup.findAll('table', {'class': 'wikitable'})
for movie in movie_list:
rows = movie.findAll('tr')
...
You could have also used a [`CSS
Selector`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-
selectors), but, in this case, it would not be easy to distinguish rows
between movies:
rows = soup.select('table.wikitable tr')
* * *
As a bonus, here is how you can collect all of the "Releases" into a
dictionary where the keys are the periods and the values are lists of movies:
from pprint import pprint
import urllib2
from bs4 import BeautifulSoup
url = 'http://en.wikipedia.org/wiki/List_of_Bollywood_films_of_2014'
soup = BeautifulSoup(urllib2.urlopen(url))
headers = ['Opening', 'Title', 'Genre', 'Director', 'Cast']
results = {}
for block in soup.select('div#mw-content-text > h3'):
title = block.find('span', class_='mw-headline').text
rows = block.find_next_sibling('table', class_='wikitable').find_all('tr')
results[title] = [{header: td.text for header, td in zip(headers, row.find_all('td'))}
for row in rows[1:]]
pprint(results)
This should get you much closer to solving the problem.
|
BeautifulSoup login - How to get the crsf field with a specific attribute and value
Question: I am using the following script to authenticate logging into LinkedIn and then
using Beautiful Soup to scrape the HTML.
The login authenticates with no issue (I see my account info) but when I try
to load the page I get a "fs.config({"failureRedirect})" error.
import cookielib
import os
import urllib
import urllib2
import re
import string
import sys
from bs4 import BeautifulSoup
username = "MY USERNAME"
password = "PASSWORD"
ofile = open('Text_Dump.txt', "wb")
cookie_filename = "parser.cookies.txt"
class LinkedInParser(object):
def __init__(self, login, password):
""" Start up... """
self.login = login
self.password = password
# Simulate browser with cookies enabled
self.cj = cookielib.MozillaCookieJar(cookie_filename)
if os.access(cookie_filename, os.F_OK):
self.cj.load()
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(self.cj)
)
self.opener.addheaders = [
('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; '
'Windows NT 5.2; .NET CLR 1.1.4322)'))
]
# Login
title = self.loginPage()
sys.stderr.write("Login"+ str(self.login) + "\n")
#title = self.loadTitle()
ofile.write(title)
def loadPage(self, url, data=None):
"""
Utility function to load HTML from URLs for us with hack to continue despite 404
"""
# We'll print the url in case of infinite loop
# print "Loading URL: %s" % url
try:
if data is not None:
response = self.opener.open(url, data)
else:
response = self.opener.open(url)
return ''.join(response.readlines())
except:
# If URL doesn't load for ANY reason, try again...
# Quick and dirty solution for 404 returns because of network problems
# However, this could infinite loop if there's an actual problem
return self.loadPage(url, data)
def loginPage(self):
"""
Handle login. This should populate our cookie jar.
"""
html = self.loadPage("https://www.linkedin.com/")
soup = BeautifulSoup(html)
csrf = soup.find(id="csrfToken-postModuleForm")['value']
login_data = urllib.urlencode({
'session_key': self.login,
'session_password': self.password,
'loginCsrfParam': csrf,
})
html = self.loadPage("https://www.linkedin.com/uas/login-submit", login_data)
return
def loadTitle(self):
html = self.loadPage("https://www.linkedin.com/")
soup = BeautifulSoup(html)
return soup.get_text().encode('utf-8').strip()
parser = LinkedInParser(username, password)
ofile.close()
The script for the login came from: [Logging in to LinkedIn with python
requests sessions](http://stackoverflow.com/questions/18907503/logging-in-to-
linkedin-with-python-requests-sessions)
Any thoughts?
Answer: your syntax is wrong
first - the crsf is an input field not a div tag / inspect element and you
will see
second - to find a tag with a specified attribute and value you need to use
`.find('type_of_tag' :{'tag_attribute':'value'})`
third to access the value of a specific attribute's value within the specified
tag you need to use bracket syntax or .get()
here is your code that you have to replace
html = self.loadPage("https://www.linkedin.com/")
soup = BeautifulSoup(html)
csrf = soup.find('input', {"name" : "csrfToken"})
csrf_token = csrf['value']
print csrf_token
|
Python subprocess execute command with \ in command string
Question: I'm writing a simple program that takes in a command line string and executes
it.
An example command line string could be dir "c:\users\xxx\My Documents"
I'm having trouble trying to execute this due to the '\'. I've specified a dir
name as an example of a string that has a backslash in it.
Since the command I receive could be anything - say regex's etc, the \ should
be maintained. How would I ensure that the user input stays as entered in the
python script?
import platform
import subprocess
import sys
if __name__ == '__main__':
command = sys.argv[0].split()
if platform.system().lower() == 'windows':
runShell = True
out = subprocess.Popen(command,shell=runShell,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
for line in out.stdout.readlines():
print line.strip()
Answer: So I found the answer on how to parse shell commands provided as a string to a
py module.
Use the shlex module - <https://docs.python.org/2/library/shlex.html> to split
the command str into a list that can be executed by the subprocess.Popen
method.
|
Control python class remotely
Question: I made python class that controls my sound system in my house, the class looks
like that:
from django.db import models
import youtube_dl, pygame, glob
class PlayerControl(object):
def __init__(self):
pygame.mixer.init()
def download_music(self, video_url):
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'forcefilename': True,
}
ydl = youtube_dl.YoutubeDL(ydl_opts);
ydl.download(video_url)
def get_mp3_files_list(self):
return glob.glob("*.mp3")
def play_music(self, fileName):
pygame.mixer.music.load("1.mp3")
pygame.mixer.music.play()
def pause(self):
pygame.mixer.music.pause()
def replay(self):
pygame.mixer.music.play()
def get_volume(self):
return pygame.mixer.music.get_volume()
def set_volume(self, volume_to_set):
pygame.mixer.music.set_volume(volume_to_set)
To take a step forward, I wanted to make kind of an interface the controls
this class remotely, using a better interface compared to python shell...
I guess that controlling it via a browser would be the simplest thing to do,
My question is - how to I modify python classes from a browser, using HTTP
requests.
Answer: If you want to control this over http, you'll need to take what you have and
build a web-accessible API. The standard industry practice for this at the
moment wild be a REST API, but for your first attempt I wouldn't get caught up
in the details.
I would recommend that you start with a micro framework such as Bottle or
Flask. The good news is that you have already written the model you want to
interact with, now you simply need to hook it up to something.
Following the MVC pattern, you will want to write a View layer which takes
information from your model, or from the return value of its methods, and
displays it in a way you wish to consume. Then write a controller using your
web micro framework of choice, which binds the model and view together such
that when you make a http request on a given endpoint it calls the relevant
methods and returns the relevant data.
I've kept everything at a high level here, but would be happy to answer
specific questions from comments.
|
requests.get(url).json() gives JSONDecodeError
Question: I am writing an api to get the data of an app in another app. I have my views
setup to get the data from the url like:
import requests
user = 'hello'
pwd = 'python'
class SomeView(APIView):
def get(self, request):
if request.user.is_authenticated():
r = requests.get('http://localhost:8000/foo/bar/',
auth=HTTPBasicAuth(user, pwd))
return HttpResponse(r.json())
else:
return HttpResponse(json.dumps({'success':'false', 'message':'login required '}))
This gives me error like:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/requests/models.py", line 799, in json
return json.loads(self.text, **kwargs)
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/simplejson/__init__.py", line 505, in loads
return _default_decoder.decode(s)
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/simplejson/decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/simplejson/scanner.py", line 127, in scan_once
return _scan_once(string, idx)
File "/home/abhishek/Documents/venv/local/lib/python2.7/site-packages/simplejson/scanner.py", line 118, in _scan_once
raise JSONDecodeError(errmsg, string, idx)
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I have django == 1.4.5 and requests == 2.5.1 installed in my virtual
environment. I have checked almost everything and now i am starting to
conclude that the requests version and django version have something to do
with the following traceback. I also have simplejson==3.6.5 installed in my
virtual environment, which i think has no relevance. Help Please.
Answer: you can do something like this
import requests
from rest_framework.response import Response
...
if request.user.is_authenticated():
r = requests.get('http://localhost:8000/foo/bar/',
auth=HTTPBasicAuth(user, pwd))
return Response(r.json())
return Response({'success':'false', 'message':'login required '})
|
stacking 2D matrix using Python
Question: I have a script that reshapes a 1024x1024 matrix into 32x32 matrices. Here it
is the code:
import numpy as np
filename = r'bb1e03'
background = r'bb1e03_background'
size = 1024
resize = 32
n = np.arange(size)
T0 = np.loadtxt(filename, unpack=False)
bg = np.loadtxt(background, unpack=False)
T = T0-bg
for s in n: # s here is the row number
B = np.reshape(T[s], (resize, resize))
B_rev = B[...,::-1]
name = str(filename) + '_column_'+ str.zfill(str(s), 4)
np.savetxt(name+'.txt', B_rev)
Now I need all 32x32 matrices stacked so that in the end I have a 32x32x1024
matrix. Could you please tell me how I can do that? I have found that
np.dstack would do the job but I have no idea how to include it in the script.
Thank you.
Answer: Since `np.dstack` needs a tuple of all of the matrices to stack you are going
to have to store them separately as you go along anyway.
A simple solution to your problem would be to put the reshaped matrices in
place in the stacked structure as you generate them.
stacked = np.empty((32, 32, 1024))
for s in xrange(1024):
B = T[s].reshape((32, 32))
B_rev = B[..., ::-1]
stacked[...,s] = B_rev
You could also do this in one step with the one liner
stacked = T.reshape((1024,32,32)).transpose((1,2,0))[:,::-1]
This method should be preferred as with some brief benchmarking I've found it
to be **much** (1000x) faster than the plain python loop.
|
How to use for-loop in Jython PythonInterpreter?
Question: Is it possible and how to write down _for-loop_ in `PythonInterpreter` using
`exec()` method?
With `exec()` it looks fine and like interactive line by line input in the
Python command line, but the following with `for` statement doesn't work:
PythonInterpreter python = new PythonInterpreter();
python.exec("import sys");
python.exec("for p in sys.path:");
python.exec(" print p");
Answer: You are passing in separate lines, how is Python supposed to parse those
separately and validate that you have valid code?
Use one string:
python.exec("for p in sys.path:\n" +
" print p");
The `import sys` line can still be passed in separately because the namespace
into which the module is imported is persisted in the `PythonInterpreter`
instance.
In essence, each string passed to `exec()` must follow the [`stmt_list`
grammar
token](https://docs.python.org/2/reference/compound_stmts.html#grammar-token-
stmt_list); compound statements must be complete.
|
Use subprocess in Python
Question: I am writing a small program in Python, to record an audio WITH printing some
text at same time.
But my Print is executed until finishing of audio recording. Can you please
help me to resolve this issue?
import picamera, subprocess, os, sys
a1 = "arecord -f cd -D plughw:0 -d 10 a.wav"
subprocess.call(a1,shell= True)
print("Audio record is only for 10sec")
Answer: You're using
[`subprocess.call`](https://docs.python.org/3/library/subprocess.html#subprocess.call),
which blocks:
> Run the command described by args. **Wait for command to complete** , then
> return the returncode attribute.
You can use a
[`Popen`](https://docs.python.org/3/library/subprocess.html#popen-objects)
object, which doesn't block:
proc = subprocess.Popen(a1.split())
# code will proceed
# use proc.communicate later on
Or you can have two things run separately using a
[`Thread`](https://docs.python.org/3/library/threading.html#thread-objects)
(which then spawns a process in it's own context):
import picamera, subprocess, os, sys
import threading
def my_process():
a1 = "arecord -f cd -D plughw:0 -d 10 a.wav"
subprocess.call(a1,shell= True)
thread = threading.Thread(target=my_process)
thread.start()
print("Audio record is only for 10sec")
|
Unable to load C++ dll in python
Question: I have a **C++** **dll** which I'm trying to use it in **Python** ,
>>> from ctypes import *
>>> mydll = cdll.LoadLibrary("C:\\TestDll.dll")
until now there are no errors, system seem to be doing what I wanted, but when
I try to access `mydll`, the Intellisence in the Python IDLE shows the
following,

from the above pic, it's clear that the intellisence doesn't show up any
available functions of the dll, but when I checked the same TestDll.dll with
`dumpbin /EXPORTS TestDll.dll` it has 45 functions, but none of those
functions are available with python.

**Please Note** : There are several questions on this topic, I tried the
following suggestions but no use,
* [incompatible version of Python installed or the DLL](http://stackoverflow.com/a/13268880/1463551) [TestDll.dll & Python both are 32 bit versions]
* [I think ctypes is the way to go](http://stackoverflow.com/a/252473/1463551) [Same Issue, cant see any functions, but loads the dll]
Now my question is how do I load all the available functions(as shown by
dumpbin)?
**Edit 1**
Based on [eryksun](http://stackoverflow.com/users/205580/eryksun) suggestion,
I was able to make some progress. The `TestDll.dll` comes along with a header
file `TestDll.h`(my bad I missed this file earlier), from which I could see
the available Exported Functions.
**`TestDll.h:`**
_stdcall Function1 (const char* prtFileString, cont char* prtDescrip, struct FileParams* ptrParsms);
struct FileParams
{
float val1;
void* pMarker;
};
now I've tried the following,
>>> mydll = CDLL("c:\\TestDll.dll")
>>> Function1 = mydll.Function1
>>> Function1.restype = c_int
until now it's fine, but when I try to define the **argTypes** , not sure how
to do it for structs?
>>> Function1.argtypes = (c_char_c, c_char_c, ???)
any suggestions are much appreciated.
Answer: Based on your header, here's a dummy C file (for Windows) that can be used to
test a `ctypes` wrapper. You mentioned C++ but the example was a C interface,
which is a good thing because `ctypes` works with C functions not C++.
### x.c
#include <stdio.h>
struct FileParams
{
float val1;
void* pMarker;
};
__declspec(dllexport) _stdcall Function1 (const char* prtFileString, const char* prtDescrip, struct FileParams* ptrParsms)
{
printf("%s\n%s\n%f %p\n",prtFileString,prtDescrip,ptrParsms->val1,ptrParsms->pMarker);
}
Here's the `ctypes` wrapper. Note that `ctypes` does not inspect the DLL and
automatically load all the functions. You have to declare the functions,
parameters and return values yourself. See [ctypes:structures and
unions](https://docs.python.org/3/library/ctypes.html#structures-and-unions)
for the `Structure` syntax.
Also note that for a DLL with `_stdcall` functions use `WinDLL` instead of
`CDLL`.
### x.py
#!python3
import ctypes
class FileParams(ctypes.Structure):
_fields_ = [('val1',ctypes.c_float),
('pMarker',ctypes.c_void_p)]
x = ctypes.WinDLL('x')
x.Function1.argtypes = [ctypes.c_char_p,ctypes.c_char_p,ctypes.POINTER(FileParams)]
x.Function1.restype = ctypes.c_int
fp = FileParams(1.234,None)
x.Function1(b'abc',b'def',ctypes.byref(fp))
And the output:
abc
def
1.234000 0000000000000000
|
front command given self idiom
Question: This is the lec4 code and given code respectively:
# non-mutable; persistent linked lists; also a stack
# immutable collections are much easier to use concurrently
#
# NOTE: There are no assignments to self.tail after its initialization
#
class EmptyListE :
def __str__(self) :
return "Exception: list is empty"
class NotFoundE :
def __str__(self) :
return "Exception: element not found"
class IndexOutOfBoundsE :
def __str__(self) :
return "Exception: index out of bounds"
#---
class List :
"""Non-mutable persistent lists
>>> xs = EmptyList().add(1).add(2).add(3).add(4)
>>> print xs
4, 3, 2, 1, []
>>> ys = xs.append(100)
>>> print ys
4, 3, 2, 1, 100, []
>>> print xs
4, 3, 2, 1, []
"""
def size (self) :
"""O(n).
Returns the number of elements in the current list.
>>> EmptyList().size()
0
>>> EmptyList().add(1).add(2).add(3).size()
3
"""
pass
def isEmpty (self) :
"""O(1).
Returns True or False depending on whether the current list is empty or not.
>>> EmptyList().isEmpty()
True
>>> EmptyList().add(1).add(2).add(3).isEmpty()
False
"""
pass
def search (self, v) :
"""O(n).
Returns True or False depending on whether 'v' occurs in the current list or not.
>>> EmptyList().search(1)
False
>>> EmptyList().add(1).add(2).add(3).search(2)
True
>>> EmptyList().add(1).add(2).add(3).search(100)
False
"""
pass
def elem (self, i) :
"""O(n).
Returns the element at zero-based index 'i' in the current list. If 'i' is out
of bounds, raises an exception.
>>> try :
... EmptyList().elem(0)
... except IndexOutOfBoundsE as e :
... print e
...
Exception: index out of bounds
>>> try :
... EmptyList().add(1).add(2).add(3).elem(10)
... except IndexOutOfBoundsE as e :
... print e
...
Exception: index out of bounds
>>> EmptyList().add(1).add(2).add(3).elem(0)
3
>>> EmptyList().add(1).add(2).add(3).elem(1)
2
>>> EmptyList().add(1).add(2).add(3).elem(2)
1
"""
pass
def index (self, v) :
"""O(n).
Returns the zero-based index of the first occurrence of 'v' in the current
list. If 'v' does not occur in the list, raises NotFoundE exception.
>>> try :
... EmptyList().index(1)
... except NotFoundE :
... print 'Not found'
...
Not found
>>> EmptyList().add(1).add(2).add(3).index(3)
0
>>> EmptyList().add(1).add(2).add(3).index(2)
1
>>> EmptyList().add(1).add(2).add(3).index(1)
2
>>> try :
... EmptyList().add(1).add(2).add(3).index(10)
... except NotFoundE :
... print 'Not found'
...
Not found
"""
pass
def insert(self, i, v) :
"""O(n).
Inserts 'v' at the given zero-based index 'i'. If the index i is too large,
throw IndexOutOfBoundsE exception.
>>> str (EmptyList().insert(0,5))
'5, []'
>>> try :
... EmptyList().insert(100,5)
... except IndexOutOfBoundsE as e :
... print e
...
Exception: index out of bounds
>>> str (EmptyList().add(1).add(2).add(3).insert(0,100))
'100, 3, 2, 1, []'
>>> str (EmptyList().add(1).add(2).add(3).insert(1,100))
'3, 100, 2, 1, []'
>>> str (EmptyList().add(1).add(2).add(3).insert(2,100))
'3, 2, 100, 1, []'
>>> str (EmptyList().add(1).add(2).add(3).insert(3,100))
'3, 2, 1, 100, []'
>>> try :
... str (EmptyList().add(1).add(2).add(3).insert(4,100))
... except IndexOutOfBoundsE as e :
... print e
...
Exception: index out of bounds
"""
pass
def remove(self,v) :
"""O(n).
Remove the first occurrence (if any) of 'v' from the current list.
>>> str(EmptyList().remove(10))
'[]'
>>> str(EmptyList().add(1).add(2).add(3).remove(2))
'3, 1, []'
>>> str(EmptyList().add(2).add(2).add(3).remove(2))
'3, 2, []'
"""
pass
def append(self,v) :
"""O(n).
Inserts 'v' at the end of the current list.
>>> str(EmptyList().append(10))
'10, []'
>>> str(EmptyList().add(1).add(2).add(3).append(10))
'3, 2, 1, 10, []'
>>> xs = EmptyList().add(1).add(2).add(3)
>>> print xs
3, 2, 1, []
>>> print xs.append(10)
3, 2, 1, 10, []
>>> print xs
3, 2, 1, []
"""
pass
def drop(self,i) :
"""Drops the first 'i' elements and returns the remaining list; raises an
exception if the index is too large.
>>> xs = EmptyList().add(1).add(2).add(3).add(4)
>>> print xs.drop(0)
4, 3, 2, 1, []
>>> print xs.drop(1)
3, 2, 1, []
>>> print xs.drop(2)
2, 1, []
>>> print xs.drop(3)
1, []
>>> print xs.drop(4)
[]
>>> try :
... xs.drop(5)
... except IndexOutOfBoundsE as e :
... print e
...
Exception: index out of bounds
"""
pass
def add(self,v) :
"""O(1).
Inserts 'v' at the front of the list.
>>> str(EmptyList().add(1).add(2).add(3))
'3, 2, 1, []'
"""
return Node(v,self)
def __iter__ (self) :
"""Creates an iterator.
>>> it = iter(EmptyList().add(1).add(2).add(3))
>>> it.next()
3
>>> it.next()
2
>>> it.next()
1
>>> try :
... it.next()
... except StopIteration :
... print 'Done'
...
Done
>>> for i in EmptyList().add(1).add(2).add(3) :
... print i
...
3
2
1
>>> [ i * i for i in EmptyList().add(1).add(2).add(3) ]
[9, 4, 1]
"""
return ListIterator(self)
#---
class EmptyList (List) :
def size (self) :
return 0
def isEmpty (self) :
return True
def search (self, v) :
return False
def elem (self, i) :
raise IndexOutOfBoundsE()
def index (self, v) :
raise NotFoundE()
def insert(self, i, v) :
if i == 0 :
return Node(v,self)
else :
raise IndexOutOfBoundsE()
def remove(self,v) :
return self
def append(self,v) :
return Node(v,self)
def drop(self,i) :
if i == 0 :
return self
else :
raise IndexOutOfBoundsE()
def __str__ (self) :
return "[]"
#---
class Node (List) :
def __init__ (self, head, tail) :
self.head = head
self.tail = tail
def size (self) :
return 1 + self.tail.size()
def isEmpty (self) :
return False
def search (self, v) :
return self.head == v or self.tail.search(v)
def elem (self, i) :
if i == 0 :
return self.head
else :
return self.tail.elem(i-1)
def index (self, v) :
if self.head == v :
return 0
else :
return 1 + self.tail.index(v)
def insert(self, i, v) :
if i == 0 :
return Node(v,self)
else :
return Node(self.head,self.tail.insert(i-1,v))
def remove(self,v) :
if self.head == v :
return self.tail
else :
return Node(self.head,self.tail.remove(v))
def append(self,v) :
return Node(self.head,self.tail.append(v))
def drop (self,i) :
if i == 0 :
return self
else :
return self.tail.drop(i-1)
def __str__ (self) :
return "%s, %s" % (self.head, self.tail)
#---
class ListIterator :
def __init__(self,list) :
self.list = list
def next(self) :
if self.list.isEmpty() :
raise StopIteration
else :
v = self.list.head
self.list = self.list.tail
return v
#-----------------------------------------------------------------------------
if __name__ == "__main__" :
import doctest
doctest.testmod()
End of the lec4.py
from lec4 import *
class MutableList :
"""Mutable lists. We maintain a pointer 'front' to a list and use DELEGATION
for read-only operations. Operations that change the list are implemented by
explicit pointer manipulations that update 'front' or self.tail for the relevant
node in the list.
"""
def __init__ (self) :
self.front = EmptyList()
#- easy delegations
def search (self,v) :
"""Returns True or False depending on whether 'v' occurs in the current list or not.
>>> xs = MutableList()
>>> xs.search(1)
False
>>> xs.add(1)
>>> xs.add(2)
>>> xs.add(3)
>>> xs.add(4)
>>> xs.search(2)
True
>>> xs.search(10)
False
"""
#your code goes here
if self.front.isEmpty(self) :
return False
elif !self.front.isEmpty(self) :
return self.front.search(v)
else :
return True
#end of your code
return self.front.search(v)
def isEmpty (self) :
"""Returns True or False depending on whether the current list is empty or not.
>>> xs = MutableList()
>>> xs.isEmpty()
True
>>> xs.add(1)
>>> xs.isEmpty()
False
"""
#your code goes here
if self.front == None : #looks for no elements
return True
else : #an element exists
return False
#code ends here
pass
The code I used to attempt:
if self.front == None : #looks for no elements
return True
else : #an element exists
return False
pass
I've looked at <https://docs.python.org/2/tutorial/classes.html> and
<https://docs.python.org/2/tutorial/datastructures.html> and have not found
anything about a front idiom. I am unsure of the exact function and what it
does. If someone could explain what exactly the front does and its return
declaration is, if it has one.
When I do the debugger it says that it returns nothing meaning it doesn't even
enter the if statement. Why is it saying this?
Answer: All I needed to do was access the isEmpty() function from the class Node.
Thanks for the help though.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.