append time difference values in a list - python

I am using Raspberry pi with python for a project and i am also a beginner to Python.
I have tried this code in Spyder IDE in windows and it was working fine but now i am facing the error for the same in raspberry pi inbuilt python IDE. I know that i made a small mistake somewhere but unfortunately, i could not find. Can someone please help me to rectify?
import time
import matplotlib.pyplot as plt
a = list(range(150))
t=[]
str_time = time.time()
for x in range(150):
time.sleep(0.001)
t.append((time.time() - str_time))
y= [x * 1000 for x in t]
plt.plot(y,a)
plt.show()
Error:

Related

Jupyter Notebook malfunctioning

I am running Julia and Python on Jupyter notebook. I like the UI and the auto indentation and other features (I'm a beginner). However, while running Julia today the entire notebook just appears blank. The code blocks are not colour coded, and there is no auto indentation. However, when I open a Python notebook/change the kernel from Julia to Python, it works as usual. I have attached pictures here for comparison.
I don't know what has changed. How do I fix this?
EDIT: Adding some code for reference:
Julia
using Plots
function lattice(N)
lat = zeros(N,N)
for i in (1:N)
for j in (1:N)
if rand() < 0.5
lat[i,j] = 1
else lat[i,j] = -1
end
end
end
return(lat)
end
Python
import numpy as np
def ran_ini_cond(L):
spins = np.zeros((L,L))
for i in range(L):
for j in range(L):
spins[i,j] = np.random.choice([1,-1])
print('inital lattice')
return(spins)
These are two different versions of the same program I am trying to run on Julia and Python. The code works, but a lot of the IJulia and/or Jupyter notebook features are disabled for Julia (as seen in the pictures).

Setting up Adafruit PDM with Rapsberry Pi 4

I am relatively new to working with Raspberry pi, Adafruit products and python coding. I have been working on setting up a Adafruit PDM Microphone connected to my RPi 4 and am attempting to running it on python 3. Adafruits tutorials have been amazing so far but I am having some issues getting all the required modules and libraries installed for this one. Is there a way to install Adafruit_zeroPDM and Adafruit_zeroDMA into python? I followed the github download links and tried several methods for installing them using pip3 however I am repeatedly getting errors about missing modules that should be in Adafruit's circuit python library. Is the Adafruit PDM microphone not compatible with RPi?
I have been using the following python code, which is directly taken form the adafruit website(https://learn.adafruit.com/adafruit-pdm-microphone-breakout/circuitpython):
import time
import array
import math
import board
import audiobusio
def mean(values):
return sum(values) /len(values)
def normalized_rms(values):
minbuf = int(mean(values))
samples_sum = sum(
float(sample - minbuf) * (sample - minbuf)
for sample in values
)
return math.sqrt(samples_sum / len(values))
#Main program
mic = audiobusio.PDMIn(board.TX, board.D12, sample_rate=16000, bit_depth=16)
samples = array.array('H', [0] * 160)
while True:
mic.record(samples, len(samples))
magnitude = normalized_rms(samples)
print((magnitude,))
print("Decible Quired")
time.sleep(10)
I am unable to solve a library and module problem. I have downloaded Adafruit_circuitpython library and Adafruit_Blinka library as well as the required Adafruit_ZeroPDM and Adafruit_ZeroDMA however I keep getting the following error.
ModuleNotFoundError: No module named 'audiobusio'
Any help would be greatly appreciated.
Best

Getting matplotlib to work - plots not showing

I was able to successfully install matplotlib; however, when I run my code, I don't get an error, but instead the Python icon bouncing over and over again.
I don't know if it has anything to do with
from rcParamsSettings import *
I don't have any idea what that is, but if I try to run it with that line uncommented out, I get
ImportError: No module named rcParamsSettings
Here's the code I'm trying to run:
import pylab
#from rcParamsSettings import *
import random
def flipPlot(minExp, maxExp):
"""Assumes minExp and maxExp positive integers; minExp < maxExp
Plots results of 2**minExp to 2**maxExp coin flips"""
ratios = []
diffs = []
xAxis = []
for exp in range(minExp, maxExp + 1):
xAxis.append(2**exp)
for numFlips in xAxis:
numHeads = 0
for n in range(numFlips):
if random.random() < 0.5:
numHeads += 1
numTails = numFlips - numHeads
ratios.append(numHeads/float(numTails))
diffs.append(abs(numHeads - numTails))
pylab.title('Difference Between Heads and Tails')
pylab.xlabel('Number of Flips')
pylab.ylabel('Abs(#Heads - #Tails)')
pylab.plot(xAxis, diffs)
pylab.figure()
pylab.title('Heads/Tails Ratios')
pylab.xlabel('Number of Flips')
pylab.ylabel('#Heads/#Tails')
pylab.plot(xAxis, ratios)
random.seed(0)
flipPlot(4, 20)
What do I need to do to get the code running?
Note: My experience with programming and Python is very limited; I'm just starting out.
You need to use pylab.show() otherwise nothing will come up.
See the example here: http://matplotlib.org/examples/pylab_examples/simple_plot.html
(although you should avoid using from pylab import *, the way you import is fine.)
There are cases in MatPlotLib where you do not want to show the graph. An example I have is designing a graph on a server using data collected by an automated process. The server has no screen and is only accessed by a terminal, and therefore trying to show a graph will result in an error as there is no DISPLAY variable set (there is no screen to display to).
In this case it would be normal to save the figure somewhere using pylab.savefig(), and then maybe email it or use an ftp to send it somewhere it can be viewed.
Because of this MatPlotLib will not implicitly show a graph and must be asked to show it.
Your code works for me if I add a pylab.show().
Alternatively, you could save the plot to a file:
pylab.savefig("file.png")
This makes sense if you are updating your plot frequently.

Python Spyder Display Symbolic Math

In Spyder 2 (Anaconda distribution) and in the IPython QT Console I'm able to print results of symbolic calculations (from an answer I got for a previous post) but I can't get equations in strings to print with the a IPython's Rich Display System:
from sympy import *
from IPython.display import display, Math
init_printing(use_unicode=False, wrap_line=False, no_global=True)
x, y, z = symbols('x y z')
#----- prints correctly
ii = integrate(x**2 + x + 1, x)
display(ii)
#----- does not print
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
The above prints the results of the integrate correctly but the Math() does not print (no error -- just skips it). Note it all works in SciPy web notebook.
Thank you!
The Math class doesn't generate the rendered image from your Latex, that's why it doesn't work directly.
To get what you want you need to use this code
from IPython.display import Image, display
from IPython.lib.latextools import latex_to_png
eq = r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'
data = latex_to_png(eq, wrap=True)
display(Image(data=data))
Then you will see the right image
Hello guys im still having the problem, whe i use
from IPython.display import display, Math, Latex
display((Math(r'P(Purchase|Male)= \frac{Numero\ total\ de\ compras\ hechas\ por\ hombres\}{Total\ de\ hombres\ en\ el\ grupo\} = \frac{Purchase\cap Male}{Male}')))
on jupyter it works fine, but when i do the exact same code on spyder it doesnt work
im using python 3.6 , spyder 3.3.3
also i tried the marked asnwer but latex_to_png makes a NoneType Object on spyder

Python Kernel died when using Gurobi in Enthought Canopy on Win 7

I was trying to use Gurobi for Python to solve a Mixed Integer Optimization problem, but every time I run the code I wrote according to the Gurobi tutorial, a message popped up, saying:
"The Kernel has died, would you like to restart it? If you do not restart the kernel, you will be able to save the notebook, but running code will nor work until the notebook is reopened."
I used Enthought Canopy with Python 2.7 and Gurobipy from Gurobi on Win 7.
Here is a small trial optimization problem I tried to solve, and the message above showed up after I run it:
import gurobipy
import numpy
from gurobipy import *
def minVol(N1,solution):
model=Model()
x=model.addVar(lb=0.0,ub=1.0,vtype=GRB.CONTINUOUS)
y=model.addVar(lb=0.0,ub=1.0,vtype=GRB.CONTINUOUS)
model.update()
varibles=model.getVars()
model.setObjective(2*x+y,GRB.Maximize)
model.update()
model.optimize()
if model.status==GRB.OPTIMAL:
s=model.getAttr('s',varibles)
for i in range(N1):
solution[i]=s[i]
return True
else:
return False
N1=2
solution=[0]*(N1)
success=minVol(N1,solution)
if success:
print solution
Anyone would help me with this? Thank you very much!

Categories