text
stringlengths
226
34.5k
Can't draw function using python Question: I have made a function RC(n) that given any n changes the digits of n according to a rule. The function is the following def cfr(n): return len(str(n))-1 def n_cfr(k,n): J=str(k) if "." in J: J2=J.replace(".", ""...
How to find the diameter of objects using image processing in Python? Question: Given an image with some irregular objects in it, I want to find their individual diameter. [Thanks to this answer](http://stackoverflow.com/questions/33707095/how-to- locate-a-particular-region-of-values-in-a-2d-numpy-array?answertab=acti...
How do I install modules on qpython3 (Android port of python) Question: I found this great module on within and downloaded it as a zip file. Once I extracted the zip file, i put the two modules inside the file(setup and the main one) on the module folder including an extra read me file I needed to run. I tried installi...
historical stock price ten days before holidays for the past twenty years Question: even though still as a noob, I have been enthusiastically learning Python for a while and here's a project I'm working on. I need to collect historical stock price ten days before US public holidays in the past twenty years and here's w...
PyInstaller/Py2exe - include os.system call with third party scripts in single file compilation Question: I'm using tkinter and pyinstaller/py2exe (either one would be fine), to create an executable as a single file from my python script. I can create the executable, and it runs as desired when not using the bundle opt...
Looping through HTML tags using BeautifulSoup Question: As mentioned in the previous questions, I am using Beautiful soup with python to retrieve weather data from a website. Here's how the website looks like: <channel> <title>2 Hour Forecast</title> <source>Meteorological Services Singapore</so...
Regex not working as required Question: Here is my HTML code: <ul class="hide menuSearchType"> <li><a href="../../dynamic/city_select.aspx">Search by city</a></li> <li><a href="../../searchbyphone.aspx">Search by phone</a></li> <li><a href="../searchbyaddress.aspx">Search by addre...
I need to figure out how to make my program repeat. (Python coding class) Question: I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user woul...
Python searching multiple directories and reading select files Question: I am looking for some help performing actions on a set of files in two different directories using Python. I am attempting to: 1. Search two different directories 2. Find the 15 last modified files (comparing files in both directories) 3...
Running a Python script in a Makefile Question: I have a Python script (scr1.py) that calls another Python script (scr2.py) and they both on the same path. When I open CMD and run scr1.py everything works perfectly. I want to run scr1.py inside a Makefile that is NOT on the same path as the scripts. The scr1.py is exe...
Caffe to Tensorflow (Kaffe by Ethereon) : TypeError: Descriptors should not be created directly, but only retrieved from their parent Question: I wanted to use the wonderful package caffe-tensorflow by ethereon and I ran into the same problem described in [this closed issue](https://github.com/ethereon/caffe-tensorflow...
need to package jinja2 template for python Question: (UPDATE: I've made a better question with a better answer [here](http://stackoverflow.com/questions/38642557/how-to-load-jinja-template- directly-from-filesystem). I was going to delete this question, but some of the answers might prove useful to future searchers.) ...
Python NLTK Word Tokenize UnicodeDecode Error Question: I get the error when trying the below code. I try to read from a text file and tokenize the words using nltk. Any ideas? The text file can be found [here](https://pythonprogramming.net/static/downloads/short_reviews/positive.txt) from nltk.tokenize ...
Tensorflow : how to insert custom input to existing graph? Question: I have downloaded a tensorflow GraphDef that implements a VGG16 ConvNet, which I use doing this : Pl['images'] = tf.placeholder(tf.float32, [None, 448, 448, 3], name="images")...
Download images automatically Question: I have written this piece of python code which downloads a number of images from a repository of images and saves them in specified folder. The code looks like this: import urllib.request import cv2 import numpy as np import os def store_raw_im...
Execute IPython notebook cell from python script Question: In the IPython notebook, you can execute an outside script, say `test.py`, using the run magic: %run test.py Is there a way to do the opposite, i.e. given an IPython notebook, accessing and then running a particular cell inside it from a py...
Python binding of functions within a c++ program Question: I have a program written in c++ that functions on it's own, however we want to make it accessible to Python. Specifically, we have several functions that are more efficient in c++, but we do a lot of other things with the output using Python scripts. I don't wa...
Custom gradient for a chain of ops Question: I've got a chain of standard TensorFlow operations, and I need to specify a custom gradient for this chain as a whole. Say that, in the example below, these operations are grouped in a single Python function: 'my_op'. What I'm trying to do is to specify a custom gradient fo...
Nested `ImportError` on Py3 but not on Py2 Question: I'm having trouble understanding how nested imports work in a python project. For example: test.py package/ __init__.py package.py subpackage/ __init__.py `test.py`: import package `pac...
shell multipipe broken with multiple python scripts Question: I am trying to get the stdout of a python script to be shell-piped in as stdin to another python script like so: find ~/test -name "*.txt" | python my_multitail.py | python line_parser.py It should print an output but nothing comes out o...
Python 3.x tkinter Place Entries on top of eachother Question: import tkinter from tkinter import * root = tkinter.Tk() root.title("Gmail App") def login(): L1 = Label(root, text="Email") L1.pack( side = LEFT) E1 = Entry(root, bd =5) E1.pack(side = LEFT) ...
Calling another method to another class Question: i newbie on python programming, i so confused, why i cant call another method from another class, this is my source- file : 8_turunan lanjut.py class Karyawan(object): 'untuk kelas karyawan' jml_karyawan = 0 # Class variable # construct...
Returning to the main menu in my game - Python Question: I am creating a Rock, Paper, Scissors game. The game has a main menu which I need to be able to return to from each sub menu. I've tried a few different method I could think of as well as looked here and elsewhere online to determine a method of solving my proble...
How to paste a PNG image with transparency to another image in PIL without white pixels? Question: I have two images, a background and a PNG image with transparent pixels. I am trying to paste the PNG onto the background using Python-PIL but when I paste the two images I get white pixels around the PNG image where ther...
Add elements of two list of dictionaries based on a key value pair match Question: Given n lists with m dictionaries as their elements, I would like to produce a new list, with a joined set of dictionaries. l1 = [{"index":'a', "b":2,'c':9}, {"index":'b', "b":3,"c":5}, {"index":'c', "b":8,"c":8}] l2 =...
Python, how to move dict under itself with a new attribute? Eg dict['key'] = dict Question: I have an array of very large dictionaries, and need to put each dict itself under a new key. I know `dict['key'] = dict` won't work and will result a recursive dict in python. Currently, I'm doing something like: ...
How to turn off autoscaling in matplotlib.pyplot Question: I am using matplotlib.pyplot in python to plot my data. The problem is the image it generates seems to be autoscaled. How can I turn this off so that when I plot something at (0,0) it will be placed fixed in the center? Answer: You want the [`autoscale`](http...
Python issue gave up around 4am Question: program that requests four number (integer or floating-point) from the user. your program should compute the average the first three numbers and compare the average to the fourth. if they are equal, your program should print 'Equal' on the screen. import math ...
Python import error no module named bz2 Question: I have libbz2-dev installed however I am still getting the following import error while importing gensim : >>> import gensim Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/krishna/gensimenv/lib/python2.7...
Encode IP address using all printable characters in Python 2.7.x Question: I would like to encode an IP address in as short a string as possible using all the printable characters. According to <https://en.wikipedia.org/wiki/ASCII#Printable_characters> these are codes 20hex to 7Ehex. For example: shorte...
Failing to import itertools in Python 3.5.2 Question: I am new to Python. I am trying to import izip_longest from itertools. But I am not able to find the import "itertools" in the preferences in Python interpreter. I am using Python 3.5.2. It gives me the below error- from itertools import izip_longest ...
Python Pandas self join for merge cartesian product to produce all combinations and sum Question: I am brand new to Python, seems like it has a lot of flexibility and is faster than traditional RDBMS systems. Working on a very simple process to create random fantasy teams. I come from an RDBMS background (Oracle SQL) ...
Parse GenCAD file to python lists Question: I am new to python. In my first little project I want to **parse** `GenCAD` output file and assign the `$PARTS$` content to a python list of lists data structure for further procesing. The file to import: $HEADER$ BOARD_TYPE PCB_DESIGN UNITS MM $EN...
ImportError: No module named _markerlib when trying to install via pip Question: Did somebody experienced the same problem? I tried to run a solution from SO: pip install --upgrade distribute and pip install --upgrade setuptools And I got the same result, every time: ...
Finding the format of my timestamp in Python Question: My time format is screwy, but it seemed workable, as a string with the following format: '47:37:00' I tried to set a variable where: DT = '%H:%M:%S' So I could find the difference between two times, but it's given me the fo...
Python - Speech Recognition time offsets Question: I am trying to do speech recognition using python. In addition to this, I need to get the times of beginning and end of each word. I would rather use a free library that can deal with this. I've heard that Sphinx is able to do this but I couldn't find any examples (fo...
Python: Can an exception class identify the object that raised it? Question: When a Python program raises an exception, is there a way the exception handler can identify the object in which the exception was raised? If not, I believe I can find out by defining the exception class like this... class Foob...
Create a bar graph using datetimes Question: I am using matplotlib and pyplot to create some graphs from a CSV file. I can create line graphs no problem, but I am having a lot of trouble creating a bar graph. I referred to this post [matplotlib bar chart with dates](http://stackoverflow.com/questions/5902371/matplotli...
Reading JSON file with Python 3 Question: I'm using Python 3.5.2 on Windows 10 x64. The `JSON` file I'm reading is [this](http://pastebin.com/Yjs6FAfm "this") which is a `JSON` array containing 2 more arrays. I'm trying to parse this `JSON` file using the `json` module. As described in the [docs](https://docs.python.o...
What is the equivalent of Serial.available() in pyserial? Question: When I am trying to read multiple lines of serial data on an Arduino, I use the following idiom: String message = ""; while (Serial.available()){ message = message + serial.read() } In Arduino C, `Serial.available()...
AttributeError: LinearRegression object has no attribute 'coef_' Question: I've been attempting to fit this data by a Linear Regression, following a tutorial on bigdataexaminer. Everything was working fine up until this point. I imported LinearRegression from sklearn, and printed the number of coefficients just fine. T...
Python: Including only the last 7 values in each key Question: I have a dictionary where each key has multiple values. Would it be possible to include only the last 7 values for each key, and then do basic arithmetic with it (ex: addition, subtraction, multiplication, division)? The end objective is to be able to uplo...
Authenticating a Controller with a Tor subprocess using Stem Question: I am trying to launch a new tor process (no tor processes currently running on the system) using a 'custom' config by using stems `launch_tor_with_config`. I wrote a function that will successfully generate and capture a new hashed password. I then...
tarfile compressionerror bz2 module is not available Question: I'm trying to install twisted pip install <https://pypi.python.org/packages/18/85/eb7af503356e933061bf1220033c3a85bad0dbc5035dfd9a97f1e900dfcb/Twisted-16.2.0.tar.bz2#md5=8b35a88d5f1a4bfd762a008968fddabf> This is for a `django-channels` project and I'm havi...
Implement Cost Function of Neural Network (Week #5 Coursera) using Python Question: Based on the Coursera Course for Machine Learning, I'm trying to implement the cost function for a neural network in python. There is a [question](http://stackoverflow.com/questions/21441457/neural-network-cost- function-in-matlab) simi...
csv file compression without using existing libraries in Python Question: I'm trying to compress a .csv file without using any 3rd party or framework provided compression libraries. I have tried, what I wish to think, everything. I looked at Huffman, but since I'm not allowed to use that solution I tried to do my own....
Python Class Self Object Question: This may seems a weird question, I have a variable which has the function name of another class which I have already imported. Now I have to call that function using self.variable_name(argument) Is it possible? name = analyser['name'] analyser_execution = self.nam...
Open .exe file through .bat file in Flask Question: I am trying to open an .exe file (e.g. Paint) with a html button using Flask, so I wrote a small .bat file that runs it properly when I run it through Python, but does not seem to work when I open it through Flask. The Python is: @app.route('/assemblie...
Color between the x axis and the graph in PyPlot Question: I have a graph that was plotted using datetime objects for the x axis and I want to be able to color beneath the graph itself (the y-values) and the x axis. I found this post [Matplotlib's fill_between doesnt work with plot_date, any alternatives?](http://stack...
Python/Pyomo with glpk Solver - Error Question: I am trying to run some simle example with Pyomo + glpk Solver (Anaconda2 64bit Spyder): from pyomo.environ import * model = ConcreteModel() model.x_1 = Var(within=NonNegativeReals) model.x_2 = Var(within=NonNegativeReals) model.obj = Object...
pandas read_csv raises ValueError Question: I want to read txt data seperated by ',' and '\t', and I use code below: `io_df = pd.read_csv('input_output.txt',sep='\D|\t',engine = 'python')` This triggered error information below: `--------------------------------------------------------------------------- ValueError ...
Getting Turtle in Python to recognize click events Question: I'm trying to make Connect 4 in python, but I can't figure out how to get the coordinates of the screen click so I can use them. Right now, I want to draw the board, then have someone click, draw a dot, then go back to the top of the while loop, wipe the scre...
wxpython wx.Slider: how to fire an event only if a user pauses for some predetermined time Question: I have a `wx.Slider` widget that is bound to an event handler. As a user moves the slider, some process will run. However, because the process can take up to 3 seconds to run, I don't want the event to fire continuously...
Setting values for a numpy ndarray using mask Question: I want to calculate business days between two times, both of which contain null values, following [this question](http://stackoverflow.com/questions/37576552/dealing-with-none- values-when-using-pandas-groupby-and-apply-with-a-function) related to calculating busi...
return inverse string selection in python Question: I have a python snippet that returns the contents within two strings using regex. res = re.search(r'Presets = {(.*)Version = 1,', data, re.DOTALL) What I now want to do is return the two strings surrounding this inner part. Keep in mind this is a ...
Python win32api get "stack" of windows Question: I'm looking for a way to find out what order windows are open on my desktop in order to tell what parts of what windows are visible to the user. Say, in order, I open up a maximized chrome window, a maximized notepad++ window, and then a command prompt that only covers ...
Custom logger with time stamp in python Question: I have lots of code on a project with print statements and wanted to make a quick a dirty logger of these print statements and decided to go the custom route. I managed to put together a logger that prints both to the terminal and to a file (with the help of this site),...
TensorFlow: AttributeError: 'Tensor' object has no attribute 'shape' Question: I have the following code which uses TensorFlow. After I reshape a list, it says > AttributeError: 'Tensor' object has no attribute 'shape' when I try to print its shape. # Get the shape of the training data. print "trai...
restarted computer and got: ImportError: No module named django.core.management Question: I have been having some issues with gulp serving my files so I restarted my computer, upon going back to my project and starting the server I suddenly got the error: `ImportError: No module named django.core.management`. I am wor...
Using Concurrent.Futures.ProcessPoolExecutor to run simultaneous & independents ABAQUS models Question: I wish to run a total of **_nAnalysis=25_** Abaqus models, each using X number of Cores, and I can run concurrently **_nParallelLoops=5_** of these models. If one of the current 5 analysis finishes, then another anal...
Return all keys along with value in nested dictionary Question: I am working on getting all text that exists in several `.yaml` files placed into a new singular YAML file that will contain the English translations that someone can then translate into Spanish. Each YAML file has a lot of nested text. I want to print th...
Authorizing a python script to access the GData API without the OAuth2 user flow Question: I'm writing a small python script that will retrieve a list of my Google Contacts (using the [Google Contacts API](https://developers.google.com/google-apps/contacts/v3/)) and will randomly suggest one person for me to contact (g...
initialization of multiarray raised unreported exception python Question: I am a new programmer who is picking up python. I recently am trying to learn about importing csv files using numpy. Here is my code: import numpy as np x = np.loadtxt("abcd.py", delimiter = True, unpack = True) print(x) ...
Missing dll files when using pyinstaller Question: Good day! I'm using python 3.5.2 with qt5, pyqt5 and sip14.8. I'm also using the latest pyinstaller bracnch (3.3.dev0+g501ad40). I'm trying to create an exe file for a basic hello world program. from PyQt5 import QtWidgets import sys class...
python division result not true and different results Question: I am trying to solve fractional knapsack problem. I have to find items with maximum calories per weight. I will fill my bag up to defined/limited weight with maximum calories. Though algorithm is true, I can't find true result because of python division ...
'module' object has no attribute 'questiоn'. Class name considered an attribute? Question: I'm trying to make a quiz for my project and I'm getting this error: `AttributeError: 'module' object has no attribute 'question'`. I don't understand why it thinks my class is an attribute. * questionbf.py is where I made the...
In Python, bool(a.append(3)) is False. Why? Question: It seems `bool(a.append)` and `bool(a)` are all `True`, but why `bool(a.append(3))` is `False`? My question is from the code here: class MovingAverage(object): def __init__(self, size): self.next = lambda v, q=collections.deque(()...
How to nest numba jitclass Question: I'm trying to understand how the @jitclass decorator works with nested classes. I have written two dummy classes: fifi and toto fifi has a toto attribute. Both classes have the @jitclass decorator but compilation fails. Here's the code: fifi.py from numba import jitc...
Python IF ELSE statement now working Question: Simple question for some. I have my first program I am trying to make using python. The IF ELSE statement is not working. The output remains "Incorrect" even if the correct number is inputted by the user. I'm curious if it's that the random number and the user input are di...
Print dataframe after grouping H2o python Question: **Data:** "<https://github.com/estimate/pandas-exercises/blob/master/baby- names2.csv>" In pandas: df=pd.read_csv("baby-names2.csv") df_group=df.groupby("year") print df_group.head() It prints the dataframe grouped by year. **How do ...
How to properly display image in Python? Question: I found this code: from PIL import Image, ImageTk import tkinter as tk root = tk.Tk() img = Image.open(r"Sample.jpg") canvas = tk.Canvas(root, width=500, height=500) canvas.pack() tk_img = ImageTk.PhotoImage(img) can...
python basic show and return values Question: I'm using python to input data to my script then trying to return it back on demand to show the results I tried to write it as simple as possible since it's only practicing and trying to get the hang of python here's how my script looks like #!/usr/python ...
Add current element in array + next element in array while iterating through array in Python Question: What's the best way to add the first element in an array to the next element in the same array, then add the result to the next element of the array, and so on? For example, I have an array: s=[50, 1.26...
Serialize a string without changes in Django Rest Framework? Question: I'm using Python's json.dumps() to convert an array to a string and then store it in a Django Model. I'm trying to figure out how I can get Django's REST framework to ignore this field and send it 'as is' without serializing it a second time. For e...
Script to replace characters in file Question: i'm facing trouble trying to replace characters in a file. #!/usr/bin/env python with open("crypto.txt","r") as arquivo: data = arquivo.read() for caracter in data: if "a" in data: data = data.replace("a","c") ...
MySQL get multiple items from a table as a input for a single field of another table Question: I have two tables one is teachers another is subjects and I need to link the subjects to the teachers , thats an easy one but the problem is that a single teacher can have multiple subjects.Thus I need a kind of array for tha...
How to display an error message in mpl_connect() callback function Question: My understanding is that: Normally, when an error happens, it's thrown down through all the calling functions, and then displayed in the console. Now there's some packages that do their own error handling, especially GUI related packages often...
Difficulty parsing text file Python 2.7 Question: Using Python 2.7, I want to take a file as input, remove some charachters from it, and write that to another file. I'm not entirely succeeding with the below code: print 'processing .ujc file for transmit' infile, outfile = open('app_code.ujc','r'), o...
Set default value for cut off date and ballot date using value of date field in the same model in django Question: I have created a model for entering sitting date of a session along with cut off date and ballot date. My model is: from datetime import datetime, timedelta class Sitting(models.Model): ...
Slicing a graph Question: I have created a graph in python but I now need to take a section of the graph and expand this by using a small range of the original data, but I don't know how to find the row number of the results that form the range or how I can create a graph using just these results form the file. This is...
how to convert string into dictionary in python 3.*? Question: I want to convert the following string into dictionary without using eval() function in python 3.5 . d="{'Age': 7, 'Name': 'Manni'}"; Can anybody tell me the good way than using the eval() function?? (Actually i want to know about the function which can d...
Python pause thread, do manually and reset time Question: I need to call function every x seconds but with option to call it manually and in this case reset time. I have sth like this: import time import threading def printer(): print("do it in thread") def do_sth(event): ...
ElasticSearch AND query in python Question: I am trying to query elastic search for logs which have one field with some value and another fields with another value my logs looks like this in Kibana: { "_index": "logstash-2016.08.01", "_type": "logstash", "_id": "6345634653456", ...
Optimising the generation of a large number of random numbers using python 3 Question: I am wanting to generate eight random numbers within a range (0 to pi/8), add them together, take the sine of this sum, and after doing this N times, take the mean result. After scaling this up I get the correct answer, but it is too...
Windows path with spaces in python Question: I have a problem with passing windows path to a function in python. Now, if I hard code the path everything actually works. So, my code is: from pymatbridge import Matlab lab = Matlab(executable=r'"c:\Program Files \MATLAB\bin\matlab.exe"') lab.start()...
Run sqoop in python script Question: I'm trying to run sqoop command inside Python script. I had no problem to do that trough shell command, but when I'm trying to execute python stript: #!/usr/bin/python sqoopcom="sqoop import --direct --connect abcd --username abc --P --query "queryname" " ...
How to parse logs and extract lines containing specific text strings? Question: I've got several hundred log files that I need to parse searching for text strings. What I would like to be able to do is run a Python script to open every file in the current folder, parse it and record the results in a new file with the o...
Google Drive API POST requests? Question: I'm trying to interact with the Google Drive API and while their example is working, I'd like to learn how to make the POST requests in python instead of using their pre-written methods. For example, in python how would I make the post request to insert a file? [Insert a File](...
Speedup GPU vs CPU for matrix operations Question: I am wondering how much GPU computing would help me speed up my simulations. The critical part of my code is matrix multiplication. Basically the code looks like the following python code with matrices of order 1000 and long for loops. import numpy as n...
How to call variables from an imported parameter-dependent script? Question: I've just begun to use python as a scripting language, but I'm having difficulty understanding how I should call objects from another file. This is probably just because I'm not too familiar on using attributes and methods. For example, I cre...
Calling Class, getting TypeError: unbound method must be called Question: I have reviewed the error on Stackoverflow, but none of the solutions I've seen resolve my problem. I'm attempting to create a class for cx_Oracle to put my database connectivity in a class, and call it during my database instances. I've created ...
Formatting a CSV for a Python dictionary Question: If I have a CSV file that looks like this: ### Name | Value 1 | Value 2 Foobar | 22558841 | 96655 Barfool | 02233144 | 3301144 How can I make it into a dictionary that looks like this: dict = { 'Foobar': { 'Value 1': 2255841, ...
Is it possible to use SQL Server in python without external libs? Question: I'm developing on an environment which I'm not allowed to install anything. It's a monitoring server and I'm making a script to work with logs and etc. So, I need to connect to a SQL Server with Python 2.7 without any lib like pyodbc installed...
python multiprocessing pool timeout Question: I want to use [multiprocessing.Pool](https://docs.python.org/3.4/library/multiprocessing.html#multiprocessing.pool.Pool), but multiprocessing.Pool can't abort a task after a timeout. I found [solution](http://stackoverflow.com/questions/29494001/how-can-i-abort-a-task- in-a...
How to close cmd after opening a file using Python in Windows? Question: I have a written a program using Python to open a particular file (txt) which it creates during execution. I have made a batch file to access the script using command line. The batch script is as follows: @echo off python F:\pro...
Python Json Config 'Extended Interpolation' Question: I am currently using the Python library configparser: from configparser import ConfigParser, ExtendedInterpolation I find the ExtendedInterpolation very useful because it avoids the risk of having to reenter constants in multiple places. I now ...
How to create a timetracker? Question: I'm very new to Python. I want to create a script for time tracking with a grafical interface. Once you hit start the start time should be stored and when you hit stop the time difference shoult be displayed. This is my approach to the topic: import datetime fr...
change a range of colors to white in python Question: I use following code to change specific colors (grays) to white in photos. But the code is too slow. any suggestion or alternative is welcomed. import os import numpy as np from PIL import Image for j in range(1,160): im = Image.op...
How can I extract the text outside the <em> tag in BeautifulSoup Question: Can someone help me extract the test that is after the _From_ , I want to extract the sender name. It is situated right outside the em tag. I'm using the python BeautifulSoup package. Here is a link to the webpage: <http://seclists.org/fulldisc...
How can I decode a utf-8 byte array to a string in Python2? Question: I have an array of bytes representing a utf-8 encoded string. I want to decode these bytes back into the string in Pyton2. I am relying on Python2 for my overall program, so I can not switch to Python3. array = [67, 97, 102, **-61, -87...