Differences between BaseHttpServer and wsgiref.simple_server

I’m looking for a module that provides me a basic http server capabilities for local access. It seems like Python has two methods to implement simple http servers in the standard library: wsgiref.simple_server and BaseHttpServer.

Python Recursion through objects and child objects, Print child depth numbers

I have a simple class with an attribute that can contain a list of objects of the same class

Column arithmetic in pandas dataframe using dates

I think this should be easy but I’m hitting a bit of a wall. I have a dataset that was imported into a pandas dataframe from a Stata .dta file.

Compare similarity of terms/expressions using NLTK?

I’m trying to compare terms/expressions which would (or not) be semantically related – these are not full sentences, and not necessarily single words; e.g. –

Converting comma-separated string to list [duplicate]

Converting comma-separated string to list [duplicate]

Django What is the best way to format forms?

I have just gotten into Django and read a bunch of books, now im building my first app. When I render my forms in my template im using…

Flask: Using a global variable to load data files into memory

I have a large XML file which is opened, loaded into memory and then closed by a Python class.

Identical databases in Flask-SQLAlchemy

I’ve already asked a similar question, but I thought maybe I could rephrase it, or show what I’ve done further to shed some light onto what’s going on here.

Numpy Convert String Representation of Boolean Array To Boolean Array

Numpy Convert String Representation of Boolean Array To Boolean Array

Print python os.urandom output on terminal

how can i print the output of os.urandom(n) in terminal?

What’s the most pythonic method for specifying a configuration file?

I’m writing a daemon script in Python and would like to be able to specify settings in a file that the program expects to read (like .conf files).

Compute on pandas dataframe concurrently

Is it feasible to do multiple group-wise calculation in dataframe in pandas concurrently and get those results back?

Hiding selected subcommands using argparse

I am using argparse and have set-up subcommands to my program. I have created sub-parsers to define these sub-commands.

MemoryError with Pickle in Python

I am processing some data and I have stored the results in three dictionaries, and I have saved them to the disk with Pickle. Each dictionary has 500-1000MB.

Automatically shorten long strings when dumping with pretty print

Automatically shorten long strings when dumping with pretty print

Django-tables2: How to use accessor to bring in foreign columns?

I’ve tried reading the docs and previous answers to this question without much luck.

Django. Get values for all fields in one object

Django. Get values for all fields in one object

For each row, what is the fastest way to find the column holding nth element that is not NaN?

I have a Python pandas DataFrame in which each element is a float or NaN.For each row, I will need to find the column which holds the nth number of the row.

Getting Python version using Go

I’m trying to get my Python version using Go:

How can I change drives using python os?

How can I change drives using python os?

How to install igraph for python on windows

How to install igraph for python on windows

How to use a specific data structure as the default_factory for a defaultdict?

I am currently using a defaultdict of Counter to uniquely count several unpredictable values for unpredictable keys:

Is there a Python method to access all non-private and non-builtin attributes of a class?

I would like to call a method to give me a dict of all of the “non-private” (I use the term “private” somewhat loosely here since it does not really exist in Python) and non-builtin attributes (i.e. those that do not begin with a single or double underscore) on a class.

Marshmallow not giving errors

Marshmallow not giving errors

Numpy element wise division not working as expected

From the docs, here is how element division works normally

Pip default behavior conflicts with virtualenv?

Pip default behavior conflicts with virtualenv?

Proper way to make functions extensible by the user

What is the proper way in Python to allow the user to extend the types on which a function can operate without altering the original code of the function?

Python Matplotlib – Impose shape dimensions with Imsave

I plot a great number of pictures with matplotlib in order to make video with it but when i try to make the video i saw the shape of the pictures is not the same in time…It induces some errors.

Python – pandas – Append Series into Blank DataFrame

Python – pandas – Append Series into Blank DataFrame

Should the order of import statements matter when importing a .so?

I am getting the following import error when trying to load a python module compiled using boost python.

Twisted reactor is stopped, but program doesn’t end?

So I’m writing a small script to use with Deluge. Deluge uses Twisted, and I really don’t have a firm grasp on how it works.

Why does this Python script have a \ before the multi-line string and what does it do?

Why does this Python script have a \ before the multi-line string and what does it do?

Why wouldn’t I want to add Python.exe to my System Path at install time?

I’m reinstalling Python, on Windows 7, and one of the first dialog boxes is the Customize Python screen.

Flask-SQLAlchemy join across 3 models and a Table construct

Flask-SQLAlchemy join across 3 models and a Table construct

Why does installing numpy require python-dev in Kubuntu 12.04

Just starting out in python on a pendrive 12.04 Kubuntu environment. I had to install GCC (understand that), but I also had to install python-dev before I could use PIP to install numpy. Why do I need python-dev?

Multiplying elements in a sparse array with rows in matrix

Multiplying elements in a sparse array with rows in matrix

Can you race condition in Python while there is a GIL?

My understanding is that due to the Global Interpreter Lock in cPython, only one thread can ever be executed at any one time. Does this or does this not automatically protected against race conditions, such as the lost update problem?

Why is my Python app stalled with ‘system’ / kernel CPU time

First off I wasn’t sure if I should post this as a Ubuntu question or here.But I’m guessing it’s more of an Python question than a OS one.

Deploying Flask, parallel requests

When I test my new Flask application with the built in web server, everything is “single threaded” and blocking. The server can not serve one request without finishing another. It can only process one request at a time.

print first paragraph in python

I have a book in a text file and I need to print first paragraph of each section. I thought that if I found a text between \n\n and \n I can find my answer. Here is my codes and it didn’t work. Can you tell me that where am I wrong ?

“Fire and forget” a process from a Python script

How do I start a process (another Python script, for example) from a Python script so the “child” process is completely detached from the “parent”, so the parent can a) continue on its merry way without waiting for child to finish and b) can be terminated without terminating the child process?

Pythonic way: Utility functions in class or module

I’m a python beginner, and is wondering what’s more pythonic way to write utility functions? As in Java/C++, create a utility class and have methods inside it or write functions inside the module? The function is to be used across various classes in the same module.

Using pyDub to chop up a long audio file

I’d like to use pyDub to take a long WAV file of individual words (and silence in between) as input, then strip out all the silence, and output the remaining chunks is individual WAV files.

Variable scope in nested functions

Could someone explain why the following program fails:

Django login with django-axes

I created a site with django. Users should be able to login.

Pandas scatter_matrix – plot categorical variables

I am looking at the famous Titanic dataset from the Kaggle competition found here: http://www.kaggle.com/c/titanic-gettingStarted/data

Django–django-admin.py on windows does not work

I am just starting Django these days but I cannot run this command

How to use Non-Standard Custom Font with Stylesheets?

I have a PyQt4 application that is being styled by an external .qss file by using the following code:

Represent a class as a dict or list

I’ve classes that is used for getting data from one system, making some modifications and then outputting them into another system. Which usually goes the way of converting it into a dict or a list after I’ve made all the necessary conversions.

Django Many To Many intersection filtering

For the sake of simplicity let’s say I only have 2 models: Book, Author

Saving binary data into file on model via django storages boto s3

I’m pulling back a pdf from the echosign API, which gives me the bytes of a file.I’m trying to take those bytes and save them into a boto s3 backed FileField. I’m not having much luck.

ReactorNotRestartable when launching two equivalent unittest with twisted and trial

I’ve two test classes (TrialTest1 and TrialTest2) written in two files (test_trial1.py and test_trial2.py) mostly identical (the only difference is the class name)

Display and format Django DurationField in template

Im using Django 1.8, and i have one of my field defined as DurationField, but i dont find any way to correctly display it on my template

Lasso on sklearn does not converge

Lasso on sklearn does not converge

Append two multiindexed pandas dataframes

Can you please help to append two multiindexed pandas dataframes? Trying to append df_future to df_current. COMPANY and DATE are the indexes.

In python, can one iterate through large text files using buffers and get the correct file position at the same time?

I’m trying to search some keywords through a large text file (~232GB). I want to take advantage of buffering for speed concerns and also want to record beginning positions of lines containing those keywords.

Indentation marker/vertical lines for Python in pydev

Is there a setting in Pydev source editor (Aptana studio for Eclipse) where I can see what indentation level a particular line in a Python file has? Something like a vertical line or a marker on the top/bottom window edges (as seen in image processing tools).

Writing pandas/matplotlib image directly into XLSX file

I am generating plots in pandas/matplotlib and wish to write them to an XLSX file. I am not looking to create native Excel charts; I am merely writing the plots as non-interactive images. I am using the XlsxWriter library/engine.

pip: Uninstalling package from specific directory

I installed package into specific local directory using pip install -t <dir>.

How do I free up the memory used by an lxml.etree?

I’m loading data from a bunch of XML files with lxml.etree, but I’d like to close them once I’m done with this initial parsing.

difference between ‘is’ and ‘==’ [duplicate]

Quite a simple question really.

Finding shortest combinations in array/sequence that equals sum

I’m totally stuck and have no idea how to go about solving this. Let’s say I’ve an array

Why does nosetests say –with-coverage is not an option?

I am using nosetests to automatically discover and run my unittests. I would also like to have it generate coverage reports.

Why can’t Python execute java.exe via subprocess?

After upgrading Java from 1.6 to 1.7 x64 (on Windows 7), I suddenly can’t launch java.exe via Python 2.7’s subprocess module anymore. The following script used to just work:

Quit Python program when it hits memory limit

I have a couple of Python/Numpy programs that tend to cause the PC to freeze/run very slowly when they use too much memory. I can’t even stop the scripts or move the cursor anymore, when it uses to much memory (e.g. 3.8/4GB)

matshow with sparse matrices

How can you visualize the sparsity pattern of a large sparse matrix?

Python 3 doesn’t need __init__.py in this situation?

Python 3 doesn’t need __init__.py in this situation?

Raise an exception for undefined attributes in jinja2

Raise an exception for undefined attributes in jinja2

Sample two pandas dataframes the same way

I’m doing a machine learning computations having two dataframes – one for factors and other one for target values. I have to split both into training and testing parts.

change in import handling / modules from python2 to python3?

I was trying to following the design pattern shown in this previous question related to SQLAlchemy and intended to share a common Base instance across multiple files. The code exactly as is works on python2 and python3.

Fill matrix with transposed version

Fill matrix with transposed version

Hello_World is a word in Python, it is different in an other mode. How I change it?

In python mode, when I forward-word. The cursor jumps from H to d (Hello_World). But in another mode(shell-mode or c-mode), the cursor jumps from H to _.

Python: fastest way to write pandas DataFrame to Excel on multiple sheets

I need to export 24 pandas data frames ( 140 columns x 400 rows) to Excel, each into a different sheet.

Dynamically add subplots in matplotlib with more than one column

How can I dynamically add a new plot to bunch of subplots if I’m using more than one column to display my subplots?

Calculating angles between line segments (Python) with math.atan2

I am working on a spatial analysis problem and part of this workflow is to calculate the angle between connected line segments.

PyYaml parsing of the Environment variable in the Yaml configuration file

PyYaml parsing of the Environment variable in the Yaml configuration file

Image skewness& kurtosis in python

Is there a python package that will provide me a way to clacluate Skewness and Kurtosis of an image?. Any example will be great.

Mysql with Python can’t insert record with autoincrement id, why?

I create a table ‘test’ with two column:(age int, name TEXT) in mysql database.

Scikit Learn – Calculating TF-IDF from a corpus of arrays of features instead of from a corpus of raw documents

Scikit-Learn’s TfidfVectorizer converts a collection of raw documents to a matrix of TF-IDF features. Instead of raw documents, I would like to convert a matrix of feature names to TF-IDF features.

Safely iterating over WeakKeyDictionary and WeakValueDictionary

The documentation of Python 3.2‘s weakref module’s WeakKeyDictionary and WeakValueDictionary have a note on iterating over these containers:

Doctest NORMALIZE_WHITESPACE does not work

Doctest NORMALIZE_WHITESPACE does not work

Including a GeoDjango Point in a model

I am working with GeoDjango for the first time and am having trouble adding a PointField to my model. Here is my model code:

Numpy multi-dimensional array indexing swaps axis order

I am working with multi-dimensional Numpy arrays. I have noticed some inconsistent behavior when accessing these arrays with other index arrays.

Enumerate sentences in python

I have a tuple of strings that consists of two sentences

Compile latex from python

I have made some python function for compiling passed string as pdf file using latex. The function works as expected and has been quite useful, therefore I look for ways to improve it.

Very poor weakref performance in Python/SQL Alchemy

I’ve spent the day trying to debug a memory problem in my Python script. I’m using SQL Alchemy as my ORM. There are several confounding issues here, and I’m hoping that if I list them all out, somebody will be able to point me in the right direction.

Scrapy with selenium, webdriver failing to instantiate

I am trying to use selenium/phantomjs with scrapy and I’m riddled with errors. For example, take the following code snippet:

Django with Twitter Bootstrap3 and Themes

I’ve been researching this a long time and experimenting and I can’t seem to figure out what the best way to go about accomplishing this. I know I’m doing it wrong so some clarification as well as some quick examples would help a lot.

Using git-remote-hg on windows

This doesn’t seem to work all that smooth on Windows tough.

How to create a bar chart/histogram with bar per discrete value?

I am trying to create a histogram that will show the amount of ratings per value in a discrete star ratings (1-5).

How can I play a Spotify audio with Python?

I would like to know if it’s possible to play songs from Spotify with Python (version 2.7 if possible) and how.

How to remove an 2d array subset?

I have a 800×800 array and I want to analize just the elements in the outter part of it.I need a new array without the elements of the slice [5:-5,5:-5].It doesn’t necessarily have to return a 2d array, a flat array or a list will do as well.

Is there a way to write formatted text from Python?

If you are writing to a file with python, is there any way to make certain parts of the text bold, italic, or underlined ?

Pass argument to scrapy spider within a python script

I can run crawl in a python script with the following recipe from wiki :

Using counts and tfidf as features with scikit learn

I’m trying to use both counts and tfidf as features for a multinomial NB model. Here’s my code:

Python tkinter disable the button until all the fields are filled

Let’s say I have 2 entry widgets, 1 option menu(drop down list) and 1 button in tkinter. How can i set the button widget state to DISABLED until all 3 widgets are filled by the user?

Manually-defined axis labels for Matplotlib imshow()

Manually-defined axis labels for Matplotlib imshow()

Numpy: Apply an array of functions to a same length 2d-array of value as if multiplying elementwise? (using a python function as an operator?)

I have numpy.arrays where the columns contain different data types, and the columns should also to have different functions applied to them. I have the functions in an array as well.

setup/teardown using conftest in pytest

I have different test folders(packages). I want to setup and teardown some data for a specific package(folder).

How do I remove the last character of an R-T-L string in python?

I am trying to remove the last character of a string in a “right-to-left” language. When I do, however, the last character wraps to the beginning of the string.

Is there a more vectorized way to perform numpy.outer along an axis?

Is there a more vectorized way to perform numpy.outer along an axis?

Specifying exact Python version for Travis CI in combination with tox

Specifying exact Python version for Travis CI in combination with tox

Scipy minimize fmin – problems with syntax

I have a function which takes several arguments (one array and two floats) and returns a scalar (float).

Scipy minimize fmin – problems with syntax

I have a function which takes several arguments (one array and two floats) and returns a scalar (float).

Python : Adding a code routine at each line of a block of code

I want to have a piece of code run after each line of another block of code. For example, want to be able to evaluate a global variable before or after executing the next line of a function.

subprocess.call does not wait for the process to complete

Per Python documentation, subprocess.call should be blocking and wait for the subprocess to complete.

Random cropping data augmentation convolutional neural networks

I am training a convolutional neural network, but have a relatively small dataset. So I am implementing techniques to augment it.

Writing to a File with Python — ”While not done:” Confusing Me

Writing to a File with Python — ”While not done:” Confusing Me

Quickest way of Importing 500GB Text File taking only the sections wanted

I have about 500GB of text file seperated in months. In these text files the first 43 lines are just connection information (not needed). the next 75 lines are descriptors for an observation.

Django-filter ‘__in’ lookup

Django-filter ‘__in’ lookup

Finding voronoi regions that contain a list of arbitrary coordinates

I am working with an algorithm that, for each iteration, needs to find which region of a Voronoi diagram a set of arbirary coordinats belong to. that is, which region each coordinate is located within.

Python: How can I use ggplot with a simple 2 column array?

Python: How can I use ggplot with a simple 2 column array?

Popen.communicate() returns (None, None) even if script print results

Popen.communicate() returns (None, None) even if script print results

import csv with different number of columns per row using Pandas

What is the best approach for importing a CSV that has a different number of columns for each row using Pandas or the CSV module into a Pandas DataFrame.

Python Multiprocessing Kill Processes

I am learning how to use the Python multiprocessing library. However, while I am going through some of the examples, I ended up with many python processes running in my background.

How to stop program if there is a warning

I try to use nltk to do some words processing, but there is a warning. I find out the if there is the word like “Nations�“, the program would throw a warning.

How to compare wrapped functions with functools.partial?

How to compare wrapped functions with functools.partial?

Finding index of maximum element from Python list

Finding index of maximum element from Python list

Login to a website via Python – how to deal with CSRF?

I’m using Python 3 for a script that will monitor updates in a user’s profile on a webpage. The login to this site is protected by CSRF countermeasures, which is a good thing.

Using CX_Freeze with Scipy: scipy.special._ufuncs.py

I am having problems freezing a programm of mine. I narrowed it down to the scipy module.

Suppress “The program can’t start because X.dll is missing” error popup

I have a Python program which uses os.system to execute various commands. (It can’t use subprocess because it has to be backward compatible all the way to Python 2.0.)

Writing data to LMDB with Python very slow

Creating datasets for training with Caffe I both tried using HDF5 and LMDB. However, creating a LMDB is very slow even slower than HDF5. I am trying to write ~20,000 images.

Faster alternative to Series.add function in pandas

I am trying to add two pandas Series together. The first Series is very large and has a MultiIndex. The index of the second series is a small subset of the index of the first.

Very simple user input in django

My underlying struggle is I am having trouble understanding how django templates, views, and urls are tied together…

Flask: login session times out too soon

While editing a record, if there is a long wait of let say a few minutes (getting coffee) and then coming back to press the save (POST), I get redirected to the main page to login instead and the data is lost.

Is it always bad to collect all instances in a class variable?

Consider two versions of a simple weather model which stores the location of clouds

Python: How to get local maxima values from 1D-array or list

I am pretty new in Python and I have a problem which I could not solve with found answers… hopefully someone can help

How to get image from video using opencv python

I want to get image from video and store it in ‘.jpeg’ or ‘.png’ format please help me how to do this with opencv My code is

Integrating Ember CLI with Django app

Before Ember CLI, I use to create an index.html page within Django project, plus the App.js file and all seemed to be working great.

How to check if an element from List A is not present in List B in Python?

How to check if an element from List A is not present in List B in Python?

Is it costly in Python to put classes in different files?

I am a Java programmer and I have always created separate files for Classes, I am attempting to learn python and I want to learn it right.

setting a cookie in flask

I am trying to create a cookie in flask.

Why doesn’t Python auto escape ‘\’ in __doc__?

It seems that some escape chars still matter in docstring. For example, if we run python foo.py (Python 2.7.10), it will emit error like ValueError: invalid \x escape.

Can I use pymysql.connect() with “with” statement?

Can I use pymysql.connect() with “with” statement?

Pythonic way to find key of weighted minimum and maximum from a dictionary

Pythonic way to find key of weighted minimum and maximum from a dictionary

Installing Pyomo on Windows with Anaconda (Python)

I would like to solve LP and ILP with Pyomo (Coopr) but unfortunately I am so newbie and I cannot run it properly.

Comparing two dictionaries with numpy matrices as values

I want to assert that two Python dictionaries are equal (that means: equal amount of keys, and each mapping from key to value is equal; order is not important).

Is there any way to have output piped line-by-line from a currently executing python program?

When piping printed output from a python script to a command like grep, the output from the script seems to only be piped to the follow-up command after completion of the entire script.

Embedded Documents issue with MongoEngine

I am using MongoDB with Flask-MongoEngine as my ORM component to my web app.

How to use Bcrypt to encrypt passwords in Django

I am trying to use Bcrypt to encrypt passwords that users provide upon registration and then use Bcrypt to validate a password a user provides upon login against the hashed version stored in the database.

How to use “suggest” in elasticsearch pyes?

How to use the “suggest” feature in pyes? Cannot seem to figure it out due to poor documentation.

sqlAlchemy, concrete inheritance, but parent has foreignKey

sqlAlchemy, concrete inheritance, but parent has foreignKey

filling numpy array with random element from another array

I’m not sure if this is possible but here goes. Suppose I have an array

How to install new packages for pyramid without getting a pkg_resources.DistributionNotFound: once a project has been created

I have installed pyramid and successfully created a project, but when I try to add new packages to the setup.py requirements they always give me a pkg_resources.DistributionNotFound error.

Twisted clients within pygame mainloop?

I’m trying to run a twisted-server with pygame-clients:

Django REST Framework : “This field is required.” with required=False and unique_together

I want to save a simple model with Django REST Framework. The only requirement is that UserVote.created_by is set automatically within the perform_create() method.

Python CSV reader return Row as list

Im trying to parse a CSV using python and would like to be able to index items in a row so they can be accessed using row[0], row[1] and so on.

How can I tell Scrapy to only crawl links inside an Xpath?

I am new to Scrapy and what I am trying to do is make a crawler which will only follow the links inside an HTML element on the given start_urls

In Python 3.2, is “lambda” considered a “keyword,” an “operator” or both?

In Python 3.2, is “lambda” considered a “keyword,” an “operator” or both?

If I truncate a file to zero in Python 3 do I also need to seek to position zero?

According to the answers from this question calling truncate does not actually move the position of a file.

How do I “multi-process” the itertools product module?

So I tried I tried calculating millions and millions of different combinations of the below string but I was only calculating roughly 1,750 combinations a second which isn’t even near the speed I need.

Django restframework browsable api login with ouath

I have created a sample api by using djangorestframework which worked fine and I could use browsable api without any problem.

Is python’s shutil.copyfile() atomic?

I’m writing a python script that copies a file using shutil.copyfile() on Linux. During the copying, other processes may be trying to read the file. Is the following sufficient to ensure that an external process doesn’t get a corrupted view of the file?

Python confusing function reference

Can anyone explain to me why the two functions below a and b are behaving differently. Function a changes names locally and b changes the actual object.

Error when indexing with 2 dimensions in NumPy

Error when indexing with 2 dimensions in NumPy

How can I obtain the same ‘special’ solutions to underdetermined linear systems that Matlab’s `A \ b` (mldivide) operator returns using numpy/scipy?

I found a link where it is shown with an example that the Matlab mldivide operator (\) gives ‘special’ solutions when the system of linear equations has infinitely many solutions.

wrapping subsections of text with tags in BeautifulSoup

I want the BeautifulSoup equivalent of this jQuery question.

wrapping subsections of text with tags in BeautifulSoup

I want the BeautifulSoup equivalent of this jQuery question.

Why can’t you reference modules that appear to be automatically loaded by the interpreter without an additional `import` statement?

When you start your Python interpreter it appears that some modules/packages are automatically imported during the startup process:

Understanding os.fork and Queue.Queue

I wanted to implement a simple python program using parallel execution. It’s I/O bound, so I figured threads would be appropriate (as opposed to processes). After reading the documentation for Queue and fork, I thought something like the following might work.

Python multiprocessing pool – iterating over objects methods?

Perhaps someone more fluent in Python‘s Multiprocessing Pool code could help me out. I am trying to connect to several hosts on my network simultaneously (N at any one time) over a socket connection and execute some RPC’s.

Merge multiple backups of the same table schema into 1 master table

I have about 200 copies of a SQLite database. All taken at different times with different data in them. Some rows are deleted and some are added. They are all in a single directory.

How to increment a row count in groupby in DataFrame

I need to calculate the number of activity_months for each product in a pandas DataFrame.

what’s the PYTHONPATH when there is no PYTHONPATH?

I need to add a new directory location to my PYTHONPATH, but the problem is I’m on a clean, newly-installed system (Linux) where no PYTHONPATH has yet been defined.

How to handle complex URL in a elegant way?

I’m writing a admin website which control several websites with same program and database schema but different content.

Is ‘or’ used on the right-hand-side of an assignment pythonic?

The following situation is just exemplary. This question applys to anything that can evaluate to boo

In Python Pandas, boolean operation

I am performing boolean operation on two Series. I was expecting the boolean operation to automatically do the operation corresponding to the same index.

concatenating arrays in python like matlab without knowing the size of the output array

I am trying to concatenate arrays in python similar to matlab

Difficulties on pymc3 vs. pymc2 when discrete variables are involved

I’m updating some calculations where I used pymc2 to pymc3 and I’m having some problems with samplers behavior when I have some discrete random variables on my model.

Is a SQLAlchemy query vulnerable to injection attacks?

I have the following query that uses like to search a blog. I am not sure if I’m making myself vulnerable to a SQL injection attack if I do this. How is SQLAlchemy handling this? Is it safe?

Writing append only gzipped log files in Python

I am building a service where I log plain text format logs from several sources (one file per source). I do not intend to rotate these logs as they must be around forever.

Want to save & run Python script in Jupyter Notebook (Anaconda)

Another python newbie here.Currently, I’m using Jupypter notebook in anaconda framework.

Can’t fix pyparsing error

So, I’m in the middle of refactoring a project, and I’m separating out a bunch of parsing code. The code I’m concerned with is pyparsing.

When I run the full test suite in Django, I get errors about missing MessageMiddleware

My app is called abcapp. I am running Django 1.5b1 on Python 2.7. The same issue happens in the latest trunk release of django.

How to efficiently concatenate many arange calls in numpy?

I’d like to vectorize calls like numpy.arange(0, cnt_i) over a vector of cnt values and concatenate the results like this snippet:

How to get a window title and scan it every 100ms use python?

with python, I want to get a window title,a stock software window.

15 Best PyTorch Books

Deep Learning with PyTorch will make that journey engaging and fun. PyTorch is another deep learning library that's is actually a fork of Chainer(Deep learning library completely on python) with the capabilities of torch.

How to set QDockWidget initial (default) size in the app with no central widget (PyQt4)?

I have an app with a lot of QDockWidgets and without central widget. I want to set some of those QDockWidgets initial size (size at application’s start), but I don’t want to limit their min/max sizes.

Changing the Digit Color of QLCD Number

I want to change the background and digit color of QLCDNumber in Qt Designer and I am going to use that design(GUI) on my Python program.

TypeError: function() argument after * must be a sequence, not generator

While trying to write a tiny, obfuscated type checker, an unacceptable code pattern was discovered. However, it inconsistently fails to work properly. This is the code that was initally written to test it with.

Call Python code from LLVM JIT

I write a language lexer/parser/compiler in python, that should run in the LLVM JIT-VM (using llvm-py) later. The first two steps are quite straightforward for now, but (even if I didn’t start the compile-task yet) I see a problem, when my code wants to call Python-Code (in general), or interact with the Python lexer/parser/compiler (in special) respectively. My main concern is, that the code should be able to dynamically load additional code into the VM at runtime and thus it must trigger the whole lexer/parser/compiler-chain in Python from within the VM.

Can anyone identify this encoding?

Im working on a program to interface with some hardware that is sending data that has been encoded and wrapped to send within a CDATA block in an XML document.

Can SO_REUSEPORT be used on Unix domain sockets?

Linux kernels >= 3.9 allow sharing of sockets between processes with in-kernel load-balancing by setting SO_REUSEPORT: http://lwn.net/Articles/542629/ How can this be used for sockets of type AF_UNIX?

Can’t terminate a sudo process created with python, in Ubuntu 15.10

I just updated to Ubuntu 15.10 and suddenly in Python 2.7 I am not able to terminate a process I created when being root.

Formation of dictionary from list element

Hi I have list as follows which contain meta data from images as follows:

Get month by week, day and year

I want to know how you get the months by the giving day, week number and year.

Hello guys I have wanted for a long time to find out how to clear something like print(“example”) in python, but I cant seem to find anyway or figure anything out.

Is there a way to clear your printed text in python?

How do I find and remove white specks from an image using SciPy/NumPy?

I have a series of images which serve as my raw data which I am trying to prepare for publication. These images have a series of white specks randomly throughout which I would like to replace with the average of some surrounding pixels.

How do I make ipython aware of changes made to a selfwritten module?

When trying a selfwritten module, it is likely to end with errors at the first few times.

How to create a CSV file if it does not exist and then only append to it Python

Hello I want to know how to create a file if it does not exist in direcotry. I want only to append data.

How to force my whole package to use a __future__ directive?

How to force my whole package to use a __future__ directive?

How to make python’s argparse generate Non-English text?

The argparse module “automatically generates help and usage messages”. I can give Non-English names to the arguments and provide Non-English help texts; but the help output then becomes a mixture of at least two languages, because terms like usage, positional arguments, optional arguments and show this help message and exit are automatically generated in English.

Index 2D numpy array by a 2D array of indices without loops

I am looking for a vectorized way to index a numpy.array by numpy.array of indices.

Legend transparency, when using secondary axis

The legend of the plot of a secondary axis somehow is transparent to the plot of the other axis. A minimal example to reproduce the problem:

Overcoming MemoryError / Slow Runtime in Ashton String task

In the Ashton String task, the goal is to

pip install error: “Unknown archive format: .whl”

I’m new to virtualenv (on windows). I’m trying to use pip (1.5) install a local wheel file, but it is failing.

pycurl equivalent of “curl –data-binary”

I’d like to know the equivalent of this curl command in pycurl:

Pyspark Invalid Input Exception try except error

I am trying to read the last 4 months of data from s3 using pyspark and process the data but am receiving the following exception.

python argparse – pass values WITHOUT command line

I think I’m not understanding something basic about python‘s argparse. I am trying to use the Google YouTube API for python script, but I am not understanding how to pass values to the script without using the command line.

python comprehension with multiple ‘for’ clauses and single ‘if’

Imagine a discrete x,y,z space : I am trying to create an iterator which will return all points which lie within a sphere of some radial distance from a point.

Slice a Pandas dataframe by an array of indices and column names

I’m looking to replicate the behavior of a numpy array with a pandas dataframe. I want to pass an array of indices and column names and get a list of objects that are found in the corresponding index and column name.

Which is the best way to log user actions in flask views?

I would like to log user actions whenever user logs in/out and adds, edits, deletes objects in my site models in flask. Which is the best way to do this? Also I would like to show the old data and the new modified data, which happens using wtfforms. I am using flask and Flask-SQLAlchemy. I want something similar to what Django framework offers in the ‘History‘ hlink for the associated objects.

While-loop with if-statement faster than while-loop

I am doing some testing regarding the speed of if-statements in loops and their effect on speed. Something I found was that consistently, the if-statement improved performance. My code:

Why does overriding __contains__ break OrderedDict.keys?

I’m subclasssing OrderedDict (Cpython, 2.7.3) to represent a datafile. __getitem__ pulls a field out of the datafile and sets it on the current instance similar to the code I’ve posted below. now I would like to override __contains__ to return True if the field is in the dictionary or in the file on the disk since it can be read either way. However, this seems to break OrderedDict‘s ability to inspect it’s keys.

Scheduling thousands of one-off (non-reoccuring) tasks for near-simultaneous execution via Django-celery

Some context: I’m building a Django App that allows a user to pre-save an action, and schedule the exact date/time in the future they want said action to execute. E.g, scheduling a post to be programmatically pushed to ones Facebook wall next week at 5:30am.

Why does overriding __contains__ break OrderedDict.keys?

I’m subclasssing OrderedDict (Cpython, 2.7.3) to represent a datafile. __getitem__ pulls a field out of the datafile and sets it on the current instance similar to the code I’ve posted below. now I would like to override __contains__ to return True if the field is in the dictionary or in the file on the disk since it can be read either way. However, this seems to break OrderedDict‘s ability to inspect it’s keys.

Add rate of change to Pandas DataFrame

I have the following Pandas DataFrame

Disable SSL certificate validation in Python

I’m writing a script that connects to a bunch of URLs over HTTPS, downloads their SSL certificate and extracts the CN. Everything works except when I stumble on a site with an invalid SSL certificate. I absolutely do not care if the certificate is valid or not. I just want the CN but Python stubbornly refuses to extract the certificate information if the certificate is not validated. Is there any way to get around this profoundly stupid behavior? Oh, I’m using the built-in socket and ssl libraries only. I don’t want to use third-party libraries like M2Crypto or pyOpenSSL because I’m trying to keep the script as portable as possible.

Does calling random.normal on an array of values add noise?

I saw this pattern in someone’s code

How can I use a static method as a default parameter for the strategy design pattern?

I want to make a class that uses a strategy design pattern similar to this:

How to add header files in setup.py so dependencies are observed when building the extensions?

The question seems long, but it all comes down to how I can add header files to specific extension specification.

How to get properties of picked object in mplot3d (matplotlib + python)?

I plot a series of points using mplo3d

How to handle multi-page images in PythonMagick?

I want to convert some multi-pages .tif or .pdf files to individual .png images. From command line (using ImageMagick) I just do:

How to seat everyone according to preferences?

This problem is from CodeEval problem 118

Lists are the same but not considered equal?

novice at Python encountering a problem testing for equality. I have a list of lists, states[]; each state contains x, in this specific case x=3, Boolean values. In my program, I generate a list of Boolean values, the first three of which correspond to a state[i]. I loop through the list of states testing for equality (one of them is certainly correct as all possible boolean permutations are in states, but equality is never detected. No clue why, here is some code I modified to test it:

Regex, select closest match

Assume the following word sequence

Summation of only consecutive values in a python array

I am new on python (and even programing!), so I will try to be as clear as I can to explain my question. For you guys it could be easy, but I have not found a satisfactory result on this yet.

uwsgi + nginx + flask: upstream prematurely closed

I created an endpoint on my flask which generates a spreadsheet from a database query (remote db) and then sends it as a download in the browser. Flask doesn’t throw any errors. Uwsgi doesn’t complain.

Why doesn’t cv2 dilate actually affect my image?

So, I’m generating a binary (well, really gray scale, 8bit, used as binary) image with python and opencv2, writing a small number of polygons to the image, and then dilating the image using a kernel. However, my source and destination image always end up the same, no matter what kernel I use. Any thoughts?

Behavior of “round” function in Python

Could anyone explain me this pice of code

Cannot allocate 1.6 GB in Python

This code produces a MemoryError

Efficiently computing element wise product of transition matrices (m*m) * (n*n) to give (mn*mn) matrix

Consider input matrices X and Y of shapes (m,m) and (n,n) respectively. As an output we need to give a (mn,mn) shape matrix such that it multiplies corresponding entries in the two matrices.

Error : no viable alternative at input ‘for’ Python

I have strange problem, when i am using Netbeans IDE , this line

How can I change name of arbitrary columns in pandas df using lambda function?

Is there any way to change some column names in pandas dataframe using lambda, but not all? For example, suppose that this data frame has columns whose name are osx, centos, ubunto, windows. In this data frame, I want to replace all column names with that column name appended by x, so in this case, I can rename the column name by

How come Python does not include a function to load a pickle from a file name?

I often include this, or something close to it, in Python scripts and IPython notebooks.

How to read complete file with bitstring

I want to read as many 24 bit chunks as possible from a file.How can I do this using bitstrings’ ConstBitStreamwhen I don’t now how many chunks there are?

How to store environment variables in a Python Flask app?

I have a Python Flask app that accesses the Github API. For this I need to store an access token. What is the common practice to store that data and how do I access that inside my app?

Matching Features with ORB python opencv

hi im working in Matching Features with ORB python opencv but when i run this code i get this error

Round a Python list of numbers and maintain their sum

I have a list or an array of decimal numbers in Python. I need to round them to the nearest 2 decimal places as these are monetary amounts. But, I need the overall sum to be maintained, i.e. the sum of the original array rounded to 2 decimal places must be equal to the sum of the rounded elements of the array.

Subtracting numpy arrays of different shape efficiently

Using the excellent broadcasting rules of numpy you can subtract a shape (3,) array v from a shape (5,3) array X with

tweepy stops after a few hours

I use tweepy for streaming some tweet. This is my procedure

Use sсikit-learn TfIdf with gensim LDA

I’ve used various versions of TFIDF in scikit learn to model some text data.

Using Flask-Security to authenticate REST API

I am using Flask-Security to build a web app that has a public REST API. I am trying to figure out how to add user registration and login using REST calls only.

what does the error “no exception supplied” mean?

My Django app is currently throwing this error on one of my pages, does anyone know what it eans? I would supply more detail but I don’t know what this error means so I’m not sure what the relevant files are and Django apps are rather large in the amount of code spread around so I’ll post some code once I can get an idea of what this means. Thanks in advance for any help.

Why python 2.7 on Windows need a space before unicode character when print?

I use cmd Windows, chcp 65001, this is my code

Django reportlab latin2 encoding

is there any option to convert latin2 letters in a proper way? I need polish letter to my school project. Here is some code how I generate pdf

plt.figure() vs subplots in Matplotlib

In Matplotlib a lot of examples come in the form ax = subplot(111) and then functions are applied on ax, like ax.xaxis.set_major_formatter(FuncFormatter(myfunc))

sqlalchemy FULL OUTER JOIN

How to implement FULL OUTER JOIN in sqlalchemy on orm level.

SublimeLinter not obeying “pep8_ignore” settings

I am using Sublime Linter and cannot get PEP 8 (W191) to go away with the following settings.

Can only iterate once through csv reader

So I basically have an extremely long list of strings, and a CSV file that contains a column of strings and a column of numbers. I need to loop through the extremely long list of strings, and for each one, loop through the rows of the CSV file checking each string in the first column of the CSV to see if it occurs in my string, and if it does, add the number in the other column to something.

Check if value is between pair of values in a tuple?

Is there an efficient way (nice syntax) to check if a value is between two values contained in a tuple?

Django 1.6 and Celery 3.0 memory leaks

After upgrading Django to 1.6, my celery worker is eating up RAM.Seems that the memory allocated for the workers isn’t released and grows after every task.

django rest framework file upload with nested writable serializers

django rest framework file upload with nested writable serializers

Flask – nested rest api – use something other than methodview or have I made a bad design?

Just starting off with Flask, following along at http://flask.pocoo.org/docs/views/

Multiline statements using Python doctest

Is it possible to work with multiline statements using python doctest?

numpy: How to join arrays? ( to get the union of several ranges)

I use Python with numpy.

Passing numpy array to Cython

I am learning Cython. I have problem with passing numpy arrays to Cython and don’t really understand what is going on. Could you help me?

pickle/zodb: how to handle moving .py files with class definitions?

I’m using ZODB which, as I understand it, uses pickle to store class instances. I’m doing a bit of refactoring where I want to split my models.py file into several files. However, if I do this, I don’t think pickle will be able to find the class definitions, and thus won’t be able to load the objects that I already have stored in the database. What’s the best way to handle this problem?

Python : IndexError: tuple index out of range

In python i have this code

Python unable to find Elasticsearch

I am new to python and I am trying to experience with python and elasticsearch.

relation “account_emailaddress” does not exist – django error

I am following this tutorial to integrate social media login to my django project – http://www.sarahhagstrom.com/2013/09/the-missing-django-allauth-tutorial/ However after completing all the steps, when I try to login using facebook, I get this error

Using eventlet to manage socketio in Flask

I am trying to set up a small server to handle HTTP and socketio requests — I don’t have much experience setting up servers, but right now apache2 serves the http just fine. The socketio transactions, however, keep failing with error code 400 (bad request), and I see some strange errors in the server logs. Sometimes I see an engineio error and the server responds w/ a ‘bad request’ and code 400, but always it tells me the eventlet server needs to be started

Vectorized spherical bessel functions in python?

I noticed that scipy.special Bessel functions of order n and argument x jv(n,x) are vectorized in x

Writing a csv temporary file using tempfile

So I’m writing a test for this class (edited to be more clear)

Yet Another ‘Connection reset by peer’ Error

I’m creating a server/client application in python using the socket module and for whatever reason my server keeps ending the connection. The weird part is this works in Windows perfectly but not Linux. I’ve looked all over the place for a possible solution but none of them worked. Below is a sanitized version of the code which exploits the bug, however, with a higher success rate. Normally it never works. Hopefully this is still enough information

“Standard” way of creating config file suitable for Python and Java together

My application was 100% developed in pure Python. I found very useful and easy to create a config file with .py extension and than simply load it in every code.

Correct usage of os.path and os.join

I’m trying to write a handler that acts on files within various subdirectories, but while my script can see these files, it cannot do anything with them because it fails to assemble their paths.

Count bitmasks, enumerate 0s

I had the following question in an interview and I believe I gave a working implementation but I was wondering if there was a better implementation that was quicker, or just a trick I missed.

Does scipy.integrate.ode.set_solout work?

The scipy.integrate.ode interface to integration routines provides a method for stopping the integration if a constraint is violated at any step, set_solout. However, I cannot get this method to work, even in the simplest examples

How to check whether screen is off in Mac/Python?

How do I check whether the screen is off due to the Energy Saver settings in System Preferences under Mac/Python?

How to generate a json file in python from nested array/dictionary/object

I need to generate a json file like:

How to get rid of maximum recursion depth error or better solve this?

Problem: We have a square grid of 5 rows and 4 columns. We need to use these numbers to fill the grid; 1,2,3,4,5,6,7,8,9,10,12,18,20,21,24,27,30,35,36,40. We need to fill the grid in such a way that every horizontal and vertical neighbors should divide other without remainder. For example, 12 and 3 can be neighbors because 12 % 3 == 0, but 5 and 12 can’t. Grid 2×2 is given to be 10.

How to read columns of varying length from a text file in NumPy using genfromtxt()?

I have hundreds of text files like these, with each column separated by three spaces. The data is for a year: 12 months and 31 days for each month.

image_to_string doesn’t work in Mac

I’m trying to follow this example of pytesser (link) in a Mac Maverick.

Integrating Alembic with SQLAlchemy

I’m looking at a way to integrate Alembic with SQLAlchemy. What I need is a way so that Alembic detects any changes I make in models.py automatically and updates it in the MySQL database when I run alembic revision -m "<message_here>" and alembic upgrade head.

Making a countdown timer with Python and Tkinter?

I want to set a label in Tkinter using my countdown timer function. Right now all it does is set the lable to “10” once 10 is reached and I don’t really understand why. Also, even if I have the timer print to a terminal instead the “Time’s up!” bit never prints.

Microsecond accurate timestamp in python?

Is there a way to maintain microsecond accuracy when converting a Python datetime to a timestamp?

Mocking Django Model and save()

I have the following scenario:

Numpy Routine(s) to create a regular grid inside a 2d array

I am trying to write a function that would create a regular grid of 5 pixels by 5 pixels inside a 2d array. I was hoping some combination of numpy.arange and numpy.repeat might do it, but so far I haven’t had any luck because numpy.repeat will just repeat along the same row.

PNG options to produce smaller file size when using savefig

I am using matplotlib to produce a plot which I then save to a PNG file using matplotlib.pyplot.savefig.

Python 2 newline tokens in tokenize module

I am using the tokenize module in Python and wonder why there are 2 different newline tokens

python bug with __le__, __ge__?

Is it me or python that is confused with the following code ? I would expect __le__ to be called by a <= ab, not __ge__:

python ctypes structure wrong byte size

So I’m trying to figure out why the size of my ctypes.Structure is not what it should be. My code is the following, theres also the calculation of what the size should be afaik.

Python – “IOError: [Errno 0] Error”. What is Triggering This Error In My Code?

Python/programming newbie here.

scipy sparse matrices as an input for petsc4py

I can’t seem to find a way how to efficiently load scipy sparse matrices, e.g. csr_matrix, into a petsc4py matrix, e.g. PETSc.Mat().createAIJ. I found this thread, but I’m not able to apply it.

Split DatetimeIndex into date and time MultiIndex conveniently in Pandas

So let’s say I have DatetimeIndex:ed data like this (there would be several days of course)

SQLAlchemy eating RAM

I’m trying to import some XML data into my MySQL database after processing it with Python. To keep things simple, I’m doing it all from one script that uses SQLAlchemy to access my database.

Using the python MySQLDB SScursor with nested queries

The typical MySQLdb library query can use a lot of memory and perform poorly in Python, when a large result set is generated.

What python code generates all possible groupings (trees) for binary operators

As explained in several SO questions, and more abstractly at mathworld, the sequence of Catalan numbers happens to correspond to the number of parenthetical groupings that can be generated for any given number of operators. But I haven’t found an algorithm to generate all these groupings.

Why is skimage.transform.rotate significantly slower than PIL’s Image.rotate?

I’m in the process of converting some PIL-based code over to NumPy, but I’ve found that the skimage.transform.rotate function is significantly slower than PIL’s Image.rotate.

Catch empty list with colander

I’m using colander to validate (and deserialize json data) input to some web services. I would like to add a rule to a colander schema to catch an empty list, but I can not figure out how to do it.

Error because of Theano and NumPy variable types

I am writing this code using numpy 1.9 and the latest version of Theano but I get an error which I can’t fix. I doubt it could be the way I declare variable types but I can’t work it around. I appreciate your suggestions. I want to product a matrix with a vector and sum it with a bias.

GTK Label wrapping in a dialog

I’m trying to create a non-resizable dialog with a label in it. This label has a lot of text, so I want it to wrap without making the dialog ridiculously wide.

How can i write my custom link extractor in scrapy python

I want to write my custom scrapy link extractor for extracting links. The scrapy documentation says it has two built-in extractors.

How is this sorting code working?

How is this sorting code working? I cannot understand how the values returned by the iterator are being used to sort the list?

How to compare two timezones in python?

These two timezones have different names but represent the same thing, however

How to force Google App Engine [python] to use SSL (https)?

I write a web app on Google App Engine using Python.

How to push the for-loop down to numpy

I have the following piece of code doing exactly what i want (it is part of a kriging method). But the problem is that it goes too slow, and i wish to know if there is any option to push the for-loop down to numpy? If i push out the numpy.sum, and use the axis argument there, it speeds up a little bit, but apparently that is not the bottleneck. Any ideas on how i can push down the forloop to numpy to speed it up, or other ways to speed it up?)

How to speed up an already cached pip install?

I frequently have to re-create virtual environments from a requirements.txt and I am already using $PIP_DOWNLOAD_CACHE. It still takes a lot of time and I noticed the following

indexing and finding values in list of namedtuples

I have a namedtuple like the following,

Latent Semantic Analysis in Python discrepancy

I’m trying to follow the Wikipedia Article on latent semantic indexing in Python using the following code:

Most efficient way of finding the next element in a tuple

I’ve got a system in which I often (but not constantly) have to find the next item in a tuple. I’m currently doing this like so:

python – how to get the data from an plt.imshow()?

I have the following code

Python – making copies of a file

I have a file that I want copied into a directory multiple times. It could be 100, it could be 1000. That’s a variable.

Selecting Element followed by text with Selenium WebDriver

I am using Selenium WebDriver and the Python bindings to automate some monotonous WordPress tasks, and it has been pretty straightforward up until this point. I am trying to select a checkbox, but the only way that I can identify it is by the text following it. Here is the relevant portion of HTML

shell scripting checking python version

I have the following shell script to query the python version. It gives me an error stating "Integer expression expected" on the if-statement.

Get status text after failed http-request

Is there any chance to get additional status information from my respose object, if a request fails? At this point, I’m able to get the status code, but in addition, I need the status information text (which describes the error). If you’re using jQuery ajax, you could get this text from jqXHR’s responseText-attribute.

Adding external Ids to Partners in OpenERP withouth a new module

My Question is a bit complex and iam new to OpenERP. I have an external database and an OpenERP. the external one isn’t PostgreSQL.MY job is that I need to synchronize the partners in the two databases.External one being the more important. This means that if the external one’s data change so does the OpenERp’s, but if OpenERP’s data changes nothing changes onthe external one.

Calculating Point Density using Python

I have a list of X and Y coordinates from geodata of a specific part of the world. I want to assign each coordinate, a weight, based upon where it lies in the graph.

Complex query with Django (posts from all friends)

I’m new to Python and Django, so please be patient with me. I have the following models

Deleting variables in Python standard libraries

I’ve been reading some of the code in a standard threading library ( Python 2.6 ) and there was a piece of code which made me wonder. It can be shorten to the following structure ( compare to __bootstrap_inner method in threading.py )

Django cross table model structure

I have a System model, and an Interface model. An Interface is the combination between two systems. Before, this interface was represented as an Excel sheet (cross table). Now I’d like to store it in a database.

Error binding parameter 0: probably unsupported type

I can’t seem to figure out what is wrong with my code, but I keep getting the:

Generate a pdf with python

I’m trying to develop a small script that generate a complete new pdf, mainly text and tables, file as result.I’m searching for the best way to do it.

Generate functions without closures in python

right now I’m using closures to generate functions like in this simplified example

Hiding major tick labels while showing minor tick labels in matplotlib

I would like to hide the major tick labels on my x-axis while retaining just its minor labels. The idea is that my dates are displayed in between the major ticks instead of on them by default. I have seen a few other answers to similar questions as this one and tried using their way of hiding the major ticks however I am not having much luck getting it working at all

How do I get the modern style matplotlib plots often seen in iPython Notebook examples?

Take this page, for example, a sample of which is posted below:

How do I load specific rows from a .txt file in Python?

Say I have a .txt file with many rows and columns of data and a list containing integer values. How would I load the row numbers in the text file which match the integers in the list?

How do I use python variable in a javascript?

I’ve been on a prowl looking for a way to access a non visible text field using selenium’s webdriver. The only way i got it to work is using

How does the list comprehension to flatten a python list work?

I recently looked for a way to flatten a nested python list, like this: [[1,2,3],[4,5,6]], into this: [1,2,3,4,5,6].

How to cancel interpreter command in emacs python-mode

If I mistype a command in the python intepreter, sometimes I just see .... For example if I type help(random.unif and press enter I cannot enter a new command. I have to exit emacs and start python and the interpreter again. Is there way to correct this?

How to disable hostname checking in requests python

I’m using Requests to connect to a RESTful API. The server I would like to reach use ssl with self-singed certificate.

How to fix paths to solve Homebrew doctor warnings

Another newbie query. I’ve been struggling to install matplotlib for a Python project so reading around suggested Homebrew was a solid solution for package management and dependencies.

How to simply have python print “\xaa\xbb\xcc\xdd” as 0xddccbbaa?

I believe I’m misunderstanding something that should probably be simple. I’m trying to accept arguments passed to a python script. The type of argument I’m expecting is somewhere along the lines of "\xaa\xbb\xcc\xdd", and it keeps converting it to binary(i think?) instead of actually allowing me to print it out just how it was passed.

manage.py collectstatic command not found, Django 1.5.1

I am very new to python and when I run the $ python manage.py collectstatic command, It returns ‘unknown command: ‘collectstatic”

matplotlib contour input array order

Question: what order does the contour from matplotlib expect for the input 2D array? Elaborate: Matplotlib contour documentation says that the routine call is

numpy: using operator – with arrays containing None

I have a list of numbers which I put into a numpy array:

OpenCV Perspective Transform giving unexpected result

I am trying to transform from a trapezoid (in the first image) to a rectangle (in the second image), but getting a strange result (in the third image).

Paramiko: how to ensure data is received between commands

I’m using Paramiko to issue a number of commands and collect results for further analysis. Every once in a while the results from the first command are note fully returned in time and end up in the output for the second command.

Pull Tag Value using BeautifulSoup

Can someone direct me as how to pull the value of a tag using BeautifulSoup? I read the documentation but had a hard time navigating through it.

Python data structure for efficient add, remove, and random.choice

I’m looking for a built-in Python data structure that can add a new element, remove an existing element, and choose a random element, all in better than O(n) time.

python dateutil unicode warning

im parsing some tweet’s data from Twitter API using sixohsix library. Im trying to convert the date of the tweet to my locale:

Python lambda with regex

When using re.sub() part of re for python, a function can be used for sub if I am not mistaken. To my knowledge it passes in the match to whatever function is passed for example

SQLAlchemy subquery in from clause without join

i need a little help.I have following query and i’m, curious about how to represent it in terms of sqlalchemy.orm. Currently i’m executing it by session.execute. Its not critical for me, but i’m just curious. The thing that i’m actually don’t know is how to put subquery in FROM clause (nested view) without doing any join.

Understanding an issue with the namedtuple typename and pickle in Python

Earlier today I was having trouble trying to pickle a namedtuple instance. As a sanity check, I tried running some code that was posted in another answer. Here it is, simplified a little more

Use lxml to parse text file with bad header in Python

I would like to parse text files (stored locally) with lxml’s etree. But all of my files (thousands) have headers, such as:

ValueError: unsupported format character ‘{‘ (0x7b) in defining dictionary

I’m writing some code for web development using Google Python Appengine. In my code I have to concatenate strings using % and dictionary Here’s the code I’ve written.

Groupby given percentiles of the values of the chosen DataFrame column

Imagine that I have a DataFrame with columns that contain only real values.

Running Jar files from Python

I want to make a program that can execute jar files and print whatever the jar file is doing in my python program but without using the windows command line, I have searched all over the web but nothing is coming up with how to do this.

python pandas error when doing groupby counts

When doing groupby counts over multiple columns I get an error. Here is my dataframe and also an example that simply labels the distinct ‘b’ and ‘c’ groups.

Binary file download

I’m building a server using python and bottle. How can I handle a request for a binary file? I have read that I should use flask. There is a way for doing that without using flask?

Can’t run PhantomJS in python via Selenium

I have been trying to run PhantomJS via selenium for past 3 days and have had no success.So far i have tried installing PhantomJS via npm, building it from source, installing via apt-get and downloading prebuilt executable and placing it in /usr/bin/phantomjs.

Check if xml ElementTree node is None/False [duplicate]

This question already has an answer here: Why does bool(xml.etree.ElementTree.Element) evaluate to False?

creating subprojects in bottle

I’m just starting Python web development, and have chosen Bottle as my framework of choice. I’m trying to have a project structure that is modular, in that I can have a ‘core’ application that has modules built around it, where these modules can be enabled/disabled during setup (or on the fly, if possible…not sure how I would set that up tho).

Got 403 error when connecting to Google Analytics with Python 2.7.x

I tried to get data from Google Analytics API with Python client(google-api-python-client). Here’s the code I used:

Gurobi python get value of the defined variable

How do i get the value of the variable that i have define previously(using addVar) in gurobi python? I need to compare the value of the gurobi variable and then perform calculations to reach to my objective variable. The same has to be done before optimization.

How does kmeans know how to cluster documents when we only feed it tfidf vectors of individual words?

I am using scikit learn’s Kmeans algorithm to cluster comments.

Print to standard console in curses

I’m building a python curses application. I have two ways of printing to the curses window: print x, and windows.addstr(x) (and the other similar window.* options). However, for debugging purposes, I’d like to be able to print to the standard console, so when I exit the curses window, I have the infomation waiting for me to be seen. I would normally just use print x, but that prints to the curses window.

Python functools.namedtuple

I am aware of the existence and purpose of collections.namedtuple, but I have noticed that, at least in IDLE (3.2.2), this factory function is also in functools

Two instances of the same Python module?

I created a Python module with a single function that just prints ‘a!’. I opened up the Python interpreter and imported the module in 2 different syntaxes

Unexpected behavior for numpy self division

This behavior is a little bit strange to me, I always thought x/=5. was equivalent to x=x/5. . But clearly the g(x) function does not create a new reference with /= operation. Could anyone offer an explanation for this?

DataFrame of DataFrames with pandas

I have the following DataFrame gathering daily stats on 2 measures A and B

Google Cloud Storage + Python : Any way to list obj in certain folder in GCS?

I’m going to write a Python program to check if a file is in certain folder of my Google Cloud Storage, the basic idea is to get the list of all objects in a folder, a file name list, then check if the file abc.txt is in the file name list.

How can I get the “old” zip() in Python3?

I migrated from Python 2.7 to Python 3.3 and zip() does not work as expected anymore.Indeed, I read in the doc that it now returns an iterator instead of a list.

How can i quote escape characters in csv writer in python

I am writing the csv file like this

pandas: iterating over DataFrame index with loc

I can’t seem to find the reasoning behind the behaviour of .loc. I know it is label based, so if I iterate over Index object the following minimal example should work. But it doesn’t. I googled of course but I need additional explanation from someone who has already got a grip on indexing.

Python and Matplotlib and Annotations with Mouse Hover

I am currently employing this code to have pop up annotatations on a map when i click on a point in a Basemap Matplotlib Plot.

Python – Find duplicates in a list of dictionaries and group them

i’m not a programmer and also new to python, i have a list of dicts coming from a json file:

Python grequests with custom header

I saw this post about sending asynchronous requests with grequests.

pandas.DataFrame.load/save between python2 and python3: pickle protocol issues

I haven’t figure out how to do pickle load/save’s between python 2 and 3 with pandas DataFrames. There is a ‘protocol’ option in the pickler that I’ve played with unsuccessfully but I’m hoping someone has a quick idea for me to try. Here is the code to get the error:

Smoothed 2D histogram using matplotlib and imshow

I try to do a 2D histogram plot and to obtain a “smooth” picture by a sort of interpolation. Thus I do the following combining plt.hist2d and plt.imshow

Calling locals() in a function not intuitive?

This may be elementary, but may help me understand namespaces.A good explanation might step through what happens when thefunction definition is executed, and then what happens laterwhen the function object is executed.Recursion may be complicating things.

How do I implement a custom MIB in PySNMP?

I already have the MIB text file (do I need to make this into a .py file somehow??). I am trying to use PySNMP (not net-snmp). I have been able to connect to my device and print out some info, but the info was not very helpful (just ObjectName, ObjectIdentifier, etc). I want to be able to communicate with the device (send commands to change and read values), but all of the tutorials I have seen seem to be of little help. Does anyone know how I can use my custom MIB to effectively communicate with my device? Any good sites I am missing?

ImportError: No module named sklearn.datasets

os: mac os yosemitepython: 2.7.6 — 64-bitinstalled: numpy,skipy,matplotlib,nose I get the following error.

Can push notifications be done with an AngularJS+Flask stack?

I have a Python/Flask backend and an Angular frontend for my website. At the backend there is a process that occasionally checks SQS for messages and I want it to push a notification to the client which can then in turn update an Angular controller. What is the best way to do this my existing technologies?

Subprocess.poll() falsely returns a value

Subprocess.poll() falsely returns a value

Unable to get python embedded to work with zip’d library

I’m trying to embed python, and provide the dll and a zip of the python libraries and not use any installed python. That is, if a user doesn’t have python, I want my code to work using the provided dll/zip.

python queue get size, use qsize() or len()?

I’ve seen instances where qsize() and len() has been used to compute the size of the queue. What is the distinction between the two?

SQLAlchemy – condition on join fails with AttributeError: Neither ‘BinaryExpression’ object nor ‘Comparator’ object has an attribute ‘selectable’

I’m running SQLALchemy with Pyramid. I’m trying to run a query with a custom ‘join’ condition

what does [sock] = func() mean?

What does this line of code mean, from tornado?

Why doesn’t the Python 2D array index order matter when used with colon ( : )

Creating a 2D array such as