text stringlengths 226 34.5k |
|---|
Python (NumPy) Arrays with Alternative Lengths which can not be predefined
Question: I'm currently working on a numerical python code (from scratch) to solve the
following thought problem:
Imagine I have a 2D problem with a rigid ground, and a flexible layer on top
of that, which is connected to the ground by equidist... |
Use three different quotation marks in a bash command in Python scripts
Question: I want to have three different quotation marks in a python script, because I
want to execute a two-line python command, on a different computer. For
example:
import commands
command = "ssh someothercomputer 'python -c `... |
How Python threading Timer work internally?
Question: I want to know how python `threading.Timer` works.
In more detail, When i run a couple of `threading.Timer`, does it run separate
thread for counting a time and running the handler ?
Or one thread manages and counts a couple of timer together ?
I am asking becaus... |
How To Compare Items In Two Lists Python 3.3
Question: I tried using `cmp(list1, list2)` to learn it's no longer supported in Python
3.3. I've tried many other complex approaches, but none have worked.
I have two lists of which both contain just words and I want it to check to
see how many words feature in both and re... |
"maximum recursion depth exceeded" while compiling py file with py2exe
Question: The py2exe worked quite well on the same py file several months ago. But when
I tried it again today it failed by reporting a “RuntimeError: maximum
recursion depth exceeded”. I got an empty “dist” folder as a result. The Py
file works nor... |
How to solve: ImportError: "No module named 'graphlab'?
Question: With "source activate graphlab" in the terminal I can start up graphlab.
I've created it like this: "conda create -n graphlab python=2.7 anaconda",
because using virtualenv with Anaconda is untested and not recommended
(according to the warning in the t... |
Installed Spyder using pip under Canopy (OSx), how do i start Spyder?
Question: I am on a machine running Yosemite. I manage my python environment with Canopy
Enthought. I'm trying to install Spyder, so I don't have to use the Editor
that comes with Canopy.
I opened a Canopy terminal and used `pip install spyder` whic... |
How to get raw bytes from GLib.GString in Python?
Question: I have an application written in Python using GTK3 through the GObject
introspection (Python 2.7 and PyGObject 3.14). I am trying to load a web page
using WebKit and access the contents of all the resources it loads. I'm able
to accomplish this by connecting t... |
Python string recursion
Question: I have to recursively replace characters in a string with new characters. I'm
a bit stuck right now, however. I cannot import anything, so here is my code:
EDIT: I forgot to mention that I'm not allowed to use any built in functions
besides len() and index/splice operators. This means... |
pyserial 2.7 and USB Relay module
Question: I've purchased two lctech-inc.com 011801 USB Relay Modules. I'm trying to
control them with python and pyserial. The module does show up as USB-SERIAL
CH340 (COM5). The support information says:
Communication baud rate: 9600bps; Protocol: start: 0 x A0,
sw... |
Converting a Python List into a Numpy Structured array?
Question: I need to convert a Python list with mixed type (integers and floats) to a
Numpy structured array with certain column names.
I have tried the following code but for some reason I cant see it doesn't
work.
import numpy as np
lmtype = [... |
Interact with a webpage containing dynamic list using Python
Question: I am trying to write a Python program to automatically add tasks to todoist. I
am currently trying to use mechanize but not sure if this is what I need
because it is set up to interact with forms and I'm not sure if todoist is
using HTML forms for i... |
paramiko.ssh_exception.SSHException: Expecting packet from (31,), got 94
Question: When I use pysftp-0.2.8 to send a Large files to my sftp service. it always
got the same error:paramiko.ssh_exception.SSHException: Expecting packet from
(31,), got 94
The file is about 1.5G , when it transfers at 500M, it break. code h... |
IronPython attribute is not callable
Question: I have a problem with the following IronPython attribute (`RouteAttribute`):
import clr
import System
from System.Web.Http import HttpGetAttribute, ApiController, RouteAttribute
class DemoController(ApiController):
@RouteAt... |
Append object to end of list
Question: Im using python with junit_xml to parse a logfile to produce a xml output. My
logfile looks like this:
/path/to/app1,app1,success,[email protected],app1_log.log
/path/to/app2,app2,fail,[email protected],app1_log.log
I am able to do append multiple TestCase objects t... |
Solving a Tricky Integral on Python
Question: I'm currently working on solving a solid angle calculation for my physics
project. My python skills are basic and I need some hints/tips on how to go
about solving this equation which I obtained from a research paper - equation
9b on ([http://ac.els-
cdn.com/S09698043060020... |
getElementsByTagName() in Python's xml.dom.minidom is not working
Question: I am parsing an output XML file generated from gtest. I want to find the
result of each test case. A test case is failed only when "testcase" has
element "failure" otherwise test case is passed. But I could not access
element.
My xml file :-
... |
Length of the line in a file in Python returns value always as No. of Characters + 1
Question: I am using python 2.7.x
I have a file page06.txt
1
22
333
4444
55555
666666
7777777
88888888
I am reading this file through a program:
from __future__ import p... |
Converting a datetime object to an integer python
Question: I would like to convert a datetime object to an int in python:
import datetime
time_entered = datetime.datetime.strptime(raw_input("Time1: "), "%H%M")
time_left = datetime.datetime.strptime(raw_input("Time2"), "%H%M")
time_... |
Naming a folder with the name of the first file in the same folder python
Question: I have a code that reads a csv file and create multiple folders and puts a
determined number of files with a certain name within the folder. The folders
need to be called as the first file that is placed inside each folder.
... |
pyspark getattr() behavior
Question: Noticed some strange behavior with PySpark, would appreciate any insights.
Suppose I have an RDD composed of simple elements
from collections import namedtuple
Animal = namedtuple('Animal', ('name','age'))
a = Animal('jeff',3)
b = Animal('mike',5)
c =... |
string to date in python with the greatest possible year when dow is given
Question: Given:
from datetime import datetime
date = datetime.strptime('Wed 12 Nov', '%a %d %b')
It returns `datetime.datetime(1900, 11, 12, 0, 0)`. What might be the best way
to get the greatest past year?, in thi... |
python - create json file from input matrix by grouping rows
Question: Given the matrix below, I'd like to create and json output that will iterate
through the matrix rows and append items (col 1) if the group (col2) repeats:
matrix = [
['JAN', '1', 'abc'],
['FEB', '7', 'xyz']... |
How to acces class variables outside class in python
Question: I am new to python and this is my first program in python i want to know how
to access class variables outside class.I have a code which throws some error
from xxxxxxx import Products
class AccessKey(object):
def key(self):
... |
Python- Importing a dat file into an array using numpy
Question: Hey guys im trying to import text file into an array using numpy but it looks
like when it imported them with the rows as cols and vice versa. Am I
formatting the array wrong or is that what happnened?
I added a picture below:
 module. (The Cmd class
provides a simple framework for writing line-oriented command interpreters.)
My program is cli to api.
My problem is that I can't test it now.
I can run:
... |
Sublime Plugin: How can I import wx?
Question: I have trouble in making sublime text 3 plugins. I Just Installed wxPython
with python2.7 on my macintosh.
In terminal, my mac can find wxPython-import wx. But, Sublime Text Plugin
Source cannot imported wxPython.
You can check out capture below.
. With my current cloud,
I can generate a cloud, but the words all are the same size. How can I alter
the code so that my words' sizes appear... |
mpiexec and python mpi4py gives rank 0 and size 1
Question: I have a problem with running a python Hello World mpi4py code on a virtual
machine.
The hello.py code is:
#!/usr/bin/python
#hello.py
from mpi4py import MPI
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm... |
In python replacing characters from multiple char maps
Question: I haven't been able to find a solution to this problem, and it's for a
workaround in some bad platform code that I can't do anything about. I want to
render UTF-8 strings but the platform crashes if it receives a character out
side it's supported characte... |
Simple Filter Python script for Text
Question: I am trying to create what must be a simple filter function which runs a regex
against a text file and returns all words containing that particular regex.
so for example if i wanted to find all words that contained "abc", and I had
the list: `abcde`, `bce`, `xyz` and `zyx... |
How can mongomock can be use with motor?
Question: I have a server implemented with Tornado, and Motor, and I've come across this
mock of pymongo: <https://github.com/vmalloc/mongomock>
I really like the idea of doing the unit tests of my code with no real call to
the DB, for the sake of running them very fast.
I've ... |
creating vector using netcdf into array
Question: I'm fairly new to python and have found stack overflow one of the best
resources out there, now I'm hoping someone can help me with what I believe is
a fairly basic question.
I'm looking to create a land mask from a list of lats and lons and rainfall
data extracted fro... |
Passing a numpy function in python to C++ using SWIG directors
Question: My code is mainly in C++, but I want to use the SWIG director option to
redefine a C++ virtual function in python, and then pass that function back to
C++. The following is a simplified example.
Here is my base class in C++ with a virtual functio... |
using python to randomize csv file
Question: I'm new for python and would love to get some help.
I have a csv file with 2 columns, think:
1 A
2 B
3 C
4 D
My aim is to use python to "open" the file, read it, randomize the order of
the two lists (i.e. have 1 be with the same line as C, 2 with D etc.), and
then save... |
Quickly parse Python datetime in a non-local timezone, adjusting for daylight savings
Question: I need to quickly turn an ISO 8601 datetime string--with no timezone in the
string, but known to be in the US/Pacific timezone--into a numpy `datetime64`
object.
If my machine were in US/Pacific time, I could simply run
`nu... |
How to properly create and run concurrent tasks using python's asyncio module?
Question: I am trying to properly understand and implement two concurrently running
[`Task`](https://docs.python.org/3/library/asyncio-task.html#task) objects
using Python 3's relatively new
[`asyncio`](https://docs.python.org/3/library/asyn... |
Finding modes for multiple dictionary keys
Question: I currently have a Python dictionary with keys assigned to multiple values
(which have come from a CSV), in a format similar to:
{
'hours': ['4', '2.4', '5.8', '2.4', '7'],
'name': ['Adam', 'Bob', 'Adam', 'John', 'Harry'],
'salary': ['55000... |
What is %timeit in python?
Question: I always read the code to calculate the time like this way:
%timeit function()
Can you explain what means "%" here?
I think, the "%" is always used to replace something in a string, like %s
means replace a string, %d replace a data, but I have no idea about thi... |
pandas dataframe from a nested dictionary (elasticsearch result)
Question: I am having hard time translating results from elasticsearch aggregations to
pandas. I am trying to write an abstract function which would take nested
dictionary (arbitrary number of levels) and flatten them into a pandas
dataframe
Here is how ... |
Numpy individual element access slower than for lists
Question: I just started using Numpy and noticed that iterating through each element in
a Numpy array is ~4x slower than doing the same but with a list of lists. I
know now that this defeats the purpose of Numpy and I should vectorize the
function if possible. My qu... |
Python sqlite3: run different sqlite3 version
Question: I'm running a Django project using sqlite as one of the databases. I would
like to run the most recent SQLite version when running the project. By that I
mean the most recent sqlite binary, not the sqlite python library.
I have a local sqlite3 binary that is not ... |
Python timer on randint
Question: If I have this code:
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
screen.fill((r, g, b))
How do I set it so that it chooses a random number every, say, 10 seconds?
Answer: There are **many different** approaches for that problem. :)
A ... |
Python: ctypes and Pointer to Structure
Question: I am trying to make a pointer of a struct and then de-reference it. But it's
crashing. I have mimic'ed the behvior here with this simple code.
from ctypes import *
import ctypes
class File(Structure):
_fields_ = [("fileSize", c_uint),
... |
How to read multiple NetCDF files from a folder in python
Question: I am attempting to make a plot of mean temperatures of multiple years
(1979-2014), the only problem I am having is attempting to read multiple
NetCDF (.nc) files from a folder. At the moment my program will plot a single
file, but I do not understand h... |
Drawing 3D points on a 2D plot reading values from a file
Question: I have a file containing sets of points with 3 coordinates, separated by tabs.
Like this (spaces added for readability, not present in the original file):
x0 \t y0 \t z0
x0 \t y1 \t z1
x1 \t y0 \t z0
x1 \t y1 \t z1
x1 \t ... |
Python Countdown Timer includes Extra Zero
Question: I'm attempting to make a timer that, once inputing any amount of minutes, the
window will count down the time in a mm:ss format. however, when inputing a
time over 10 mins, when the minutes get below 10 after starting at any time
above 10 minutes, an extra zero appea... |
Issue With Relative Imports In Python
Question: I'm running into an issue with how to properly declare imports for some
modules that I've written.
Suppose the follow directory structure:
main_dir/
__init__.py
module_A
sub_dir/
__init__.py
module_B
module_C
... |
yum install python-setuptools to install easy_install and ansible - errors: AttributeError: other Python Errors
Question: Goal: Install ansible on a RedHat Linux machine.
**Little overview on how it all started:** When my Linux machine was RedHat
5.9 (Tikanga), the default python installed version was 2.4. I tried my ... |
Threading in python - processing multiple large files concurrently
Question: I'm new to python and I'm having trouble understanding how threading works. By
skimming through the documentation, my understanding is that calling `join()`
on a thread is the recommended way of blocking until it completes.
To give a bit of b... |
Python regex £ sign
Question: I'm reading from a text file which contains pound signs (£):
f = open(file, 'r')
string = f.read()
f.close()
Along with some other regex operations, I want to remove these pound signs,
and write the string to a new file. The closest I've got to making this work... |
Logic for if statement that executes code based on exception in Python
Question: I would like to run a script every five minutes in windows task scheduler. The
script reads a JSON web-service of service requests and writes specified
fields to an esri geodatabase.
For this process, there is a time stamp, with the infor... |
python scikit error - no module named sklearn
Question: When i follow the website
(<https://www.kaggle.com/wiki/GettingStartedWithPythonForDataScience>) and
type `python makeSubmission.py` I get the following error message :
ImportError: No module named sklearn
I think I have already successfully i... |
Python: How can i find a directory that matches the first 3 characters from a string?
Question: I have a directory with 50+ directories inside which are named `"XXX -
something"`
If I have `X = '123'` How can I find the directory that starts with `'123'`?
Answer: You can try this using
[`os.walk`](https://docs.pytho... |
IronPython: How to call a function that expects an array of value-types?
Question: I have come across a problem with IronPython that I can't solve. I need to
call a function that takes a parameter of type array to value-type. The
function-signature (in C++/CLI notation) is this:
static int PLGServiceInte... |
Why does OLS raise LinAlgError: SVD did not converge?
Question: I have an array:
Num Col2 Col3 Col4
1 6 1 1
2 60 0 2
3 60 0 1
4 6 0 1
5 60 1 1
And the code:
y = df.loc[:,'Col3'] # response
X = d... |
python3: doctest helper/internal functions?
Question: How do I make the following work so that helpers's test is run? It doesen't.
def B():
def helper():
"""
>>> some doctest
result
"""
...
if __name__ == "__main__":
import doct... |
How to make my Piecewise function zero outside the provided interval in python
Question: Here is my code:
In [61]: import sympy as sp
In [62]: x = sp.Symbol('x')
In [63]: phi_1 = sp.Piecewise( ( (1.3-x)/0.3, 1<=x <=1.3 ))
In [64]: phi_1.subs(x,1.2)
Out[6... |
python how to uppercase some characters in string
Question: Here is what I want to do but doesn't work:
mystring = "hello world"
toUpper = ['a', 'e', 'i', 'o', 'u', 'y']
array = list(mystring)
for c in array:
if c in toUpper:
c = c.upper()
print(array)
`"e"... |
How can I ask for entry data in tkinter in python 3.4?
Question: How can I ask for entry data in tkinter? I tried using standard if statement
but it seems like I'm doing something wrong.
from tkinter import *
class Search(Tk):
def __init__(self):
Tk.__init__(self)
... |
Twist failure when using scrapy to crawl a bbs
Question: I am a newbie to python scrapy, and wrote a simple script to crawl posts from
my school's bbs. However, when my spider runs, it get error messages like
this:
> 015-03-28 11:16:52+0800 [nju_spider] DEBUG: Retrying
> http://bbs.nju.edu.cn/bbstcon?board=WarAndPeace... |
Python - count words not in a distance of three (3) words from specific words
Question: I am using the following `Python` code to `count words in text (.txt) files`,
checking whether any of the words in text file belong in any of the `two lists
of words that I am considering (the word lists are .csv files, imagine thes... |
Face Detection using Haar - OpenCV python
Question: I am trying this python code snippet:
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('img.jp... |
PySerial doesn't work in script
Question: I have problem with this script:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
import time
ser = serial.Serial("COM3", 9600, timeout=1)
ser.write("test")
print "Test started\n"
time.sleep(1)
ans = ser.read(4... |
Forcing a thread to block all other threads from executing
Question: UPDATE:
[This answer](http://stackoverflow.com/a/16262657/336527 "This answer") states
that what I'm trying to do is impossible as of April 2013. This, however,
seems to contradict what Alex Martelli says in [Python
Cookbook](http://shop.oreilly.com/... |
Stripping timestamp from Json int
Question: In a third-party script, it's meant to spit out Json for me to decode but
instead prepends a timestamp:
2015-03-28T16:32:41.875199+00:00 {"1": {"Power (kW)": "0.301", "Energy Imported (kWh)": "62.281"...}}
All of this is in one big integer. I've tried to ... |
Exception gevent.hub.LoopExit: LoopExit('This operation would block forever',)
Question: I am always getting this error when running my Flask App with Websockets. I
have tried to follow this guide - <http://blog.miguelgrinberg.com/post/easy-
websockets-with-flask-and-gevent>
I have a flask app that provides the GUI in... |
The view didn't return an HttpResponse object. It returned None instead. Request Method: POST
Question: The problem appears when I submit the form. A few days ago it worked, I
changed nothing in this code, but now it fails. Is it possible that different
module makes that part of code crashed? Traceback:
Environment:
... |
How to convert '*' to *
Question: I am making a math quiz game in python, where the computer selects 2 numbers
and 1 symbol from a list and prints it, then the user answers the question. In
my list with the symbols, I have the math symbols as strings, but when I want
the computer to get the answer, It can't, because th... |
Send data to Arduino on keypress Raspberry Pi
Question: I'm trying to build a car (Wild Thumper) that i can drive from my Raspberry
Pi. Currently i'm using my Raspberry Pi over SSH. It should send to data to my
Arduino so it knows when it has to go forward or when to turn.
I've tried making scripts that get called by ... |
Python queue linking object running asyncio coroutines with main thread input
Question: I have a script running where the main thread takes input from stdin and then
passes it to a child thread using a queue. In the child thread I'm using
asyncio coroutines to spin up a listener on a socket and wait for connections.
On... |
Why is Python sort faster than that of C++
Question: Sorting a list of ints in python 3 seems to be faster than sorting an array of
ints in C++. Below is the code for 1 python program and 2 C++ programs that I
used for the test. Any reason why the C++ programs are slower? It doesn't make
sense to me.
\----- Program 1 ... |
Read specific column from .dat-file in Python
Question: I have a results.dat file with some data like this:
7522126 0 0 0 0 0 0 -419.795 -186.24 1852.86 0.134695 -0.995462 -2.53153
7825452 0 0 0 0 0 0 -419.795 -186.24 1852.86 0.134695 -0.995462 -2.53153
807... |
Why are my dictionary values changing after the loop?
Question: Following is my python code:
from collections import defaultdict
data = {"Manoj":{"India":{"Airtel":2000,"Vodafone":5000},"Pakistan":{"Airtel":3000}},
"Shafiq":{"Pakistan":{"Airtel":5000,"BP":10000}},
"Shams":{"India":{"B... |
How to open a simple image using streams in Pillow-Python
Question:
from PIL import Image
image = Image.open("image.jpg")
file_path = io.BytesIO();
image.save(file_path,'JPEG');
image2 = Image.open(file_path.getvalue());
I get this error `TypeError: embedded NUL ... |
'connection refused' with Celery
Question: I have a Django project on an Ubuntu EC2 node, which I have been using to set
up an asynchronous using `Celery`.
I am following [How to list of the queued items in
celery?](http://stackoverflow.com/questions/29319889/how-to-list-of-the-
queued-items-in-celery) along with the ... |
Python: Print data while waiting for input
Question: Writing a chat program and am looking for the ability for it to print messages
that are being received when they are received while the user can enter a
message to the other person. Currently the program sends message to other
computer then receives the other compute... |
Troubles with MySQL, SQLAlchemy, Flask, and flask.ext.script -- create_all() doesn't create tables
Question: I am not able to create tables when I do the following in my virtualenv:
(plasma) $ python checkup_web.py shell
> from app import db
> db.create_all()
There is no error message thro... |
Starting CherryPy application with HTTP method dispatcher
Question: I am new to cherrypy, and I am trying to start a simple application using the
method dispatcher. I have been trying to learn about cherrypy configuration
using this site:
<https://cherrypy.readthedocs.org/en/3.2.6/concepts/config.html>, but I am
still ... |
Indexing pandas dataframes inside pandas dataframes with python
Question: I have a series of dataframes inside a dataframe.
The top level dataframe is structured like this :
24hr 48hr 72hr
D1 x x x
D2 x x x
D3 x x x
In each case x is a datafram... |
BeautifulSoup/Python/HTML - Return the div class right after a specific div class
Question: Example:
<div class="label">Employee Count</div>
<div class="field">331,000</div>
How can I use beautiful soup (or a different python lib) to search an HTML
file for "Employee Count" then return the valu... |
Python character and word counts
Question: I'm a beginner with python and would like to know how to use two txt files to
count the characters as well as counter the 10 most common characters. also
how to convert all characters in the file to lower case and eliminate all
characters other than a-z
here's what i've tried... |
Calling `sed` from inside a python program
Question: I have the following code snippet in bash which I use for processing a JSON
file.I want to do the exactly same functionality in python. Can I call `sed`
from python? Or how do I achieve the same thing.
for file in /home/Work/ts_parts/*
do
... |
Attribute error in python unittest
Question: On executing this unittest getting
AttributeError: 'BaseUnit' object has no attribute 'driver'
import unittest
import redis
from selenium import webdriver
redis = redis.Redis(host='abc', port='123')
keys = redis.keys('*')
raw_baseunit = re... |
Django Tutorial Error: Setting up the test client
Question: I'm on part 5 of the Django Tutorial and I've hit a snag. I'm trying to setup
the test client with the following commands in the python shell:
from django.test.utils import setup_test_environment
setup_test_environment()
I get the foll... |
Yet another python scoping issue
Question: I've read bunch of scoping posts but I haven't found answer to mine. I use
python 2.7.6. Here's the code:
def play(A, B):
state = START_STATE
#player = None
while state[1] < goal and state[2] < goal:
if state[0]:
... |
Networkx node deletion / removal callback
Question: Given a directed networkx graph. I would like to have a function, say
"`abc()`", called for every node that is deleted from the graph. I went
through the networkx documentation but did not find any such callback feature.
What I considered:
1. Adding a call to `abc... |
Need to create a user application in python-Django framework where based on input data will insert or update in the database
Question: I am a newbie in python-Django and i have a requirement where i need to create
a template where there will be a text input name (id) and a drop down as
OPS(view,insert,edit) and by givi... |
Dictionaries x.update(y) for pandas DataFrames?
Question: I am sitting in front of a probably very simple problem. I have two pandas
DataFrames with some common Indices, like so:
import pandas as pd
x = pd.DataFrame(index=[1, 2, 3, 4],
data={'d': [5, 5, 5, 5]})
y = pd.DataFra... |
selenium - python - identify suspected phishing sites
Question: I'm trying running code (in Python) that can identify suspected phishing
sites. I'm using Selenium's chromedriver. This is my code:
import os, os.path, sys
from selenium import webdriver
from selenium.webdriver.chrome.options import ... |
Extracting data from `:` till <br> using python
Question:
Page load for http://xxxx?roxy=www.yahoo.com&eventto=https://mywebsite?event took 4001 ms (Ne: 167 ms, Se: 2509 ms, Xe: 1325 ms)<br><br><br>Topic: Yahoo!! My website is a good website | Mywebsite<br>
I want to use regular expressions in python to extr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.