text stringlengths 226 34.5k |
|---|
Duplicating Python int * numpy.array behavior
Question: I'm attempting to build a class representation of a matrix complete with most
of the normal mathematical operations. I've hit a snag with the scalar
multiplication operation.
The relevant part of the code is as follows:
import numpy
class ... |
trying to regex in python
Question: _Can anyone please help me understand this code snippet,
from<http://garethrees.org/2007/05/07/python-challenge/> Level2_
>>> import urllib
>>> def get_challenge(s):
... return urllib.urlopen('http://www.pythonchallenge.com/pc/' + s).read()
...
>>> ... |
Stem as a Python Tor client fails
Question: I am using Stem to start a Tor process. Using the [To Russia with
love](https://stem.torproject.org/tutorials/to_russia_with_love.html#using-
socksipy) tutorial as a guide. This is the code:
import requests
import socket
import socks
import stem.pro... |
python: langton's ant pygame first step issues
Question: I'm trying to make a graphic representation of the Langton's ant algorithm but
I'm stuck.
here's the [Langton's Ant video
description](https://www.youtube.com/watch?v=1X-gtr4pEBU)
That's what the output should be:

stdscr.addstr(10, 10, "foobar")
this code the result screen: **foobar** (OK)
stdscr.addstr(10, 10, "foobar", curses.A_REVERSE)
But how to get the result screen fo**ob** ar ?
Pleas... |
How to call django-pipeline compressor with jinja2 templates
Question: I wish to compress the JS and CSS in my Jinja2 based Python project for Google
App engine. I have installed django-pipeline, and added it to my project path.
Some of the [documentation](http://django-
pipeline.readthedocs.org/en/latest/usage.html) ... |
Retrieving multiple values from a large jsonb field faster (postgresql 9.4)
Question: **tl;dr**
Using PSQL 9.4, is there a way to retrieve multiple values from a jsonb field,
such as you would with the imaginary function:
jsonb_extract_path(x, ARRAY['a_dictionary_key', 'a_second_dictionary_key', 'a_thir... |
Remove non-GtkListBoxRow parent from GtkListBox
Question: Just a quick note about something I have encountered recently. I used python,
but I guess, it applies for other languages as well.
from gi.repository import Gtk
win = Gtk.Window()
listbox = Gtk.ListBox()
somewidget = Gtk.Somewidge... |
Python: Error importing OpenCV
Question: I installed opencv with Homebrew. I'm getting the following error -
>>> import cv2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/usr/local/lib/python2.7/site-packages/cv2.so, 2): Library not loaded: /usr/... |
How to do a simple Pika SelectConnection to send a message, in python?
Question: I am trying to convert my code to send rabbitmq messages via Pika instead. I
am having a lot of trouble understanding how to send a simple message using an
asynchronous connection (such as SelectConnection).
In my old code, which I use th... |
Operational Error No such table Django
Question: Hi I am doing the djangogirls tutorial and have come across the
OperationalError no such table: blog_post. This works perfect on my virtual
environment, but I get the OperationalError after pushing to heroku.
I am using Django 1.7.7. More information on the error is ava... |
Unsure of my python explanatory comments
Question: I'm doing Learn Python the Hard Way exercise 15
A study drill is to explain every line with comments, but I feel unsure of my
explanations. I'm looking for corrections to my mistakes and improvements.
Correct term usage is my biggest worry, especially when it comes to... |
How to let MagicMock behave like a dict?
Question: mock(<http://mock.readthedocs.org/en/latest/index.html>) is a great tool in
python for unit test. It can conveniently mock a method or class or dict.But I
encountered a problem which I couldn't find a straightforward way to deal with
by mock.
This is the function to b... |
Why is python giving large errors when dividing the results of sin()
Question: I was trying to find the values for the first ten integer inputs of n for an
equation I found: `x = sin(2π / n) / sin(π / n)`. The output I got from the
code I wrote to find them was quite surprising:
>>> for i in range(1, 11)... |
Python, optimizing a list comprehension for string concatenation
Question: I'm using `cProfile` to run benchmarks on a script that process strings via
list comprehension. The target line I'd like to optimize looks like this:
signals = [('prefix' + str(day) + '_' + s) for s in signals]
where `day` i... |
M2Crypto installation
Question: I am struggling to get my M2Crypto installation to work
C:\Python27>python
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from M2Crypto import RSA
... |
Ubuntu, Anaconda: Cannot import python shapely package
Question: [Shapely Import problem Related to MAC OS
X](http://stackoverflow.com/questions/25761682/python-cant-import-shapely)
I installed shapely using `sudo apt-get install python-shapely`.
I am using `Python 2.7.8 |Anaconda 2.1.0 (64-bit)|` with `ubuntu 14.04 ... |
Python Django: Minimal Django + Cassandra local application
Question: I am trying to put together a minimum Django application that uses Cassandra
as the database.
Here is what I tried:
1. Started a brand new Django project in PyCharm. Checked that `python manage.py runserver` works as expected.
2. Installed Cas... |
undefined symbol: PyUnicodeUCS2_Decode
Question: I'm trying to connect to my google sheets with gspread. Here is the code:
#IMPORT STANDARD LIBRARIES
import json
import os
#IMPORT THIRD PARTY LIBRARIES
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
... |
mvpa2.suite: Runtime warning and erro in Python 2.7.6
Question: I just installed mvpa2 module on my ubuntu 14.04, Python 2.7.6. following the
instruction at <http://www.pymvpa.org/installation.html> using `sudo aptitude
install python-mvpa2`
Command `import mvpa2` works well, but when I run `from mvpa2.suite import *`... |
Trouble importing yahoo finance to python
Question: I have installed yahoo finance from the PyPI with pip, and when I go to run
the following script i get an import error: No module named yahoo_finance
from yahoo_finance import Share
BlackDiamond = Share('BDE')
print(BlackDiamond.get_open)
... |
Release the Python import lock from a thread you do not control & do not have access to
Question: So, I'm injecting a DLL into a Cython application in order to extend its
functionality. I am doing this using the following code: Note: using Python
2.7; uses the old ModuleNoBlock scheme
PyGILState_STATE sM... |
Replace CSS block of text within file Python
Question: I'm tying to make a python program to help me make simple edits to a config
file. I want to be able to read the file, replace a section of the file and
then write the changes. One of the problems i have been having is that there
are multiple lines that are the same... |
Sending Response to OPTIONS in Python Flask application
Question: I have a python Flask listener waiting on port 8080. I expect another process
to make a series of POST's to this port.The code for listener is as follows.
#!/usr/bin/env python2
from __future__ import print_function
from flask impo... |
Avoiding TCP/IP connection hanging
Question: I am communicating with an instrument via TCP/IP using the Python `socket`
package.
The program sends a command to the instrument to perform an action, and then
repetitively sends another "check" command until it receives a "done" reply.
However, after many loops, the progr... |
What is the purpose of creating symbolic variables in Theano?
Question: In Theano, variables are written as 'symbols':
x = T.matrix("x")
y = T.vector("y")
From reading the documentation, it is implied that the reason we create these
symbols may be due to the fact that these variables are compil... |
How to set timeout to pyplot.show() in matplotlib?
Question: I am using python's matplotlib to draw figures.
I want to draw a figure with a timeout, say 3 seconds, and the window will
close to move on the code.
I have known that pyplot.show() will create a blocking window with unlimited
timeout; pyplot.show(block=Fal... |
edit:pandas multiline value in ipython notebook
Question: If I put something with newlines in cell into pandas dataframe, for example:
pd.DataFrame(data=[["""aa\n<br>
bb"""], ['bb']], columns=["col"])
I get something where all "newlines" are escaped. (html source looks like:
<td> aa\n<br>... |
Local variable referenced before assignment, using multi-threading
Question: Code to add and delete values in a list are operations performed in different
threads.
using these global variables in multi-threading:
from threading import Thread
import time
a=[]
i = 0
j = 0
functi... |
Find variable closest to a value in a list
Question: I have only programmed basic functions in python before, so I hope this is
clear.
I have a list of variables `[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10]` to 1
decimal place. I have a variable B which can be any number to decimal place. I
would like to find the closes... |
Textexpander with Python to match phone numbers
Question: I want to use Textexpander and Python to match phone numbers via the
clipboard:
1. Click a phone number formated like `0798008080` in one application, _copy_ the number and insert the clipboard content with a Textexpander-Shortcut in another application like ... |
Python 3.4 : cStringIO vs. StringIO
Question: # QUESTION
I am returning an ImportError: No module named 'cStringIO'. Unfortunately
cStringIO doesn't exist anymore and I need to use StringIO as a replacement.
How can I do this?
import edgar
import ftplib
from io import StringIO
ftp = ft... |
Run 'query session' from python
Question: So I am making a program in python that will report the users on a system who
connected with RGS.
One way to get users on windows is the `query session` command. I have tried
with both `os.popen` and `subprocess.Popen` with and without shell=True. I
even specified the full pat... |
Dividing point clouds into quadrants in python
Question: Suppose I have an array of 30 points in 3 dimensions cast as a numpy array in
python:
import numpy as np
b = np.round(np.random.random((30,3))*20)
b = b - b.mean(axis=0)
I want to separate these points into eight quadrants with refere... |
Mutually recursive coroutines with asyncio
Question: I had the hypothesis that if I wrote mutually recursive coroutines with
asyncio, they would not hit the maximum recursion depth exception, since the
event loop was calling them (and act like a trampoline). This, however, is not
the case when I write them like this:
... |
All of a sudden str.decode('unicode_escape') stopped working [2.7.3]
Question: This snippet is taken from my recent python work. And it used to work just
fine
strr = "What is th\u00e9 point?"
print strr.decode('unicode_escape')
But now it throws the unicode decoding error:
Traceb... |
Multi threading using Python and pymongo
Question: Hi im looking to make a program that will class tweets positively and
negatively classifies tweets about a company already saved in a mongodb and
once classified, to update a integer based on then result.
I have code made to make this possible but i would like to mult... |
Binomial iterated expectation in Cython
Question: I am brand new to Cython. How to convert the Python function called Values
below to Cython? With factors=2 and i=60 this takes 2.8 secs on my big Linux
box. The goal is sub 1 sec with factors=2 and i=360.
Here's the code. Thanks!
import numpy as np
i... |
Python Traceback Error
Question: Unable to create a response with this api.I am unable to call the function
locu_search('new york'). I get the following error shown below. I am using
Komodo as my IDE, this started when I created a new python shell.
import urllib2
import json
local_api = '0d5... |
Popen not responding to kill
Question: Environment: Raspberry Pi Wheezy
I have a python program that uses Popen to call another python program
from subprocess import *
oJob = Popen('sudo python mypgm.py',shell=True)
Another menu option is supposed to end the job immediately
... |
Sum elements in a row (Python/Numpy)
Question: Working on a project that gives us free reign on what to use. So I decided I'd
learn python for it.
To make this short, I want sum all the elements in a "row" of a matrix I'm
reading in.
This is what my 2D array looks like after I read in my table from my text
file.
... |
Sending a C++ array to Python and back (Extending C++ with Numpy)
Question: I am going to send a `c++` array to a python function as `numpy array` and get
back another `numpy array`. After consulting with `numpy` documentation and
some other threads and tweaking the code, finally the code is working but I
would like to... |
Re render content in angular
Question: I am using angular for front end and Python-Django as backend . I am rendering
an HTML in python using `TemplateResponse()` and this response is then sent to
angular as response where I store this in some `$scope variable` . The
important thing here is The HTML I am rendering in P... |
Sum of an array
Question: So in Python `sum([])` will yield 0, which is pretty important.
Whereas in ruby `[].reduce(:+)` will give nil, of course the ternary operator
isn't a replacement, because:
(my_complicated_mapping).empty? ? 0 : (my_complicated_mapping).reduce(:+)
Will call `my_complicated... |
How can we convert 01-01-2011 19:00 to weekdays like Mon ,Tue .. in python?
Question: I was working on a pandas dataframe where I had a column of datetime now I
haveto convert it into Weekdays.How can I do this?
Answer: There is a datetime module you may want to use.
[strptime and
strftime](http://www.tutorialspoint... |
Port C++ class to PyQt
Question: I am trying to convert a Qt4 custom widget written in C++ to a Python 2.7
custom widget. However, I have not been able to figure out how
`QLabel(parent)` would be written in Python. This is the original C++ code
from the ".ccp" file:
DocumentWidget::DocumentWidget(QWidget... |
Matplotlib graph appearing as a Python list type
Question: The following code produces a graph:
import matplotlib
gr = matplotlib.pyplot.plot([1,2,3])

Now, if I check the type of this seemingly graph object:
typ... |
Using Mozmill for testing Firefox addon
Question: I have a Mozilla Firefox addon and wanna test it. I've found Mozmill and wrote
the small Python script, which is just taking each Firefox version and run the
command like this:
mozmill --binary=C:\browsers\firefox\38.0.1\firefox.exe
--addon=C:\my_ext... |
Review Board Setup Issue - Target WSGI script cannot be loaded as Python module
Question: Complete Review Board set-up but getting following error on accessing Apache
web server, please suggest fix for the problem.
Error logs for Apache web server:
[Fri May 22 13:17:47.175095 2015] [core:notice] [pid 23... |
How to block import of specific python package?
Question: I need to programmatically block import of a python package and all child
packages.
For example, I need to block loading of the package "foo" and also ensure that
all children of foo such as "foo.bar" cannot be imported.
How can this be achieved in python 2.x ... |
Python sockets will not connect
Question: I'm trying to run a server and a client on two separate Windows 7 machines on
the same network using sockets in Python 2.7. First I'm just trying to get
them to connect before trying to do anything.
Currently my server is:
import socket
host = '0.0.... |
How can I pass a file from a python program to a perl script and then reopen it in python?
Question: I have a python program that opens and manipulates a file. It takes a file
with a single fasta entry (ex1) and splits it into a mulit-fasta file (ex2).
ex1:
>genome_fasta
ATCG.... (thousands of chars... |
Error: Set not JSON Serializable while converting TSV File into JSON Format using Python
Question: I'm looking to convert a TSV File I have into JSON Format for mapping (google
fusion maps doesn't support mapping multiple objects in the same location so
I'm converting it to JSON format to try on Mapbox). Here's my TSV ... |
JSON SyntaxError: Unexpected end of input
Question: I have the following ajax call where I am passing the data in JSON format and
when this code gets executed I get the error shown below,I showed the
Console.log(data_cp) below and I validated it in <http://jsonlint.com/> and it
is a validated input?what am I missing he... |
Python Django installing mysql: easy_install and pip errors
Question: Trying to `python manage.py syncdb` but it gives me an error. Similar to a lot
of other questions on here, but the solutions provided do not solve the error
after I install them.
My `settings.py` file inside my project directory
DATAB... |
Python Requests set cookies in a non-random order
Question: I need to send cookies in a specific, not random order.
Python requests use a dictionary to manage cookies, so the predefined cookies
I set are always in a random order.
Also, the subsequent cookies from the session are placed randomly after the
predefined c... |
TypeError: 'Weather' object is not callable
Question: I'm very new to programming so please excuse me if I lack the correct
terminology.
I'm trying to retrieve an image from a website and post it onto a GUI with
tkinter. It works, insofar as it posts the image on the GUI; however it still
produces an error as per the ... |
python - is it possible to enter user-chosen input and output files
Question: I'm a newbie in python, so please bear with me.
I don't know how to describe,so I'll just show an example.
python CODE.py -i1 input1.txt -i2 input2.txt -o output.txt
Is such thing possible with python? I've looked up for... |
python install lxml on mac os 10.10.1
Question: I bought a new macbook and I am so new to mac os. However, I read a lot on
internet about how to install scrap
I did everything, but i have a problem with installing lxml
I tried this on terminal
pip install lxml
and a lot of stuff started to be dow... |
attribute error in python (code-skulpor)
Question: im trying to run the following code on codeskulptor. and its giving an error:
Line 17: AttributeError: 'card' object has no attribute 'rank'. y is this so?
import simplegui
ranks=('A','2','3','4','5','6','7','8','9','T','J','Q','K')
suits=('... |
fabric.api vs fabric.operations
Question: I am new to Python and Fabric, using Fabric==1.10.1 and Python 2.7.6. I don't
understand the difference between fabric.api and fabric.operations calls, both
seem to be doing the same thing. Which one should I use in fabfile? One thing
that I noticed is when I do `fabric.api.reb... |
Create a thread using a class constructor as function
Question: I know that I can create and start a thread in Python using the following
syntax:
import threading
tracker_thread = threading.Thread(target=func, args=(x,y,z))
tracker_thread.daemon = True
tracker_thread.start()
What I... |
Django - Save file to static directory from view
Question: I am building a website with Django, hosted on PythonAnywhere. One of the
website pages is a private page that I use to build content that will be then
displayed in the public pages. Rather than saving the content produced within
the private page to the databas... |
Sending multiple POST data in Python
Question: I have a Python code that sends POST request to a website, reads the response
and filters it. For the POST data I used ('number', '11111') and it works
perfect. However, I want to create a txt file that contains 100 different
numbers as 1111,2222,3333,4444... and then send... |
I'm getting a recursive error [RuntimeError: maximum recursion depth exceeded while calling a Python object] - but my code is iterative -- or is it?
Question: I'm getting a recursive error:
> RuntimeError: maximum recursion depth exceeded while calling a Python object
But my code is iterative...or is it? I thought it... |
Python: parallelizing operations on a big array iteratively
Question: I am trying to parallelize operations on a big array. I summarized my approach
in the code snippet below. Since the operations on the big array are costly,
of the 100 processes, I want to parallelize 4 (i.e. n_cpus) at each iteration.
After an iterat... |
How to read a particular data format
Question: What shold I use in python 3 to read Json format?
Answer: To read in a some JSON data in a file:
from json import loads
with open("data.txt", "r") as f:
data = loads(f.read())
To get the first date in "items":
first_da... |
and operator with random
Question: i dont understand why the code bellow doesnt work properly. If both variables
a and b < 0 it should print that both numbers are negative,else the last
message. But it just dont work so, what am i doing wrong? please help!
import random
while True:
input()
... |
sikuli (python) script starting at xx hour of the day, wait("image.png",highnumber) not working?
Question: first i'd like to thanks everyone who can help me
i've been using a program that automated some boring features in a game i
like, but it's not working anymore.
the thing i want it to do is really stupid, but am ... |
Python using a string (with variables) in lambda expression
Question: I want to use a string of a polynomial in a lambda expression, but I couldn't
figure out how to do it. It may not be possible, but if it is I'd love some
help!
An example of what I'm trying to do is:
f = lambda x: '3*x^3 + 2*x^2 -4*x ... |
Cant Add Shape (image)
Question: I am trying to add a image to my code but it keep raising the error
> Bad arguments for register_shape
I am following the tutorial at <http://blog.trinket.io/using-images-in-turtle-
programs/>
my code is:
import turtle
screen = turtle.Screen()
# click... |
Connecting to Google Datastore using gcloud
Question: I am trying to connect to my Google Datastore instance but I can't find any
sample code for how to initialize a connection!
Gcloud's main [documentation](https://googlecloudplatform.github.io/gcloud-
python/latest/datastore-api.html) immediately starts with how to ... |
python / kivy .kv file wont read
Question: I have just started learning to program I have a really basic App based on a
pong game tutorial on the kivy.org site but I must have a basic flaw that I
can't see as when I run the program all I am getting is a blank screen rather
than the expected canvas and labels. Please he... |
xlsxwriter expected an indented block
Question: After spending some time to compile
[libxlsxwriter](http://libxlsxwriter.github.io/) as a dylib for osx without
success, I made the decision to switch to NSTask using the Python module
[XlsxWriter](http://xlsxwriter.readthedocs.org/). But another problem come
out: indenta... |
I've mangled Cython badly, it's performing worse than pure Python. Why?
Question: I'm rather new to Python and absolutely ignorant of C (unfortunately) so I am
struggling to properly understand some aspects of working with Cython.
After profiling a Python program and discovering that it was just a couple of
loops that... |
Python Tkinter shown before rest of program executed
Question: I'm working on creating a Launcher/updater for my small scale game I'm
building. I have the program create the gui then have it auto start
downloading the version file to check if it needs to be updated. Sadly the
gui, which is made using Tkinter, won't sho... |
Issue in deploying django application
Question: I am getting "Internal Server Error" when I try to access the django website.
I am using Django 1.8, Python 2.7.10, centos 6.5 and apache.
In apache log I am getting the following error:
mod_wsgi (pid=23866): Target WSGI script '/abc/abc/abc/wsgi.py' canno... |
Tkinter GUI and reading serial
Question: I am new to python and tkinter... I am using Tkinter to display a gauge and
receive the info through serial com. I have my GUI ready and now need to read
the serial values.
The problem I am facing is that I am not being able to read continuously the
serial COM. I came across `s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.