files = !ls
files

"""
Explanation: IPython speaks many languages
Insert a joke about Glossolalia and snakes.
Run commands in bash and get useful representations back:
End of explanation
"""


%%bash
uname -a
echo $PWD

"""
Explanation: or run multiple lines in a cell that is all bash
End of explanation
"""


# requires `conda install cython`
%load_ext Cython

def f(x):
    return x**2-x

def integrate_f(a, b, N):
    s = 0; dx = (b-a)/N
    for i in range(N):
        s += f(a+i*dx)
    return s * dx

%%cython
cdef double fcy(double x) except? -2:
    return x**2-x

def integrate_fcy(double a, double b, int N):
    cdef int i
    cdef double s, dx
    s = 0; dx = (b-a)/N
    for i in range(N):
        s += fcy(a+i*dx)
    return s * dx

%timeit integrate_f(0, 1, 100)
%timeit integrate_fcy(0, 1, 100)

"""
Explanation: Cython
Cython is an optimising static compiler for both the Python programming language and the extended Cython programming language (based on Pyrex). It makes writing C extensions for Python as easy as Python itself.
Quasi random numbers, Tim's knowledge on wrapping C/C++ libraries for easy use from python
TL;DR: use python syntax, get C speed.
Load the cython extension. Read more about ipython extensions
End of explanation
"""


%%cython?

%%cython -lm
# Link the m library (like g++ linker argument)
from libc.math cimport sin
print 'sin(1)=', sin(1)

%%cython -a
cdef double fcy(double x) except? -2:
    return x**2-x

def integrate_fcy(double a, double b, int N):
    cdef int i
    cdef double s, dx
    s = 0; dx = (b-a)/N
    for i in range(N):
        s += fcy(a+i*dx)
    return s * dx

"""
Explanation: Getting help
What options does the cython magic have?
End of explanation
"""


