\section{Abstract}
Rossby waves are a way to conceptualize large scale, time-dependent motion in the atmosphere and ocean. Analytically we expect Rossby waves to travel westwards, and this was tested numerically with different time-stepping methods for a periodic and finite domain. \\

The numerical results show that Rossby waves travel westwards. For the finite domain the Rossby wave hits the wall and is reflected backwards to the east. This results in some resonance for the finite case. For the periodic case only regular sinusoidal shaped waves of constant amplitude was observed.

\section{Introduction}
In this project I will study Rossby waves. Rossby waves are a way to conceptualize large scale, time-dependent motion in the atmosphere and ocean. These waves typically have scales of hundreds to thousands of kilometers. Two examples of phenomenon that we try to understand with Rossby waves is the meandering of the atmospheric Jet Stream, and the adjustment of the ocean to changes in wind forcing, also called geostrophic adjustment.\cite{geofludyn}

Rossby waves exist because of the Coriolis acceleration, which acts perpendicular to the velocity of a fluid parcel. In the Northern Hemisphere we have positive Coriolis acceleration, and in the Southern Hemisphere we have negative Coriolis. The Coriolis acceleration varies with latitude, strengthens towards the poles and weakens towards the equator. This is also why Rossby waves are treated a bit differently around the equator, and most of the time examined in mid- or high- latitudes. \cite{rossby}

Around the equator we usually apply the equatorial beta plane approximation ($f=\beta y$, where $\beta$ is the variation of Coriolis in the y-direction(north-south) given by $\beta = df/dy$), where we may study equatorial Kelvin waves, which are lightning bolts compared to Rossby waves. Without a mean flow, equatorial Rossby waves (slow waves propagating with speeds on order of cm/s) are observed to travel west and Kelvin waves travel east (propagation speeds on order of m/s) around the equator.\cite{equator}\\

The variation in Coriolis acceleration with latitude causes fluid parcels to change their spin, in context of a continuum called the vorticity \cite{vorticity}, as they move to different latitudes.\\

Introducing short hand notations for derivatives in as shown below:\\

$\partial_t = \frac{\partial}{\partial t}$\\

$\partial_x = \frac{\partial}{\partial x}$\\

$\partial_{xx} = \frac{\partial^2}{\partial x^2}$\\

The vorticity equation is then given as:\\

\begin{equation}
\partial_t\zeta + \beta\partial_x\psi = 0
\end{equation}\\

Where $\zeta$ is the vorticity, $\beta$ comes from the $\beta$-plane approximation explained below and $\psi$ is the streamfunction determining the velocities:\\

\begin{equation}
u = -\partial_y\psi  \\\   ,  \\\  v = \partial_x\psi
\end{equation}\\

Where u is the east-west velocity and v is the north-south velocity.\\

Vorticity is defined as the curl, and the horizontal Laplacian of the streamfunction:\\

\begin{equation}
\zeta = \partial_xv - \partial_yu = \nabla^2_H\psi
\end{equation}\\

The Coriolis parameter is defined by:\\

\begin{equation}
f = 2\Omega sin(\theta)
\end{equation}\\

where $\theta$ is the latitude and $\Omega$ is the rotation rate of the earth, $\Omega = 2\pi/day$. As hinted at before, we often approximate f as a linear function centered on a latitude $\theta_0$:\\

\begin{equation}
f\approx f_0 + \beta y
\end{equation}\\

where $f_0 = 2\Omega sin(\theta_0)$, $\beta = 2\Omega cos(\theta_0)/R_e$ and $y = R_e(\theta - \theta_0)$, if $R_e$ is the Earth's radius. This linear representation is called the $\beta$-plane approximation and is the $\beta$ term in equation (1). Using the definition of vorticity we can rewrite the vorticity equation (1) in terms of only one variable, the streamfunction:\\

\begin{equation}
\partial_t\nabla^2_H\psi + \beta\partial_x\psi = 0
\end{equation}\\

This is the barotropic Rossby wave equation, barotropic meaning that the density variations are only dependent on the change in pressure.\\

We will examine solutions of the vorticity equation in a periodic and closed domain, both analytically and numerically. For the periodic case we can consider a re-entrant domain, like going around the Earth's atmosphere. For a closed domain we can think of continents acting as walls bounding the ocean.

\section{Methods}
\subsection{Analytical solutions}
My calculations are mainly based on the lecture notes from geophysical fluid dynamics: \cite{geofludyn}\\

\subsubsection{Solution to the Rossby equation in a periodic domain}
Consider the vorticity equation from (6) in one dimension. Assuming the periodic domain in x = [0,L] I can propose a wave solution on the form:\\

\begin{equation}
\psi = Acos(\frac{2n\pi x}{L}-\omega t)
\end{equation}\\

, where n is an integer, $\omega$ is the wave frequency and A is the amplitude.\\

I need to show that the solution on the two boundaries are the same, satisfying periodic domain, and then solve for $\omega$ to find the dispersion relation. Using the proposed wave solution in (7) I have the following:\\

\begin{equation}
\begin{gathered}
\zeta = \partial_xv = \partial_{xx}\psi\\
\partial_x\psi = -A\frac{2n\pi}{L}sin(\frac{2n\pi x}{L}-\omega t)\\
\zeta = \partial_{xx}\psi = -A(\frac{2n\pi}{L})^2cos(\frac{2n\pi x}{L}-\omega t)\\
\zeta(x=0,t) = -A(\frac{2n\pi}{L})^2cos(-\omega t)\\
\zeta(x=L,t) = -A(\frac{2n\pi}{L})^2cos(\frac{2n\pi L}{L}-\omega t) = -A(\frac{2n\pi}{L})^2cos(2n\pi-\omega t) = -A(\frac{2n\pi}{L})^2cos(-\omega t)\\
\end{gathered}
\end{equation}

Equation 8 shows that periodic boundary conditions are ok. Inserting $\zeta$ into equation (6) yields:\\

\begin{equation}
\begin{gathered}
\partial_t\nabla^2_H\psi + \beta\partial_x\psi = \partial_t\zeta + \beta\partial_x\psi =\\
-A(\frac{2n\pi}{L})^2\omega \sin(\frac{2n\pi x}{L}-\omega t) - \beta A\frac{2n\pi}{L}\sin(\frac{2n\pi x}{L}-\omega t)\\
\implies A\frac{2n\pi}{L}(\frac{2n\pi \omega}{L}+\beta)\sin(\frac{2n\pi x}{L}-\omega t) = 0\\
\implies \omega = -\frac{\beta L}{2\pi n}
\end{gathered}
\end{equation}

This is the dispersion relation of the wave. The phase speed is the speed at which Rossby waves move. Consider the phase of the wave as:\\

$\theta = \frac{n\pi x}{L}-\omega t$\\

If we choose $\theta = 2\pi$ we get $\psi = Acos(2\pi) = A$, which means that we have a high pressure point with amplitude A. Solving for x we can find how this point moves, and taking the time derivative of that expression gives us an expression for the phase speed:\\

$x = \frac{\theta L}{2n\pi} + \frac{\omega tL}{2n\pi}$\\

$c = \frac{dx}{dt} = \frac{\omega L}{2n\pi}$\\

Inserting my expression for $\omega$ I get the Rossby phase speed in the x direction:\\

$c_x = \frac{\omega L}{2n\pi} = -\beta(\frac{L}{2n\pi})^2$\\

Thus, I find that the Rossby wave is moving westwards.\\

\subsubsection{Solution to the Rossby equation with solid boundaries}

In the ocean it's more appropriate to apply boundary conditions of no flow at the two end points. This can be enforced with Dirichlet conditions: $\psi = 0$ at $x=0$ and $x=L$. Proposing a wave solution of the form:\\

\begin{equation}
\psi = A(x)cos(kx-\omega t)
\end{equation}\\

, where A(x) indicates that the amplitude has a structure which must be solved for the boundary conditions. Inserting the wave solution above into equation (6) I get the following:\\

\begin{equation}
\begin{gathered}
\psi(x=0,t) = \psi(x=L,t)=0\\
\psi(x,t)=A(x)cos(kx-\omega t)\\
\partial_x\psi = A'(x)cos(kx-\omega t) - A(x)ksin(kx-\omega t)\\
\zeta = \partial_{xx}\psi = A''(x)cos(kx-\omega t)-A'(x)ksin(kx-\omega t) - A'(x)ksin(kx-\omega t) - A(x)k^2cos(kx-\omega t) =\\
(A''(x)-A(x)k^2)cos(kx-\omega t)-2A'(x)ksin(kx-\omega t)\\
\implies \partial_t\zeta + \beta\partial_x\psi =\\
(A''(x)-A(x)k^2)\omega sin(kx-\omega t)+2A'(x)k\omega cos(kx-\omega t) + \beta(A'(x)cos(kx-\omega t) - A(x)ksin(kx-\omega t))\\
\implies ((A''(x)-A(x)k^2)\omega - \beta A(x)k)sin(kx-\omega t) + A'(x)(2k\omega + \beta)cos(kx-\omega t) = 0
\end{gathered}
\end{equation}\\

This holds if:\\

$(A''(x)-A(x)k^2)\omega - \beta A(x)k = 0$\\

and solving for $\omega$ I find an initial expression for the dispersion relation. \\

$2k\omega + \beta = 0$\\
$\implies \omega = \frac{-\beta}{2k}$\\

and

$c_x = \frac{\omega}{k} = \frac{-\beta}{2k^2}$\\

Solving for the structure:\\

\begin{equation}
\begin{gathered}
A''(x) - A(x)(k^2+\frac{\beta k}{\omega} = 0\\
r^2-(k^2+\frac{\beta k}{\omega})=0\\
r = \pm k\sqrt{1+\frac{\beta}{k\omega}}\\
= \pm k\sqrt{1-\frac{\beta}{k\beta/2k}} = \pm k\sqrt{1-2} = \pm ik\\
\implies A(x) = C\cos(kx) + D\sin(kx)
\end{gathered}
\end{equation}\\

Need to satisfy Dirichlet conditions:\\

\begin{equation}
\begin{gathered}
\psi(x=0,t) = A(0)\cos(-\omega t) = 0\\
\implies C + D\sin(0) = 0
\implies C = 0\\
\psi(x=L,t) = A(L)\cos(kL-\omega t) = 0\\
\implies A(L) = D\sin(kL) = 0\\
\implies kL = n\pi\\
\implies k_n = \frac{n\pi}{L}\\
\end{gathered}
\end{equation}\\

I find that the allowed frequencies given by the dispersion relation becomes:\\

$\omega_n = \frac{-\beta L}{2\pi n}$\\

and the Rossby phase speed:\\

$c_x = \frac{\omega_n}{k_n} = \frac{\beta}{2}(\frac{L}{n\pi})^2$\\

The full wave solution becomes:\\

\begin{equation}
\psi(x,t) = D\sin(\frac{n\pi x}{L})\cos(\frac{n\pi x}{L}+\frac{\beta Lt}{2\pi n})
\end{equation}

, where D must be determined from the initial conditions for a specific problem.

\subsection{Method for solving the barotropic Rossby wave equation numerically}
A numerical solution to equation (6), involves two steps. If we know the velocity or streamfunction initially, we can advance the vorticity in time to a new time. Then the streamfunction at the new time is found by inverting equation (3). This process is repeated to find a complete numerical solution.\\

Since the vorticity does not vary with change in y-direction for the one dimensional case I have:\\

\begin{equation}
\zeta = \partial_{xx}\psi
\end{equation}

This is a specification of equation (3), which is solved as the Poisson equation, the same way as used in project 1. We have the same form:\\

$u''(x) = f(x)$ , the Poisson structure is recognized as:\\

$\partial_{xx} \psi = \zeta$\\

which, for the rigid boundary conditions can be solved the exact same way:

To discretize the equations, we assume a grid of equally-spaced
points:

\begin{equation}
x_j = j\Delta x
\end{equation}
where $\Delta x$ is the grid spacing. We discretize time in a similar way:

\begin{equation}
t^n = n\Delta t
\end{equation}
where $\Delta t$ is the time step. Thus $t^0=0$, $t^1=\Delta t$, and so on.\\

We then approximate the derivatives by finite differences. For
the spatial derivatives, we use centered-differences:

\begin{align}
	\partial_x\psi &\approx \frac{\psi_{j+1}^{n} - \psi_{j-1}^{n}}{2\Delta x}, \\
	\partial_{xx}\psi &\approx \frac{\psi_{j+1}^{n} - 2\psi_{j}^{n} + \psi_{j-1}^{n}}{\Delta x^2},
\end{align}

Thus the discretized 1D Poisson equation becomes a set of algebraic equations:\\

\begin{align}
\implies \psi_{j+1}^{n} - 2\psi_{j}^{n} + \psi_{j-1}^{n} = \zeta_j^n {\Delta x^2}
\end{align}

, where j is the space step j = 1,2,...,$j_{max}$\\

For periodic boundary conditions it's much more difficult to satisfy the boundary conditions. The boundary at x=0 we must be carefully handled with an extra imaginary point $x_{-1}$, since we have that the last step should be the first step for the next cycle. For j = 0 I get:\\

\begin{align}
\psi_{1}^{n} - 2\psi_{0}^{n} + \psi_{-1}^{n} = \zeta_0^n {\Delta x^2}
\end{align}\\

, where $\psi_{-1}^{n}$ is the problem term. To solve it I utilize equation (18), by saying that\\

\begin{align}
\partial_x \psi_{0}^{n} = \frac{\psi_{1}^{n} - \psi_{-1}^{n}}{2\Delta x}
\end{align}\\

Rearranging and solving the equation in regards to
$\psi_{-1}^{n}$ I get:\\

\begin{align}
\psi_{-1}^{n} = \psi_{1}^{n} - 2\Delta x \partial_x \psi_{0}^{n}
\end{align}\\

Substituting this expression into the previous equation (21) I get:\\

\begin{align}
\psi_{1}^{n} - 2\psi_{0}^{n} + \psi_{1}^{n} - 2\Delta x \partial_x \psi_{0}^{n} = \zeta_0^n {\Delta x^2}
\end{align}

Rearranging again I get the result of the boundary condition:\\

\begin{align}
\psi_{1}^{n} - \psi_{0}^{n}  = \frac{\zeta_0^n {\Delta x^2} + 2\Delta x \partial_x \psi_{0}^{n}}{2}
\end{align}\\

Now we can introduce the vector $\mathbf{F}$, as done in equation 5 of \cite{poisson}. The elements of $\mathbf{F}$ are $F_j$ defined by:\\

\begin{equation}
\begin{gathered}
F_0 = \frac{\zeta_0^n {\Delta x^2}}{2} + \Delta x \partial_x\psi_0\\
F_{j_{max}} = \Delta x^2 \zeta_{j_{max}} - \psi_0\\
F_j = \Delta x^2 \zeta_j
\end{gathered}
\end{equation}

, where j = 1, 2, ..., $j_{max}-1$\\

I obtain the following matrix equation:\\

\[
\begin{bmatrix}
       -1& 1& 0 &\dots   & \dots &0 \\
       1 & -2 & 1 &0 &\dots &\dots \\
       0&1 &-2 & 1 & 0 & \dots \\
       & \dots   & \dots &\dots   &\dots & \dots \\
       0&\dots   &  &1 &-2& 1 \\
       0&\dots    &  & 0  &1 & -1 \\
\end{bmatrix}
\begin{bmatrix}
	\psi_0 \\
	\psi_1 \\
	\psi_2 \\
	\vdots \\
	\psi_{j_{max}-1} \\
	\psi_{j_{max}} \\
\end{bmatrix} =
\Delta x^2
\begin{bmatrix}
	\zeta_0 \\
	\zeta_1 \\
	\zeta_3 \\
	\vdots \\
	\zeta_{j_{max}-1} \\
	\zeta_{j_{max}} \\
\end{bmatrix}
\]\\

This tridiagonal matrix is then solved numerically with the Thomas algorithm as prescribed in \cite{trisolve} or chapter 6.4 in \cite{lecturenote}.\\

Equation (6) is a prognostic equation, which will be solved numerically by using a time-stepping method.

For the time stepping, we will test two methods. One involves a
forward difference:

\begin{equation}
  \label{eq:Rossby3}
  \partial_t\psi \approx \frac{\psi_{j}^{n+1} - \psi_{j}^{n}}{\Delta t} ,
\end{equation}

while the second involves a centered difference:

\begin{align}
  \label{eq:Rossby4}
	\partial_t\psi &\approx \frac{\psi_{j}^{n+1} - \psi_{j}^{n-1}}{2\Delta t}.
\end{align}\\

The forward method is rearranged to be solved using the following algorithm\\

\begin{align}
\zeta_j^{n+1} = \Delta t(\frac{\psi_{j+1}^n-\psi_{0}^n}{\Delta x})+\zeta_j^{n}
\end{align}\\

and the central method is rearranged to:\\

\begin{align}
\zeta_j^{n+1} = 2\Delta t(\frac{\psi_{j+1}^n-\psi_{j-1}^n}{2\Delta x})+\zeta_j^{n-1}
\end{align}\\

\newpage
\section{Implementation}
For all programs, see:\\
$\href{https://github.com/larsjbro/FYS4150/tree/master/project_5/source}{https://github.com/larsjbro/FYS4150/tree/master/project_5/source}$

\subsection{Tridiagonal matrix solver}
The Thomas method is implemented to find an expression for the vorticity. This method is implemented in the functions

\begin{verbatim}
tridiagonal_solve_specific
\end{verbatim}

is used for solving the finite domain

and

\begin{verbatim}
tridiagonal_solve
\end{verbatim}

is used to solve for the periodic domain.

The result from the solver is then inserted into the Rossby wave equation and solved with time stepping methods.

\subsection{Rossby wave solution for finite and periodic domain}
A solver for the barotropic Rossby wave equation for finite and perodic domain is implemented with the functions

\begin{verbatim}
solve_rossby_with_walls
\end{verbatim}

and

\begin{verbatim}
solve_rossby_periodic
\end{verbatim}

respectively.

%*Code/Implementations/test: Readability of code, implementation, testing and discussion of benchmarks. Total number of possible points 20*

\section{Results}
%*Analysis: of results and the effectiveness of their selection and presentation. Are the results well understood and discussed? Total number of possible points: 20*

\subsection{Agreement between analytical and numerical simulations}

Theoretically we expect the Rossby wave to travel westwards barring a strong mean flow to the east. From figure 1 and 2 I see that this case is confirmed, as I can see the wave moving westwards with increasing time. I can also see that the waves are interfering as the amplitude of the waves are changed with time for the finite domain!

\subsubsection{Finite domain}
Figure 1 and 2 shows the Rossby wave propagation going westwards and also showing some change in amplitude due to the finite boundaries resulting in reflection of waves.

\FloatBarrier
\begin{figure}[!ht]
\centering
\FloatBarrier
\includegraphics[width=0.70\textwidth]{task_5c_psi_Wall_central1000.png}

\caption{Plot of streamfunction for finite domain with central method, for three different times}
\label{fig:Earth_orbit_sun_Forward_Euler_k_2}
\end{figure}
\FloatBarrier

\FloatBarrier
\begin{figure}[!ht]
\centering
\FloatBarrier
\includegraphics[width=0.70\textwidth]{task_5c_psi_Wall_forward1000.png}

\caption{Plot of streamfunction for finite domain with forward stepping method, for three different times.}
\label{fig:Earth_orbit_sun_Forward_Euler_k_2}
\end{figure}
\FloatBarrier

\subsubsection{Periodic domain}
Figure 3 and 4 show that also the periodic waves travel westwards but are are not distorted in their shape, which is because there is no reflection at a wall.

\FloatBarrier
\begin{figure}[!ht]
\centering
\FloatBarrier
\includegraphics[width=0.70\textwidth]{task_5c_psi_Periodic_central1000.png}

\caption{Plot of streamfunction for periodic domain with central stepping method, for three different times.}
\label{fig:Earth_orbit_sun_Forward_Euler_k_2}
\end{figure}
\FloatBarrier

\FloatBarrier
\begin{figure}[!ht]
\centering
\FloatBarrier
\includegraphics[width=0.70\textwidth]{task_5c_psi_Periodic_forward1000.png}

\caption{Plot of streamfunction for periodic domain with forward stepping method, for three different times.}
\label{fig:Earth_orbit_sun_Forward_Euler_k_2}
\end{figure}
\FloatBarrier

\section{Conclusion}
Barotropic Rossby waves travel in the western direction, but the numerical solution to the problem is quite difficult. Especially for the case of a periodic domain, when the boundary conditions introduced a stepping problem.

I find that the central method was slightly better as a numerical method. I also find that the Rossby waves travel westwards for both the periodic and the finite domain. In the finite domain I can see that the amplitude of the wave is distorted which is a sign that there is reflection of waves at the walls resulting in resonance.

%*Conclusions, discussions and critical comments: on what was learned about the method used and on the results obtained. Possible directions and future improvements? Total number of possible points: 10*

\begin{thebibliography}{99}
\bibitem{lecturenote}$\href{https://github.com/CompPhysics/ComputationalPhysics/blob/gh-pages/doc/Lectures/lectures2015.pdf}{https://github.com/CompPhysics/ComputationalPhysics/blob/gh-pages/doc/Lectures/lectures2015.pdf}$, November 19 2017\\
\bibitem{equator}$\href{https://en.wikipedia.org/wiki/Equatorial\_wave}{https://en.wikipedia.org/wiki/Equatorial\_wave}$
\bibitem{geofludyn}$\href{http://folk.uio.no/josepl/papers/dynbook7.pdf}{http://folk.uio.no/josepl/papers/dynbook7.pdf}$
\bibitem{rossby}$\href{https://en.wikipedia.org/wiki/Rossby\_wave}{https://en.wikipedia.org/wiki/Rossby\_wave}$
\bibitem{poisson}$\href{http://file.scirp.org/pdf/JEMAA_2014092510103331.pdf}{http://file.scirp.org/pdf/JEMAA_2014092510103331.pdf}$
\bibitem{vorticity}$\href{https://en.wikipedia.org/wiki/Vorticity}{https://en.wikipedia.org/wiki/Vorticity}$
\bibitem{trisolve}$\href{https://www.cfd-online.com/Wiki/Tridiagonal\_matrix\_algorithm\_-\_TDMA\_(Thomas\_algorithm)}{https://www.cfd-online.com/Wiki/Tridiagonal\_matrix\_algorithm\_-\_TDMA\_(Thomas\_algorithm)}$
\end{thebibliography}

%\FloatBarrier
%\begin{figure}[!ht]
%\centering
%\FloatBarrier
%\includegraphics[width=0.45\textwidth]{eigenvector_rho29n128omega500.png}
%
%\caption{Normalized energy for the three lowest eigenvalues for repulsive Coulomb interaction with n=128 and $\omega_r$=5}
%\label{fig:Eigenvalue_states_n_320_omega_500}
%\end{figure}
%\FloatBarrier


namespace ct_common {

// Class mapping typeid to class name.
class ClassNameMap final {
 public:
  ClassNameMap() = default;
  ~ClassNameMap() = default;

  template <typename T>
  static const std::string& GetClassName(const T& obj) {
    return GetInstance().GetClassNameInternal(typeid(obj));
  }

  static void Register(const std::type_index& info, const std::string& name) {
    GetInstance().RegisterInternal(info, name);
  }

 private:
  static ClassNameMap& GetInstance();

  const std::string& GetClassNameInternal(const std::type_index& idx) const;
  void RegisterInternal(const std::type_index& info, const std::string& name);

  using NameMap = std::unordered_map<std::type_index, std::string>;
  NameMap name_map_;
};

class GlobalInitializer {
 public:
  using FuncType = std::function<void()>;
  explicit GlobalInitializer(FuncType func) {
    func();
  }
};

}  // namespace ct_common

#define REGISTER_CLASS_NAME(name)                                       \
  namespace {                                                           \
  const ct_common::GlobalInitializer sClassNameRegisterer##name(        \
      std::bind(ClassNameMap::Register,                                 \
                std::type_index(typeid(name)), #name));                 \
  }

#endif  // CT_COMMON_BASE_CLASS_NAME_UTILS_H_


Compiled example
----------------
![Example](topology-cube-divided.png)


import datetime
import os
import re
import tempfile
import urllib2

from lxml import etree
from optparse import make_option
from tempfile import gettempdir

from django.core.files import File
from django.core.management.base import BaseCommand, CommandError
from django.utils.timezone import utc

from airmozilla.main.models import Category, Event, Tag, Template

DEFAULT_VIDLY_TEMPLATE = """
<video controls width="100%" controls preload="none" poster="https://d3fenhwk93s16g.cloudfront.net/{{ tag }}/poster.jpg">
    <source src="http://cf.cdn.vid.ly/{{ tag }}/mp4.mp4" type="video/mp4">
    <source src="http://cf.cdn.vid.ly/{{ tag }}/webm.webm" type="video/webm">
    <source src="http://cf.cdn.vid.ly/{{ tag }}/ogv.ogv" type="video/ogg">

</video>
"""
DEFAULT_VIDLY_NAME = "Vid.ly"

DEFAULT_OGG_TEMPLATE = """
<video width="620" height="350" controls="controls">
  <source src="{{ url }}" type="video/ogg" />
</video>
"""
DEFAULT_OGG_NAME = "Ogg Video"

class Command(BaseCommand):
    args = '<wordpress_xml_dump.xml> <default_thumb>'
    option_list = BaseCommand.option_list + (
        make_option('--clear',
            action='store_true',
            dest='clear',
            default=False,
            help='Clear all events before running the migration.'),
    )
    nsmap = {
        'wp': 'http://wordpress.org/export/1.2/',
        'dc': 'http://purl.org/dc/elements/1.1/',
        'content': 'http://purl.org/rss/1.0/modules/content/',
        'excerpt': 'http://wordpress.org/export/1.2/excerpt/'
    }
    import_cache = tempfile.gettempdir()

    def _check_video_templates(self):
        # make sure we have some assumed Video templates in the database
        try:
            Template.objects.get(name=DEFAULT_VIDLY_NAME)
        except Template.DoesNotExist:
            Template.objects.create(
                name=DEFAULT_VIDLY_NAME,
                content=DEFAULT_VIDLY_TEMPLATE
            )
        try:
            Template.objects.get(name=DEFAULT_OGG_NAME)
        except Template.DoesNotExist:
            Template.objects.create(
                name=DEFAULT_OGG_NAME,
                content=DEFAULT_OGG_TEMPLATE
            )

    def handle(self, *args, **options):
        if options['clear']:
            for e in Event.objects.all():
                e.delete()
        self._check_video_templates()
        attachments = {}
        try:
            wordpress_xml_dump = args[0]
            item_parser = etree.iterparse(wordpress_xml_dump, tag='item')
        except IndexError:
            raise CommandError('Please provide an XML dump.')
        except IOError:
            raise CommandError('The provided file does not exist or is not'
                               ' a valid Wordpress XML dump')
        try:
            self.default_thumb_path = args[1]
            self.default_thumb = open(self.default_thumb_path, 'rb')
        except IOError:
            raise CommandError('Please provide a valid default thumbnail.')

        for _, element in item_parser:
            fields = {
                'title': 'title',
                'status': 'wp:status',
                'start_time': 'pubDate',
                'description': 'content:encoded',
                'short_description': 'excerpt:encoded',
                'created': 'wp:post_date',
                'slug': 'wp:post_name',
                'type': 'wp:post_type',
                'attachment': 'wp:attachment_url',
                'post_id': 'wp:post_id'
            }
            item = self.extract_item(element, fields)
            if Event.objects.filter(slug=item['slug']).exists():
                self.stdout.write(
                    'Event %s already exists, skipping.\n' % item['slug']
                )
                continue

            if item['type'] == 'attachment':
                # The item is a thumbnail attachment; save for later
                attachments[item['post_id']] = item['attachment']
            elif item['type'] == 'post':
                # Create and initiate a new event
                event = Event()
                event.title = item['title']
                event.slug = item['slug']
                try:
                    event.start_time = datetime.datetime.strptime(
                        item['start_time'],
                        '%a, %d %b %Y %H:%M:%S +0000'
                    ).replace(tzinfo=utc)
                except ValueError:
                    event.start_time = datetime.datetime.strptime(
                        item['created'],
                        '%Y-%m-%d %H:%M:%S'
                    ).replace(tzinfo=utc)
                event.archive_time = (
                    event.start_time + datetime.timedelta(hours=1)
                )
                # Set status & public status from WP metadata
                event.status = Event.STATUS_INITIATED
                event.public = False
                if item['status'] == 'publish':
                    event.status = Event.STATUS_SCHEDULED
                    event.public = True
                elif item['status'] == 'private':
                    event.status = Event.STATUS_SCHEDULED
                elif item['status'] == 'trash':
                    event.status = Event.STATUS_REMOVED
                # Parse out the video from the event description
                event.description = 'n/a'
                if item['description']:
                    self.parse_description(event, item['description'])
                event.short_description = item['short_description'] or ''
                # Add categories and tags
                event.save()
                for category in element.findall('category'):
                    domain = category.attrib['domain']
                    text = category.text
                    if domain == 'category' and not event.category:
                        cat, _ = Category.objects.get_or_create(name=text)
                        event.category = cat
                    else:
                        tag = text.lower().strip()
                        tag_add, _ = Tag.objects.get_or_create(name=tag)
                        event.tags.add(tag_add)
                # Add thumbnail and save
                thumbnail_id = 0
                for meta in element.findall('wp:postmeta',
                                            namespaces=self.nsmap):
                    meta_key, meta_val = meta.getchildren()
                    if meta_key.text == '_thumbnail_id':
                        thumbnail_id = meta_val.text
                if thumbnail_id in attachments:
                    self.attach_thumbnail(event, attachments[thumbnail_id])
                else:
                    self.attach_thumbnail(event)
                    self.stdout.write(
                        'No thumb found for %s, used default.\n' % event.slug
                    )
                event.save()
                self.stdout.write('Saved event %s\n' % event.slug)

    def extract_item(self, element, fields):
        """Returns a shortcut dictionary of element's children parsed
           according to fields (destination_key: source_child_tag)."""
        item = {}
        for name, tag in fields.iteritems():
            child = element.find(tag, namespaces=self.nsmap)
            try:
                item[name] = child.text.encode('utf-8').strip()
            except AttributeError:
                item[name] = None
        return item

    def parse_description(self, event, description_raw):
        """Parse out video embeds from the description, correctly set
           templates and their environments; leave descriptions clean."""
        vidly_tag = re.compile('\[vidly code="(\w+)?"\]')
        vidly_template = Template.objects.get(name='Vid.ly')
        ogg_tag = re.compile('<video src="([^"]*)".*?>')
        ogg_template = Template.objects.get(name='Ogg Video')

        event.description = description_raw
        vidly_search = vidly_tag.search(description_raw)
        ogg_search = ogg_tag.search(description_raw)
        if vidly_search:
            event.description = event.description.replace(
                vidly_search.group(0), ''
            )
            event.template = vidly_template
            event.template_environment = {'tag': vidly_search.group(1)}
        elif ogg_search:
            event.description = event.description.replace(
                ogg_search.group(0), ''
            )
            event.template = ogg_template
            event.template_environment = {'url': ogg_search.group(1)}
        else:
            event.status = Event.STATUS_REMOVED
        event.description = event.description.strip()

    def attach_thumbnail(self, event, url=None):
        """Download, cache, and attach an event's placeholder image."""
        if not url:
            # Use a default image, provided
            _, ext = os.path.splitext(self.default_thumb_path)
            img_temp = File(self.default_thumb)
        else:
            _, ext = os.path.splitext(url)
            cache_path = os.path.join(self.import_cache, event.slug) + ext
            try:
                # Read a cached image
                img_temp = File(
                    open(cache_path, 'rb')
                )
            except IOError:
                # Download and create the image
                img_temp = File(
                    open(cache_path, 'wb+')
                )
                img_temp.write(urllib2.urlopen(url).read())
                img_temp.flush()
        event.placeholder_img.save('img%s' % ext, img_temp)


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;

namespace SpecAid.Helper
{
    public static class AssemblyEntryFinderInUnitTests
    {
        // Because Assembly.GetEntryAssembly() doesn't work in UnitTests...
        public static Assembly Go()
        {
            var specAidAssembly = Assembly.GetExecutingAssembly();

            StackTrace stackTrace = new StackTrace();           // get call stack
            StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

            Assembly assembly = null;
            foreach (var stackFrame in stackFrames)
            {
                try
                {
                    var dType = stackFrame.GetMethod().DeclaringType;

                    if (dType == null)
                        continue;

                    assembly = dType.Assembly;

                    if (specAidAssembly.FullName != assembly.FullName)
                    {
                        return assembly;
                    }
                }
// ReSharper disable EmptyGeneralCatchClause
                catch
// ReSharper restore EmptyGeneralCatchClause
                {
                    // Throw away the exception...
                    // Either we have the assembly in the Stack or we don't...
                }
            }

            return assembly;
        }
    }
}


LongishDark Theme for Linux


struct PapayaMemory;
struct Profile;

enum PapayaUndoOp_ {
    PapayaUndoOp_Brush,
    PapayaUndoOp_COUNT
};

struct UndoData {
    // TODO: Convert into a union of structs once multiple types of undo ops are required
    u8 op_code; // Stores enum of type PapayaUndoOp_
    UndoData* prev, *next;
    Vec2i pos, size; // Position and size of the suffixed data block
    bool IsSubRect; // If true, then the suffixed image data contains two subrects - before and after the brush
    Vec2 line_segment_start_uv;
    // Image data goes after this
};

struct UndoBuffer {
    void* start;   // Pointer to beginning of undo buffer memory block // TODO: Change pointer types to i8*?
    void* top;     // Pointer to the top of the undo stack
    UndoData* base;    // Pointer to the base of the undo stack
    UndoData* current; // Pointer to the current location in the undo stack. Goes back and forth during undo-redo.
    UndoData* last;    // Last undo data block in the buffer. Should be located just before Top.
    size_t size;  // Size of the undo buffer in bytes
    size_t count;  // Number of undo ops in buffer
    size_t current_index; // Index of the current undo data block from the beginning
};

namespace undo {
    void init(PapayaMemory* mem);
    void destroy(PapayaMemory* mem);
    void push(UndoBuffer* undo, Profile* profile, Vec2i pos, Vec2i size,
              i8* pre_brush_img, Vec2 line_segment_start_uv);
    void pop(PapayaMemory* mem, bool load_pre_brush_image);
    void visualize_undo_buffer(PapayaMemory* mem);
}


/* Authenticating with Persona. */

api.onLoginRequired = function() {
    var R = Route.replace(), self = this;
    R["persona/page"]({ button: function(R) {
	R.$[0].onclick = function() {
	    navigator.id.get(function(assertion){
		self.AUTH('people/auth/persona', {assertion:assertion}, function(r){
		    Route.dispatch();
		});
	    },{
		siteName: i18n.title
	    });
	};
    }});
    R.show();
};


<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 336244 $ -->
<refentry xml:id="pdo.errorcode" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>PDO::errorCode</refname>
  <refpurpose>
   Fetch the SQLSTATE associated with the last operation on the database handle
  </refpurpose>
 </refnamediv>
 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <type>mixed</type><methodname>PDO::errorCode</methodname>
   <void/>
  </methodsynopsis>

 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   Returns an SQLSTATE, a five characters alphanumeric identifier defined in
   the ANSI SQL-92 standard.  Briefly, an SQLSTATE consists of a
   two characters class value followed by a three characters subclass value. A
   class value of 01 indicates a warning and is accompanied by a return code
   of SQL_SUCCESS_WITH_INFO. Class values other than '01', except for the
   class 'IM', indicate an error.  The class 'IM' is specific to warnings
   and errors that derive from the implementation of PDO (or perhaps ODBC,
   if you're using the ODBC driver) itself.  The subclass value '000' in any
   class indicates that there is no subclass for that SQLSTATE.
  </para>
  <para>
   <function>PDO::errorCode</function> only retrieves error codes for operations
   performed directly on the database handle. If you create a PDOStatement
   object through <function>PDO::prepare</function> or
   <function>PDO::query</function> and invoke an error on the statement
   handle, <function>PDO::errorCode</function> will not reflect that error.
   You must call <function>PDOStatement::errorCode</function> to return the error
   code for an operation performed on a particular statement handle.
  </para>
  <para>
   Returns &null; if no operation has been run on the database handle.
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example><title>Retrieving an SQLSTATE code</title>
    <programlisting role="php">
<![CDATA[
<?php
/* Provoke an error -- the BONES table does not exist */
$dbh->exec("INSERT INTO bones(skull) VALUES ('lucy')");

echo "\nPDO::errorCode(): ", $dbh->errorCode();
?>
]]>
    </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
PDO::errorCode(): 42S02
]]>
    </screen>
   </example>
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>PDO::errorInfo</function></member>
    <member><function>PDOStatement::errorCode</function></member>
    <member><function>PDOStatement::errorInfo</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


@class DBTEAMLOGShowcaseChangeEnabledPolicyDetails;
@class DBTEAMLOGShowcaseEnabledPolicy;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - API Object

///
/// The `ShowcaseChangeEnabledPolicyDetails` struct.
///
/// Enabled/disabled Dropbox Showcase for team.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGShowcaseChangeEnabledPolicyDetails : NSObject <DBSerializable, NSCopying>

#pragma mark - Instance fields

/// New Dropbox Showcase policy.
@property (nonatomic, readonly) DBTEAMLOGShowcaseEnabledPolicy *dNewValue;

/// Previous Dropbox Showcase policy.
@property (nonatomic, readonly) DBTEAMLOGShowcaseEnabledPolicy *previousValue;

#pragma mark - Constructors

///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param dNewValue New Dropbox Showcase policy.
/// @param previousValue Previous Dropbox Showcase policy.
///
/// @return An initialized instance.
///
- (instancetype)initWithDNewValue:(DBTEAMLOGShowcaseEnabledPolicy *)dNewValue
                    previousValue:(DBTEAMLOGShowcaseEnabledPolicy *)previousValue;

- (instancetype)init NS_UNAVAILABLE;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `ShowcaseChangeEnabledPolicyDetails` struct.
///
@interface DBTEAMLOGShowcaseChangeEnabledPolicyDetailsSerializer : NSObject

///
/// Serializes `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` instances.
///
/// @param instance An instance of the
/// `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` API object.
///
+ (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMLOGShowcaseChangeEnabledPolicyDetails *)instance;

///
/// Deserializes `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` API object.
///
/// @return An instantiation of the
/// `DBTEAMLOGShowcaseChangeEnabledPolicyDetails` object.
///
+ (DBTEAMLOGShowcaseChangeEnabledPolicyDetails *)deserialize:(NSDictionary<NSString *, id> *)dict;

@end

NS_ASSUME_NONNULL_END


Colocation API
==============
The colocation API wraps the [TransIP colocation SOAP service](https://api.transip.nl/wsdl/?service=ColocationService).

### General
The colocation API is available through the `Client` and can be accessed by calling `colocation()` or `api('colocation')`.

### Methods

#### Request access to the data-center.
````php
$visitors = [
    'Firstname Lastname',
];

$client->colocation()->requestAccess('2012-12-23 00:00:00', 60, $visitors, '+31612312399');
````

#### Request remote hands.
````php
$client->colocation()->requestRemoteHands('colocationFoo', 'Firstname Lastname', '+31612312399', 60, 'Instructions');
````

#### Get colocation names.
````php
$client->colocation()->getColocationNames();
````

#### Get active IP addresses for a colocation.
````php
$client->colocation()->getIpAddresses('colocationFoo');
````

#### Get IP ranges for a colocation.
````php
$client->colocation()->getIpRanges('colocationFoo');
````

#### Create a new ipv4 or ipv6 address.
````php
$client->colocation()->createIpAddress('127.0.0.1', '127.0.0.1.in-addr.arpa');
````

#### Delete an IP address.
````php
$client->colocation()->deleteIpAddress('127.0.0.1');
````

#### Get Reverse DNS for an IP address.
````php
$client->colocation()->getReverseDns('127.0.0.1');
````

#### Set Reverse DNS for an IP address.
````php
$client->colocation()->setReverseDns('127.0.0.1', '127.0.0.1.in-addr.arpa');
````


In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
  advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
  address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
  professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at david.herman@gmail.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org


<!DOCTYPE html >

          <meta http-equiv="X-UA-Compatible" content="IE=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
          <title>ScalaTest 3.0.6  - org.scalatest.enablers.Futuristic</title>
          <meta name="description" content="ScalaTest 3.0.6 - org.scalatest.enablers.Futuristic" />
          <meta name="keywords" content="ScalaTest 3.0.6 org.scalatest.enablers.Futuristic" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

        ScalaTest 3.0.6
        < Back

            <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
            
            

Packages

        

        package

        root

Definition Classes

root

        

        package

        org

Definition Classes

root

        

        package

        scalatest

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

Definition Classes

org

        

        package

        enablers

Definition Classes

scalatest

                        Aggregating

                        AggregatingHighPriorityImplicits

                        AggregatingImpls

                        AggregatingJavaImplicits

                        AggregatingStandardImplicits

                        CheckerAsserting

                        Collecting

                        Containing

                        ContainingHighPriorityImplicits

                        ContainingImpls

                        ContainingStandardImplicits

                        Definition

                        Emptiness

                        Existence

                        Futuristic

                        InspectorAsserting

                        JavaContainingImplicits

                        KeyMapping

                        Length

                        Messaging

                        Readability

                        Sequencing

                        Size

                        Sortable

                        TableAsserting

                        Timed

                        UnitCheckerAsserting

                        UnitInspectorAsserting

                        UnitTableAsserting

                        UnitWheneverAsserting

                        ValueMapping

                        WheneverAsserting

                        Writability

o

org.scalatest.enablers

Futuristic

        

            Companion trait Futuristic

        object

        Futuristic

Companion object for trait Futuristic that contains implicit Futuristic providers for
FutureOutcome and Future[T] for any type T.

Source

Futuristic.scala

            Linear Supertypes

AnyRef, Any

          

            <input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />

          

            Ordering

Alphabetic

By Inheritance

                  Inherited

Futuristic

AnyRef

Any

Hide All

Show All

              Visibility

Public

All

Value Members

        

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        

        def

        clone(): AnyRef

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @native()

                @throws(

      ...
    )

        

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        def

        finalize(): Unit

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        

        implicit
        def

        futuristicNatureOfFutureOf[V](implicit executionContext: ExecutionContext): Futuristic[Future[V]]

Provides a Futuristic value for Future[V] for any type V that performs cleanup using the
implicitly provided execution context.

Provides a Futuristic value for Future[V] for any type V that performs cleanup using the
implicitly provided execution context.

executionContext

an execution context that provides a strategy for executing the cleanup function

returns

a Futuristic instance for Future[V]

        

        implicit
        def

        futuristicNatureOfFutureOutcome(implicit executionContext: ExecutionContext): Futuristic[FutureOutcome]

Provides a Futuristic value for FutureOutcome that performs cleanup using the
implicitly provided execution context.

Provides a Futuristic value for FutureOutcome that performs cleanup using the
implicitly provided execution context.

executionContext

an execution context that provides a strategy for executing the cleanup function

returns

a Futuristic instance for FutureOutcome

        

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

Annotations

                @native()

        

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

Annotations

                @native()

        

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        final
        def

        notify(): Unit

Definition Classes

AnyRef

Annotations

                @native()

        

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

Annotations

                @native()

        

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        

        def

        toString(): String

Definition Classes

AnyRef → Any

        

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @native()

                @throws(

      ...
    )

Inherited from AnyRef

Inherited from Any

Ungrouped


<?php
/**
 *
 * @author Alberto 'alb-i986' Scotto
 */

#namespace BootstraPHPed;
#use BootstraPHPed\classes\Persistence;

/*
spl_autoload_register( function( $class ) {
	$class_filename = 'models/class-' . strtolower($class) . '.php';
	echo '<p>loading class '.$class_filename;
    require_once $class_filename;
});
*/

require_once './config.inc.php';

// sets the defaults for the constants that have not been defined in config.inc.php
if( !defined('DEBUG_MODE') )
	define( 'DEBUG_MODE', false );
if( !defined('HOSTNAME') )
	define( 'HOSTNAME', $_SERVER['HTTP_HOST'] );
if( !defined('URL_BASE') )
	define( 'URL_BASE', '/' );
if( !defined('SYSTEM_NAME') )
	define( 'SYSTEM_NAME', 'BootstraPHPed Web Site' );
if( !defined('WEBMASTER_NAME') )
	define( 'WEBMASTER_NAME', 'webmaster' );
if( !defined('WEBMASTER_EMAIL') )
	define( 'WEBMASTER_EMAIL', 'webmaster@'.HOSTNAME );
if( !defined('TZ') )
	define( 'TZ', 'Europe/Rome' );

// define some paths
define( 'ROOT_ABSPATH', realpath(__DIR__ . '/..') );	// absolute path of the root (not exposed by the web server)
define( 'PUBLIC_ROOT_ABSPATH', __DIR__ );			// absolute path of the public dir containing PHP scripts exposed by the web server
define( 'CLASS_PATH', ROOT_ABSPATH . '/classes/');
define( 'FORM_HANDLERS_RELPATH', './form_handlers/');
define( 'VIEWS_PATH', ROOT_ABSPATH.'/views/');
define( 'LOGS_PATH', ROOT_ABSPATH . '/logs/');

define( 'URL_HOME', 'http://'. $_SERVER['HTTP_HOST'] . URL_BASE);	// URL of the home page (useful for redirects)

// Now, require all the core PHP scripts

// 3rd party libraries
require_once ROOT_ABSPATH.'/lib/adodb5/adodb.inc.php';
require_once ROOT_ABSPATH.'/lib/log4php/Logger.php';
require_once ROOT_ABSPATH.'/lib/phpass-0.3/PasswordHash.php';

// CLASSES imports

// EXCEPTIONS
require_once CLASS_PATH.'class-exception-adodb.php';
require_once CLASS_PATH.'class-exception-illegal-object-state.php';
require_once CLASS_PATH.'class-exception-validation.php';

require_once CLASS_PATH.'models/class-dao_core.php';
require_once CLASS_PATH.'models/class-dao.php';
// MODELS
require_once CLASS_PATH.'models/class-model.php';
	// ELEMENTS
	require_once CLASS_PATH.'models/class-element.php';
		//require_once CLASS_PATH.'models/class-role.php';
		require_once CLASS_PATH.'models/class-user.php';
		//require_once CLASS_PATH.'models/class-post.php';
	// COLLECTIONS
	//require_once CLASS_PATH.'models/class-collection.php';
	//	require_once CLASS_PATH.'models/class-users.php';

require_once './session.inc.php';

$dao = DAO::getInstance();

// default exception handler
set_exception_handler( function($ex) {
	if( DEBUG_MODE == true )
		$msg = nl2br("Uncaught exception:\n" . $ex->getMessage() . "\n". $ex->getTraceAsString() . "\n");
	else
		$msg = nl2br("Uncaught exception:\n" . $ex->getMessage() . "\n");
	showErr(0, $msg);
});

date_default_timezone_set(TZ);


/*Jeu du pendu réalisé par Romain Dauby*/

#ifndef FCT_H_INCLUDED
#define FCT_H_INCLUDED

int cpt;

char lireCaractere();
void afficherCoups(int cpt);
char proposezLettre();
void afficherMotSecret(int *table, const char *table2);
void initialiser_motTrouve(int *table, int taille);
void testLettre(char lettre, int *table1, const char *table2);
int testGagne(int *motTrouve, const char *motSecret);

#endif // FCT_H_INCLUDED


#nullable enable
namespace Gu.Reactive
{
    using System;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Linq.Expressions;

    /// <summary>
    /// Factory methods for creating trackers for max value.
    /// </summary>
    public static class MaxTracker
    {
        /// <summary>
        /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/>
        /// </summary>
        /// <typeparam name="TItem">The type of the items in <paramref name="source"/></typeparam>
        /// <typeparam name="TValue">The type of the max value.</typeparam>
        /// <param name="source">The source collection.</param>
        /// <param name="selector">The function used when producing a value from an item.</param>
        /// <returns>A tracker with Value synced with source.Max()</returns>
        public static MaxTracker<TValue> TrackMax<TItem, TValue>(this ObservableCollection<TItem> source, Expression<Func<TItem, TValue>> selector)
            where TItem : class, INotifyPropertyChanged
            where TValue : struct, IComparable<TValue>
        {
            return new MaxTracker<TValue>(new NestedChanges<ObservableCollection<TItem>, TItem, TValue>(source, selector));
        }

        /// <summary>
        /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/>
        /// </summary>
        /// <typeparam name="TValue">The type of the max value.</typeparam>
        /// <param name="source">The source collection.</param>
        /// <returns>A tracker with Value synced with source.Max()</returns>
        public static MaxTracker<TValue> TrackMax<TValue>(this ObservableCollection<TValue> source)
            where TValue : struct, IComparable<TValue>
        {
            return new MaxTracker<TValue>(new SimpleChanges<ObservableCollection<TValue>, TValue>(source));
        }

        /// <summary>
        /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/>
        /// </summary>
        /// <typeparam name="TItem">The type of the items in <paramref name="source"/></typeparam>
        /// <typeparam name="TValue">The type of the max value.</typeparam>
        /// <param name="source">The source collection.</param>
        /// <param name="selector">The function used when producing a value from an item.</param>
        /// <returns>A tracker with Value synced with source.Max()</returns>
        public static MaxTracker<TValue> TrackMax<TItem, TValue>(this ReadOnlyObservableCollection<TItem> source, Expression<Func<TItem, TValue>> selector)
            where TItem : class, INotifyPropertyChanged
            where TValue : struct, IComparable<TValue>
        {
            return new MaxTracker<TValue>(new NestedChanges<ReadOnlyObservableCollection<TItem>, TItem, TValue>(source, selector));
        }

        /// <summary>
        /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/>
        /// </summary>
        /// <typeparam name="TValue">The type of the max value.</typeparam>
        /// <param name="source">The source collection.</param>
        /// <returns>A tracker with Value synced with source.Max()</returns>
        public static MaxTracker<TValue> TrackMax<TValue>(this ReadOnlyObservableCollection<TValue> source)
            where TValue : struct, IComparable<TValue>
        {
            return new MaxTracker<TValue>(new SimpleChanges<ReadOnlyObservableCollection<TValue>, TValue>(source));
        }

        /// <summary>
        /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/>
        /// </summary>
        /// <typeparam name="TItem">The type of the items in <paramref name="source"/></typeparam>
        /// <typeparam name="TValue">The type of the max value.</typeparam>
        /// <param name="source">The source collection.</param>
        /// <param name="selector">The function used when producing a value from an item.</param>
        /// <returns>A tracker with Value synced with source.Max()</returns>
        public static MaxTracker<TValue> TrackMax<TItem, TValue>(this IReadOnlyObservableCollection<TItem> source, Expression<Func<TItem, TValue>> selector)
            where TItem : class, INotifyPropertyChanged
            where TValue : struct, IComparable<TValue>
        {
            return new MaxTracker<TValue>(new NestedChanges<IReadOnlyObservableCollection<TItem>, TItem, TValue>(source, selector));
        }

        /// <summary>
        /// Creates a <see cref="MaxTracker{TValue}"/> for <paramref name="source"/>
        /// </summary>
        /// <typeparam name="TValue">The type of the max value.</typeparam>
        /// <param name="source">The source collection.</param>
        /// <returns>A tracker with Value synced with source.Max()</returns>
        public static MaxTracker<TValue> TrackMax<TValue>(this IReadOnlyObservableCollection<TValue> source)
            where TValue : struct, IComparable<TValue>
        {
            return new MaxTracker<TValue>(new SimpleChanges<IReadOnlyObservableCollection<TValue>, TValue>(source));
        }
    }
}


package com.jetbrains.python.inspections;

import com.jetbrains.python.fixtures.PyInspectionTestCase;
import org.jetbrains.annotations.NotNull;

public class PyTypedDictInspectionTest extends PyInspectionTestCase {

  public void testUnknownKey() {
    doTestByText("from typing import TypedDict\n" +
                 "class Movie(TypedDict, total=False):\n" +
                 "    name: str\n" +
                 "    year: int\n" +
                 "Movie2 = TypedDict('Movie2', {'name': str, 'year': int}, total=False)\n" +
                 "movie = Movie2(name='Blade Runner')\n" +
                 "movie2 = Movie2(name='Blade Runner')\n" +
                 "movie['year'] = 42\n" +
                 "movie2['year'] = 42\n" +
                 "movie[<warning descr=\"TypedDict \\\"Movie2\\\" has no key 'id'\">'id'</warning>] = 43\n" +
                 "movie2[<warning descr=\"TypedDict \\\"Movie2\\\" has no key 'id'\">'id'</warning>] = 43\n");
  }

  public void testMetaclass() {
    doTestByText("from typing import TypedDict\n" +
                 "\n" +
                 "class Movie(TypedDict, <warning descr=\"Specifying a metaclass is not allowed in TypedDict\">metaclass=Meta</warning>):\n" +
                 "    name: str");
  }

  public void testExtraClassDeclarations() {
    doTestByText("from typing import TypedDict\n" +
                 "class Movie(TypedDict):\n" +
                 "    name: str\n" +
                 "    def <weak_warning descr=\"Invalid statement in TypedDict definition; expected 'field_name: field_type'\">my_method</weak_warning>(self):\n" +
                 "        pass\n" +
                 "    class <weak_warning descr=\"Invalid statement in TypedDict definition; expected 'field_name: field_type'\">Horror</weak_warning>:\n" +
                 "        def __init__(self):\n" +
                 "            ...");
  }

  public void testInitializer() {
    doTestByText("from typing import TypedDict\n" +
                 "class Movie(TypedDict):\n" +
                 "    name: str\n" +
                 "    year: int = <warning descr=\"Right-hand side values are not supported in TypedDict\">42</warning>");
  }

  public void testPass() {
    doTestByText("from typing import TypedDict\n" +
                 "class Movie(TypedDict):\n" +
                 "    <weak_warning descr=\"Invalid statement in TypedDict definition; expected 'field_name: field_type'\">...</weak_warning>\n" +
                 "class HorrorMovie(TypedDict):\n" +
                 "    pass");
  }

  public void testNonTypedDictAsSuperclass() {
    doTestByText("from typing import TypedDict, NamedTuple\n" +
                 "class Bastard:\n" +
                 "    pass\n" +
                 "class X(TypedDict):\n" +
                 "    x: int\n" +
                 "class Y(TypedDict):\n" +
                 "    y: str\n" +
                 "class XYZ(X, <warning descr=\"TypedDict cannot inherit from a non-TypedDict base class\">Bastard</warning>):\n" +
                 "    z: bool\n" +
                 "class MyNT(NamedTuple):\n" +
                 "    a: str");
  }

  public void testNameAndVariableNameDoNotMatch() {
    doTestByText("from typing import TypedDict\n" +
                 "Movie2 = TypedDict(<warning descr=\"First argument has to match the variable name\">'Movie'</warning>, {'name': str, 'year': int}, total=False)");
  }

  public void testKeyTypesAlternativeSyntax() {
    doTestByText("from typing import TypedDict, Any, Optional\n" +
                 "Movie = TypedDict('Movie', {'name': Optional[int], 'smth': type, 'smthElse': Any, 'year': <weak_warning descr=\"Value must be a type\">2</weak_warning>}, total=False)");
  }

  public void testKeyTypes() {
    doTestByText("from typing import TypedDict, Any, Optional\n" +
                 "class Movie(TypedDict):\n" +
                 "    name: Optional[int]\n" +
                 "    smth: type\n" +
                 "    smthElse: Any\n" +
                 "    year: <weak_warning descr=\"Value must be a type\">2</weak_warning>");
  }

  public void testFinalKey() {
    doTestByText("from typing import TypedDict, Final\n" +
                 "class Movie(TypedDict):\n" +
                 "    name: str\n" +
                 "    year: int\n" +
                 "YEAR: Final = 'year'\n" +
                 "m = Movie(name='Alien', year=1979)\n" +
                 "years_since_epoch = m[YEAR] - 1970");
  }

  public void testStringVariableAsKey() {
    doTestByText("from typing import TypedDict, Final\n" +
                 "class Movie(TypedDict):\n" +
                 "    name: str\n" +
                 "    year: int\n" +
                 "year = 'year'\n" +
                 "year2 = year\n" +
                 "m = Movie(name='Alien', year=1979)\n" +
                 "years_since_epoch = m[year2] - 1970\n" +
                 "year = 42\n" +
                 "print(m[<warning descr=\"TypedDict key must be a string literal; expected one of ('name', 'year')\">year</warning>])");
  }

  public void testDelStatement() {
    doTestByText("from typing import TypedDict\n" +
                 "class Movie(TypedDict):\n" +
                 "    name: str\n" +
                 "    year: int\n" +
                 "class HorrorMovie(Movie, total=False):\n" +
                 "    based_on_book: bool\n" +
                 "year = 'year'\n" +
                 "year2 = year\n" +
                 "m = HorrorMovie(name='Alien', year=1979)\n" +
                 "del (m['based_on_book'], m[<warning descr=\"Key 'name' of TypedDict 'HorrorMovie' cannot be deleted\">'name'</warning>])\n" +
                 "del m[<warning descr=\"Key 'year' of TypedDict 'HorrorMovie' cannot be deleted\">year2</warning>], m['based_on_book']");
  }

  public void testDictModificationMethods() {
    doTestByText("from typing import TypedDict\n" +
                 "class Movie(TypedDict):\n" +
                 "    name: str\n" +
                 "    year: int\n" +
                 "class Horror(Movie, total=False):\n" +
                 "    based_on_book: bool\n" +
                 "m = Horror(name='Alien', year=1979)\n" +
                 "m.<warning descr=\"This operation might break TypedDict consistency\">clear</warning>()\n" +
                 "name = 'name'\n" +
                 "m.pop('based_on_book')\n" +
                 "m.<warning descr=\"Key 'year' of TypedDict 'Horror' cannot be deleted\">pop</warning>('year')\n" +
                 "m.<weak_warning descr=\"This operation might break TypedDict consistency\">popitem</weak_warning>()\n" +
                 "m.setdefault('based_on_book', <warning descr=\"Expected type 'bool', got 'int' instead\">42</warning>)");
  }

  public void testUpdateMethods() {
    doTestByText("from typing import TypedDict, Optional\n" +
                 "class Movie(TypedDict):\n" +
                 "    name: str\n" +
                 "    year: Optional[int]\n" +
                 "class Horror(Movie, total=False):\n" +
                 "    based_on_book: bool\n" +
                 "m = Horror(name='Alien', year=1979)\n" +
                 "d={'name':'Garden State', 'year':2004}\n" +
                 "m.update(d)\n" +
                 "m.update({'name':'Garden State', 'year':<warning descr=\"Expected type 'int | None', got 'str' instead\">'2004'</warning>, <warning descr=\"TypedDict \\\"Horror\\\" cannot have key 'based_on'\">'based_on'</warning>: 'book'})\n" +
                 "m.update(name=<warning descr=\"Expected type 'str', got 'int' instead\">1984</warning>, year=1984, based_on_book=<warning descr=\"Expected type 'bool', got 'str' instead\">'yes'</warning>)\n" +
                 "m.update([('name',<warning descr=\"Expected type 'str', got 'int' instead\">1984</warning>), ('year',None)])");
  }

  public void testDocString() {
    doTestByText("from typing import TypedDict\n" +
                 "class Cinema(TypedDict):\n" +
                 "    \"\"\"\n" +
                 "        It's doc string\n" +
                 "    \"\"\"");
  }

  public void testFieldOverwrittenByInheritance() {
    doTestByText("from typing import TypedDict\n" +
                 "class X(TypedDict):\n" +
                 "    y: int\n" +
                 "class Y(TypedDict):\n" +
                 "    y: str\n" +
                 "class XYZ<warning descr=\"Cannot overwrite TypedDict field 'y' while merging\">(X, Y)</warning>:\n" +
                 "    <warning descr=\"Cannot overwrite TypedDict field\">y</warning>: bool");
  }

  public void testIncorrectTypedDictArguments() {
    doTestByText("from typing import TypedDict\n" +
                 "c = TypedDict(\"c\", [1, 2, 3])");
  }

  public void testTypedDictNonStringKey() {
    doTestByText("from typing import TypedDict\n" +
                 "Movie = TypedDict('Movie', {'name': str, 'year': int}, total=False)\n" +
                 "class Movie2(TypedDict, total=False):\n" +
                 "    name: str\n" +
                 "    year: int\n" +
                 "movie = Movie()\n" +
                 "movie2 = Movie2()\n" +
                 "movie[<warning descr=\"TypedDict key must be a string literal; expected one of ('name', 'year')\">2</warning>]\n" +
                 "movie2[<warning descr=\"TypedDict key must be a string literal; expected one of ('name', 'year')\">2</warning>]");
  }

  public void testTypedDictKeyValueWrite() {
    doTestByText("from typing import TypedDict\n" +
                 "Movie = TypedDict('Movie', {'name': str, 'year': int}, total=False)\n" +
                 "class Movie2(TypedDict, total=False):\n" +
                 "    name: str\n" +
                 "    year: int\n" +
                 "movie = Movie()\n" +
                 "movie2 = Movie2()\n" +
                 "movie['year'], movie2['year'] = <warning descr=\"Expected type 'int', got 'str' instead\">'1984'</warning>, " +
                 "<warning descr=\"Expected type 'int', got 'str' instead\">'1984'</warning>\n");
  }

  public void testTypedDictKeyValueWriteToTypedDictField() {
    doTestByText("from typing import TypedDict\n" +
                 "X = TypedDict('X', {'d': dict}, total=False)\n" +
                 "class X2(TypedDict, total=False):\n" +
                 "    d: dict\n" +
                 "x = X()\n" +
                 "x2 = X2()\n" +
                 "x['d']['k'], x2['d']['k'] = 'v', 'v'");
  }

  public void testIncorrectTotalityValue() {
    doTestByText("from typing import TypedDict\n" +
                 "class X(TypedDict, total=<warning descr=\"Value of 'total' must be True or False\">1</warning>):\n" +
                 "    x: int\n");
  }

  public void testIncorrectTotalityValueAlternativeSyntax() {
    doTestByText("from typing import TypedDict\n" +
                 "X = TypedDict('X', {'x': int}, total=<warning descr=\"Value of 'total' must be True or False\">1</warning>)");
  }

  public void testGetWithIncorrectKeyType() {
    doTestByText("from typing import TypedDict\n" +
                 "class X(TypedDict):\n" +
                 "    x: int\n" +
                 "x = X()\n" +
                 "x.get(<warning descr=\"Key should be string\">42</warning>, 67)");
  }

  public void testGetWithIncorrectKeyValue() {
    doTestByText("from typing import TypedDict\n" +
                 "class X(TypedDict):\n" +
                 "    x: int\n" +
                 "x = X()\n" +
                 "x.get(<warning descr=\"TypedDict \\\"X\\\" has no key 'y'\">'y'</warning>, 67)\n" +
                 "x.get('x', '')");
  }

  // PY-39404
  public void testImportedTypedDict() {
    doMultiFileTest();
  }

  // PY-40906
  public void testLiteralAsTypedDictKey() {
    doTestByText("from typing import TypedDict, Literal, Union\n" +
                 "class Movie(TypedDict):\n" +
                 "    name: str\n" +
                 "    year: int\n" +
                 "def get_value(movie: Movie, key: Literal['year', 'name']) -> Union[int, str]:\n" +
                 "    return movie[key]\n" +
                 "def get_value(movie: Movie, key: Literal['name']) -> Union[int, str]:\n" +
                 "    return movie[key]\n" +
                 "def get_value(movie: Movie, key: Literal['name1']) -> Union[int, str]:\n" +
                 "    return movie[<warning descr=\"TypedDict \\\"Movie\\\" has no key 'name1'\">key</warning>]\n" +
                 "def get_value(movie: Movie, key: Literal['year', 42]) -> Union[int, str]:\n" +
                 "    return movie[<warning descr=\"TypedDict key must be a string literal; expected one of ('name', 'year')\">key</warning>]\n" +
                 "def get_value(movie: Movie, key: Literal['year', 'name1', '42']) -> Union[int, str]:\n" +
                 "    return movie[<warning descr=\"TypedDict \\\"Movie\\\" has no keys ('name1', '42')\">key</warning>]\n" +
                 "def get_value(movie: Movie, key: Literal[42]) -> Union[int, str]:\n" +
                 "    return movie[<warning descr=\"TypedDict key must be a string literal; expected one of ('name', 'year')\">key</warning>]");
  }

  // PY-44714
  public void testNoneAsType() {
    doTestByText("from typing import TypedDict\n" +
                 "class X(TypedDict):\n" +
                 "    n: None\n" +
                 "Y = TypedDict('Y', {'n': None})\n");
  }

  @NotNull
  @Override
  protected Class<? extends PyInspection> getInspectionClass() {
    return PyTypedDictInspection.class;
  }
}


from __future__ import unicode_literals

import unittest
import sys

from bibtexparser.bparser import BibTexParser
from bibtexparser.bwriter import BibTexWriter, to_bibtex
from bibtexparser.customization import author

class TestBibtexWriterList(unittest.TestCase):

    ###########
    # ARTICLE
    ###########
    def test_article(self):
        with open('bibtexparser/tests/data/article.bib', 'r') as bibfile:
            bib = BibTexParser(bibfile.read())

        with open('bibtexparser/tests/data/article_output.bib', 'r') as bibfile:
            expected = bibfile.read()
        result = to_bibtex(bib)
        if not sys.version_info >= (3, 0):
            if isinstance(result, unicode):
                result = result.encode('utf-8')
        self.maxDiff = None
        self.assertEqual(expected, result)

    ###########
    # BOOK
    ###########
    def test_book(self):
        with open('bibtexparser/tests/data/book.bib', 'r') as bibfile:
            bib = BibTexParser(bibfile.read())

        with open('bibtexparser/tests/data/book_output.bib', 'r') as bibfile:
            expected = bibfile.read()
        result = to_bibtex(bib)
        self.maxDiff = None
        self.assertEqual(expected, result)

    ###########
    # COMMA FIRST
    ###########
    def test_comma_first(self):
        with open('bibtexparser/tests/data/book.bib', 'r') as bibfile:
            bib = BibTexParser(bibfile.read())

        with open('bibtexparser/tests/data/book_comma_first.bib', 'r') as bibfile:
            expected = bibfile.read()
        writer = BibTexWriter()
        writer.indent = '   '
        writer.comma_first = True
        result = writer.write(bib)
        self.maxDiff = None
        self.assertEqual(expected, result)

    ###########
    # MULTIPLE
    ###########
    def test_multiple(self):
        with open('bibtexparser/tests/data/multiple_entries.bib', 'r') as bibfile:
            bib = BibTexParser(bibfile.read())

        with open('bibtexparser/tests/data/multiple_entries_output.bib', 'r') as bibfile:
            expected = bibfile.read()
        result = to_bibtex(bib)
        self.maxDiff = None
        self.assertEqual(expected, result)

    ###########
    # Exception
    ###########
    def test_exception_typeerror(self):
        with open('bibtexparser/tests/data/article.bib', 'r') as bibfile:
            bib = BibTexParser(bibfile.read(), customization=author)
        self.assertRaises(TypeError, to_bibtex, bib)


<?php

namespace Taskeet\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * EventCategory
 *
 * @ORM\Table(name="event_category")
 * @ORM\Entity
 * @Vich\Uploadable
 */
class EventCategory
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=32)
     */
    private $name;

    /**
     * @Assert\File(
     *     maxSize="1M",
     *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
     * )
     * @Vich\UploadableField(mapping="event_image", fileNameProperty="imageName")
     *
     * @var File $image
     */
    private $image;

    /**
     * @var string
     *
     * @ORM\Column(name="imageName", type="string", length=255)
     */
    private $imageName;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return EventCategory
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param \Symfony\Component\HttpFoundation\File\File $image
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * @return \Symfony\Component\HttpFoundation\File\File
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set imageName
     *
     * @param string $imageName
     * @return EventCategory
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;

        return $this;
    }

    /**
     * Get imageName
     *
     * @return string
     */
    public function getImageName()
    {
        return $this->imageName;
    }

    public function __toString()
    {
        return $this->name;
    }
}


package chapter.sixteen

import ExerciseOne._

import org.scalatest._
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith

@RunWith(classOf[JUnitRunner])
class ExerciseOneSpec extends FlatSpec with Matchers {

  "function" should "" in {
  }
}


{% extends "layout/default.html" %}

{% set active_page = 'events' %}

{% block title %}
  Events{{ super() }}
{% endblock %}

{% block main_body %}

      Upcoming events and presentations

	    26 October 2016, "Speech presentation in 19th century literature: A hands-on approach" as part of the CCR Corpus Training Sessions, Johan de Joode

		1 November 2016, Michaela Mahlberg will deliver a keynote at the Cardiff Digital Cultures Network

	    30 November 2016, "Discourse and dialogue: Annotating and aggregating corpus data" as part of the CCR Corpus Training Sessions, Johan de Joode

      Past events and presentations

		 16-18 September 2016, Michaela Mahlberg gave a keynote at the  American Association for Corpus Linguistics (AACL) Conference

4 July 2016, CLiC Workshop at University of Kent

20-24 June 2016 Corpus Linguistics Summer School at CCR

20 June 2016 Michaela Mahlberg delivers 11th Annual Sinclair Lecture:
You can watch a video of the lecture here.

4 June 2016 - Hay Festival, University of Birmingham series, ‘Hot off the press’ John Holmes, Michaela Mahlberg and Will Tattersdill

14 March 2016, CLiC Workshop for the Schools Partnership Gateway, ‘Corpus Stylistics for the English Classroom’, University of Nottingham

16 November 2015, CLiC Workshop hosted jointly organised the CCR and AQA, ‘Corpus Stylistics for A-level Teachers’ – see here for a review

12 November 2015, Advanced CLiC – User-defined annotation, Centre for Advanced Research in English, Johan de Joode

29 October 2015, Using CLiC to study literature, Centre for Advanced Research in English, Johan de Joode

    {% include "blocks/twitter.html" %}

{% endblock %}

{% block scripts %}
  {{ super() }}
{% endblock %}


/*
 * drop the SQL schema used by org.apache.slide.impl.rdbms.PostgresAdapter.
 * Tested with Postgres 7.4.
 *
 */

DROP VIEW LOCKS_VIEW;
DROP VIEW PERMISSIONS_VIEW;
DROP VIEW BINDING_VIEW;
DROP VIEW OBJECT_VIEW;
DROP TABLE PROPERTIES;
DROP TABLE VERSION_CONTENT;
DROP TABLE VERSION_PREDS;
DROP TABLE VERSION_LABELS;
DROP TABLE VERSION_HISTORY;
DROP TABLE VERSION;
DROP TABLE BINDING;
DROP TABLE PARENT_BINDING;
DROP TABLE LINKS;
DROP TABLE LOCKS;
DROP TABLE BRANCH;
DROP TABLE LABEL;
DROP TABLE PERMISSIONS;
DROP TABLE OBJECT;
DROP TABLE URI;


var fs = require('fs');
var gdal = require('gdal');
var in_file = process.argv[2];
var out_base_name = process.argv[3];
var ds = gdal.open(in_file);
var wgs84 = gdal.SpatialReference.fromEPSG(4326);

gdal.verbose();
gdal.config.set('CPL_DEBUG', 'ON');
gdal.config.set('CPL_LOG_ERRORS', 'ON');

ds.layers.forEach(function (lyr) {
	console.log('processing: ', lyr.name);
	var lyr_name = lyr.name.replace(':', ''); //strip invalid filename characters
	var out_name = out_base_name + '_' + lyr_name + '.geojson';
	if (fs.existsSync(out_name)) { fs.unlink(out_name);}
	var out_ds = gdal.open(out_name, 'w', 'GeoJSON');
	var geojson = out_ds.layers.create(lyr_name, wgs84, lyr.geomType);
	lyr.features.forEach(function (in_feat) {
		geojson.features.add(in_feat);
	})
	geojson.flush();
	out_ds.flush();
	out_ds.close();
});