I am working on the file "Spring_semester_first_session.ipynb".
The first task is:
Task: Calculate the full many-body spectrum as function of $\mu/\Delta$, find the many-body groundstate for
$\mu/\Delta=-5,0,5$
Can you write Python code for it?

muran=linspace(-5,5,100)
fig=figsize(4,5)
dat=[]
cc=fermion_Fock_matrices(2)
for mu in muran:
    dat.append(eigvalsh(Singe_Site_Superconductor_Fock_Ham(cc,mu,1.)))
plot(muran,dat,lw=3);
#stuff below is only to make figure nice
xticks(fontsize=16)
yticks(fontsize=16)
grid()
xlabel(r'$\mu/\Delta$',fontsize=16);
ylabel(r'$E_n$',fontsize=16);

for mu in [-5,0,5]:
    val,vec=eigh(Singe_Site_Superconductor_Fock_Ham(fermion_Fock_matrices(2),mu,1.))
    print (val[0])
    print (vec[:,0])


I am working on the file "Spring_semester_first_session.ipynb".
The first task is:
The Bogoliubov–de Gennes "trick"
One can rewrite a generic superconductor many-body Hamiltonian
$$
\hat{H} = \sum_{\alpha,\beta} \left(
c_\alpha^\dagger h_{\alpha,\beta}
c_{\beta} + \frac{1}{2}c_\alpha^\dagger \Delta_{\alpha,\beta}
c_\beta^\dagger  + \frac{1}{2}c_\beta \Delta_{\alpha,\beta}^\ast
c_\alpha \right)
$$
as
$$
\hat{H} = \frac{1}{2}
 \begin{matrix}\begin{pmatrix} c^\dagger & c \end{pmatrix}\\mbox{}\end{matrix}
\mathcal{H}{\mathrm{BdG}}
\begin{pmatrix} c \ c^\dagger \end{pmatrix} + \frac{1}{2} \mathrm{Tr} h \mathbb{1}{\mathrm{Fock}}
$$
where we have introduced the Bogoliubov–de Gennes matrix as
$$
\mathcal{H}_{\mathrm{BdG}} = \begin{pmatrix}
h & \Delta \
-\Delta^\ast & -h^\ast \end{pmatrix}.
$$
The positive eigenvalues of the Bogoliubov–de Gennes matrix correspond to the single particle excitation spectrum of the full many-body Hamiltonian.
Task: Write a routine that calculates the Bogoliubov–de Gennes matrix of the Kitaev model, calculate the spectrum and compare the spectrum to the excitation spectrum of the many-body Hamiltonian.
Can you write Python code for it?

#Define the Pauli matrices unit matrix and the zero matrix
s0=matrix([[1,0],[0,1]])
s1=matrix([[0,1],[1,0]])
s2=matrix([[0,-1j],[1j,0]])
s3=matrix([[1,0],[0,-1]])
z2=zeros_like(s0);

def Kitaev_wire_BDG_Ham(N,mu,t,Delta):
    idL=eye(N); # identity matrix of dimension L
    odL=diag(ones(N-1),1);# upper off diagonal matrix with ones of size L
    U=mu*s3
    T=-t*s3+1.0j*Delta*s2
    return kron(idL,U)+kron(odL,T)+kron(odL,T).H

def playBdG(N=10,Delta=0.2):
    dat=[]
    for u in uran:
        dat.append(eigvalsh(Kitaev_wire_BDG_Ham(N,u,1,Delta)))
    plot(uran,dat,'k',lw=6);
    plot(uran,array(dat)[:,0],'k',lw=6,label=r'$E^{\mathrm{BdG}}_n$')

#This lets you play with the BdG spectrum
uran=linspace(-3,3,100)
interact(playBdG,N=(3,20),Delta=(0,2,0.1));
xlabel(r'$\mu$',fontsize=16);
ylabel(r'$E^{\mathrm{BdG}}_n$',fontsize=16);
grid();

figsize(4,5)
uran=linspace(0,4,50)
NN=6;Delta=0.9;
playBdG(NN,Delta)
playFock(NN,Delta)
ylim(-6,6)
xticks(linspace(min(uran),max(uran),5),fontsize=16)
yticks(linspace(-6,6,5),fontsize=16)
xlabel(r'$\mu$',fontsize=16)
grid()
legend(fontsize=16,loc='lower right');


I am working on the file "Spring_semester_first_session.ipynb".
The first task is:
Topological insulators II/01: Superconductivity and the Kitaev model
Many-body approach
We first construct annihilation operators $\hat{c}_i$ acting on the Fock space of fermions in the binary sequence basis.
Can you write Python code for it?

def fermion_Fock_matrices(NN=3):
    '''
    Returns list of 2^NN X 2^NN sparse matrices,
    representing fermionic annihilation operators
    acting on the Fock space of NN fermions.
    '''
    l=list(map(lambda x: list(map(int,list(binary_repr(x,NN)))),arange(0,2**NN)))
    ll=-(-1)**cumsum(l,axis=1)
    AA=(array(l)*array(ll))[:,::-1]
    cc=[]
    for p in range(NN):
        cc.append(scsp.dia_matrix((AA[:,p],array([2**p])),shape=(2**NN,2**NN), dtype='d'))
    return cc


I am working on the file "Spring_semester_second_session.ipynb".
The first task is:
Finally we can check the values of the two calculated Berry's phases:
Can you write Python code for it?

print(r"Berry's phase for the even subspace:",angle(ProjectorProductEven.trace()[0,0]))
print(r"Berry's phase for the odd subspace:",angle(ProjectorProductOdd.trace()[0,0]))
print(r'Numeeric value of $\pi/4$',pi/4)


I am working on the file "Spring_semester_second_session.ipynb".
The first task is:
Hint: You can use predifined functions in topobp.py
First let us define four fermionic annihilation $\hat{c}_i$ operators:
Can you write Python code for it?

# construct the c operators; Nsp stands for the number of single-particle states,
# that is 4 for our 4-site T-junction
Nsp = 4;
c = fermion_Fock_matrices(Nsp,dense=True);


I am working on the file "Spring_semester_second_session.ipynb".
The first task is:
Now we are ready to perform the braiding. Below we write a simple for loop and calculate the Berry's phase for the even and odd parity groundstate:
Can you write Python code for it?

# loop for time points
# set the initial value of the even and odd projector products as the identity matrix
ProjectorProductEven = IdentityMatrix;
ProjectorProductOdd = IdentityMatrix;
taumin = 0.0;
taumax = 6.0;
taunum=300;
tran=linspace(taumin,taumax,taunum,endpoint=False)
for t in tran:
    [val,vec]=eigh(Braid_Fock_Ham(t))
    GSProjector=vec[:,0]*vec[:,0].H+vec[:,1]*vec[:,1].H
    ## construct the projectors of the even and odd ground states and update the projector product
    ProjectorProductEven = ProjectorProductEven*(PEven*GSProjector*PEven)
    ProjectorProductOdd = ProjectorProductOdd*(POdd*GSProjector*POdd)

# end of loop for time points


I am working on the file "Spring_semester_second_session.ipynb".
The first task is:
Once we have the $\hat{c}_i$ operators we can build up a parameter dependent Hamiltonian that performs the braiding:
Can you write Python code for it?


I am working on the file "Spring_semester_second_session.ipynb".
The first task is:
Then the projectors for the even and odd fermion number subspaces:
Can you write Python code for it?

# construct the projectors on the even and odd subpsaces
PEven , POdd =  even_odd_Fock_operators(Nsp,dense=True)
#Identity matrix
IdentityMatrix=PEven+POdd


I am working on the file "Spring_semester_second_session.ipynb".
The first task is:
Topological insulators II/02: Majorana fermions and brading
Task: Berry-phase calculation for four-site y-turn braiding.
Some helper functions you may use for the braiding protocol:
Can you write Python code for it?

def fOn(t,n):
    '''
    A piecewise function ...
    '''
    return ( 1*((t>=n)&(t<n+1)) + 0*((t<n)&(t>=n+1)));

def fSwitchOn(t,n):
    return (t-n)*fOn(t,n);

def fSwitchOff(t,n):
    return fOn(t,n)*(1-fSwitchOn(t,n));


I am working on the file "Spring_semester_second_session.ipynb".
The first task is:
We shall also nead the functions that describe how different hopping and pairing amplitudes change as we vary time:
Can you write Python code for it?

# define the functions that govern the braiding protocol
def ft23(t):
    return fSwitchOff(t,0) + fSwitchOn(t,3) + fOn(t,4) + fOn(t,5);
def ft34(t):
    return fOn(t, 0) + fOn(t, 1) + fSwitchOff(t, 2) + fSwitchOn(t, 5);
def ft13(t):
    return fSwitchOn(t, 1) + fOn(t, 2) + fOn(t, 3) + fSwitchOff(t, 4);


I am working on the file "Springleaf - preprocess - date columns.ipynb".
The first task is:
Delete the original date columns and join the years, months and days DataFrames with the original DataFrame
Can you write Python code for it?

df = df.drop(date_cols, axis=1)
df = df.join(years)
df = df.join(months)
df = df.join(days)

date_cols = years.columns.tolist() + months.columns.tolist() + days.columns.tolist()


I am working on the file "Springleaf - preprocess - date columns.ipynb".
The first task is:
Eliminate all columns with standard deviation equal to 0
Can you write Python code for it?

std_series = df_desc.loc['std', :]
null_std_cols = std_series[std_series == 0]
df = df.drop(null_std_cols.index, axis=1)


I am working on the file "Springleaf - preprocess - date columns.ipynb".
The first task is:
Eliminate columns with 0 variance
See which columns have low standard deviation
Can you write Python code for it?

df_desc = df.describe()
df_desc[sorted(df_desc.columns, key=lambda x: df_desc.loc['std', x])]


I am working on the file "Springleaf - preprocess - date columns.ipynb".
The first task is:
Parse the weird date format of the date column
Can you write Python code for it?

def parse_date_str(date_val):
    if isinstance(date_val, datetime):
        return date_val
    date_val = str(date_val).lower()
    date_val = None if date_val == 'nan' else date_val
    if date_val is None:
        return pd.NaT
    date_val = date_val[:-2] if date_val[-2:] == '.0' else date_val
    try:
        return datetime.strptime(date_val, '%d%b%y:%H:%M:%S')
    except:
        try:
            return datetime.strptime(date_val, '%d%b%y')
        except:
            try:
                return datetime.strptime(date_val, '%Y')
            except:
                print date_val
                return pd.NaT

df_date_cols = df[date_cols].applymap(parse_date_str).astype('datetime64[ns]')
df_date_cols.describe()

df[date_cols] = df_date_cols


I am working on the file "Springleaf - preprocess - date columns.ipynb".
The first task is:
Remove columns with only NaNs
Can you write Python code for it?

nan_cols = df.isnull().all()
nan_cols = nan_cols.index[nan_cols].tolist()
nan_cols


I am working on the file "Springleaf - preprocess - date columns.ipynb".
The first task is:
Vectorize Datetime colums
Create dataframes to separately store the year, month and day information of the date columns
Can you write Python code for it?

df[date_cols] = df[date_cols].astype('datetime64[ns]')
years = pd.DataFrame(columns=[c+'_year' for c in date_cols], index=df.index, dtype=np.int)
months = pd.DataFrame(columns=[c+'_month' for c in date_cols], index=df.index, dtype=np.int)
days = pd.DataFrame(columns=[c+'_day' for c in date_cols], index=df.index, dtype=np.int)

for c in date_cols:
    dateIndex = pd.DatetimeIndex(df[c])
    years[c+'_year'] = dateIndex.year
    months[c+'_month'] = dateIndex.month
    days[c+'_day'] = dateIndex.day


I am working on the file "Springleaf - preprocess - string columns.ipynb".
The first task is:
Cast string columns as string and make 'null' data uniform (instead of nan, -1, [], etc.)
Can you write Python code for it?

def filter_str(str_cell):
    str_cell = re.sub(r'[\W_]+', ' ', str(str_cell))
    str_cell = str_cell.strip().lower()
    if str_cell in ('1', '-1', '[]', 'nan', ''):
        return None
    else:
        return str_cell

df[str_cols] = df[str_cols].astype(np.str).applymap(filter_str)
df[str_cols]


I am working on the file "Springleaf - preprocess - string columns.ipynb".
The first task is:
Columns VAR_0202, VAR_0216, VAR_0222 and VAR_0466 have only one value. Check if there's some correlation between the values and the target.
Replace their string values for 1 if there was something in the cell, or 0 if there wasn't.
Can you write Python code for it?


I am working on the file "Springleaf - preprocess - string columns.ipynb".
The first task is:
Define columns
Can you write Python code for it?


I am working on the file "Springleaf - preprocess - string columns.ipynb".
The first task is:
Encode the labels of the rest of the columns
Can you write Python code for it?

encoder = LabelEncoder()
for col in str_cols:
    df[col] = encoder.fit_transform(df[col])


I am working on the file "Springleaf - preprocess - string columns.ipynb".
The first task is:
Save preprocessed data to another csv file
Can you write Python code for it?

df.to_csv(PTRAIN_PATH)

with open('deleted_str_cols.pickle', 'wb') as fp:
    pickle.dump(['VAR_0044', 'VAR_0202', 'VAR_0216', 'VAR_0222', 'VAR_0466'], fp)


I am working on the file "Springleaf - preprocess - string columns.ipynb".
The first task is:
See if the classes are skewed
Can you write Python code for it?

neg_samples_count = len(df['target'][df['target']==0])
pos_samples_count = len(df['target'][df['target']==1])
print '%s negative samples; %.2f%% of total' % (neg_samples_count, neg_samples_count/len(df)*100)
print '%s positive samples; %.2f%% of total' % (pos_samples_count, pos_samples_count/len(df)*100)


I am working on the file "Springleaf - preprocess - string columns.ipynb".
The first task is:
Vectorize String and Datetime colums
String columns
See how many different values the string columns have
Can you write Python code for it?

str_desc = df[str_cols].describe()
str_desc = pd.DataFrame(str_desc, columns=sorted(str_desc.columns, key=lambda c: str_desc.loc['std', c]))
str_desc


I am working on the file "Sputter yield functions.ipynb".
The first task is:
$\Gamma$
The Y96 model requires one more parameter. $$\Gamma=\frac{W(Z_2)}{1+(M_1/7)^3}$$ requires also a tabulated parameter $W(Z_2)$ which has index 6 in the array.
Can you write Python code for it?

def Gamma(Projectile,Target):
    '''
    from equ. 16 in Y96
    '''
    return get_Atom_prop(Target,'W')/(1.0+(get_Atom_prop(Projectile,'M')/7.0)**3)


I am working on the file "Sputter yield functions.ipynb".
The first task is:
All the different values will be computed in functions so we can call them at anytime, and reuse them for making graphs and similar stuff
Reduced Energy
The formula for the reduced energy is the same in Y96 and M84. The following is Equ 22 from Y96.
$$\epsilon=\frac{0.03255}{Z_1Z_2(Z_1^{2/3}+Z_2^{2/3})^{1/2}}\frac{M_2}{M_1+M_2}$$
For Sigmund I reimplement L. Bischoff's BASIC program he uses: $$\epsilon=\frac{0.069497M_2aE}{(M_1+M_2)Z_1Z_2}$$
where $a=0.469209/(Z_1^{2/3}+Z_2^{2/3})^{1/2}$
Can you write Python code for it?

def reduced_energy(Projectile,Target,Energy,sputter_model):
    '''
    Uses equ. 2 from M84
    '''
    Z1=get_Atom_prop(Projectile,'Z')
    Z2=get_Atom_prop(Target,'Z')
    M1=get_Atom_prop(Projectile,'M')
    M2=get_Atom_prop(Target,'M')
    if sputter_model=="Sigmund":
        a=0.469209/((Z1**(2.0/3.0)+Z2**(2.0/3.0))**(1.0/2.0))
        return  (0.069497*M2*a*Energy)/((M1+M2)*Z1*Z2)
    else:
        # This will be used for Y96 and M84
        return 0.03255/(Z1*Z2*(Z1**(2./3)+Z2**(2./3))**0.5)*M2/(M1+M2)*Energy


I am working on the file "Sputter yield functions.ipynb".
The first task is:
Nuclear stopping $S_n=Ks_n$
The conversion factor from the elastic reduced stopping corss section $s_n$ to the stopping cross secion $S_n$ $K$ is given by (3) in M84 $$K=\frac{S_n}{s_n}=8.478\frac{Z_1Z_2}{(Z_1^{2/3}+Z_2^{2/3})^{1/2}}\frac{M_1}{M_1+M_2}$$ this than has the unit $eV cm^{2}/10^{15} atoms$. from there we can calculate $S_n$.
In Y96 the equation is the same but different units are used ($eVA^2/atom$). As a result for Y96 the value is bigger by a factor 10. This has to be done as other empirical parameters are also in the new unit system.
We are not interested in $K$ but $S_n$ so we calculate that one directly from $s_nK$.
Can you write Python code for it?

def Sn(Projectile,Target,Energy,sputter_model,nuc_x_section_model):
    '''
    Calculats Sn needs the model for the nuclear stopping to calculate the reduced stopping power
    '''
    Z1=get_Atom_prop(Projectile,'Z')
    Z2=get_Atom_prop(Target,'Z')
    M1=get_Atom_prop(Projectile,'M')
    M2=get_Atom_prop(Target,'M')
    if sputter_model=="Sigmund":
        a=0.469209/((Z1**(2.0/3.0)+Z2**(2.0/3.0))**(1.0/2.0))
        return (18.081264*Z1*Z2*M1*reduced_nuc_stopping_x_section(Projectile,Target,Energy,sputter_model,nuc_x_section_model)*a)/(M1+M2)
    else:
        # We end up here if we use either M84 or Y96
        # the first parameter is 84 in Y96 instead of 8 in M84 due to different units used. This is corrected by also changing the Y(E) from 0.042 (Y96) to 0.42 (M84)
        return 8.478*Z1*Z2/(Z1**(2./3)+Z2**(2./3))**0.5*M1/(M1+M2)*reduced_nuc_stopping_x_section(Projectile,Target,Energy,sputter_model,nuc_x_section_model)


I am working on the file "Sputter yield functions.ipynb".
The first task is:
Reduced nuclear stopping cross section $s_n$
Next comes the reduced nuclear stopping cross section. In M84 this is Linhards elastic reduced stopping cross section $$s_n(\epsilon)=\frac{3.441\sqrt{\epsilon}\ln(\epsilon+2.718)}{1+6.355\sqrt{\epsilon}+\epsilon(-1.708+6.882\sqrt{\epsilon})}$$ This Thomas Fermi based approach is also used for Sigmund sputtering.
In Y96 two different expresion for the reduced nuclear stopping power are suggested. ONe is based on the Thomas-Fermi potential and identical to the M84 experssion for $s-n(\epsilon)$. The other is based on the Kr-C and comes from Eckstein in the wollwoing paper: W. Eckstein, C. Garcia-Rosales, J. Roth, and W. Ot- tenberger, IPP 9/82 (Inst. Plasma Physics, Garching, Germany, 1993)
A new swithc is introduced that allows to use the KrC based equation in the calculation.$$s_n^{KrC}(\epsilon)=\frac{0.5ln(1+1.2288\epsilon)}{\epsilon+0.1728\sqrt{\epsilon}+0.008\epsilon^{0.1504}}$$
Can you write Python code for it?

def reduced_nuc_stopping_x_section(Projectile,Target,Energy,sputter_model,model):
    '''
    based on equ. A1
    calcultes reduced_energy(Projectile,Target,Energy)
    Depending on the last parameter 'model' we either use a Kr-C based stopping power (model=KrC) or in all other
    cases a Thomas-Fermi based approach as used in M84
    '''
    # lets first calculate the reduced energy
    eps=reduced_energy(Projectile,Target,Energy,sputter_model)
    # we have two different models. If model is KrC we use the one introduced by Eckstein and mentioned in Y96
    if model=="KrC":
        return 0.5*ln(1+1.2288*eps)/(eps+0.1728*np.sqrt(eps)+0.0088*eps**0.1504)
    # in all other cases we use the M84 Thomas-Fermi model
    else:
        # This is the Thomas Fermi as given in Y96 and M84 we also use this for Sigmund
        return 3.441*np.sqrt(eps)*ln(eps+2.718)/(1+6.355*np.sqrt(eps)+eps*(-1.708+6.882*np.sqrt(eps)))


I am working on the file "Sputter yield functions.ipynb".
The first task is:
Sputteryield
The sputter yield can now be calculated. Depending on model we use different equations.
SRIM
SRIM based sputter yields have been calculated for 30keV only but will be geiven as reference below.
Sigmund
For Sigmund we copy from L. Bischoff $$Y(E)=0.42\frac{\alpha{}S_n}{U_s}$$
Matsunami
Eq. 1 from M84 $$Y(E)=0.42\frac{\alpha^*QKs_n(\epsilon)}{U_s\left[1+0.35U_ss_e(\epsilon)\right]}\left[1-(E_{th}/E)^{1/2}\right]^{2.8}$$ $Q$ can be assumed to be one of no other value is listed. The values in the ATOMDATA file have been set to one. We need to make sure that $E>E_{th}$ otherwise the calculation fails
Yamamura
In Y96 a different equation (15) is used. Please be aware that also some of the other equations have changed and correct parameters have to be used to. $$Y(E)=0.042\frac{Q(Z_2)\alpha^*(M2/M1)}{U_s}\frac{S_n(E)}{1+\Gamma k_e\epsilon^{0.3}}\left[1-\sqrt\frac{E_{th}}{E}\right]^s$$
The last parameter $s$ is empirical and is either 2.5 or 2.8 for a small set of materials. To be able to provide an estimate we set $s=2.65$ for the remainig materials which have now value assigned in Y96.
The equation from Y96 uses different units therefore the prefactor is 0.042 and not 0.42 as in M84. this corresponds to a change in the way $S_n$ is calculated. for the computation according to Y96 the factor 10 has been transfered from $S_n$ to $Y(E)$. As a result the used equations idffer by a factor 10 but give consistent results. Like above $E$ needs to be larger than $E_{th}$ otherwise the calculation fails for obvious reasons.
$s$ is tabulated only for a few values. Interpreting Y96 I set it to 2.65 for all other cases.
Can you write Python code for it?

def yE(Projectile,Target,Energy,sputter,model):
    '''
    Equ. 1
    the first three parameters are straight forward. th elast one switches between different models for the Sputteryield
    calculation. If model is M84 the calculation is based on that paper. Y96 uses the newer version.
    the same holds for the xsection_model. See reduced_nuc_stopping_x_section() for details.
    '''
    if User_SBE==-1:
        Us=get_Atom_prop(Target,'SBE')#Atoms[3][Atoms[0].index(Target)]
    else:
        Us=User_SBE
    Q84=get_Atom_prop(Target,'Q84')
    Q96=get_Atom_prop(Target,'Q96')
    s=get_Atom_prop(Target,'s')#Atoms[7][Atoms[0].index(Target)]
    if s==0:
        s=2.65
    if sputter=="M84":
        if Energy>eth(Projectile,Target,sputter): # Otherwise we try to get the sqrt of a negative number
            return (0.42*(alpha_stern(Projectile,Target,sputter)*Q84*Sn(Projectile,Target,Energy,sputter,model))/(Us*(1+0.35*Us*reduced_elec_stopping_x_section(Projectile,Target,Energy,sputter)))*(1-(eth(Projectile,Target,sputter)/Energy)**(0.5))**(2.8))
        else:
            return 0
    elif sputter=="Y96":
        if Energy>eth(Projectile,Target,sputter): # Otherwise we try to get the sqrt of a negative number
            return ((0.42*Q96*alpha_stern(Projectile,Target,sputter)*Sn(Projectile,Target,Energy,sputter,model))/(Us*(1.0+(Gamma(Projectile,Target)*k(Projectile,Target)*reduced_energy(Projectile,Target,Energy,sputter)**0.3)))*((1-np.sqrt(eth(Projectile,Target,sputter)/Energy))**s))
        else:
            return 0
    elif sputter=="Sigmund":
        if Energy>Us: # Otherwise we try to get the sqrt of a negative number
            return 0.42*alpha_stern(Projectile,Target,sputter)*Sn(Projectile,Target,Energy,sputter,model)/Us
        else:
            return 0
    else:
        print("No or invalid model selected. Can only be M84 or Y96.")
        return 0


I am working on the file "Sputter yield.ipynb".
The first task is:
All the results
Can you write Python code for it?

print ('for {:s} into {:s} using an energy of {:d} eV.'.format(Projectile, Target, Energy))
print ('Y(Sigmund)={:2g}'.format(yE(Projectile,Target,Energy,"Sigmund",model)))
print ('Y(Matsunami)={:2g}'.format(yE(Projectile,Target,Energy,"M84",model)))
print ('Y(Yamamura)={:2g}'.format(yE(Projectile,Target,Energy,"Y96",model)))
print ('For reference we quote the result of the SRIM simulation done at 30 keV')
print ('Y(He,30keV)={:2g}'.format(get_Atom_prop(Target,'y30_He_srim')))
print ('Y(Ne,30keV)={:2g}'.format(get_Atom_prop(Target,'y30_Ne_srim')))


I am working on the file "Sputter yield.ipynb".
The first task is:
Energy
Can you write Python code for it?


I am working on the file "Sputter yield.ipynb".
The first task is:
First we create a plot that shows the sputter yeild for the selected ion (proj) for all possible targets.
Create the xaxis i.e. fill it with the atoms where all data ia available
Can you write Python code for it?

'''
Lets calculate the sputter yields for all elements
'''

for sputter in sputter_models:
    Atom_props["yE_"+str(sputter)]=None
    for i in Atom_props.index:
        if (sputter=="Y96")&(Atom_props.ix[i,'SBE']!=0)&(Atom_props.ix[i,'Q96']!=0):
            # If we use M84 we have more elements available
            # we only calculate for the ones where we do have SBE
            Atom_props.ix[i, "yE_"+str(sputter)] =yE(str(Projectile),Atom_props.Symbol.iloc[i],Energy,sputter,model)
        elif Atom_props.ix[i,'SBE']!=0:
            Atom_props.ix[i, "yE_"+str(sputter)] =yE(str(Projectile),Atom_props.Symbol.iloc[i],Energy,sputter,model)


I am working on the file "Sputter yield.ipynb".
The first task is:
Intermediate results leading to the above numbers:
Can you write Python code for it?

print ('eps={:3g}'.format(reduced_energy(Projectile,Target,Energy,sputter)))
print ('sn=%.3g'%reduced_nuc_stopping_x_section(Projectile,Target,Energy,sputter,model))
print ('se=%.3g'%(reduced_elec_stopping_x_section(Projectile,Target,Energy,sputter)))
print ('K=%.3g'%(Sn(Projectile,Target,Energy,sputter,model)/reduced_nuc_stopping_x_section(Projectile,Target,Energy,sputter,model)))
print ('Sn=%.3g'%(Sn(Projectile,Target,Energy,sputter,model)))
print ('a*=%.3g'%(alpha_stern(Projectile,Target,sputter)))
if User_SBE==-1:
    print ('Us=%.3g'%(get_Atom_prop(Target,'SBE')))
else:
    print ('Us=%.3g'%(User_SBE))
print ('Eth=%.3g'%(eth(Projectile,Target,sputter)))


I am working on the file "Sputter yield.ipynb".
The first task is:
Lets define what we want to calculate
Projectile
Can you write Python code for it?


I am working on the file "Sputter yield.ipynb".
The first task is:
Lets first import some stuff
Can you write Python code for it?

# These are imported by Sputter funcs already but it doesn't harm to import tham again
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from math import log as ln
from itertools import cycle # used to create a loopable colormap


I am working on the file "Sputter yield.ipynb".
The first task is:
Lets read in the data
Can you write Python code for it?

'''
Try to read in the datafile as pandas frame
'''
Atom_props=pd.read_table(SRIM_ATOM_DATA_FILE,delim_whitespace=True)
#Atom_props.get_value('He','Natural Mass')


I am working on the file "Sputter yield.ipynb".
The first task is:
Surface binding energy
Use this to fix the surface displacment energy to a fixed value, which is not in the database. If this is set to -1 the tabulated value will be used in all other cases User_SBW will be used instead of the tabulated value.
Can you write Python code for it?


I am working on the file "Sputter yield.ipynb".
The first task is:
The following variable holds the ions we use for the energy dependent plot of the target material (ziel).
Can you write Python code for it?


I am working on the file "Sputter yield.ipynb".
The first task is:
This defines the location of a file that holds all the atomic data we need. the files holds values fro the calculation of the sputter yield according to Sigmund as weel as Matsunami1984 and Yamamura1996. The latter two modify the calculation in a way that makes it more suitable for litgh ions aka He and Ne.
Can you write Python code for it?


I am working on the file "Sputter yield.ipynb".
The first task is:
Which Sputter model should we use
can be either Sigmund, M84 or Y96
Can you write Python code for it?


I am working on the file "Sputter yield.ipynb".
The first task is:
Y_He_srim contains the results of a SRIM simulation of the sputter yield for 30 keV He into the elements. Y_Ne_srim the same data for Ne.
Can you write Python code for it?

Y_Ne_srim=pd.read_csv(SRIM_Ne_FILE,header=None)
Y_Ne_srim['y30_Ne_srim']=Y_Ne_srim[1]/Y_Ne_srim[2]

# Lets merge the Ne data from SRIM with the ATOMDATA
Atom_props=pd.merge(Atom_props,Y_Ne_srim.drop([1,2],axis=1),left_on='Z',right_on=0)
# Next we merge the He data from SRIM and drop the additional column "0" thet is left from merging
Atom_props=pd.merge(Atom_props,Y_He_srim.drop([' Anzahl Gesputterte',' Anzahl Simulierte'],axis=1),left_on='Z',right_index=True).drop(0,axis=1)


I am working on the file "Sql Practice.ipynb".
The first task is:
It returned empty because there is no zoidberg in our list.
Add it below.
Name: Zoidberg
Legal name: Planet Express
City: New New York
State: New New York
Can you write Python code for it?

# Add the zoidberg data to the database below. remeber to commit()

# Search for zoidberg again. This time, you should get the results below:


I am working on the file "Sql Practice.ipynb".
The first task is:
Next: Compare the number of practices in New york (NY) vs Texas (Tx)
Can you write Python code for it?

# Count number of practices in New York vs Texas

# 1st, get number in New York. You should get the values below

print("Number in NY: ", len(result))

# Now get Texas:

print("Number in TX: ", len(result))


I am working on the file "Sql Practice.ipynb".
The first task is:
There is a problem with the above: It will include names like Johnathan.
What if we only want people with the name John?
Hint: In the search query, use 'john %'. Notice the space before %
Try that below:
Can you write Python code for it?

print(len(result))

#This time, printing the 1st 6 results as well, to check.
print(result[:6])

# Now find all Johns in the state 'AL'

print(len(result))
print(result[:6])

# Finally, Johns in AL and city of Mobile.

print(len(result))
print(result[:6])

#Always close the database!

conn.close()


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Backtest SquareMathLevels
Cíl
Ověření hypotézy, že SquareMath Levels fungují jako S/R úrovně, tzn. trh má tendenci se od nich odrážet.
Ověření na statistice ZN 1min, SML - 30min SQUARE 16
Příprava dat
Nastavení pro kalkulaci SquareMath
Can you write Python code for it?

SQUARE = 128
SQUARE_MULTIPLIER = 1.5
# how many
BARS_BACK_TO_REFERENCE = np.int(np.ceil(SQUARE * SQUARE_MULTIPLIER))
# set higher timeframe for getting SquareMathLevels
MINUTES = 30 # range 0-59

PD_RESAMPLE_RULE = f'{MINUTES}Min'
# set the period of PD_RESAMPLE_RULE will be started. E.g. PD_RESAMPLE_RULE == '30min':
# PD_GROUPER_BASE = 5, periods will be: 8:05:00, 8:35:00, 9:05:00, etc...
# PD_GROUPER_BASE = 0, means 8:00:00, 8:30:00, 9:00:00, etc...
PD_GROUPER_BASE = 0


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Data, která se budou analyzovat
Can you write Python code for it?

TICK_SIZE_STR = f'{1/32*0.5}'
TICK_SIZE = float(TICK_SIZE_STR)
#SYMBOL = 'ZN'
TICK_SIZE_STR

DATA_FILE = '../../Data/ZN-1s.csv'

read_cols = ['Date', 'Time', 'Open', 'High', 'Low', 'Last']
data = pd.read_csv(DATA_FILE, index_col=0, skipinitialspace=True, usecols=read_cols, parse_dates={'Datetime': [0, 1]})
data.rename(columns={"Last": "Close"}, inplace=True)
data.index.name = 'Datetime'
data['Idx'] = np.arange(data.shape[0])
df = data
df


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Dál nebudu potřebovat unrecognized trades
Can you write Python code for it?

stats.drop(stats[stats.unrecognizableTrade].index, inplace=True)

shorts_mask = stats.lots<0
longs_mask = stats.lots>0

stats.loc[shorts_mask, 'PnL'] = ((stats[shorts_mask].entryPrice - stats[shorts_mask].exitPrice) / TICK_SIZE).round()
stats.loc[longs_mask, 'PnL'] = ((stats[longs_mask].exitPrice - stats[longs_mask].entryPrice) / TICK_SIZE).round()
stats.PnL = stats.PnL.astype(int)

stats['runPTicks'] = ((stats.entryPrice - stats.runningProfit).abs() / TICK_SIZE).round().astype(int)
stats['runLTicks'] = ((stats.entryPrice - stats.runningRisk).abs() * -1 / TICK_SIZE).round().astype(int)

stats['ptTicks'] = ((stats.entryPrice - stats.pt).abs() / TICK_SIZE).round().astype(int)
stats['slTicks'] = ((stats.entryPrice - stats.sl).abs() * -1 / TICK_SIZE).round().astype(int)

stats['tradeTime'] = stats.exitIdx - stats.entryIdx

stats


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Jen pro kontrolu. Win == True, Loss == False
Can you write Python code for it?

# stats['Win'] = profit_mask
# smlvl_stats_buy_sell2 = stats[['entrySmLvl', 'PnL', 'lots', 'Win']].groupby(['entrySmLvl', 'lots', 'Win']).sum()
# smlvl_stats_buy_sell2.sort_index(ascending=False, inplace=True)
# smlvl_stats_buy_sell2.rename(columns={'PnL':'WinLossCount'}, inplace=True)
# smlvl_stats_buy_sell2


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Low
Can you write Python code for it?

# calculate min low for actual record from higher tiframe his period
df_helper_gr = df[['Low']].groupby(pd.Grouper(freq=PD_RESAMPLE_RULE, base=PD_GROUPER_BASE))
df_helper = df_helper_gr.rolling(PD_RESAMPLE_RULE, min_periods=1).min().dropna() # cummin() with new index
df_helper['bigCumMinLow'] = df_helper.assign(l=df_helper_gr.min().dropna().rolling(BARS_BACK_TO_REFERENCE-1).min().shift().loc[df_helper.index.get_level_values(0)].to_numpy()).min(axis=1, skipna=False)

df_helper.set_index(df_helper.index.get_level_values(1), inplace=True) # drop multiindex
df['SMLLowLimit'] = df_helper.bigCumMinLow
df


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Max pohyb v zisku ve ztrátových obchodech
Can you write Python code for it?


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Max pohyb ve ztrátě ve ztrátových obchodech
Can you write Python code for it?

sns.distplot(selected_stats.runLTicks, color="r");

sns.distplot(selected_stats.runLTicks/selected_stats.slTicks, color="r");


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Maximální high a low za posledních BARS_BACK_TO_REFERENCE svíček z vyššího timeframu.
High
Can you write Python code for it?

# calculate max high for actual record from higher tiframe his period
df_helper_gr = df[['High']].groupby(pd.Grouper(freq=PD_RESAMPLE_RULE, base=PD_GROUPER_BASE))
df_helper = df_helper_gr.rolling(PD_RESAMPLE_RULE, min_periods=1).max().dropna() # cummax() with new index
df_helper['bigCumMaxHigh'] = df_helper.assign(l=df_helper_gr.max().dropna().rolling(BARS_BACK_TO_REFERENCE-1).max().shift().loc[df_helper.index.get_level_values(0)].to_numpy()).max(axis=1, skipna=False)

df_helper.set_index(df_helper.index.get_level_values(1), inplace=True) # drop multiindex
df['SMLHighLimit'] = df_helper.bigCumMaxHigh
df


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
PT adjustment ve ziskových obchodech - Max pohyb v zisku
Can you write Python code for it?


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
PT adjustment ve ztrátových long obchodech - Max pohyb v zisku
Can you write Python code for it?


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Poměrově pohyb v zisku k PT u ziskových obchodů.
Can you write Python code for it?


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Poměrově pohyb v zisku k nastavenému PT u ziskových obchodů.
Can you write Python code for it?


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Počet vstupů Buy nebo Sell na SML
Can you write Python code for it?

stats.lots.replace({1: 'Long', -1: 'Short'}, inplace=True)

smlvl_stats_buy_sell = stats[['entrySmLvl', 'PnL', 'lots']].groupby(['entrySmLvl', 'lots']).count()
smlvl_stats_buy_sell.sort_index(ascending=False, inplace=True)
smlvl_stats_buy_sell.rename(columns={'PnL':'LongShortCount'}, inplace=True)
smlvl_stats_buy_sell
smlvl_stats_buy_sell['LongShortTotal%'] = smlvl_stats_buy_sell.LongShortCount / smlvl_stats_buy_sell.LongShortCount.sum() *100
smlvl_stats_buy_sell['SMLlongOrShort%'] = smlvl_stats_buy_sell[['LongShortCount']].groupby(level=0).apply(lambda x: 100 * x / float(x.sum()))
smlvl_stats_buy_sell


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
SL djustment  ve ztrátových obchodech - max pohyb v zisku
Can you write Python code for it?

sns.distplot(selected_stats[selected_stats.PnL<0].runLTicks, color="r");

sns.distplot(selected_stats[selected_stats.PnL<0].runLTicks/selected_stats[selected_stats.PnL<0].slTicks, color="r"); # kontrola


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
SL djustment v ziskových obchodech - max pohyb ve ztrátě
Can you write Python code for it?

sns.distplot(selected_stats[selected_stats.PnL>0].runLTicks, color="r");

sns.distplot(selected_stats[selected_stats.PnL>0].runLTicks/selected_stats[selected_stats.PnL>0].slTicks, color="r"); # kontrola


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Seřazeny výsledky dle úspěsnosti:
Can you write Python code for it?


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Statistika výsledků
Backtest základní info
Can you write Python code for it?

print('Od:', df.iloc[0].name)
print('Do', df.iloc[-1].name)
print('Časové období:', df.iloc[-1].name - df.iloc[0].name)
print('Počet obchodních dnů:', df.Close.resample('1D').ohlc().shape[0])
print('Počet záznamů jemného tf:', df.shape[0])


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Validita nízkého timeframe pro backtest - možná zasenesená chyba
Zjištění, zda je zvolený SQUARE na vyšším timeframu dostatečný pro backtest na tomto nízkém timeframu. Tzn. pokud mám Square=32 z vyššího timeframe='30min', mohu zjistit jestli jsou záznamy timeframe='1min' vhodné pro backtest.
Pokud by byla vysoká chyba rozlišení nízkého timeframe (např. nad 5%), je třeba pro relevatní výsledky zvolit buď nižší rozlišení pro backtest např. '30s' příp. '1s', nebo zvýšit SQUARE=64 nebo zvýšit vysoký timeframe pro výpočet SML `1h, 2h, 4h, 8h, 1d, ...'.
Počet průrazů na jednu malou svíčku
Dává informaci o tom, zda je tento malý rámec dostatečný pro výpočet obchodů a může mít vypovídající informaci o chybovosti.
Can you write Python code for it?

touchCounts = df.SMLTouchCount.value_counts().to_frame(name='Occurences')
touchCounts['Occ%'] = touchCounts / df.shape[0]*100
print(f'Počet protnutích více něž jedné SML v jednom záznamu: v {(df.SMLTouchCount>1).sum()} případech ({(df.SMLTouchCount>1).sum()/df.shape[0]*100:.3f}%) z {df.shape[0]} celkem\n')
touchCounts


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Validita výsledků obchodů
Can you write Python code for it?

finishedCount = stats.shape[0]
print('Total finished trades:', finishedCount)
# pokud je opravdu hodně "unrecognizableTrade", mám moc nízké rozlišení SquareMath levels (malý square)
unrec_trades = stats.unrecognizableTrade.sum()
print('Unrecognizable trades:', unrec_trades, f'({unrec_trades/finishedCount *100:.3f}%)')
print('Opened trades:', stats_opened.shape[0])


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Velmi nízký SML spread
Can you write Python code for it?

spread_stats = df.spread.value_counts().to_frame(name='Occurences')
spread_stats['Occ%'] = spread_stats / df.shape[0]*100
spread_stats['Ticks'] = spread_stats.index / TICK_SIZE # index musím
print(f'Počet spredu SML menších než 2 ticky v jednom záznamu: v {(df.spread/TICK_SIZE<2).sum()} případech ({(df.spread/TICK_SIZE<2).sum()/df.shape[0]*100:.3f}%) z {df.shape[0]} celkem\n')
spread_stats


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Vstupy na jednotlivých levelech
Can you write Python code for it?


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Výpočet SMLevels pro každý záznam
Can you write Python code for it?

from vhat.squaremath.funcs import calculate_octave

SML_INDEXES = np.arange(-2, 10+1, dtype=np.int) # from -2/8 to +2/8

def round_to_tick_size(values, tick_size):
    return np.round(values / tick_size) * tick_size

def get_smlines(r):
    tick_size = TICK_SIZE
    lowLimit = r.SMLLowLimit
    highLimit = r.SMLHighLimit
    zeroLine, frameSize = calculate_octave(lowLimit, highLimit)
    spread = frameSize * 0.125
    sml = SML_INDEXES * spread + zeroLine
    sml = round_to_tick_size(sml, tick_size)
    return [sml, zeroLine, frameSize, spread]

temp = df.apply(get_smlines, axis=1, result_type='expand')
temp.columns = ['SML', 'zeroLine', 'framSize', 'spread']
df = df.join(temp)
del temp
df


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Výpočet dotyku SML
Musím vypočítat dotyk předchozího průrazu kvůli frame-shift.
Can you write Python code for it?

df['prevSML'] = df.SML.shift()
df.dropna(inplace=True)
df

df['SMLTouch'] = df.apply(lambda r: np.bitwise_and(r.Low<=r.prevSML, r.prevSML<=r.High), axis=1)
df['SMLTouchCount'] = df.SMLTouch.apply(lambda v: sum(v))
df

from dataclasses import dataclass
from typing import List

@dataclass
class Trade:
    tId: int
    # vstupní data, která znám dopředu
    entry_idx: int
    entry_sml_number: int
    entry_sml_spread: float
    entry_price: float
    entry_lots: int # -1 short, 1 long
    profit_target: float
    stop_loss: float

    # průběh a vývoj trhu v otevřeném obchodu
    max_running_profit_price: float
    max_running_loss_price: float

    # výstupní data, která se vyplní až na konci
    exit_idx: int = -1
    exit_price: float = 0.0
    exit_sml_number: int = 9999

    # pokud obchod skončí tak, že nebude možné zjistit výsledek, co bylo realizováno dříve, nastaví se tahle proměnná
    unrecognizable_trade: bool = False

@dataclass
class TradeList:
     trades: List[Trade]

def check_open_trades(v, finished_trades, r):
    # TODO: dodělat indexy aktuální svíce
    trades_to_close = []
    for tid, trade in opened_trades.items():

        # průběžné statistiky
        if trade.entry_lots == 0 : raise Exception('Něco jsem dojebal - open trades má entry lots == 0')
        long_trade = trade.entry_lots>0
        if long_trade:
            trade.max_running_profit_price = max(min(r.High, trade.profit_target), trade.max_running_profit_price)
            trade.max_running_loss_price = min(max(r.Low, trade.stop_loss), trade.max_running_loss_price)
        else: # short trade
            trade.max_running_profit_price = min(max(r.Low, trade.profit_target), trade.max_running_profit_price)
            trade.max_running_loss_price = max(min(r.High, trade.stop_loss), trade.max_running_loss_price)

        # zasažení PT nebo SL
        hit_pt = True if r.Low<=trade.profit_target<=r.High else False
        hit_sl = True if r.Low<=trade.stop_loss<=r.High else False
       ...


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Zahození nepotřebných prostředků a záznamů NaN, které nemůžu analyzovat
Can you write Python code for it?

del df_helper
del df_helper_gr
df.dropna(inplace=True)
df


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Ziskové obchody
Can you write Python code for it?

selected_stats = stats[profit_mask]
selected_pnl_stats = selected_stats.PnL.value_counts().to_frame(name='PnLOccurences')
selected_pnl_stats['Occ%'] = selected_pnl_stats / selected_stats.shape[0]*100
selected_pnl_stats['Ticks'] = selected_pnl_stats.index / TICK_SIZE
selected_pnl_stats


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
Ztrátové obchody
Can you write Python code for it?

selected_stats = stats[loss_mask]
selected_pnl_stats = selected_stats.PnL.value_counts().to_frame(name='PnLOccurences')
selected_pnl_stats['Occ%'] = selected_pnl_stats / selected_stats.shape[0]*100
selected_pnl_stats['Ticks'] = selected_pnl_stats.index / TICK_SIZE
selected_pnl_stats


I am working on the file "SquareMath/2020-04-10-SquareMathLevels-Backtest-example-ZN-1min-30M-128.ipynb".
The first task is:
poměr vývoje ztráty k zadanému SL v ziskových obchodech
Can you write Python code for it?


I am working on the file "SquaresAndFibonacci.ipynb".
The first task is:
Fibonacci Recursion
Can you write Python code for it?

calls = 0
def fib(x, i):
    '''
    Recursively determine the xth fibonacci number.
    i is used only for the indentation which represents the recursive
    depth.
    '''
    global calls
    calls += 1
    i += 1
    if x in [0,1]:
        print "."*4*i, '%d --> %d' % (x, x)
        return x
    f1 = fib(x-1, i)
    f2 = fib(x-2, i)
    print "."*4*i, '%d --> %d' % (x, f1+f2)
    return f1 + f2

answer = fib(8,0)
print 'Answer:', answer
print 'Calls :', calls


I am working on the file "Stack.ipynb".
The first task is:
iii. Explain what private and public do
The private and public, also protected restrict the access to the class members.
A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.
A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member function.
A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes.
//From: https://www.tutorialspoint.com/cplusplus/cpp_class_access_modifiers.htm
Can you write Python code for it?

//*Quote from comments:*
    // This structure type is private to the class, and used as a form of
    // linked list in order to contain the actual (static) data stored by the Stack class


I am working on the file "Stack.ipynb".
The first task is:
ix. Explain what a list initializer does
Constructor is a special non-static member function of a class that is used to initialize objects of its class type.
In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual base subobjects and non-static data members.
The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:
1) If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists).

2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list.

3) Then, non-static data members are initialized in order of declaration in the class definition.

4) Finally, the body of the constructor is executed.
//From:http://en.cppreference.com/w/cpp/language/initializer_list
Can you write Python code for it?

//*Quote from comments*

// Implementation of default constructor
Stack::Stack()
    : depth(0)       // internal depth is 0
    , head(nullptr)  // internal linked list is null to start
{};
// The construction ": var1(val1), var2(val2) {}" is called a
// "list initializer" for a constructor, and is the preferred
// way of setting default field values for a class instance
// Here 0 is the default value for Stack::depth
// and nullptr is the default value for Stack::head


I am working on the file "Stack.ipynb".
The first task is:
v. Explain why this code avoids the use of C pointers
First, raw pointers must under no circumstances own memory. That means you must delete after use it.
Second, most uses of pointers in C++ are unnecessary. C++ has very strong support for value semantics, you can use smart pointer, container classes, design patterns like RAII, ect, instead of pointer.
In computer science, a smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking. These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency. Smart pointers typically keep track of the objects they point to for the purpose of memory management.
The misuse of pointers is a major source of bugs: the constant allocation, deallocation and referencing that must be performed by a program written using pointers introduces the risk that memory leaks will occur. Smart pointers try to prevent memory leaks by making the resource deallocation automatic: when the pointer (or the last in a series of pointers) to an object is destroyed, for example because it goes out of scope, the pointed object is destroyed too.
//From: http://softwareengineering.stackexchange.com/questions/56935/why-are-pointers-not-recommended-when-coding-with-c
vi. Explain what new and delete do in C++, and how they relate to what you have done in C
"New" creates a pointer to an allocated memory block.  "Delete" deallocates the memory that is allocated by "new".
It works differently from the way in C:
Allocate memory:

C++: Node *n = new Node();

C  : Node *n = (Node *)calloc(1, sizeof(Node));
Deallocate memory:

C++: delete n;

C  : free(n);
vii. Explain what a memory leak is, and what you should do to avoid it
Memory leak means running out of system memory. When a program needs to store some temporary information during execution, it can dynamically request a chunk of memory from the system. However, the system has a fixed amount of...
Can you write Python code for it?

//*Quote from comments:*
    // However, by using the "unique_ptr" type above, we carefully avoid any
    // explicit memory allocation by using the allocation pre-defined inside the
    // unique_ptr itself. By using memory-safe structures in this way, we are using
    // the "Rule of Zero" and simplifying our life by defining ZERO of them:
    //   https://rmf.io/cxx11/rule-of-zero/
    //   http://www.cplusplus.com/reference/memory/unique_ptr/


I am working on the file "Stack.ipynb".
The first task is:
x. Explain what the "Rule of Zero" is, and how it relates to the "Rule of Three"
Rule of Zero: Classes that have custom destructors, copy/move constructors or copy/move assignment operators should deal exclusively with ownership (which follows from the Single Responsibility Principle). Other classes should not have custom destructors, copy/move constructors or copy/move assignment operators.
Rule of Three: a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator.  It almost certainly requires all three.
Rule of Zero does not need those three functions, but Rule of Three requires them.
//From: http://en.cppreference.com/w/cpp/language/rule_of_three
Can you write Python code for it?

//*Quote from comments:*
    // Normally we would have to implement the following things in C++ here:
    //    1) Class Destructor : to deallocate memory when a Stack is deleted
    //       ~Stack();
    //
    //    2) Copy Constructor : to define what Stack b(a) does when a is a Stack
    //                          This should create a copy b of the Stack a, but
    //                          should be defined appropriately to do that
    //       Stack(const Stack&);
    //
    //    3) Copy Assignment  : to define what b = a does when a is a Stack
    //                          This should create a shallow copy of the outer
    //                          structure of a, but leave the inner structure as
    //                          pointers to the memory contained in a, and should
    //                          be defined appropriately to do that
    //       Stack& operator=(const Stack&);
    //
    // The need for defining ALL THREE of these things when managing memory for a
    // class explicitly is known as the "Rule of Three", and is standard
    //   http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three
    //
    // However, by using the "unique_ptr" type above, we carefully avoid any
    // explicit memory allocation by using the allocation pre-defined inside the
    // unique_ptr itself. By using memory-safe structures in this way, we are using
    // the "Rule of Zero" and simplifying our life by defining ZERO of them:
    //   https://rmf.io/cxx11/rule-of-zero/
    //   http://www.cplusplus.com/reference/memory/unique_ptr/


I am working on the file "Standard Regression (BQML).ipynb".
The first task is:
0) Dependencies
Can you write Python code for it?

################################################################################
######################### CHANGE BQ PROJECT NAME BELOW #########################
################################################################################

project_name = '' #add proj name and dataset

# Google credentials authentication libraries
from google.colab import auth
auth.authenticate_user()

# BigQuery Magics
'''
BigQuery magics are used to run BigQuery SQL queries in a python environment.
These queries can also be run in the BigQuery UI
'''

from google.cloud import bigquery
from google.cloud.bigquery import magics
magics.context.project = project_name #update project name
client = bigquery.Client(project=magics.context.project)
%load_ext google.cloud.bigquery
bigquery.USE_LEGACY_SQL = False

# data processing libraries
import numpy as np
import pandas as pd

# modeling and metrics
from statsmodels.stats.stattools import durbin_watson
import statsmodels.api as sm

!pip install relativeImp
from relativeImp import relativeImp

# visutalization
import matplotlib.pyplot as plt
import seaborn as sns


I am working on the file "Standard Regression (BQML).ipynb".
The first task is:
1) Import dataset
Import the data using the bigquery magics (%% command).
Pulls all of the data from the cleaned data table and stores into a dataframe "df"
Can you write Python code for it?


I am working on the file "Standard Regression (BQML).ipynb".
The first task is:
2.1) Print the model coefficient results
Call the model coefficient weights from the model and save to a dataframe "model_coefficients_results".
The standardize parameter is an optional parameter that determines whether the model  weights should be standardized to assume that all features have a mean of zero and a  standard deviation of one. Standardizing the weights allows the absolute magnitude of the weights to be compared to each other.
Can you write Python code for it?

%%bigquery model_coefficients_results
SELECT
  *
FROM
  ML.WEIGHTS(MODEL `.RBA_demo.RBA_model`,
    STRUCT(true AS standardize)) #update project name

model_coefficients_results


I am working on the file "Standard Regression (BQML).ipynb".
The first task is:
2.2) Print the model evaluation metrics
Can you write Python code for it?


I am working on the file "Standard Regression (BQML).ipynb".
The first task is:
3) Calculate contribution of each digital media tactic on conversions
Use the relativeImp package
to conduct key driver analysis and generate relative importance values by feature in the model.
The relativeImp function produces a raw relative importance and a normalized relative importance value.
- Raw relative importance sums to the r-squared of the linear model.
- Normalized relative importance is scaled to sum to 1
Can you write Python code for it?

conversions = 'y1'
tactics = df[df.columns[df.columns != conversions]].columns.to_list()
relative_importance_results = relativeImp(df,
                                          outcomeName = conversions,
                                          driverNames = tactics)

relative_importance_results


I am working on the file "Standard Regression (BQML).ipynb".
The first task is:
4) Validate Linear Regression Model Assumptions
For any statistical model it is important to validate model assumptions.
With RBA, we validate the standard linear model assumptions of:

Linearity
Normality of errors
Absence of multicollinearity
Homoscedasticity
Absence of autocorrelation of residuals

If any of the model assumptions fail, a different model specification, as well as re-examination of the data should be considered
Incorrect model use can lead to unreliable results
4.1) Generate model predictions and residuals
Can you write Python code for it?


I am working on the file "Standard Regression (BQML).ipynb".
The first task is:
4.3) Normality of Errors
Visually inspect the residuals to confirm normality
Can you write Python code for it?

fig = sm.qqplot(model_predictions.residuals)
plt.xlabel('Model Residuals'); plt.ylabel('Density'); plt.title('Distribution of Residuals');


I am working on the file "Standard Regression (BQML).ipynb".
The first task is:
4.4) Absence of Multicollinearity
Multicollinearity was checked and handled during data pre-processing stage.
4.5) Homoscedasticity
Visually inspect residuals to confirm constant variance
Can you write Python code for it?


I am working on the file "Standard Regression (BQML).ipynb".
The first task is:
4.6) Absence of Autocorrelation of the residuals
The Durbin Watson test is a statistical test for detecting autocorrelation of the model residuals
Can you write Python code for it?

dw = durbin_watson(model_predictions.residuals)
print('Durbin-Watson',dw)

if dw < 1.5:
        print('Positive autocorrelation', '\n')
elif dw > 2.5:
        print('Negative autocorrelation', '\n')
else:
        print('Little to no autocorrelation', '\n')


I am working on the file "Standard Regression (BQML).ipynb".
The first task is:
Select the predicted conversions (y1) of the model and actual conversions from the data (y1) using the ML.PREDICT function
Can you write Python code for it?

%%bigquery model_predictions
SELECT
  *
FROM
  ML.PREDICT(MODEL `.RBA_demo.RBA_model`, #update project name
    (
    SELECT
        *
    FROM
      `.RBA_demo.cleaned_data`)); #update project name


I am working on the file "Standard_Primal_v_Dual_GUROBI.ipynb".
The first task is:
2. Dual
Can you write Python code for it?

# Instantiate Model
mDual_Standard_GUROBI = gbp.Model(' -- Standard Dual Linear Programming Problem -- ')

# Set Focus to Optimality
gbp.setParam('MIPFocus', 2)

# Decision Variables
desc_var = []
for orig in rows:
    desc_var.append([])
    desc_var[orig].append(mDual_Standard_GUROBI.addVar(vtype=gbp.GRB.CONTINUOUS,
                                    name='u'+str(orig+1)))
# Slack Variables
slack_var = []
for dest in cols:
    slack_var.append([])
    slack_var[dest].append(mDual_Standard_GUROBI.addVar(vtype=gbp.GRB.CONTINUOUS,
                                   name='t'+str(dest+1)))
# Update Model
mDual_Standard_GUROBI.update()

#Objective Function
mDual_Standard_GUROBI.setObjective(gbp.quicksum(Bi[orig]*desc_var[orig][0]
                        for orig in rows),
                        gbp.GRB.MAXIMIZE)
# Constraints
for dest in cols:
    mDual_Standard_GUROBI.addConstr(gbp.quicksum(Aij[orig][dest]*desc_var[orig][0]
                        for orig in rows) +
                        slack_var[dest][0] -
                        Cj[dest] == 0)

# Optimize
mDual_Standard_GUROBI.optimize()
# Write LP file
mDual_Standard_GUROBI.write('LP.lp')
print '\n*************************************************************************'
print '    |   Decision Variables'
for v in mDual_Standard_GUROBI.getVars():
    print '    |  ', v.VarName, '=', v.x
print '*************************************************************************'
val = mDual_Standard_GUROBI.objVal
print '    |   Objective Value ------------------ ', val
print '    |   Aij Sum -------------------------- ', AijSum
print '    |   Cj Sum --------------------------- ', CjSum
print '    |   Bi Sum --------------------------- ', BiSum
print '    |   Matrix Dimensions ---------------- ', Aij.shape
print '    |   Date/Time ------------------------ ', dt.datetime.now()
print '*************************************************************************'
print '-- Gurobi Standard Dual Linear Programming Problem --'
print '\nJames Gaboardi, 2015'


I am working on the file "Standard_Processing_ROI_Stats/PhenoCam_ROI_stats.ipynb".
The first task is:
Basically, all I've done so far is split the image into R,G and B components and created a numpy "masked array".  For simple stats, like mean, used in the previous calculations we could just use masked array functions.  Here I'm going to grab the un-masked values and put them in 1-d arrays.  This also makes it easier to do the plotting.
Can you write Python code for it?

# first let's get percentiles for R, G and B
nvalues = g_ma.size
r_values = r_ma.compressed()
g_values = g_ma.compressed()
b_values = b_ma.compressed()

print "Number of pixels in image: {0}".format(nvalues)
print "Number of masked pixels: {0}".format(len(g_values))

# calculate mean, median and std-dev for R, G, B
r_mean = np.mean(r_values)
r_median = np.median(r_values)
r_var = np.var(r_values)
r_std = np.std(r_values)
g_mean = np.mean(g_values)
g_median = np.median(g_values)
g_var = np.var(g_values)
g_std = np.std(g_values)
b_mean = np.mean(b_values)
b_median = np.median(b_values)
b_var = np.var(b_values)
b_std = np.std(b_values)

# calculate percentiles for each array
r_percentiles = np.percentile(r_values, (5., 10., 25., 50., 75., 90., 95.))
g_percentiles = np.percentile(g_values, (5., 10., 25., 50., 75., 90., 95.))
b_percentiles = np.percentile(b_values, (5., 10., 25., 50., 75., 90., 95.))

# histogram the value for R, G, B
fig = plt.figure(figsize=[20,6])

r_95 = r_percentiles[-1]
r_low = r_mean - r_std
r_high = r_mean + r_std
plt.subplot(1,3,1)
plt.hist(r_values,20,color='r')
plt.plot([r_mean, r_mean], [0,60000], 'k--', lw=2)
plt.plot([r_low, r_low], [0,60000], 'k:', lw=2)
plt.plot([r_high, r_high], [0,60000], 'k:', lw=2 )
plt.text(150,50000,'mean:      {0:.2f}'.format(r_mean), size=14)
plt.text(150,47000,'std. dev.: {0:.2f}'.format(r_std), size=14)
plt.xlim([0,255])

g_95 = g_percentiles[-1]
g_low = g_mean - g_std
g_high = g_mean + g_std
plt.subplot(1,3,2)
plt.hist(g_values,20,color='g')
plt.plot([g_mean, g_mean], [0,60000], 'k--', lw=2)
plt.plot([g_low, g_low], [0,60000], 'k:', lw=2)
plt.plot([g_high, g_high], [0,60000], 'k:', lw=2 )
plt.text(150,50000,'mean:       {0:.2f}'.format(g_mean), size=14)
plt.text(150,47000,'std. dev.:  {0:.2f}'.format(g_std), size=14)
plt.xlim([0,255])

b_95 = b_percentiles[-1]
b_low = b_mean - b_std
b_high = b_mean + b_std
plt.subplot(1,3,3)
plt.hist(b_values,20,color='b')
plt.plot([b_mean, b_mean], [0,70000], 'k--', lw=2)
plt.plot([b_low, b_low], [0,70000], 'k:',...


I am working on the file "Standard_Processing_ROI_Stats/PhenoCam_ROI_stats.ipynb".
The first task is:
The quantity we use for phenological studies is the "green chromatic coordinate" or "gcc" value.  This is defined as:
$$ gcc = \frac{g_{mean}}{r_{mean} + g_{mean} + b_{mean}} $$
To further characterize the distribution of color over the ROi we also calculate the percentiles of the distributions of the digital number (DN) values for each color plane.  The correlations coefficients between the DN's of the different color planes are also calculated.  Here is the function used in standard processing routines.
Can you write Python code for it?

def get_roi_stats(im, roimask):
    """
    Function to return a collection of stats for DN values for an image / mask pair.
    """

    # split into bands
    (im_r, im_g, im_b) = im.split()

    # create numpy arrays with bands
    r_array = np.asarray(im_r, dtype=np.int16)
    g_array = np.asarray(im_g, dtype=np.int16)
    b_array = np.asarray(im_b, dtype=np.int16)

    # try applying mask to red image ... if mask and image don't
    # have same size this will raise an exception.
    try:
        r_ma = np.ma.array(r_array,mask=roimask)
    except:
        errstr = "Error applying mask to image file.\n"
        sys.stderr.write(errstr)
        return None

    # make masked arrays for G,B
    g_ma = np.ma.array(g_array,mask=roimask)
    b_ma = np.ma.array(b_array,mask=roimask)

    # find mean, std
    r_vals = r_ma.compressed()
    r_mean = r_vals.mean()
    r_diff = np.float64(r_vals) - r_mean
    r_std = np.sqrt(np.dot(r_diff, r_diff)/r_vals.size)

    g_vals = g_ma.compressed()
    g_mean = g_vals.mean()
    g_diff = np.float64(g_vals) - g_mean
    g_std = np.sqrt(np.dot(g_diff, g_diff)/g_vals.size)

    b_vals = b_ma.compressed()
    b_mean = b_vals.mean()
    b_diff = np.float64(b_vals) - b_mean
    b_std = np.sqrt(np.dot(b_diff, b_diff)/b_vals.size)

    # calculate percentiles for each array
    r_pcts = np.percentile(r_vals, (5., 10., 25., 50., 75., 90., 95.))
    g_pcts = np.percentile(g_vals, (5., 10., 25., 50., 75., 90., 95.))
    b_pcts = np.percentile(b_vals, (5., 10., 25., 50., 75., 90., 95.))

    # calculate covariance
    rg_cov = np.dot(r_diff, g_diff)/r_diff.size
    gb_cov = np.dot(g_diff, b_diff)/g_diff.size
    br_cov = np.dot(b_diff, r_diff)/b_diff.size

    # correlation coefficients
    RG_cor = rg_cov/(r_std * g_std)
    GB_cor = gb_cov/(g_std * b_std)
    BR_cor = br_cov/(b_std * r_std)

    # return list of values
    return [{'mean': r_mean,
             'stdev': r_std,
             'percentiles': r_pcts},
            {'mean': g_mean,
           ...


I am working on the file "Standard_Processing_ROI_Stats/PhenoCam_ROI_stats.ipynb".
The first task is:
To get a better idea of what these numbers mean let's repeat the above without using a function.  That way we can examine some of the intermediate steps.  In particular it would be nice to examine the distribution of DN values over the ROI for each of the color planes.
Can you write Python code for it?

# split into bands
(im_r, im_g, im_b) = img.split()

# create numpy arrays with bands
r_array = np.asarray(im_r, dtype=np.float64)
g_array = np.asarray(im_g, dtype=np.float64)
b_array = np.asarray(im_b, dtype=np.float64)
brt_array = r_array + g_array + b_array

# apply mask to brightness image
brt_ma = np.ma.array(brt_array,mask=roimask)

# make masked arrays for R,G,B
g_ma = np.ma.array(g_array,mask=roimask)
r_ma = np.ma.array(r_array,mask=roimask)
b_ma = np.ma.array(b_array,mask=roimask)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
A slice of an array is a view into the same data, so modifying it will modify the original array.
Can you write Python code for it?

print ("Original Matrix before modification:", a[0, 1])

b[0, 0] = 77    # b[0, 0] is the same piece of data as a[0, 1]
print ("Original Matrix after modification:", a[0, 1])


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Arrays
A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.

Why using Numpy Array over Python Lists ?
NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy.
Maybe you don't care that much for just a million cells, but you definitely would for a billion cells -- neither approach would fit in a 32-bit architecture, but with 64-bit builds NumPy would get away with 4 GB or so, Python alone would need at least about 12 GB (lots of pointers which double in size) -- a much costlier piece of hardware!
The difference is mostly due to "indirectness" -- a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value -- and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers takes 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists!
Author: Alex Martelli
Source: StackOverFlow

We can initialize numpy arrays from nested Python lists, and access elements using square brackets:
Can you write Python code for it?

a = np.array([1, 2, 3])  # Create a rank 1 array
print (type(a), a.shape, a[0], a[1], a[2])

a[0] = 5                 # Change an element of the array
print (a)

b = np.array([[1,2,3],[4,5,6]])   # Create a rank 2 array
print (b)

print (b.shape)
print (b[0, 0], b[0, 1], b[1, 0])


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Broadcasting
Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.
For example, suppose that we want to add a constant vector to each row of a matrix. We could do it like this:
Can you write Python code for it?

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x)   # Create an empty matrix with the same shape as x

# Add the vector v to each row of the matrix x with an explicit loop
for i in range(4):
    y[i, :] = x[i, :] + v

print (y)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Broadcasting typically makes your code more concise and faster, so you should strive to use it where possible.
This brief overview has touched on many of the important things that you need to know about numpy, but is far from complete. Check out the numpy reference to find out much more about numpy.
Matplotlib
Matplotlib is a plotting library. In this section give a brief introduction to the matplotlib.pyplot module, which provides a plotting system similar to that of MATLAB.
Can you write Python code for it?


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
By running this special iPython command, we will be displaying plots inline:
Can you write Python code for it?


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Dictionaries
A dictionary stores (key, value) pairs, similar to a Map in Java or an object in Javascript. You can use it like this:
Can you write Python code for it?

d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
print ("Value of the dictionary for the key 'cat':", d['cat'])       # Get an entry from a dictionary; prints "cute"
print ("Is 'cat' is the dictionary d:", 'cat' in d)     # Check if a dictionary has a given key; prints "True"

d['fish'] = 'wet'    # Set an entry in a dictionary
print ("Value of the dictionary for the key 'fish':", d['fish'])      # Prints "wet"

print (d['monkey'])  # KeyError: 'monkey' not a key of d

print ("Get 'monkey' value or default:", d.get('monkey', 'N/A'))  # Get an element with a default; prints "N/A"
print ("Get 'fish' value or default:", d.get('fish', 'N/A'))      # Get an element with a default; prints "wet"

del d['fish']        # Remove an element from a dictionary
print ("Get 'fish' value or default:", d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Functions
Python functions are defined using the def keyword. For example:
Can you write Python code for it?

def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'

for x in [-1, 0, 1]:
    print (sign(x))


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
If you want access to the index of each element within the body of a loop, use the built-in enumerate function:
Can you write Python code for it?

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
    print ('#%d: %s' % (idx + 1, animal))


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Integer array indexing: When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array.
Here is an example:
Can you write Python code for it?

a = np.array([[1,2], [3, 4], [5, 6]])

# An example of integer array indexing.
# The returned array will have shape (3,) and
print (a[[0, 1, 2], [0, 1, 0]])

# The above example of integer array indexing is equivalent to this:
print (np.array([a[0, 0], a[1, 1], a[2, 0]]))

# When using integer array indexing, you can reuse the same
# element from the source array:
print (a[[0, 0], [1, 1]])

# Equivalent to the previous integer array indexing example
print (np.array([a[0, 1], a[0, 1]]))

# Create a new array from which we will select elements
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print (a)

# Create an array of indices
b = np.array([0, 2, 0, 1])
b_range = np.arange(4)
print ("b_range:", b_range)

# Select one element from each row of a using the indices in b
print ("Selected Matrix Values:", a[b_range, b])  # Prints "[ 1  6  7 11]"

# Mutate one element from each row of a using the indices in b
a[b_range, b] += 10 # Only the selected values are modified in the "a" matrix.
print ("Modified 'a' Matrix:\n", a)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
List comprehensions can also contain conditions:
Can you write Python code for it?

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print (even_squares)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
List comprehensions:
When programming, frequently we want to transform one type of data into another. As a simple example, consider the following code that computes square numbers:
Can you write Python code for it?

nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
    squares.append(x ** 2)
print (squares)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Loops
You can loop over the elements of a list like this:
Can you write Python code for it?

animals = ['cat', 'dog', 'monkey']
for animal in animals:
    print (animal)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Loops: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:
Can you write Python code for it?

animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print ('#%d: %s' % (idx + 1, animal))


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Note that unlike MATLAB, * is elementwise multiplication, not matrix multiplication. We instead use the dot function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices. dot is available both as a function in the numpy module and as an instance method of array objects:
Can you write Python code for it?

x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])

v = np.array([9,10])
w = np.array([11, 12])

# Inner product of vectors; both produce 219
print ("v.w 'dot' product:", v.dot(w))
print ("numpy 'dot' product (v,w):", np.dot(v, w))

# Matrix / vector product; both produce the rank 1 array [29 67]
print ("x.v 'dot' product:", x.dot(v))
print ("numpy 'dot' product (x,v):", np.dot(x, v))

# Matrix / matrix product; both produce the rank 2 array
# [[19 22]
#  [43 50]]
print ("x.y 'dot' product:\n", x.dot(y))
print ("numpy 'dot' product (x,y):\n", np.dot(x, y))


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Numpy
Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. If you are already familiar with MATLAB, you might find this tutorial useful to get started with Numpy.
To use Numpy, we first need to import the numpy package:
Can you write Python code for it?

import numpy as np
import warnings
warnings.filterwarnings('ignore') # To remove warnings about "deprecated" or "future" features


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Numpy also provides many functions to create arrays:
Can you write Python code for it?

a = np.zeros((2,2))  # Create an array of all zeros
print (a)

b = np.ones((1,2))   # Create an array of all ones
print (b)

c = np.full((2,2), 7) # Create a constant array
print (c)

d = np.eye(2)        # Create a 2x2 identity matrix
print (d)

e = np.random.random((2,2)) # Create an array filled with random values
print (e)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Numpy provides many useful functions for performing computations on arrays; one of the most useful is sum:
Can you write Python code for it?

x = np.array([[1,2],[3,4]])

print ("Sum of all element:", np.sum(x))  # Compute sum of all elements; prints "10"
print ("Sum of each column:", np.sum(x, axis=0))  # Compute sum of each column; prints "[4 6]"
print ("Sum of each row:", np.sum(x, axis=1))  # Compute sum of each row; prints "[3 7]"


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Python versions
There are currently two different supported versions of Python, 2.7 and 3.4. Somewhat confusingly, Python 3.0 introduced many backwards-incompatible changes to the language, so code written for 2.7 may not work under 3.4 and vice versa. For this class all code will use Python 2.7.
You can check your Python version at the command line by running python --version.
Basic data types
Numbers
Integers and floats work as you would expect from other languages:
Can you write Python code for it?

x = 3
print (x, type(x))

print ("Addition:", x + 1)   # Addition;
print ("Subtraction:", x - 1)   # Subtraction;
print ("Multiplication:", x * 2)   # Multiplication;
print ("Exponentiation:", x ** 2)  # Exponentiation;

x += 1
print ("Incrementing:", x)  # Prints "4"
x *= 2
print ("Exponentiating:", x)  # Prints "8"

y = 2.5
print ("Type of y:", type(y)) # Prints "<type 'float'>"
print ("Many values:", y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Sets
A set is an unordered collection of distinct elements. As a simple example, consider the following:
Can you write Python code for it?

animals = {'cat', 'dog'}
print ("Is 'cat' in the set:", 'cat' in animals)   # Check if an element is in a set; prints "True"
print ("Is 'fish' in the set:", 'fish' in animals)  # prints "False"

animals.add('fish')        # Add an element to a set
print ("Is 'fish' in the set:", 'fish' in animals)
print ("What is the length of the set:", len(animals))       # Number of elements in a set;

animals.add('cat')       # Adding an element that is already in the set does nothing
print ("What is the length of the set:", len(animals))

animals.remove('cat')    # Remove an element from a set
print ("What is the length of the set:", len(animals))


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Subplots
You can plot different things in the same figure using the subplot function. Here is an example:
Can you write Python code for it?

# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# Set up a subplot grid that has height 2 and width 1,
# and set the first such subplot as active.
plt.subplot(2, 1, 1)

# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')

# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')

# Show the figure.
plt.show()


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
The line y = x + v works even though x has shape (4, 3) and v has shape (3,) due to broadcasting; this line works as if v actually had shape (4, 3), where each row was a copy of v, and the sum was performed elementwise.
Broadcasting two arrays together follows these rules:

If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.
The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.
The arrays can be broadcast together if they are compatible in all dimensions.
After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.
In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension

If this explanation does not make sense, try reading the explanation from the documentation or this explanation.
Functions that support broadcasting are known as universal functions. You can find the list of all universal functions in the documentation.
Here are some applications of broadcasting:
Can you write Python code for it?

# Compute outer product of vectors
v = np.array([1,2,3])  # v has shape (3,)
w = np.array([4,5])    # w has shape (2,)
# To compute an outer product, we first reshape v to be a column
# vector of shape (3, 1); we can then broadcast it against w to yield
# an output of shape (3, 2), which is the outer product of v and w:

print (np.reshape(v, (3, 1)) * w)

# Add a vector to each row of a matrix
x = np.array([[1,2,3], [4,5,6]])
# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),
# giving the following matrix:

print (x + v)

# Add a vector to each column of a matrix
# x has shape (2, 3) and w has shape (2,).
# If we transpose x then it has shape (3, 2) and can be broadcast
# against w to yield a result of shape (3, 2); transposing this result
# yields the final result of shape (2, 3) which is the matrix x with
# the vector w added to each column. Gives the following matrix:

print ((x.T + w).T)

# Another solution is to reshape w to be a row vector of shape (2, 1);
# we can then broadcast it directly against x to produce the same
# output.
print (x + np.reshape(w, (2, 1)))

# Multiply a matrix by a constant:
# x has shape (2, 3). Numpy treats scalars as arrays of shape ();
# these can be broadcast together to shape (2, 3), producing the
# following array:
print (x * 2)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
This works; however when the matrix x is very large, computing an explicit loop in Python could be slow. Note that adding the vector v to each row of the matrix x is equivalent to forming a matrix vv by stacking multiple copies of v vertically, then performing elementwise summation of x and vv. We could implement this approach like this:
Can you write Python code for it?

vv = np.tile(v, (4, 1))    # Stack 4 copies of v on top of each other
print (vv)                 # Prints "[[1 0 1]
                           #          [1 0 1]
                           #          [1 0 1]
                           #          [1 0 1]]"

y = x + vv  # Add x and vv elementwise
print (y)

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v  # Add v to each row of x using broadcasting
print (y)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Tuples
A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot. Here is a trivial example:
Can you write Python code for it?

d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
t = (5, 6)       # Create a tuple
print (type(t))
print (d[t])
print (d[(1, 2)])

print ("Access the 1st value of Tuple:", t[0])
print ("Access the 2nd value of Tuple:", t[1])

t[0] = 1 # This does NOT work !

t = (1, t[1]) # This DOES work !
print (t)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
Two ways of accessing the data in the middle row of the array. Mixing integer indexing with slices yields an array of lower rank, while using only slices yields an array of the same rank as the original array:
Can you write Python code for it?

row_r1 = a[1, :]    # Rank 1 view of the second row of a
row_r2 = a[1:2, :]  # Rank 2 view of the second row of a
row_r3 = a[[1], :]  # Rank 2 view of the second row of a
print ("Rank 1 access of the 2nd row:", row_r1, row_r1.shape)
print ("Rank 2 access of the 2nd row:", row_r2, row_r2.shape)
print ("Rank 2 access of the 2nd row:", row_r3, row_r3.shape)

# We can make the same distinction when accessing columns of an array:
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print ("Rank 1 access of the 2nd column:", col_r1, col_r1.shape)
print ()
print ("Rank 2 access of the 2nd column:\n", col_r2, col_r2.shape)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
We will often define functions to take optional keyword arguments, like this:
Can you write Python code for it?

def hello(name, loud=False):
    if loud:
        print ('HELLO, %s' % name.upper())
    else:
        print ('Hello, %s!' % name)

hello('Bob')
hello('Fred', loud=True)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
With just a little bit of extra work we can easily plot multiple lines at once, and add a title, legend, and axis labels:
Can you write Python code for it?

y_sin = np.sin(x)
y_cos = np.cos(x)

# Plot the points using matplotlib
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array. Note that this is quite different from the way that MATLAB handles array slicing:
Can you write Python code for it?

# Create the following rank 2 array with shape (3, 4)
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print (a)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
You can find a list of all string methods in the documentation
Containers
Python includes several built-in container types: lists, dictionaries, sets, and tuples.
Lists
A list is the Python equivalent of an array, but is resizeable and can contain elements of different types:
Can you write Python code for it?

xs = [3, 1, 2]   # Create a list
print (xs, xs[2])
print (xs[-1])     # Negative indices count from the end of the list; prints "2"

xs[2] = 'foo'    # Lists can contain elements of different types
print (xs)

xs.append('bar') # Add a new element to the end of the list
print (xs)

x = xs.pop()     # Remove and return the last element of the list
print (x, xs)


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
You can find all you need to know about dictionaries in the documentation.
It is easy to iterate over the keys in a dictionary:
Can you write Python code for it?

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
    legs = d[animal]
    print ('A %s has %d legs' % (animal, legs))


I am working on the file "Stanford CS228 - Python and Numpy Tutorial.ipynb".
The first task is:
You can make this code simpler using a list comprehension:
Can you write Python code for it?

nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print (squares)


I am working on the file "Stanford DH Asia Python Basics.ipynb".
The first task is:
A Few Data Types
Integers
Whole numbers. This behave a bit differently than expected when you divide them. Integer division drops the remainder. By default, Python 3 performs float division. Two slashes (//) allow for Integer division (we will see it later).
Can you write Python code for it?

# Here are some integers:
2
5
5000

# Here is some regular division:
5/2

# Here is some integer division:
5//2


I am working on the file "Stanford DH Asia Python Basics.ipynb".
The first task is:
Boolean Values
True and False are important values. They allow us to create logic in our programs.
Checking Boolean Values
<
is less than
>
is greater than
<=
is less than or equal to
>=
is greater than or equal to
==
is equal to
!=
is not equal to
Can you write Python code for it?


I am working on the file "Stanford DH Asia Python Basics.ipynb".
The first task is:
For loops
Iterate through each item in a list (or other enumerable object).
Can you write Python code for it?

animals = ["tiger", "lion", "monkey", "pig"]
for animal in animals:
    print(animal)


I am working on the file "Stanford DH Asia Python Basics.ipynb".
The first task is:
Libraries
We can use code other people have written by importing libraries. These extend the basic functionality of Python. They are not automatically imported into the namespace for efficiency reasons. Anaconda comes with many libraries that will make our life much easier. We will import them as needed
Can you write Python code for it?


I am working on the file "Stanford DH Asia Python Basics.ipynb".
The first task is:
Lists
This is an object that can store information. It is ordered and very useful. Denoted with square brackets.
Can you write Python code for it?

# This is an empty list:
[]

# This is a list with some information.
[1, 2, 3, 4, 5, 6]


I am working on the file "Stanford DH Asia Python Basics.ipynb".
The first task is:
Note the trailing numbers. They are not extremely precise. Be careful
Strings
Words. These are denoted using either single or double quotation marks.
Can you write Python code for it?

"This is a string."
'This is also a string.'


I am working on the file "Stanford DH Asia Python Basics.ipynb".
The first task is:
Printing
This statement allows you to print (display) something to the console. This is not sending anything to your printer.
Can you write Python code for it?


I am working on the file "Stanford DH Asia Python Basics.ipynb".
The first task is:
Python Structure
Python uses indentation to denote code blocks. Some languages use keywords, like "end"
Loops
loops allow you to run the same piece of code over and over.
While loops
While a statment is true, execute the code inside the block:
Can you write Python code for it?

i = 0
while i < 4:
    print(i)

    # Increase i by one. This can also be written i += 1
    i = i + 1


I am working on the file "Stanford DH Asia Python Basics.ipynb".
The first task is:
Retreiving information from a dictionary
Can you write Python code for it?

holiday_dates = {"Independence Day":"July 4th", "Halloween":"October 31st", "Labor Day 2016":"September 6th"}

print(holiday_dates["Halloween"])


I am working on the file "Stanford DH Asia Python Basics.ipynb".
The first task is:
Retriving Information From Lists
You can get information out of a list by calling an item's index. Python is 0 indexed (meaning the first element is a 0 not a 1).
Can you write Python code for it?

numbers = [1,2,3,4,5,6]
print(numbers[0])


I am working on the file "Stanford DH Asia Stylometry.ipynb".
The first task is:
Adding some color
Sometimes it helps to add a bit of color to the figure so you can easily interpret it.
Can you write Python code for it?

dendrogram(linkage_matrix, labels=title_list)
plt.title("Textual Relationships")
plt.xlabel("Texts")
plt.ylabel("Distance")
plt.xticks(rotation=60)

# Create a dictionary for color selection
# Here we are using genre as the basis for color
# You would need to change this if you wanted to color based on authorship.
color_dict = {"传奇":"red", "小说":"blue", "话本":"magenta"}

# Return information about the tick labels
plt_info = plt.gca()
tick_labels = plt_info.get_xmajorticklabels()

# Iterate through each tick label and assign a new color
for tick_label in tick_labels:
    # Get the genre from the title to genre dictionary
    genre = title_genre[tick_label.get_text()]

    # Get the color from the dictionary
    color = color_dict[genre]

    # Set the color
    tick_label.set_color(color)

# Show the plot
plt.show()


I am working on the file "Stanford DH Asia Stylometry.ipynb".
The first task is:
Deal with Metadata
If you have structured your data well, you should have a metadata file that keeps track of each document in your corpus. This is not essential, but it is very helpful.
Read metadata file into a dictionary.
There are a variety of ways of doing this. I am just going to break the text apart and build the dictionary manually.
Can you write Python code for it?

# Create a dictionary to store the information
metadata = {}

# open and extract the string
metadatafile = open("metadata.txt", "r", encoding="utf8")
metadatastring = metadatafile.read()
metadatafile.close()

# split into by line
lines = metadatastring.split("\n")
for line in lines:
    # split using tabs
    cells = line.split("\t")

    # use the first column as the key, which I use store
    # the rest of the columns
    metadata[cells[0]] = cells[1:]

print(metadata)


I am working on the file "Stanford DH Asia Stylometry.ipynb".
The first task is:
Hierarchical Cluster Analysis: Making a Dendrogram
Now we can start calculating the relationships among these works. We will have to decide if we want to use euclidean distance or cosine similarity. We will import several tools to help us do this
Euclidean Distance
Each vector is understood as a point in space. You will need to calculate the distance between each point. We will use these to judge similarity.
Cosine similarity
Here we are interested in the direction that each vector points. You will calculate the angle between each point.
Can you write Python code for it?

from sklearn.metrics.pairwise import euclidean_distances, cosine_similarity

euc_or_cosine = "euc"
if euc_or_cosine == "euc":
    similarity = euclidean_distances(word_count_matrix)
elif euc_or_cosine == "cos":
    similarity = cosine_similarity(word_count_matrix)


I am working on the file "Stanford DH Asia Stylometry.ipynb".
The first task is:
If you do not have a file with whitespace between items:
Here we will just use characters to tokenize. This works well with Imperial Chinese. Particularly with wenyan texts. Here we are telling it to look at characters, rathern than words, 1-grams, and the 100 most common characters.
Can you write Python code for it?

vectorizer = CountVectorizer(analyzer="char",ngram_range=(1,1),
                             max_features = 100)


I am working on the file "Stanford DH Asia Stylometry.ipynb".
The first task is:
It is a bit more complicated if you break texts apart
Can you write Python code for it?

# Create empty lists/dictionaries to store the information
info_list = []
title_list = []
author_list = []
era_list = []
genre_list = []
title_author = {}
title_era = {}
title_genre = {}

# We should also track which section number
section_number = []

for root, dirs, files in os.walk("corpus"):
    for filename in files:
        if filename[0] != ".":
            f = open(root + "/" + filename, "r", encoding="utf8")
            c = f.read()
            f.close()
            c = re.sub("\s+", "", c)
            c = clean(c)

            # Get metadata. the [:-4] removes the .txt from filename
            metainfo = metadata[filename[:-4]]

            # The dictionary formation stays the same
            title_author[metainfo[0]] = metainfo[1]
            title_era[metainfo[0]] = metainfo[2]
            title_genre[metainfo[0]] = metainfo[3]

            # Break the Text apart
            broken_sections = textBreak(c)

            # We will need to extend, rather than append
            info_list.extend(broken_sections)

            title_list.extend([metainfo[0] for i in
                               range(0,len(broken_sections))])
            author_list.extend([metainfo[1] for i in
                                range(0,len(broken_sections))])
            era_list.extend([metainfo[2] for i in
                             range(0,len(broken_sections))])
            genre_list.extend([metainfo[3] for i in
                               range(0,len(broken_sections))])
            section_number.extend([i for i in range(0, len(broken_sections))])

print(author_list[:20])


I am working on the file "Stanford DH Asia Stylometry.ipynb".
The first task is:
Now it is time to visualize the relationships
When run normally, this will open a new window (and it will be higher quality than the image here). You will have to close it for later parts of the script to continue to run.
Can you write Python code for it?

# import the plotting library.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.font_manager

# Set the font to a Chinese Font Family
# STHeiti works for Macs, SimHei should work on Windows
# Linux does not come with a compatible Chinese font.
# Here I have defaulted to a Japanese font.
# I've added logic that checks what system you are using.
from sys import platform
if platform == "linux" or platform == "linux2":
    print("Sorry, I can't see the appropriate fonts, defaulting to Japanese")
    matplotlib.rc('font', family="TakaoPGothic")
elif platform == "win32" or platform == "win64":
    matplotlib.rc('font', family="SimHei")
elif platform == "darwin":
    matplotlib.rc('font', family='STHeiti')

# Make the Dendrogram
dendrogram(linkage_matrix, labels=title_list)
plt.show()


I am working on the file "Stanford DH Asia Stylometry.ipynb".
The first task is:
Now we can start calculating common characters
There are a variety of ways to do this. Here I will just use code packaged in the Sci-kit learn module.
Can you write Python code for it?

from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer


I am working on the file "Stanford DH Asia Stylometry.ipynb".
The first task is:
Opening parameters
open() takes several parameters. First, the file path then the open mode.
"r" means read
"w" means write
"a" means append
Be careful with "w"!
If you open a file in write mode, if it exists, the program will wipe the files contents without warning you. If it doesn't exist, it will automatically create the file.
Setting the encoding
By default, strings in Python3 are Unicode. If the file you are opening is not unicode, you have to tell python. If it is unicode, you don't have to tell it anything
Can you write Python code for it?

my_file = open("test.txt", "r", encoding="utf-8")
file_contents = my_file.read()
print(file_contents)