text:
package och.util.servlet;

import static och.util.Util.*;
import static och.util.servlet.WebUtil.*;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class BaseI18nFilter extends BaseFilter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	protected void doFilter(HttpServletRequest req, HttpServletResponse resp,
			FilterChain chain) throws IOException, ServletException {

		String paramLang = req.getParameter("lang");
		String cookieLang = getCookieVal(req, "lang");

		String lang = paramLang;
		if( ! hasText(lang)) lang = cookieLang;
		if( ! hasText(lang)) lang = getDefaultLang();

		if( hasText(lang) && ! lang.equals(cookieLang)){
			resp.addCookie(cookieForYear("lang", lang, false));
		}

		req.setAttribute("lang", lang);

		beforeChain(req, resp, lang);
		try {
			chain.doFilter(req, resp);
		} finally {
			afterChain(req, resp, lang);
		}

	}

	protected String getDefaultLang() {
		return null;
	}

	/**
	 * @param lang - can be null
	 */
	protected void beforeChain(HttpServletRequest req, HttpServletResponse resp, String lang) {}

	/**
	 * @param lang - can be null
	 */
	protected void afterChain(HttpServletRequest req, HttpServletResponse resp, String lang) {}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="OptimLib: a C++ numerical optimization library.">
    <meta name="author" content="Keith O'Hara">

    <meta name="keywords" content="Optimization, C++, C++11, Differential Evolution, Particle Swarm Optimization, Root Finding, OpenMP, Parallel Optimization, BFGS, L-BFGS, Keith O'Hara, Economics, Econometrics, Research, NYU, New York University" />

    <link rel="shortcut icon" type="image/x-icon" href="siteicon.ico">

    <title>OptimLib: Conjugate Gradient</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <link href="css/kthohr_settings.css" rel="stylesheet">

    <link type="text/css" rel="stylesheet" href="css/swift_theme.css">

OptimLib: Conjugate Gradient

                    Definition

                    Details

                    Examples

The Nonlinear Conjugate Gradient (CG) method generalizes its linear namesake to a broader class of convex optimization problems.

Definition and Syntax

bool cg(arma::vec& init_out_vals, std::function<double (const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)> opt_objfn, void* opt_data);
bool cg(arma::vec& init_out_vals, std::function<double (const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)> opt_objfn, void* opt_data, algo_settings_t& settings);

Function arguments:

init_out_vals a column vector of initial values; will be replaced by the solution values.

opt_objfn the function to be minimized, taking three arguments:

vals_inp a vector of inputs;

grad_out a vector to store the gradient; and

opt_data additional parameters passed to the function.

opt_data additional parameters passed to the function.

settings parameters controlling the optimization routine; see below.

Optimization control parameters:

double err_tol the tolerance value controlling how small $\| \nabla f \|$ should be before 'convergence' is declared.

int iter_max the maximum number of iterations/updates before the algorithm exits.

bool vals_bound whether the search space is bounded. If true, then

arma::vec lower_bounds this defines the lower bounds.

arma::vec upper_bounds this defines the upper bounds.

int cg_method which updating formula to use; see the details section below.

double cg_restart_threshold the value $\nu$ in the details section below.

Details

Let $x^{(i)}$ denote the function input values at stage $i$ of the algorithm. The Nonlinear Conjugate Gradient updating rule is as follows.

The descent direction is computed using
        $$d_i = - \nabla f_{i} + \beta_i \times d_{i-1}$$
    where $\beta$ is calculated using one of several updating rules below, depending on the value cg_method.

The Nonlinear CG method is known to perform better with periodic restarting (setting $\beta = 0$). In OptimLib, this occurs when

    $$\dfrac{|\nabla f_i \cdot \nabla f_{i-1}|}{\nabla f_{i} \cdot \nabla f_{i}} > \nu$$

The values are then updated:
            $$x^{(i+1)} = x^{(i)} + \alpha^{(i)} d^{(i)}$$
        where $\alpha^{(i)}$ is found via line search:
            $$\alpha^{(i)} = \arg \min_\alpha f(x^{(i)} + \alpha d^{(i)})$$
        The line search method used in OptimLib is that of More and Thuente (1994).

The algorithm stops when $\| \nabla f \|$ is less than err_tol, or the total number of iterations exceeds iter_max.

Updating Formula:

cg_method = 1 Fletcher–Reeves (FR):

        $$\beta_{\text{FR}} = \dfrac{\nabla f_i \cdot \nabla f_i}{\nabla f_{i-1} \cdot \nabla f_{i-1}}$$

cg_method = 2 Polak-Ribiere (PR) '+':

        $$\beta_{\text{PR+}} = \max \left\{ 0 , \dfrac{\nabla f_i \cdot (\nabla f_i - \nabla f_{i-1})}{\nabla f_{i-1} \cdot \nabla f_{i-1}} \right\}$$

cg_method = 3 FR-PR Hybrid:

        $$\beta = \begin{cases}
            - \beta_{\text{FR}} & \text{ if } \beta_{\text{PR}} < - \beta_{\text{FR}} \\
              \beta_{\text{PR}} & \text{ if } |\beta_{\text{PR}}| \leq \beta_{\text{FR}} \\
              \beta_{\text{FR}} & \text{ if } \beta_{\text{PR}} > \beta_{\text{FR}}
        \end{cases}$$

cg_method = 4 Hestenes-Stiefel:

        $$\beta_{\text{HS}} = \dfrac{\nabla f_i \cdot (\nabla f_i - \nabla f_{i-1})}{(\nabla f_{i} - \nabla f_{i-1}) \cdot d_i}$$

cg_method = 5 Dai-Yuan:

        $$\beta_{\text{DY}} = \dfrac{\nabla f_i \cdot \nabla f_i}{(\nabla f_{i} - \nabla f_{i-1}) \cdot d_i}$$

cg_method = 6 Hager-Zhang:

        $$\beta_{\text{HZ}} = \left( y - 2 \times \dfrac{y \cdot y}{y \cdot d} \times d \right) \cdot \dfrac{\nabla f_i}{y \cdot d}, \ \ \ y := \nabla f_i - \nabla f_{i-1}$$

Examples

As examples, consider minimization of:

the Sphere function
    $$\min_{x \in \mathbb{R}^n} \sum_{i=1}^n x_i^2$$
    The solution is the zero vector

Booth's function
    $$\min_{x \in [-10,10]^2} \left\{ (x_1 + 2x_2 - 7)^2 + (2 x_1 + x_2 - 5)^2 \right\}$$
    The global minimum is located at $(1,3)$.

Below are plots of each example, restricted to the two-dimensional problem where relevant.

Sphere

Booth

Code solving each example using OptimLib is given below.

#include "optim.hpp"

double sphere_fn(const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)
{
    double obj_val = arma::dot(vals_inp,vals_inp);
    //
    if (grad_out) {
        *grad_out = 2.0*vals_inp;
    }
    //
    return obj_val;
}

double booth_fn(const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)
{
    double x_1 = vals_inp(0);
    double x_2 = vals_inp(1);

    double obj_val = std::pow(x_1 + 2*x_2 - 7.0,2) + std::pow(2*x_1 + x_2 - 5.0,2);
    //
    if (grad_out) {
        (*grad_out)(0) = 2*(x_1 + 2*x_2 - 7.0) + 2*(2*x_1 + x_2 - 5.0)*2;
        (*grad_out)(1) = 2*(x_1 + 2*x_2 - 7.0)*2 + 2*(2*x_1 + x_2 - 5.0);
    }
    //
    return obj_val;
}

int main()
{
    //
    // sphere function

    const int test_dim = 5;

    arma::vec x = arma::ones(test_dim,1); // initial values (1,1,...,1)

    bool success = optim::cg(x,sphere_fn,nullptr);

    if (success) {
        std::cout << "cg: sphere test completed successfully." << std::endl;
    } else {
        std::cout << "cg: sphere test completed unsuccessfully." << std::endl;
    }

    arma::cout << "cg: solution to sphere test:\n" << x << arma::endl;

    //
    // Booth function

    arma::vec x_2 = arma::zeros(2,1) + 2; // initial values (2,2)

    bool success_2 = optim::cg(x,booth_fn,nullptr);

    if (success_2) {
        std::cout << "cg: Booth test completed successfully." << std::endl;
    } else {
        std::cout << "cg: Booth test completed unsuccessfully." << std::endl;
    }

    arma::cout << "cg: solution to Booth test:\n" << x_2 << arma::endl;

    return 0;
}

redpajama_set_name: RedPajamaGithub


text:
\documentclass[DIV16,twocolumn,10pt]{scrreprt}
\usepackage{paralist}
\usepackage{graphicx}
\usepackage[final]{hcar}

%% ODER: format ==         = "\mathrel{==}"
%% ODER: format /=         = "\neq "
%
%
\makeatletter
\@ifundefined{lhs2tex.lhs2tex.sty.read}%
  {\@namedef{lhs2tex.lhs2tex.sty.read}{}%
   \newcommand\SkipToFmtEnd{}%
   \newcommand\EndFmtInput{}%
   \long\def\SkipToFmtEnd#1\EndFmtInput{}%
  }\SkipToFmtEnd

\newcommand\ReadOnlyOnce[1]{\@ifundefined{#1}{\@namedef{#1}{}}\SkipToFmtEnd}
\usepackage{amstext}
\usepackage{amssymb}
\usepackage{stmaryrd}
\DeclareFontFamily{OT1}{cmtex}{}
\DeclareFontShape{OT1}{cmtex}{m}{n}
  {<5><6><7><8>cmtex8
   <9>cmtex9
   <10><10.95><12><14.4><17.28><20.74><24.88>cmtex10}{}
\DeclareFontShape{OT1}{cmtex}{m}{it}
  {<-> ssub * cmtt/m/it}{}
\newcommand{\texfamily}{\fontfamily{cmtex}\selectfont}
\DeclareFontShape{OT1}{cmtt}{bx}{n}
  {<5><6><7><8>cmtt8
   <9>cmbtt9
   <10><10.95><12><14.4><17.28><20.74><24.88>cmbtt10}{}
\DeclareFontShape{OT1}{cmtex}{bx}{n}
  {<-> ssub * cmtt/bx/n}{}
\newcommand{\tex}[1]{\text{\texfamily#1}}	% NEU

\newcommand{\Sp}{\hskip.33334em\relax}

\newcommand{\Conid}[1]{\mathit{#1}}
\newcommand{\Varid}[1]{\mathit{#1}}
\newcommand{\anonymous}{\kern0.06em \vbox{\hrule\@width.5em}}
\newcommand{\plus}{\mathbin{+\!\!\!+}}
\newcommand{\bind}{\mathbin{>\!\!\!>\mkern-6.7mu=}}
\newcommand{\rbind}{\mathbin{=\mkern-6.7mu<\!\!\!<}}% suggested by Neil Mitchell
\newcommand{\sequ}{\mathbin{>\!\!\!>}}
\renewcommand{\leq}{\leqslant}
\renewcommand{\geq}{\geqslant}
\usepackage{polytable}

%mathindent has to be defined
\@ifundefined{mathindent}%
  {\newdimen\mathindent\mathindent\leftmargini}%
  {}%

\def\resethooks{%
  \global\let\SaveRestoreHook\empty
  \global\let\ColumnHook\empty}
\newcommand*{\savecolumns}[1][default]%
  {\g@addto@macro\SaveRestoreHook{\savecolumns[#1]}}
\newcommand*{\restorecolumns}[1][default]%
  {\g@addto@macro\SaveRestoreHook{\restorecolumns[#1]}}
\newcommand*{\aligncolumn}[2]%
  {\g@addto@macro\ColumnHook{\column{#1}{#2}}}

\resethooks

\newcommand{\onelinecommentchars}{\quad-{}- }
\newcommand{\commentbeginchars}{\enskip\{-}
\newcommand{\commentendchars}{-\}\enskip}

\newcommand{\visiblecomments}{%
  \let\onelinecomment=\onelinecommentchars
  \let\commentbegin=\commentbeginchars
  \let\commentend=\commentendchars}

\newcommand{\invisiblecomments}{%
  \let\onelinecomment=\empty
  \let\commentbegin=\empty
  \let\commentend=\empty}

\visiblecomments

\newlength{\blanklineskip}
\setlength{\blanklineskip}{0.66084ex}

\newcommand{\hsindent}[1]{\quad}% default is fixed indentation
\let\hspre\empty
\let\hspost\empty
\newcommand{\NB}{\textbf{NB}}
\newcommand{\Todo}[1]{$\langle$\textbf{To do:}~#1$\rangle$}

\EndFmtInput
\makeatother
%
%
%
%
%
%
% This package provides two environments suitable to take the place
% of hscode, called "plainhscode" and "arrayhscode".
%
% The plain environment surrounds each code block by vertical space,
% and it uses \abovedisplayskip and \belowdisplayskip to get spacing
% similar to formulas. Note that if these dimensions are changed,
% the spacing around displayed math formulas changes as well.
% All code is indented using \leftskip.
%
% Changed 19.08.2004 to reflect changes in colorcode. Should work with
% CodeGroup.sty.
%
\ReadOnlyOnce{polycode.fmt}%
\makeatletter

\newcommand{\hsnewpar}[1]%
  {{\parskip=0pt\parindent=0pt\par\vskip #1\noindent}}

% can be used, for instance, to redefine the code size, by setting the
% command to \small or something alike
\newcommand{\hscodestyle}{}

% The command \sethscode can be used to switch the code formatting
% behaviour by mapping the hscode environment in the subst directive
% to a new LaTeX environment.

\newcommand{\sethscode}[1]%
  {\expandafter\let\expandafter\hscode\csname #1\endcsname
   \expandafter\let\expandafter\endhscode\csname end#1\endcsname}

% "compatibility" mode restores the non-polycode.fmt layout.

\newenvironment{compathscode}%
  {\par\noindent
   \advance\leftskip\mathindent
   \hscodestyle
   \let\\=\@normalcr
   \let\hspre\(\let\hspost\)%
   \pboxed}%
  {\endpboxed\)%
   \par\noindent
   \ignorespacesafterend}

\newcommand{\compaths}{\sethscode{compathscode}}

% "plain" mode is the proposed default.
% It should now work with \centering.
% This required some changes. The old version
% is still available for reference as oldplainhscode.

\newenvironment{plainhscode}%
  {\hsnewpar\abovedisplayskip
   \advance\leftskip\mathindent
   \hscodestyle
   \let\hspre\(\let\hspost\)%
   \pboxed}%
  {\endpboxed%
   \hsnewpar\belowdisplayskip
   \ignorespacesafterend}

\newenvironment{oldplainhscode}%
  {\hsnewpar\abovedisplayskip
   \advance\leftskip\mathindent
   \hscodestyle
   \let\\=\@normalcr
   \(\pboxed}%
  {\endpboxed\)%
   \hsnewpar\belowdisplayskip
   \ignorespacesafterend}

% Here, we make plainhscode the default environment.

\newcommand{\plainhs}{\sethscode{plainhscode}}
\newcommand{\oldplainhs}{\sethscode{oldplainhscode}}
\plainhs

% The arrayhscode is like plain, but makes use of polytable's
% parray environment which disallows page breaks in code blocks.

\newenvironment{arrayhscode}%
  {\hsnewpar\abovedisplayskip
   \advance\leftskip\mathindent
   \hscodestyle
   \let\\=\@normalcr
   \(\parray}%
  {\endparray\)%
   \hsnewpar\belowdisplayskip
   \ignorespacesafterend}

\newcommand{\arrayhs}{\sethscode{arrayhscode}}

% The mathhscode environment also makes use of polytable's parray
% environment. It is supposed to be used only inside math mode
% (I used it to typeset the type rules in my thesis).

\newenvironment{mathhscode}%
  {\parray}{\endparray}

\newcommand{\mathhs}{\sethscode{mathhscode}}

% texths is similar to mathhs, but works in text mode.

\newenvironment{texthscode}%
  {\(\parray}{\endparray\)}

\newcommand{\texths}{\sethscode{texthscode}}

% The framed environment places code in a framed box.

\def\codeframewidth{\arrayrulewidth}
\RequirePackage{calc}

\newenvironment{framedhscode}%
  {\parskip=\abovedisplayskip\par\noindent
   \hscodestyle
   \arrayrulewidth=\codeframewidth
   \tabular{@{}|p{\linewidth-2\arraycolsep-2\arrayrulewidth-2pt}|@{}}%
   \hline\framedhslinecorrect\\{-1.5ex}%
   \let\endoflinesave=\\
   \let\\=\@normalcr
   \(\pboxed}%
  {\endpboxed\)%
   \framedhslinecorrect\endoflinesave{.5ex}\hline
   \endtabular
   \parskip=\belowdisplayskip\par\noindent
   \ignorespacesafterend}

\newcommand{\framedhslinecorrect}[2]%
  {#1[#2]}

\newcommand{\framedhs}{\sethscode{framedhscode}}

% The inlinehscode environment is an experimental environment
% that can be used to typeset displayed code inline.

\newenvironment{inlinehscode}%
  {\(\def\column##1##2{}%
   \let\>\undefined\let\<\undefined\let\\\undefined
   \newcommand\>[1][]{}\newcommand\<[1][]{}\newcommand\\[1][]{}%
   \def\fromto##1##2##3{##3}%
   \def\nextline{}}{\) }%

\newcommand{\inlinehs}{\sethscode{inlinehscode}}

% The joincode environment is a separate environment that
% can be used to surround and thereby connect multiple code
% blocks.

\newenvironment{joincode}%
  {\let\orighscode=\hscode
   \let\origendhscode=\endhscode
   \def\endhscode{\def\hscode{\endgroup\def\@currenvir{hscode}\\}\begingroup}
   %\let\SaveRestoreHook=\empty
   %\let\ColumnHook=\empty
   %\let\resethooks=\empty
   \orighscode\def\hscode{\endgroup\def\@currenvir{hscode}}}%
  {\origendhscode
   \global\let\hscode=\orighscode
   \global\let\endhscode=\origendhscode}%

\makeatother
\EndFmtInput
%

\begin{document}

\begin{hcarentry}{Laborantin}
\report{Lucas DiCioccio}
\status{Working, development for new features}
% \participants{(PARTICIPANTS OTHER THAN MYSELF)}% optional
\makeheader

Conducting scientific experiments is hard. Laborantin is a DSL to run and
analyze scientific experiments. Laborantin is well-suited for experiments that
you can run offline such as benchmarks with many parameters.

\paragraph Laborantin encourages users to express experiments parameters,
experiment results, as well as execution, startup, and teardown procedures in a
methodical manner. For instance, the following snippet defines a network `ping'
experiment with a destination and packet-size parameters.

\begin{hscode}\SaveRestoreHook
\column{B}{@{}>{\hspre}l<{\hspost}@{}}%
\column{3}{@{}>{\hspre}l<{\hspost}@{}}%
\column{5}{@{}>{\hspre}l<{\hspost}@{}}%
\column{23}{@{}>{\hspre}l<{\hspost}@{}}%
\column{34}{@{}>{\hspre}l<{\hspost}@{}}%
\column{E}{@{}>{\hspre}l<{\hspost}@{}}%
\>[B]{}\Varid{ping}\mathrel{=}\Varid{scenario}\;\text{\tt \char34 ping\char34}\mathbin{\$}\mathbf{do}{}\<[E]%
\\
\>[B]{}\hsindent{3}{}\<[3]%
\>[3]{}\Varid{describe}\;\text{\tt \char34 ping~to~a~remote~server\char34}{}\<[E]%
\\
\>[B]{}\hsindent{3}{}\<[3]%
\>[3]{}\Varid{parameter}\;\text{\tt \char34 destination\char34}\mathbin{\$}\mathbf{do}{}\<[E]%
\\
\>[3]{}\hsindent{2}{}\<[5]%
\>[5]{}\Varid{describe}\;\text{\tt \char34 a~destination~server~(host~or~ip)\char34}{}\<[E]%
\\
\>[3]{}\hsindent{2}{}\<[5]%
\>[5]{}\Varid{values}\;[\mskip1.5mu \Varid{str}\;\text{\tt \char34 example.com\char34},\Varid{str}\;\text{\tt \char34 dicioccio.fr\char34}\mskip1.5mu]{}\<[E]%
\\
\>[B]{}\hsindent{3}{}\<[3]%
\>[3]{}\Varid{parameter}\;\text{\tt \char34 packet-size\char34}\mathbin{\$}\mathbf{do}{}\<[E]%
\\
\>[3]{}\hsindent{2}{}\<[5]%
\>[5]{}\Varid{describe}\;\text{\tt \char34 packet~size~in~bytes\char34}{}\<[E]%
\\
\>[3]{}\hsindent{2}{}\<[5]%
\>[5]{}\Varid{values}\;[\mskip1.5mu \Varid{num}\;\mathrm{50},\Varid{num}\;\mathrm{1500}\mskip1.5mu]{}\<[E]%
\\
\>[B]{}\hsindent{3}{}\<[3]%
\>[3]{}\Varid{run}\mathbin{\$}\mathbf{do}{}\<[E]%
\\
\>[3]{}\hsindent{2}{}\<[5]%
\>[5]{}(\Conid{StringParam}\;\Varid{srv})\leftarrow \Varid{param}\;\text{\tt \char34 destination\char34}{}\<[E]%
\\
\>[3]{}\hsindent{2}{}\<[5]%
\>[5]{}(\Conid{NumberParam}\;\Varid{ps})\leftarrow \Varid{param}\;\text{\tt \char34 packet-size\char34}{}\<[E]%
\\
\>[3]{}\hsindent{2}{}\<[5]%
\>[5]{}\Varid{liftIO}\;(\Varid{execPing}\;\Varid{srv}\;\Varid{ps})\bind \Varid{writeResult}\;\text{\tt \char34 ping.out\char34}{}\<[E]%
\\[\blanklineskip]%
\>[B]{}\Varid{execPing}\mathbin{::}\Conid{Text}\to \Conid{Rational}\to \Conid{IO}\;(\Conid{Text}){}\<[E]%
\\
\>[B]{}\Varid{execPing}\;\Varid{host}\;\Varid{pktSz}\mathrel{=}\mathbf{let}\;\Varid{args}\mathrel{=}[\mskip1.5mu \text{\tt \char34 -c\char34},\text{\tt \char34 10\char34}{}\<[E]%
\\
\>[B]{}\hsindent{34}{}\<[34]%
\>[34]{},\text{\tt \char34 -s\char34},\Varid{show}\;(\Varid{round}\;\Varid{pktSz}),\Varid{\Conid{T}.unpack}\;\Varid{host}\mskip1.5mu]{}\<[E]%
\\
\>[B]{}\hsindent{23}{}\<[23]%
\>[23]{}\mathbf{in}\;\Varid{fmap}\;\Varid{\Conid{T}.pack}\;(\Varid{readProcess}\;\text{\tt \char34 ping\char34}\;\Varid{args}\;\text{\tt \char34 \char34}){}\<[E]%
\ColumnHook
\end{hscode}\resethooks

Laborantin also lets users express dependencies between experiments. Laborantin
is designed to allow multiple backend (where to run and store experiments) and
multiple frontends (how a user interacts with Laborantin). The current backend
stores experiment results on the filesystem and provides a command line
frontend.

\paragraph Contributions are welcome.  In the future, we plan to enrich
Laborantin with helper modules for common tasks such as starting and collecting
outputs of remote processes, reformatting results, and generating plots (e.g.,
with Diagrams). Laborantin would also benefit from new backends (e.g., to
store results in an SQL database or HDFS) and new frontends (e.g., an
integration in IHaskell).

\FurtherReading
Hackage page: \url{http://hackage.haskell.org/package/laborantin-hs}
Example of web-benchmarks: \url{https://github.com/lucasdicioccio/laborantin-bench-web}
\end{hcarentry}

\end{document}


text:
package com.upside.echo.health;

import com.codahale.metrics.health.HealthCheck;
import ru.vyarus.dropwizard.guice.module.installer.feature.health.NamedHealthCheck;

/**
 *
Health check for the echo service.

 */
public class EchoServiceHealthCheck extends NamedHealthCheck {

    @Override
    protected HealthCheck.Result check() throws Exception {
        // FIXME replace with something more meaningful as a test of our health (e.g. db connectivity?)
        return HealthCheck.Result.healthy();
    }

    @Override
    public String getName() {
        return "EchoServiceHealthCheck";
    }
}


text:
using System.Collections.Generic;

using Debugger.MetaData;

namespace Debugger.Expressions
{
	public partial class Expression : DebuggerObject
	{
		public Expression AppendIndexer(params int[] indices)
		{
			return new ArrayIndexerExpression(this, indices);
		}

		public Expression[] AppendIndexers(ArrayDimensions dimensions)
		{
			List<Expression> elements = new List<Expression>();
			foreach(int[] indices in dimensions.Indices) {
				elements.Add(this.AppendIndexer(indices));
			}
			return elements.ToArray();
		}

		public Expression AppendFieldReference(FieldInfo fieldInfo)
		{
			return AppendMemberReference(fieldInfo);
		}

		public Expression AppendPropertyReference(PropertyInfo propertyInfo)
		{
			return AppendMemberReference(propertyInfo);
		}

		public Expression AppendMemberReference(MemberInfo memberInfo, params Expression[] args)
		{
			return new MemberReferenceExpression(this, memberInfo, args);
		}

		public Expression[] AppendObjectMembers(DebugType type, BindingFlags bindingFlags)
		{
			List<Expression> members = new List<Expression>();

			foreach(FieldInfo field in type.GetFields(bindingFlags)) {
				members.Add(this.AppendFieldReference(field));
			}
			foreach(PropertyInfo property in type.GetProperties(bindingFlags)) {
				members.Add(this.AppendPropertyReference(property));
			}

			members.Sort();
			return members.ToArray();
		}
	}
}


text:
@implementation RRecordValidationMsgFormatter

+ (NSString *)formattedValidationMessageForError:(NSError *)error
                                       withLabel:(NSString* )label {
    NSString *message = nil;

    switch ([error code]) {
        case NSValidationNumberTooLargeError:
            message = [self formatMaxValueMessageForError:error andLabel:label];
            break;
        case NSValidationNumberTooSmallError:
            message = [self formatMinValueMessageForError:error andLabel:label];
            break;
        default:
            message = [NSString stringWithFormat: @"The %@ is invaild.", label];
            break;
    }
    return message;
}

+ (NSString *)getFormattedValidationCriteriaFromError:(NSError *)error withUserInfoKey:(NSString *)userInfoKey {
    NSManagedObject *managedObject = [[error userInfo] objectForKey:@"NSValidationErrorObject"];
    NSString *attribute = [[error userInfo] objectForKey:@"NSValidationErrorKey"];
    NSEntityDescription* desc = [managedObject entity];
    NSPropertyDescription* propertyDesc = [[desc propertiesByName] objectForKey:attribute];
    return [[propertyDesc userInfo] objectForKey:userInfoKey];
}

+ (NSString *)formatMinValueMessageForError:(NSError*)error andLabel:(NSString *)label {
    NSString *message = [NSString stringWithFormat: @"The %@ is too small.", label];
    NSString *customMessage = [self getFormattedValidationCriteriaFromError:error withUserInfoKey:@"NSValidationNumberTooSmallError"];

    if (customMessage) {
        message = customMessage;
    }
    return message;
}

+ (NSString *)formatMaxValueMessageForError:(NSError*)error andLabel:(NSString *)label {
    NSString *message = [NSString stringWithFormat: @"The %@ is too large.", label];
    NSString *customMessage = [self getFormattedValidationCriteriaFromError:error withUserInfoKey:@"NSValidationNumberTooLargeError"];

    if (customMessage) {
        message = customMessage;
    }
    return message;
}

@end


text:
=================
Table of Contents
=================

.. toctree::
    :maxdepth: 2
    :caption: Getting Started

    home

.. toctree::
    :maxdepth: 2
    :caption: Techniques

    1_techniques/1_techniques
    1_techniques/2_kinduction
    1_techniques/3_invgen
    1_techniques/4_ic3

.. toctree::
    :maxdepth: 2
    :caption: Inputs and Outputs

    2_input/1_lustre
    2_input/3_machine_ints
    2_input/2_arrays
    3_output/2_machine_readable

.. toctree::
    :maxdepth: 2
    :caption: Advanced Features

    9_other/2_contract_semantics
    9_other/1_post_analyses
    9_other/3_test_generation
    9_other/4_rust_compilation
    9_other/5_proofs
    9_other/6_contract_generation
    9_other/9_invariant_printing
    9_other/8_interpreter
    9_other/10_inductive_validity_core
    9_other/11_minimal_cut_set
    9_other/12_contract_check

.. toctree::
    :maxdepth: 2
    :caption: License

    9_other/license


text:
package com.easemob.server.example.comm.utils;

import com.easemob.server.example.comm.wrapper.ResponseWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class ResponseUtils {
    public static JsonNode ResponseBodyToJsonNode(ResponseWrapper response) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(response.getResponseBody());
        JsonNode jsonNode = mapper.readTree(json);
        return jsonNode;
    }
}


text:
const { resolve } = require("path");

exports.FRONTEND_SRC_DIR = resolve(__dirname, "dist");


text:
// This class has been generated, DO NOT EDIT!

package org.tensorflow.op.risc;

import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.types.TFloat32;
import org.tensorflow.types.family.TNumber;

/**
 * The RiscRandomUniform operation
 */
@OpMetadata(
    opType = RiscRandomUniform.OP_NAME,
    inputsClass = RiscRandomUniform.Inputs.class
)
public final class RiscRandomUniform extends RawOp implements Operand<TFloat32> {
  /**
   * The name of this op, as known by TensorFlow core engine
   */
  public static final String OP_NAME = "RiscRandomUniform";

  private Output<TFloat32> output;

  public RiscRandomUniform(Operation operation) {
    super(operation, OP_NAME);
    int outputIdx = 0;
    output = operation.output(outputIdx++);
  }

  /**
   * Factory method to create a class wrapping a new RiscRandomUniform operation.
   *
   * @param scope current scope
   * @param shape The shape value
   * @param options carries optional attribute values
   * @return a new instance of RiscRandomUniform
   */
  @Endpoint(
      describeByClass = true
  )
  public static RiscRandomUniform create(Scope scope, Operand<? extends TNumber> shape,
      Options... options) {
    OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "RiscRandomUniform");
    opBuilder.addInput(shape.asOutput());
    if (options != null) {
      for (Options opts : options) {
        if (opts.seed != null) {
          opBuilder.setAttr("seed", opts.seed);
        }
      }
    }
    return new RiscRandomUniform(opBuilder.build());
  }

  /**
   * Sets the seed option.
   *
   * @param seed the seed option
   * @return this Options instance.
   */
  public static Options seed(Long seed) {
    return new Options().seed(seed);
  }

  /**
   * Gets output.
   *
   * @return output.
   */
  public Output<TFloat32> output() {
    return output;
  }

  @Override
  public Output<TFloat32> asOutput() {
    return output;
  }

  /**
   * Optional attributes for {@link org.tensorflow.op.risc.RiscRandomUniform}
   */
  public static class Options {
    private Long seed;

    private Options() {
    }

    /**
     * Sets the seed option.
     *
     * @param seed the seed option
     * @return this Options instance.
     */
    public Options seed(Long seed) {
      this.seed = seed;
      return this;
    }
  }

  @OpInputsMetadata(
      outputsClass = RiscRandomUniform.class
  )
  public static class Inputs extends RawOpInputs<RiscRandomUniform> {
    /**
     * The shape input
     */
    public final Operand<? extends TNumber> shape;

    /**
     * The seed attribute
     */
    public final long seed;

    /**
     * The T attribute
     */
    public final DataType T;

    public Inputs(GraphOperation op) {
      super(new RiscRandomUniform(op), op, Arrays.asList("seed", "T"));
      int inputIndex = 0;
      shape = (Operand<? extends TNumber>) op.input(inputIndex++);
      seed = op.attributes().getAttrInt("seed");
      T = op.attributes().getAttrType("T");
    }
  }
}


text:
%{
  version: "1.3.0",
  title: "Ειδικές Εργασίες Mix",
  excerpt: """
  Δημιουργία ειδικών εργασιών Mix για τα Elixir projects σας.
  """
}
---

## Εισαγωγή

Είναι συνηθισμένο να θέλετε να επεκτείνετε τη λειτουργικότητα των εφαρμογών σας στην Elixir προσθέτοντας ειδικές εργασίες Mix.
Πριν μάθουμε πως να το κάνουμε αυτό, ας δούμε ένα που υπάρχει ήδη:

```shell
$ mix phx.new my_phoenix_app

* creating my_phoenix_app/config/config.exs
* creating my_phoenix_app/config/dev.exs
* creating my_phoenix_app/config/prod.exs
* creating my_phoenix_app/config/prod.secret.exs
* creating my_phoenix_app/config/test.exs
* creating my_phoenix_app/lib/my_phoenix_app.ex
* creating my_phoenix_app/lib/my_phoenix_app/endpoint.ex
* creating my_phoenix_app/test/views/error_view_test.exs
...
```

Όπως μπορούμε να δούμε από την εντολή κονσόλας από πάνω, ο σκελετός εφαρμογών Phoenix έχει ειδική εργασία Mix για να δημιουργεί ένα νέο project.
Θα μπορούσαμε να δημιουργήσουμε κάτι παρόμοιο για τo project μας;  Μπορούμε, και η Elixir το κάνει πολύ έυκολο για εμάς.

## Εγκατάσταση

Ας εγκαταστήσουμε μια πολύ βασική εφαρμογή Mix.

```shell
$ mix new hello

* creating README.md
* creating .gitignore
* creating mix.exs
* creating lib
* creating lib/hello.ex
* creating test
* creating test/test_helper.exs
* creating test/hello_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

cd hello
mix test

Run "mix help" for more commands.
```

Τώρα, στο αρχείο **lib/hello.ex** που μας έφτιαξε το το Mix, ας δημιουργήσουμε μια απλή συνάρτηση που εμφανίζει το "Γειά σου, Κόσμε!"

```elixir
defmodule Hello do
  @doc """
  Outputs "Γειά σου, Κόσμε!" every time.
  """
  def say do
    IO.puts("Γειά σου, Κόσμε!")
  end
end
```

## Ειδική Εργασία Mix

Ας δημιουργήσουμε την ειδική εργασία Mix.
Δημιουργήστε ένα νέο φάκελο και ένα αρχείο μέσα σε αυτόν: **hello/lib/mix/tasks/hello.ex**.
Μέσα σε αυτό το αρχείο, ας εισάγουμε αυτές τις 7 γραμμές Elixir.

```elixir
defmodule Mix.Tasks.Hello do
  @moduledoc "The hello mix task: `mix help hello`"
  use Mix.Task

  @shortdoc "Simply calls the Hello.say/0 function."
  def run(_) do
    # καλεί την συνάρτηση μας Hello.say() από πριν
    Hello.say()
  end
end
```

Παρατηρείστε πως ξεκινούμε την δήλωση defmodule με το `Mix.Tasks` και το όνομα που θέλουμε να καλέσουμε από τη γραμμή εντολών.
Στη δεύτερη γραμμή παρουσιάζουμε την `use Mix.Task` η οποία φέρνει τη συμπεριφορά της `Mix.Task` στο namespace.
Μετά ορίζουμε μια συνάρτηση run η οποία αγνοεί όλα τα ορίσματα για τώρα.
Μέσα στη συνάρτηση, καλούμε την ενότητα μας `Hello` και τη συνάρτηση `say`.

## Φόρτωση της εφαρμογής

Το Mix δεν ξεκινά αυτόματα την εφαρμογή μας ούτε κάποια απο τις εξαρτήσεις της, το οποίο δεν είναι πρόβλημα για αρκετές περιπτώσεις χρήσης της εργασίας Mix, τι συμβαίνει όμως αν θέλουμε να χρησιμοποιήσουμε το Ecto και να αλληλεπιδράσουμε με μια βάση δεδομένων; Σε αυτή την περίπτωση πρέπει να βεβαιωθούμε οτι η εφαρμογή του Ecto.Repo έχει εκκινηθεί.
Υπάρχουν 2 τρόποι για να το χειριστούμε: ξεκινώντας ρητά μια εφαρμογή ή ξεκινώντας την εφαρμογή μας η οποία με την σειρά της θα εκκινήσει τις υπόλοιπες.

Ας δούμε πως μπορούμε να ενημερώσουμε το Mix task, ώστε να ξεκινά την εφαρμογή και τις εξαρτήσεις μας:

```elixir
defmodule Mix.Tasks.Hello do
  @moduledoc "The hello mix task: `mix help hello`"
  use Mix.Task

  @shortdoc "Simply calls the Hello.say/0 function."
  def run(_) do
    # This will start our application
    Mix.Task.run("app.start")

    Hello.say()
  end
end
```

## Εργασίες Mix εν Δράσει

Ας ελέγξουυμε την εργασία mix.
Όσο είμαστε στο φάκελο θα πρέπει να δουλεύει.
Από τη γραμμή εντολών, τρέξτε την εντολή `mix hello`, και θα πρέπει να δούμε τα ακόλουθα:

```shell
$ mix hello
Γειά σου, Κόσμε!
```

Το Mix είναι αρκετά φιλικό.
Γνωρίζει ότι όλοι μπορούν να κάνουν λάθος στην ορθογραφία μερικές φορές, έτσι χρησιμοποιεί μια τεχνική που λέγεται ασαφής αντιπαραβολή αλφαριθμητικών για να κάνει συστάσεις:

```shell
$ mix hell
** (Mix) The task "hell" could not be found. Did you mean "hello"?
```

Μήπως παρατηρήσατε ήδη ότι εισάγαμε μια νέα ιδιότητα ενότητας, την `@shortdoc`;  Αυτή είναι βολική όταν στέλνουμε την εφαρμογή στην παραγωγή, ώστε για παράδειγμα ο χρήστης να μπορεί να τρέξει την εντολή `mix help` στο τερματικό.

```shell
$ mix help

mix app.start         # Ξεκινάει όλες τις εγγεγραμμένες εφαρμογές
...
mix hello             # Απλά καλεί την συνάρτηση Hello.say/0.
...
```

Σημείωση: Ο κώδικάς μας πρέπει να έχει συνταχθεί πριν εμφανιστούν οι νέες εργασίες στην έξοδο της εντολής `mix help`.
Μπορούμε να το κάνουμε αυτό είτε τρέχοντας την εντολή `mix compile` απευθείας, ή τρέχοντας την νέα μας εργασία με την εντολή `mix hello`, το οποίο θα δώσει το έναυσμα για τη σύνταξη του κώδικα.

Είναι σημαντικό να σημειώσουμε ότι τα ονόματα των εργασιών προέρχονται από το όνομα της ενότητας, οπότε το `MixTasks.MyHelper.Utility` θα γίνει `my_helper.utility`.


text:
class CreateMovies < ActiveRecord::Migration
  def change
    create_table :movies do |t|
      t.string :title
      t.string :rating
      t.decimal :total_gross

      t.timestamps null: false
    end
  end
end


text:
package com.taotao.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.utils.HttpClientUtil;
import com.taotao.common.utils.TaotaoResult;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.EUDataGridResult;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.service.IContentService;

@Service
public class ContentServiceImpl implements IContentService {

	@Autowired
	private TbContentMapper contentMapper;
	@Value("${REST_BASE_URL}")
	private String REST_BASE_URL;
	@Value("${REST_CONTENT_SYNC}")
	private String REST_CONTENT_SYNC;

	@Override
	public EUDataGridResult getContentList(long catId, Integer page,
			Integer rows) {
		// 根据category_id查询内容列表
		TbContentExample example = new TbContentExample();
		Criteria criteria = example.createCriteria();
		criteria.andCategoryIdEqualTo(catId);
		// 分页处理
		PageHelper.startPage(page, rows);
		List<TbContent> list = contentMapper.selectByExampleWithBLOBs(example);
		// 取分页信息
		PageInfo<TbContent> pageInfo = new PageInfo<>(list);
		EUDataGridResult result = new EUDataGridResult();
		result.setRows(pageInfo.getList());
		result.setTotal(pageInfo.getTotal());
		return result;
	}

	@Override
	public TaotaoResult saveContent(TbContent content) {
		content.setCreated(new Date());
		content.setUpdated(new Date());
		contentMapper.insert(content);
		// 添加缓存同步
		try {
			HttpClientUtil.doGet(REST_BASE_URL + REST_CONTENT_SYNC
					+ content.getCategoryId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return TaotaoResult.ok();
	}

	@Override
	public TaotaoResult editContent(TbContent content) {
		contentMapper.updateByPrimaryKey(content);
		// 添加缓存同步
		try {
			HttpClientUtil.doGet(REST_BASE_URL + REST_CONTENT_SYNC
					+ content.getCategoryId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return TaotaoResult.ok();
	}

	@Override
	public TaotaoResult deleteContent(long ids) {
		TbContent content = contentMapper.selectByPrimaryKey(ids);
		contentMapper.deleteByPrimaryKey(ids);
		// 添加缓存同步
		try {
			HttpClientUtil.doGet(REST_BASE_URL + REST_CONTENT_SYNC + content.getCategoryId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return TaotaoResult.ok();
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="RTRIM" />
<meta content="RTRIM (função)" name="DC.subject" />
<meta content="RTRIM (função)" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj29026.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefsqlj32613" name="DC.Identifier" />
<meta content="pt-br" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>RTRIM</title>

RTRIM

RTRIM remove brancos do final da expressão cadeia de caracteres.

Sintaxe

RTRIM(ExpressãoCaractere)

A ExpressãoCaractere é do tipo de dado CHAR, VARCHAR ou LONG VARCHAR, ou de
qualquer tipo de dado nativo convertido implicitamente em uma cadeia de
caracteres.

RTRIM retorna NULL quando a ExpressãoCaractere é avaliada como nula.

-- retorna ' asdf'
VALUES RTRIM(' asdf  ')

-- retorna 'asdf'
VALUES RTRIM('asdf  ')

Tópico pai: Funções nativas


text:
define('customer', function (require) {
    "use strict";
    var Config = require('capital_one');

	var Customer = {
		initWithKey: function(apiKey) {
			Config.setApiKey(apiKey);
			return this;
		},
		urlWithEntity: function() {
			return Config.baseUrl+"/customers/";
		},
		urlWithAcctEntity: function() {
			return Config.baseUrl+"/accounts/";
		},
		apiKey: function() {
			return Config.apiKey;
		},
		/**
		  # @Method: getCustomers
		  # @Brief: Gets all customers the API key has acccess to.
		  # @Returns an array of JSON Objects.
		**/
		getCustomers: function() {
			var customers;
			var request = $.ajax({
				url: this.urlWithEntity(),
				data: 'key='+this.apiKey(),
				async: false,
				dataType: 'json'
			});

			request.done(function(results) {
				customers = results;
			});
			return customers;
		},
		/**
		  # @Method: getCustomerById
		  # @Brief: Gets the specified customer's information.
		  # @Parameters: CustomerId
		  # @Returns a object with the customer data
		**/
		getCustomerById: function(custId) {
			var customer;
			var request = $.ajax({
				url: this.urlWithEntity()+custId,
				data: 'key='+this.apiKey(),
				async: false,
				dataType: 'json'
			});

			request.done(function(results) {
				customer = results;
			});
			return customer;
		},
		/**
		  # @Method: Get the customer for the given account.
		  # @Parameters: AccountId
		  # @Returns a object with the specified customer data.
		**/
		getCustomerByAcountId: function(accId) {
			var customer;
			var request = $.ajax({
				url: this.urlWithAcctEntity()+accId+'/customer',
				data: 'key='+this.apiKey(),
				async: false,
				dataType: 'json'
			});

			request.done(function(results) {
				customer = results;
			});
			return customer;
		},
		/**
		  # @Method: updateCustomer
		  # @Brief: Updates a customer by id with given JSON data.
		  # @Parameters: CustomerId, Customerobject.
		  # @Note: Json is as follows:
		  #  {
		  #   "address": {
		  #     "street_number": "",
		  #     "street_name": "",
		  #     "city": "",
		  #     "state": "",
		  #     "zip": ""
		  #   }
		  # }
		  # @Returns http response code.
		**/
		updateCustomer: function(custId, json) {
			var respCode;
			var request = $.ajax({
				url: this.urlWithEntity()+custId+'?key='+this.apiKey(),
				data: json,
				contentType: 'application/json',
				async: false,
				type: 'PUT'
			});

			request.complete(function(jqXHR, textStatus) {
				respCode = jqXHR.status;
			});
			return respCode;
		}
	};
	return Customer;
});


text:
<?php

use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Exception\RouteNotFoundException;

/**
 * appdevUrlGenerator
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class appdevUrlGenerator extends Symfony\Component\Routing\Generator\UrlGenerator
{
    static private $declaredRouteNames = array(
       '_welcome' => true,
       '_demo_login' => true,
       '_security_check' => true,
       '_demo_logout' => true,
       'acme_demo_secured_hello' => true,
       '_demo_secured_hello' => true,
       '_demo_secured_hello_admin' => true,
       '_demo' => true,
       '_demo_hello' => true,
       '_demo_contact' => true,
       '_wdt' => true,
       '_profiler_search' => true,
       '_profiler_purge' => true,
       '_profiler_import' => true,
       '_profiler_export' => true,
       '_profiler_search_results' => true,
       '_profiler' => true,
       '_configurator_home' => true,
       '_configurator_step' => true,
       '_configurator_final' => true,
       'PepesanNuevoBundle_homepage' => true,
       'clientes' => true,
       'clientes_show' => true,
       'clientes_new' => true,
       'clientes_create' => true,
       'clientes_edit' => true,
       'clientes_update' => true,
       'clientes_delete' => true,
    );

    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function generate($name, $parameters = array(), $absolute = false)
    {
        if (!isset(self::$declaredRouteNames[$name])) {
            throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name));
        }

        $escapedName = str_replace('.', '__', $name);

        list($variables, $defaults, $requirements, $tokens) = $this->{'get'.$escapedName.'RouteInfo'}();

        return $this->doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute);
    }

    private function get_welcomeRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Acme\\DemoBundle\\Controller\\ClientesController::indexAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/',  ),));
    }

    private function get_demo_loginRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::loginAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/demo/secured/login',  ),));
    }

    private function get_security_checkRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::securityCheckAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/demo/secured/login_check',  ),));
    }

    private function get_demo_logoutRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::logoutAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/demo/secured/logout',  ),));
    }

    private function getacme_demo_secured_helloRouteInfo()
    {
        return array(array (), array (  'name' => 'World',  '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/demo/secured/hello',  ),));
    }

    private function get_demo_secured_helloRouteInfo()
    {
        return array(array (  0 => 'name',), array (  '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction',), array (), array (  0 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'name',  ),  1 =>   array (    0 => 'text',    1 => '/demo/secured/hello',  ),));
    }

    private function get_demo_secured_hello_adminRouteInfo()
    {
        return array(array (  0 => 'name',), array (  '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloadminAction',), array (), array (  0 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'name',  ),  1 =>   array (    0 => 'text',    1 => '/demo/secured/hello/admin',  ),));
    }

    private function get_demoRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::indexAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/demo/',  ),));
    }

    private function get_demo_helloRouteInfo()
    {
        return array(array (  0 => 'name',), array (  '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::helloAction',), array (), array (  0 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'name',  ),  1 =>   array (    0 => 'text',    1 => '/demo/hello',  ),));
    }

    private function get_demo_contactRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::contactAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/demo/contact',  ),));
    }

    private function get_wdtRouteInfo()
    {
        return array(array (  0 => 'token',), array (  '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::toolbarAction',), array (), array (  0 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'token',  ),  1 =>   array (    0 => 'text',    1 => '/_wdt',  ),));
    }

    private function get_profiler_searchRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::searchAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/_profiler/search',  ),));
    }

    private function get_profiler_purgeRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::purgeAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/_profiler/purge',  ),));
    }

    private function get_profiler_importRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::importAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/_profiler/import',  ),));
    }

    private function get_profiler_exportRouteInfo()
    {
        return array(array (  0 => 'token',), array (  '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::exportAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '.txt',  ),  1 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/\\.]+?',    3 => 'token',  ),  2 =>   array (    0 => 'text',    1 => '/_profiler/export',  ),));
    }

    private function get_profiler_search_resultsRouteInfo()
    {
        return array(array (  0 => 'token',), array (  '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::searchResultsAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/search/results',  ),  1 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'token',  ),  2 =>   array (    0 => 'text',    1 => '/_profiler',  ),));
    }

    private function get_profilerRouteInfo()
    {
        return array(array (  0 => 'token',), array (  '_controller' => 'Symfony\\Bundle\\WebProfilerBundle\\Controller\\ProfilerController::panelAction',), array (), array (  0 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'token',  ),  1 =>   array (    0 => 'text',    1 => '/_profiler',  ),));
    }

    private function get_configurator_homeRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/_configurator/',  ),));
    }

    private function get_configurator_stepRouteInfo()
    {
        return array(array (  0 => 'index',), array (  '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction',), array (), array (  0 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'index',  ),  1 =>   array (    0 => 'text',    1 => '/_configurator/step',  ),));
    }

    private function get_configurator_finalRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/_configurator/final',  ),));
    }

    private function getPepesanNuevoBundle_homepageRouteInfo()
    {
        return array(array (  0 => 'name',), array (  '_controller' => 'Pepesan\\NuevoBundle\\Controller\\DefaultController::indexAction',), array (), array (  0 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'name',  ),  1 =>   array (    0 => 'text',    1 => '/hello',  ),));
    }

    private function getclientesRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Pepesan\\NuevoBundle\\Controller\\ClientesController::indexAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/clientes/',  ),));
    }

    private function getclientes_showRouteInfo()
    {
        return array(array (  0 => 'id',), array (  '_controller' => 'Pepesan\\NuevoBundle\\Controller\\ClientesController::showAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/show',  ),  1 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'id',  ),  2 =>   array (    0 => 'text',    1 => '/clientes',  ),));
    }

    private function getclientes_newRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Pepesan\\NuevoBundle\\Controller\\ClientesController::newAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/clientes/new',  ),));
    }

    private function getclientes_createRouteInfo()
    {
        return array(array (), array (  '_controller' => 'Pepesan\\NuevoBundle\\Controller\\ClientesController::createAction',), array (  '_method' => 'post',), array (  0 =>   array (    0 => 'text',    1 => '/clientes/create',  ),));
    }

    private function getclientes_editRouteInfo()
    {
        return array(array (  0 => 'id',), array (  '_controller' => 'Pepesan\\NuevoBundle\\Controller\\ClientesController::editAction',), array (), array (  0 =>   array (    0 => 'text',    1 => '/edit',  ),  1 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'id',  ),  2 =>   array (    0 => 'text',    1 => '/clientes',  ),));
    }

    private function getclientes_updateRouteInfo()
    {
        return array(array (  0 => 'id',), array (  '_controller' => 'Pepesan\\NuevoBundle\\Controller\\ClientesController::updateAction',), array (  '_method' => 'post',), array (  0 =>   array (    0 => 'text',    1 => '/update',  ),  1 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'id',  ),  2 =>   array (    0 => 'text',    1 => '/clientes',  ),));
    }

    private function getclientes_deleteRouteInfo()
    {
        return array(array (  0 => 'id',), array (  '_controller' => 'Pepesan\\NuevoBundle\\Controller\\ClientesController::deleteAction',), array (  '_method' => 'post',), array (  0 =>   array (    0 => 'text',    1 => '/delete',  ),  1 =>   array (    0 => 'variable',    1 => '/',    2 => '[^/]+?',    3 => 'id',  ),  2 =>   array (    0 => 'text',    1 => '/clientes',  ),));
    }
}


text:
export {};

declare module 'assets.json' {
  const value: Record<string, string>;

  export = value;
}

declare const ENVIRONMENT: string;

declare const RELEASE: string;


text:
#include <windows.h>
#include <string>
#include <cmath>
#include <vector>
#include <stack>
#include <set>
#include <regex>

using std::sin;
using std::cos;
using std::tan;
using std::string;
using std::stack;
using std::vector;
using std::set;

static const double PI = 3.14159265358979;

namespace MathExpPlotter
{
	class MathExp
	{
	public:
		MathExp(string _math_exp_str);
		MathExp(LPCSTR _math_exp_lpcstr);
		~MathExp();

		void initialize();
	private:
		string math_exp_str;
		std::set<char> op_set;
	};
}


text:
/////////////////////////////////////////////////////////////////////////////
// Name:        src/generic/prntdlgg.cpp
// Purpose:     Generic print dialogs
// Author:      Julian Smart
// Modified by:
// Created:     04/01/98
// RCS-ID:      $Id: prntdlgg.cpp 55256 2008-08-25 14:39:11Z VZ $
// Copyright:   (c) Julian Smart
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

// ============================================================================
// declarations
// ============================================================================

// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#if wxUSE_PRINTING_ARCHITECTURE && (!defined(__WXMSW__) || wxUSE_POSTSCRIPT_ARCHITECTURE_IN_MSW)

#include "wx/generic/prntdlgg.h"

#ifndef WX_PRECOMP
    #include "wx/utils.h"
    #include "wx/dc.h"
    #include "wx/stattext.h"
    #include "wx/statbox.h"
    #include "wx/button.h"
    #include "wx/checkbox.h"
    #include "wx/textctrl.h"
    #include "wx/radiobox.h"
    #include "wx/filedlg.h"
    #include "wx/combobox.h"
    #include "wx/intl.h"
    #include "wx/sizer.h"
    #include "wx/cmndata.h"
#endif

#if wxUSE_STATLINE
    #include "wx/statline.h"
#endif

#if wxUSE_POSTSCRIPT
    #include "wx/generic/dcpsg.h"
#endif

#include "wx/prntbase.h"
#include "wx/printdlg.h"
#include "wx/paper.h"
#include "wx/filename.h"
#include "wx/tokenzr.h"
#include "wx/imaglist.h"

#include <stdlib.h>
#include <string.h>

#ifndef __WXUNIVERSAL__

#if wxUSE_LIBGNOMEPRINT
    #include "wx/link.h"
    wxFORCE_LINK_MODULE(gnome_print)
#endif

#endif // !__WXUNIVERSAL__

// ----------------------------------------------------------------------------
// global vars
// ----------------------------------------------------------------------------

extern wxPrintPaperDatabase *wxThePrintPaperDatabase;

#if wxUSE_POSTSCRIPT

//----------------------------------------------------------------------------
// wxPostScriptNativeData
//----------------------------------------------------------------------------

IMPLEMENT_CLASS(wxPostScriptPrintNativeData, wxPrintNativeDataBase)

wxPostScriptPrintNativeData::wxPostScriptPrintNativeData()
{
    m_previewCommand = wxEmptyString;
#ifdef __VMS__
    m_printerCommand = wxT("print");
    m_printerOptions = wxT("/nonotify/queue=psqueue");
    m_afmPath = wxT("sys$ps_font_metrics:");
#endif

#ifdef __WXMSW__
    m_printerCommand = wxT("print");
    m_printerOptions = wxEmptyString;
    m_afmPath = wxT("c:\\windows\\system\\");
#endif

#if !defined(__VMS__) && !defined(__WXMSW__)
    m_printerCommand = wxT("lpr");
    m_printerOptions = wxEmptyString;
    m_afmPath = wxEmptyString;
#endif

    m_printerScaleX = 1.0;
    m_printerScaleY = 1.0;
    m_printerTranslateX = 0;
    m_printerTranslateY = 0;
}

wxPostScriptPrintNativeData::~wxPostScriptPrintNativeData()
{
}

bool wxPostScriptPrintNativeData::TransferTo( wxPrintData &WXUNUSED(data) )
{
    return true;
}

bool wxPostScriptPrintNativeData::TransferFrom( const wxPrintData &WXUNUSED(data) )
{
    return true;
}

// ----------------------------------------------------------------------------
// Generic print dialog for non-Windows printing use.
// ----------------------------------------------------------------------------

IMPLEMENT_CLASS(wxGenericPrintDialog, wxPrintDialogBase)

BEGIN_EVENT_TABLE(wxGenericPrintDialog, wxPrintDialogBase)
    EVT_BUTTON(wxID_OK, wxGenericPrintDialog::OnOK)
    EVT_BUTTON(wxPRINTID_SETUP, wxGenericPrintDialog::OnSetup)
    EVT_RADIOBOX(wxPRINTID_RANGE, wxGenericPrintDialog::OnRange)
END_EVENT_TABLE()

wxGenericPrintDialog::wxGenericPrintDialog(wxWindow *parent,
                                           wxPrintDialogData* data)
                    : wxPrintDialogBase(parent, wxID_ANY, _("Print"),
                               wxPoint(0,0), wxSize(600, 600),
                               wxDEFAULT_DIALOG_STYLE |
                               wxTAB_TRAVERSAL)
{
    if ( data )
        m_printDialogData = *data;

    Init(parent);
}

wxGenericPrintDialog::wxGenericPrintDialog(wxWindow *parent,
                                           wxPrintData* data)
                    : wxPrintDialogBase(parent, wxID_ANY, _("Print"),
                               wxPoint(0,0), wxSize(600, 600),
                               wxDEFAULT_DIALOG_STYLE |
                               wxTAB_TRAVERSAL)
{
    if ( data )
        m_printDialogData = *data;

    Init(parent);
}

void wxGenericPrintDialog::Init(wxWindow * WXUNUSED(parent))
{
  //    wxDialog::Create(parent, wxID_ANY, _("Print"), wxPoint(0,0), wxSize(600, 600),
  //                     wxDEFAULT_DIALOG_STYLE | wxTAB_TRAVERSAL);

    wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );

    // 1) top row

    wxPrintFactory* factory = wxPrintFactory::GetFactory();

    wxStaticBoxSizer *topsizer = new wxStaticBoxSizer(
        new wxStaticBox( this, wxID_ANY, _( "Printer options" ) ), wxHORIZONTAL );
    wxFlexGridSizer *flex = new wxFlexGridSizer( 2 );
    flex->AddGrowableCol( 1 );
    topsizer->Add( flex, 1, wxGROW );

    m_printToFileCheckBox = new wxCheckBox( this, wxPRINTID_PRINTTOFILE, _("Print to File") );
    flex->Add( m_printToFileCheckBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    m_setupButton = new wxButton(this, wxPRINTID_SETUP, _("Setup...") );
    flex->Add( m_setupButton, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_RIGHT|wxALL, 5 );

    if (!factory->HasPrintSetupDialog())
        m_setupButton->Enable( false );

    if (factory->HasPrinterLine())
    {
        flex->Add( new wxStaticText( this, wxID_ANY, _("Printer:") ),
            0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
        flex->Add( new wxStaticText( this, wxID_ANY, factory->CreatePrinterLine() ),
            0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
    }

    if (factory->HasStatusLine())
    {
        flex->Add( new wxStaticText( this, wxID_ANY, _("Status:") ),
            0, wxALIGN_CENTER_VERTICAL|(wxALL-wxTOP), 5 );
        flex->Add( new wxStaticText( this, wxID_ANY, factory->CreateStatusLine() ),
            0, wxALIGN_CENTER_VERTICAL|(wxALL-wxTOP), 5 );
    }

    mainsizer->Add( topsizer, 0, wxLEFT|wxTOP|wxRIGHT|wxGROW, 10 );

    // 2) middle row with radio box

    wxString *choices = new wxString[2];
    choices[0] = _("All");
    choices[1] = _("Pages");

    m_fromText = (wxTextCtrl*)NULL;
    m_toText = (wxTextCtrl*)NULL;
    m_rangeRadioBox = (wxRadioBox *)NULL;

    if (m_printDialogData.GetFromPage() != 0)
    {
        m_rangeRadioBox = new wxRadioBox(this, wxPRINTID_RANGE, _("Print Range"),
                                         wxDefaultPosition, wxDefaultSize,
                                         2, choices,
                                         1, wxRA_VERTICAL);
        m_rangeRadioBox->SetSelection(1);

        mainsizer->Add( m_rangeRadioBox, 0, wxLEFT|wxTOP|wxRIGHT, 10 );
    }

    // 3) bottom row

    wxBoxSizer *bottomsizer = new wxBoxSizer( wxHORIZONTAL );

    if (m_printDialogData.GetFromPage() != 0)
    {
        bottomsizer->Add( new wxStaticText(this, wxPRINTID_STATIC, _("From:") ), 0, wxCENTER|wxALL, 5 );
        m_fromText = new wxTextCtrl(this, wxPRINTID_FROM, wxEmptyString, wxDefaultPosition, wxSize(40, wxDefaultCoord));
        bottomsizer->Add( m_fromText, 1, wxCENTER|wxRIGHT, 10 );

        bottomsizer->Add( new wxStaticText(this, wxPRINTID_STATIC, _("To:") ), 0, wxCENTER|wxALL, 5);
        m_toText = new wxTextCtrl(this, wxPRINTID_TO, wxEmptyString, wxDefaultPosition, wxSize(40, wxDefaultCoord));
        bottomsizer->Add( m_toText, 1, wxCENTER|wxRIGHT, 10 );
    }

    bottomsizer->Add( new wxStaticText(this, wxPRINTID_STATIC, _("Copies:") ), 0, wxCENTER|wxALL, 5 );
    m_noCopiesText = new wxTextCtrl(this, wxPRINTID_COPIES, wxEmptyString, wxPoint(252, 130), wxSize(40, wxDefaultCoord));
    bottomsizer->Add( m_noCopiesText, 1, wxCENTER|wxRIGHT, 10 );

    mainsizer->Add( bottomsizer, 0, wxTOP|wxLEFT|wxRIGHT, 12 );

    // 4) buttons

    wxSizer *sizerBtn = CreateSeparatedButtonSizer( wxOK|wxCANCEL);
    if ( sizerBtn )
        mainsizer->Add(sizerBtn, 0, wxEXPAND|wxALL, 10 );

    SetAutoLayout( true );
    SetSizer( mainsizer );

    mainsizer->Fit( this );
    Centre(wxBOTH);

    // Calls wxWindow::OnInitDialog and then wxGenericPrintDialog::TransferDataToWindow
    InitDialog();
    delete[] choices;
}

int wxGenericPrintDialog::ShowModal()
{
    return wxDialog::ShowModal();
}

wxGenericPrintDialog::~wxGenericPrintDialog()
{
}

void wxGenericPrintDialog::OnOK(wxCommandEvent& WXUNUSED(event))
{
    TransferDataFromWindow();

    // An empty 'to' field signals printing just the
    // 'from' page.
    if (m_printDialogData.GetToPage() < 1)
        m_printDialogData.SetToPage(m_printDialogData.GetFromPage());

    // There are some interactions between the global setup data
    // and the standard print dialog. The global printing 'mode'
    // is determined by whether the user checks Print to file
    // or not.
    if (m_printDialogData.GetPrintToFile())
    {
        m_printDialogData.GetPrintData().SetPrintMode(wxPRINT_MODE_FILE);

        wxFileName fname( m_printDialogData.GetPrintData().GetFilename() );

        wxFileDialog dialog( this, _("PostScript file"),
            fname.GetPath(), fname.GetFullName(), wxT("*.ps"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
        if (dialog.ShowModal() != wxID_OK) return;

        m_printDialogData.GetPrintData().SetFilename( dialog.GetPath() );
    }
    else
    {
        m_printDialogData.GetPrintData().SetPrintMode(wxPRINT_MODE_PRINTER);
    }

    EndModal(wxID_OK);
}

void wxGenericPrintDialog::OnRange(wxCommandEvent& event)
{
    if (!m_fromText) return;

    if (event.GetInt() == 0)
    {
        m_fromText->Enable(false);
        m_toText->Enable(false);
    }
    else if (event.GetInt() == 1)
    {
        m_fromText->Enable(true);
        m_toText->Enable(true);
    }
}

void wxGenericPrintDialog::OnSetup(wxCommandEvent& WXUNUSED(event))
{
    wxPrintFactory* factory = wxPrintFactory::GetFactory();

    if (factory->HasPrintSetupDialog())
    {
        // The print setup dialog should change the
        // print data in-place if not cancelled.
        wxDialog *dialog = factory->CreatePrintSetupDialog( this, &m_printDialogData.GetPrintData() );
        dialog->ShowModal();
        dialog->Destroy();
    }
}

bool wxGenericPrintDialog::TransferDataToWindow()
{
    if(m_printDialogData.GetFromPage() != 0)
    {
       if(m_fromText)
       {
          if (m_printDialogData.GetEnablePageNumbers())
          {
             m_fromText->Enable(true);
             m_toText->Enable(true);
             if (m_printDialogData.GetFromPage() > 0)
                m_fromText->SetValue(wxString::Format(_T("%d"), m_printDialogData.GetFromPage()));
             if (m_printDialogData.GetToPage() > 0)
                m_toText->SetValue(wxString::Format(_T("%d"), m_printDialogData.GetToPage()));
             if(m_rangeRadioBox)
             {
                if (m_printDialogData.GetAllPages() || m_printDialogData.GetFromPage() == 0)
                   m_rangeRadioBox->SetSelection(0);
                else
                   m_rangeRadioBox->SetSelection(1);
             }
          }
          else
          {
             m_fromText->Enable(false);
             m_toText->Enable(false);
             if(m_rangeRadioBox)
             {
                m_rangeRadioBox->SetSelection(0);
                m_rangeRadioBox->wxRadioBox::Enable(1, false);
             }
          }
       }
    }
    m_noCopiesText->SetValue(
        wxString::Format(_T("%d"), m_printDialogData.GetNoCopies()));

    m_printToFileCheckBox->SetValue(m_printDialogData.GetPrintToFile());
    m_printToFileCheckBox->Enable(m_printDialogData.GetEnablePrintToFile());
    return true;
}

bool wxGenericPrintDialog::TransferDataFromWindow()
{
    long res = 0;
    if(m_printDialogData.GetFromPage() != -1)
    {
        if (m_printDialogData.GetEnablePageNumbers())
        {
            if(m_fromText)
            {
                wxString value = m_fromText->GetValue();
                if (value.ToLong( &res ))
                    m_printDialogData.SetFromPage( res );
            }
            if(m_toText)
            {
                wxString value = m_toText->GetValue();
                if (value.ToLong( &res ))
                    m_printDialogData.SetToPage( res );
            }
        }
        if(m_rangeRadioBox)
        {
            if (m_rangeRadioBox->GetSelection() == 0)
            {
                m_printDialogData.SetAllPages(true);

                // This means all pages, more or less
                m_printDialogData.SetFromPage(1);
                m_printDialogData.SetToPage(32000);
            }
            else
                m_printDialogData.SetAllPages(false);
        }
    }
    else
    { // continuous printing
        m_printDialogData.SetFromPage(1);
        m_printDialogData.SetToPage(32000);
    }

    wxString value = m_noCopiesText->GetValue();
    if (value.ToLong( &res ))
        m_printDialogData.SetNoCopies( res );

    m_printDialogData.SetPrintToFile(m_printToFileCheckBox->GetValue());

    return true;
}

wxDC *wxGenericPrintDialog::GetPrintDC()
{
    return new wxPostScriptDC(GetPrintDialogData().GetPrintData());
}

// ----------------------------------------------------------------------------
// Generic print setup dialog
// ----------------------------------------------------------------------------

IMPLEMENT_CLASS(wxGenericPrintSetupDialog, wxDialog)

BEGIN_EVENT_TABLE(wxGenericPrintSetupDialog, wxDialog)
    EVT_LIST_ITEM_ACTIVATED(wxPRINTID_PRINTER, wxGenericPrintSetupDialog::OnPrinter)
END_EVENT_TABLE()

wxGenericPrintSetupDialog::wxGenericPrintSetupDialog(wxWindow *parent, wxPrintData* data):
wxDialog(parent, wxID_ANY, _("Print Setup"), wxPoint(0,0), wxSize(600, 600), wxDEFAULT_DIALOG_STYLE|wxTAB_TRAVERSAL)
{
    Init(data);
}

/* XPM */
static const char * check_xpm[] = {
/* width height ncolors chars_per_pixel */
"16 16 3 1",
/* colors */
" 	s None	c None",
"X	c #000000",
".	c #808080",
/* pixels */
"                ",
"                ",
"                ",
"             .. ",
"            XX  ",
"           XX.  ",
"          .XX   ",
"          XX    ",
"   X     XX.    ",
"   XX   .XX     ",
"    XX  XX      ",
"     XXXX.      ",
"      XX.       ",
"       .        ",
"                ",
"                "
};

void wxGenericPrintSetupDialog::Init(wxPrintData* data)
{
    if ( data )
        m_printData = *data;

    m_targetData = data;

    wxBoxSizer *main_sizer = new wxBoxSizer( wxVERTICAL );

    // printer selection

    wxStaticBoxSizer *printer_sizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _("Printer") ), wxVERTICAL );
    main_sizer->Add( printer_sizer, 0, wxALL|wxGROW, 10 );

    m_printerListCtrl = new wxListCtrl( this, wxPRINTID_PRINTER,
        wxDefaultPosition, wxSize(wxDefaultCoord,100), wxLC_REPORT|wxLC_SINGLE_SEL|wxSUNKEN_BORDER );
    wxImageList *image_list = new wxImageList;
    image_list->Add( wxBitmap(check_xpm) );
    m_printerListCtrl->AssignImageList( image_list, wxIMAGE_LIST_SMALL );

    m_printerListCtrl->InsertColumn( 0, wxT(" "), wxLIST_FORMAT_LEFT, 20 );
    m_printerListCtrl->InsertColumn( 1, wxT("Printer"), wxLIST_FORMAT_LEFT, 150 );
    m_printerListCtrl->InsertColumn( 2, wxT("Device"), wxLIST_FORMAT_LEFT, 150 );
    m_printerListCtrl->InsertColumn( 3, wxT("Status"), wxLIST_FORMAT_LEFT, 80 );

    wxListItem item;
    item.SetMask( wxLIST_MASK_TEXT );
    item.SetColumn( 1 );
    item.SetText( _("Default printer") );
    item.SetId( m_printerListCtrl->InsertItem( item ) );

    if (data->GetPrinterName().empty())
    {
        wxListItem item2;
        item2.SetId( item.GetId() );
        item2.SetMask( wxLIST_MASK_IMAGE );
        item2.SetImage( 0 );
        m_printerListCtrl->SetItem( item2 );
        // also select item
        m_printerListCtrl->SetItemState( item.GetId(), wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
    }

    item.SetId( 1+ item.GetId() );

    wxArrayString errors;
    wxArrayString output;
    long res = wxExecute( wxT("lpstat -v"), output, errors, wxEXEC_NODISABLE );
    if (res >= 0 && errors.GetCount() == 0)
    {
        size_t i;
        for (i = 0; i < output.GetCount(); i++)
        {
            wxStringTokenizer tok( output[i], wxT(" ") );
            wxString tmp = tok.GetNextToken(); // "device"
            if (tmp != wxT("device"))
                break;  // the lpstat syntax must have changed.
            tmp = tok.GetNextToken();          // "for"
            if (tmp != wxT("for"))
                break;  // the lpstat syntax must have changed.
            tmp = tok.GetNextToken();          // "hp_deskjet930c:"
            if (tmp[tmp.length()-1] == wxT(':'))
                tmp.Remove(tmp.length()-1,1);
            wxString name = tmp;
            item.SetText( name );
            item.SetId( m_printerListCtrl->InsertItem( item ) );
            tmp = tok.GetNextToken();          // "parallel:/dev/lp0"
            item.SetColumn( 2 );
            item.SetText( tmp );
            m_printerListCtrl->SetItem( item );
            if (data->GetPrinterName() == name)
            {
                wxListItem item2;
                item2.SetId( item.GetId() );
                item2.SetMask( wxLIST_MASK_IMAGE );
                item2.SetImage( 0 );
                m_printerListCtrl->SetItem( item2 );
                // also select item
                m_printerListCtrl->SetItemState( item.GetId(), wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
            }

            wxString command = wxT("lpstat -p ");
            command += name;
            wxArrayString errors2;
            wxArrayString output2;
            res = wxExecute( command, output2, errors2, wxEXEC_NODISABLE );
            if (res >= 0 && errors2.GetCount() == 0 && output2.GetCount() > 0)
            {
                tmp = output2[0]; // "printer hp_deskjet930c is idle. enable since ..."
                int pos = tmp.Find( wxT('.') );
                if (pos != wxNOT_FOUND)
                    tmp.Remove( (size_t)pos, tmp.length()-(size_t)pos );
                wxStringTokenizer tok2( tmp, wxT(" ") );
                tmp = tok2.GetNextToken();  // "printer"
                tmp = tok2.GetNextToken();  // "hp_deskjet930c"
                tmp = wxEmptyString;
                while (tok2.HasMoreTokens())
                {
                    tmp += tok2.GetNextToken();
                    tmp += wxT(" ");
                }
                item.SetColumn( 3 );
                item.SetText( tmp );
                m_printerListCtrl->SetItem( item );
            }

            item.SetColumn( 1 );
            item.SetId( 1+ item.GetId() );
        }
    }

    printer_sizer->Add( m_printerListCtrl, 0, wxALL|wxGROW, 5 );

    wxBoxSizer *item1 = new wxBoxSizer( wxHORIZONTAL );
    main_sizer->Add( item1, 0, wxALL, 5 );

    // printer options (on the left)

    wxBoxSizer *item2 = new wxBoxSizer( wxVERTICAL );

    wxStaticBox *item4 = new wxStaticBox( this, wxPRINTID_STATIC, _("Paper size") );
    wxStaticBoxSizer *item3 = new wxStaticBoxSizer( item4, wxVERTICAL );

    m_paperTypeChoice = CreatePaperTypeChoice();
    item3->Add( m_paperTypeChoice, 0, wxALIGN_CENTER|wxALL, 5 );

    item2->Add( item3, 0, wxALIGN_CENTER|wxALL, 5 );

    wxString strs6[] =
    {
        _("Portrait"),
        _("Landscape")
    };
    m_orientationRadioBox= new wxRadioBox( this, wxPRINTID_ORIENTATION, _("Orientation"), wxDefaultPosition, wxDefaultSize, 2, strs6, 1, wxRA_SPECIFY_ROWS );
    item2->Add( m_orientationRadioBox, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxStaticBox *item8 = new wxStaticBox( this, wxID_ANY, _("Options") );
    wxStaticBoxSizer *item7 = new wxStaticBoxSizer( item8, wxHORIZONTAL );

    m_colourCheckBox = new wxCheckBox( this, wxPRINTID_PRINTCOLOUR, _("Print in colour") );
    item7->Add( m_colourCheckBox, 0, wxALIGN_CENTER|wxALL, 5 );

    item2->Add( item7, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    item1->Add( item2, 0, wxALIGN_CENTER_HORIZONTAL, 5 );

    // spooling options (on the right)

    wxStaticBox *item11 = new wxStaticBox( this, wxID_ANY, _("Print spooling") );
    wxStaticBoxSizer *item10 = new wxStaticBoxSizer( item11, wxVERTICAL );

    wxStaticText *item12 = new wxStaticText( this, wxID_ANY, _("Printer command:") );
    item10->Add( item12, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxBoxSizer *item13 = new wxBoxSizer( wxHORIZONTAL );

    item13->Add( 20, 20, 0, wxALIGN_CENTER|wxALL, 5 );

    m_printerCommandText = new wxTextCtrl( this, wxPRINTID_COMMAND, wxEmptyString, wxDefaultPosition, wxSize(160,wxDefaultCoord) );
    item13->Add( m_printerCommandText, 0, wxALIGN_CENTER|wxALL, 5 );

    item10->Add( item13, 0, wxALIGN_CENTER|wxALL, 0 );

    wxStaticText *item15 = new wxStaticText( this, wxID_ANY, _("Printer options:") );
    item10->Add( item15, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxBoxSizer *item16 = new wxBoxSizer( wxHORIZONTAL );

    item16->Add( 20, 20, 0, wxALIGN_CENTER|wxALL, 5 );

    m_printerOptionsText = new wxTextCtrl( this, wxPRINTID_OPTIONS, wxEmptyString, wxDefaultPosition, wxSize(160,wxDefaultCoord) );
    item16->Add( m_printerOptionsText, 0, wxALIGN_CENTER|wxALL, 5 );

    item10->Add( item16, 0, wxALIGN_CENTER|wxALL, 0 );

    item1->Add( item10, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5 );

#if wxUSE_STATLINE
    // static line
    main_sizer->Add( new wxStaticLine( this, wxID_ANY ), 0, wxEXPAND | wxLEFT|wxRIGHT|wxTOP, 10 );
#endif

    // buttons

    main_sizer->Add( CreateButtonSizer( wxOK|wxCANCEL), 0, wxEXPAND|wxALL, 10 );

    SetAutoLayout( true );
    SetSizer( main_sizer );

    main_sizer->Fit( this );
    Centre(wxBOTH);

    Fit();
    Centre(wxBOTH);

    InitDialog();
}

wxGenericPrintSetupDialog::~wxGenericPrintSetupDialog()
{
}

void wxGenericPrintSetupDialog::OnPrinter(wxListEvent& event)
{
    // Delete check mark
    for (long item = 0; item < m_printerListCtrl->GetItemCount(); item++)
        m_printerListCtrl->SetItemImage( item, -1 );

    m_printerListCtrl->SetItemImage( event.GetIndex(), 0 );

    if (event.GetIndex() == 0)
    {
        m_printerCommandText->SetValue( wxT("lpr") );
    }
    else
    {
        wxListItem li;
        li.SetColumn( 1 );
        li.SetMask( wxLIST_MASK_TEXT );
        li.SetId( event.GetIndex() );
        m_printerListCtrl->GetItem( li );
        m_printerCommandText->SetValue( _T("lpr -P") + li.GetText() );
    }
}

bool wxGenericPrintSetupDialog::TransferDataToWindow()
{
    wxPostScriptPrintNativeData *data =
        (wxPostScriptPrintNativeData *) m_printData.GetNativeData();

    if (m_printerCommandText && data->GetPrinterCommand())
        m_printerCommandText->SetValue(data->GetPrinterCommand());
    if (m_printerOptionsText && data->GetPrinterOptions())
        m_printerOptionsText->SetValue(data->GetPrinterOptions());
    if (m_colourCheckBox)
        m_colourCheckBox->SetValue(m_printData.GetColour());

    if (m_orientationRadioBox)
    {
        if (m_printData.GetOrientation() == wxPORTRAIT)
            m_orientationRadioBox->SetSelection(0);
        else
            m_orientationRadioBox->SetSelection(1);
    }
    return true;
}

bool wxGenericPrintSetupDialog::TransferDataFromWindow()
{
    wxPostScriptPrintNativeData *data =
        (wxPostScriptPrintNativeData *) m_printData.GetNativeData();

    // find selected printer
    long id = m_printerListCtrl->GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
    if (id == 0)
    {
        m_printData.SetPrinterName( wxEmptyString );
    }
    else
    {
        wxListItem item;
        item.SetId( id );
        item.SetMask( wxLIST_MASK_TEXT );
        item.SetColumn( 1 );
        m_printerListCtrl->GetItem( item );
        m_printData.SetPrinterName( item.GetText() );
    }

    if (m_printerCommandText)
        data->SetPrinterCommand(m_printerCommandText->GetValue());
    if (m_printerOptionsText)
        data->SetPrinterOptions(m_printerOptionsText->GetValue());
    if (m_colourCheckBox)
        m_printData.SetColour(m_colourCheckBox->GetValue());
    if (m_orientationRadioBox)
    {
        int sel = m_orientationRadioBox->GetSelection();
        if (sel == 0)
            m_printData.SetOrientation(wxPORTRAIT);
        else
            m_printData.SetOrientation(wxLANDSCAPE);
    }
    if (m_paperTypeChoice)
    {
        int selectedItem = m_paperTypeChoice->GetSelection();
        if (selectedItem != -1)
        {
            wxPrintPaperType *paper = wxThePrintPaperDatabase->Item(selectedItem);
            if (paper != NULL)
              m_printData.SetPaperId( paper->GetId());
        }
    }

    if (m_targetData)
        *m_targetData = m_printData;

    return true;
}

wxComboBox *wxGenericPrintSetupDialog::CreatePaperTypeChoice()
{
    size_t n = wxThePrintPaperDatabase->GetCount();
    wxString *choices = new wxString [n];
    size_t sel = 0;

    for (size_t i = 0; i < n; i++)
    {
        wxPrintPaperType *paper = wxThePrintPaperDatabase->Item(i);
        choices[i] = paper->GetName();
        if (m_printData.GetPaperId() == paper->GetId())
            sel = i;
    }

    int width = 250;

    wxComboBox *choice = new wxComboBox( this,
                                         wxPRINTID_PAPERSIZE,
                                         _("Paper Size"),
                                         wxDefaultPosition,
                                         wxSize(width, wxDefaultCoord),
                                         n, choices );

    delete[] choices;

    choice->SetSelection(sel);
    return choice;
}

#endif // wxUSE_POSTSCRIPT

// ----------------------------------------------------------------------------
// Generic page setup dialog
// ----------------------------------------------------------------------------

IMPLEMENT_CLASS(wxGenericPageSetupDialog, wxPageSetupDialogBase)

BEGIN_EVENT_TABLE(wxGenericPageSetupDialog, wxPageSetupDialogBase)
    EVT_BUTTON(wxPRINTID_SETUP, wxGenericPageSetupDialog::OnPrinter)
END_EVENT_TABLE()

wxGenericPageSetupDialog::wxGenericPageSetupDialog( wxWindow *parent,
                                                    wxPageSetupDialogData* data)
    : wxPageSetupDialogBase( parent,
                wxID_ANY,
                _("Page Setup"),
                wxPoint(0,0),
                wxSize(600, 600),
                wxDEFAULT_DIALOG_STYLE|wxTAB_TRAVERSAL )
{
    if (data)
        m_pageData = *data;

    int textWidth = 80;

    wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL );

    // 1) top
    wxStaticBoxSizer *topsizer = new wxStaticBoxSizer(
      new wxStaticBox(this,wxPRINTID_STATIC, _("Paper size")), wxHORIZONTAL );

    size_t      n = wxThePrintPaperDatabase->GetCount();
    wxString   *choices = new wxString [n];

    for (size_t i = 0; i < n; i++)
    {
        wxPrintPaperType *paper = wxThePrintPaperDatabase->Item(i);
        choices[i] = paper->GetName();
    }

    m_paperTypeChoice = new wxComboBox( this,
                                        wxPRINTID_PAPERSIZE,
                                        _("Paper Size"),
                                        wxDefaultPosition,
                                        wxSize(300, wxDefaultCoord),
                                        n, choices );
    topsizer->Add( m_paperTypeChoice, 1, wxEXPAND|wxALL, 5 );
//  m_paperTypeChoice->SetSelection(sel);

    mainsizer->Add( topsizer, 0, wxTOP|wxLEFT|wxRIGHT | wxEXPAND, 10 );

    // 2) middle sizer with radio box

    wxString *choices2 = new wxString[2];
    choices2[0] = _("Portrait");
    choices2[1] = _("Landscape");
    m_orientationRadioBox = new wxRadioBox(this, wxPRINTID_ORIENTATION, _("Orientation"),
        wxDefaultPosition, wxDefaultSize, 2, choices2, 2);
    m_orientationRadioBox->SetSelection(0);

    mainsizer->Add( m_orientationRadioBox, 0, wxTOP|wxLEFT|wxRIGHT, 10 );

    // 3) margins

    wxBoxSizer *table = new wxBoxSizer( wxHORIZONTAL );

    wxBoxSizer *column1 = new wxBoxSizer( wxVERTICAL );
    column1->Add( new wxStaticText(this, wxPRINTID_STATIC, _("Left margin (mm):")),1,wxALL|wxALIGN_RIGHT,5 );
    column1->Add( new wxStaticText(this, wxPRINTID_STATIC, _("Top margin (mm):")),1,wxALL|wxALIGN_RIGHT,5 );
    table->Add( column1, 0, wxALL | wxEXPAND, 5 );

    wxBoxSizer *column2 = new wxBoxSizer( wxVERTICAL );
    m_marginLeftText = new wxTextCtrl(this, wxPRINTID_LEFTMARGIN, wxEmptyString, wxDefaultPosition, wxSize(textWidth, wxDefaultCoord));
    m_marginTopText = new wxTextCtrl(this, wxPRINTID_TOPMARGIN, wxEmptyString, wxDefaultPosition, wxSize(textWidth, wxDefaultCoord));
    column2->Add( m_marginLeftText, 1, wxALL, 5 );
    column2->Add( m_marginTopText, 1, wxALL, 5 );
    table->Add( column2, 0, wxRIGHT|wxTOP|wxBOTTOM | wxEXPAND, 5 );

    wxBoxSizer *column3 = new wxBoxSizer( wxVERTICAL );
    column3->Add( new wxStaticText(this, wxPRINTID_STATIC, _("Right margin (mm):")),1,wxALL|wxALIGN_RIGHT,5 );
    column3->Add( new wxStaticText(this, wxPRINTID_STATIC, _("Bottom margin (mm):")),1,wxALL|wxALIGN_RIGHT,5 );
    table->Add( column3, 0, wxALL | wxEXPAND, 5 );

    wxBoxSizer *column4 = new wxBoxSizer( wxVERTICAL );
    m_marginRightText = new wxTextCtrl(this, wxPRINTID_RIGHTMARGIN, wxEmptyString, wxDefaultPosition, wxSize(textWidth, wxDefaultCoord));
    m_marginBottomText = new wxTextCtrl(this, wxPRINTID_BOTTOMMARGIN, wxEmptyString, wxDefaultPosition, wxSize(textWidth, wxDefaultCoord));
    column4->Add( m_marginRightText, 1, wxALL, 5 );
    column4->Add( m_marginBottomText, 1, wxALL, 5 );
    table->Add( column4, 0, wxRIGHT|wxTOP|wxBOTTOM | wxEXPAND, 5 );

    mainsizer->Add( table, 0 );

#if wxUSE_STATLINE
    // 5) static line
    mainsizer->Add( new wxStaticLine( this, wxID_ANY ), 0, wxEXPAND | wxLEFT|wxRIGHT|wxTOP, 10 );
#endif

    // 6) buttons

    wxSizer* buttonsizer = CreateButtonSizer( wxOK|wxCANCEL);

    if (wxPrintFactory::GetFactory()->HasPrintSetupDialog())
    {
        m_printerButton = new wxButton(this, wxPRINTID_SETUP, _("Printer...") );
        buttonsizer->Add( m_printerButton, 0, wxLEFT|wxRIGHT, 10 );
        if ( !m_pageData.GetEnablePrinter() )
            m_printerButton->Enable(false);
    }
    else
    {
        m_printerButton = NULL;
    }

    //  if (m_printData.GetEnableHelp())
    //  wxButton *helpButton = new wxButton(this, (wxFunction)wxGenericPageSetupHelpProc, _("Help"), wxDefaultCoord, wxDefaultCoord, buttonWidth, buttonHeight);
    mainsizer->Add( buttonsizer, 0, wxEXPAND|wxALL, 10 );

    SetAutoLayout( true );
    SetSizer( mainsizer );

    mainsizer->Fit( this );
    Centre(wxBOTH);

    InitDialog();

    delete[] choices;
    delete [] choices2;
}

wxGenericPageSetupDialog::~wxGenericPageSetupDialog()
{
}

wxPageSetupDialogData& wxGenericPageSetupDialog::GetPageSetupDialogData()
{
    return m_pageData;
}

bool wxGenericPageSetupDialog::TransferDataToWindow()
{
    if (m_marginLeftText)
        m_marginLeftText->SetValue(wxString::Format(wxT("%d"), m_pageData.GetMarginTopLeft().x));
    if (m_marginTopText)
        m_marginTopText->SetValue(wxString::Format(wxT("%d"), m_pageData.GetMarginTopLeft().y));
    if (m_marginRightText)
        m_marginRightText->SetValue(wxString::Format(wxT("%d"), m_pageData.GetMarginBottomRight().x));
    if (m_marginBottomText)
        m_marginBottomText->SetValue(wxString::Format(wxT("%d"), m_pageData.GetMarginBottomRight().y));

    if (m_orientationRadioBox)
    {
        if (m_pageData.GetPrintData().GetOrientation() == wxPORTRAIT)
            m_orientationRadioBox->SetSelection(0);
        else
            m_orientationRadioBox->SetSelection(1);
    }

    // Find the paper type from either the current paper size in the wxPageSetupDialogData, or
    // failing that, the id in the wxPrintData object.

    wxPrintPaperType* type = wxThePrintPaperDatabase->FindPaperType(
             wxSize(m_pageData.GetPaperSize().x * 10, m_pageData.GetPaperSize().y * 10));

    if (!type && m_pageData.GetPrintData().GetPaperId() != wxPAPER_NONE)
        type = wxThePrintPaperDatabase->FindPaperType(m_pageData.GetPrintData().GetPaperId());

    if (type)
    {
        m_paperTypeChoice->SetStringSelection(type->GetName());
    }

    return true;
}

bool wxGenericPageSetupDialog::TransferDataFromWindow()
{
    if (m_marginLeftText && m_marginTopText)
    {
        int left = wxAtoi( m_marginLeftText->GetValue().c_str() );
        int top = wxAtoi( m_marginTopText->GetValue().c_str() );
        m_pageData.SetMarginTopLeft( wxPoint(left,top) );
    }
    if (m_marginRightText && m_marginBottomText)
    {
        int right = wxAtoi( m_marginRightText->GetValue().c_str() );
        int bottom = wxAtoi( m_marginBottomText->GetValue().c_str() );
        m_pageData.SetMarginBottomRight( wxPoint(right,bottom) );
    }

    if (m_orientationRadioBox)
    {
        int sel = m_orientationRadioBox->GetSelection();
        if (sel == 0)
        {
            m_pageData.GetPrintData().SetOrientation(wxPORTRAIT);
        }
        else
        {
            m_pageData.GetPrintData().SetOrientation(wxLANDSCAPE);
        }
    }

    if (m_paperTypeChoice)
    {
        int selectedItem = m_paperTypeChoice->GetSelection();
        if (selectedItem != -1)
        {
            wxPrintPaperType *paper = wxThePrintPaperDatabase->Item(selectedItem);
            if ( paper )
            {
                m_pageData.SetPaperSize(wxSize(paper->GetWidth()/10, paper->GetHeight()/10));
                m_pageData.GetPrintData().SetPaperId(paper->GetId());
            }
        }
    }

    return true;
}

wxComboBox *wxGenericPageSetupDialog::CreatePaperTypeChoice(int *x, int *y)
{
/*
    if (!wxThePrintPaperDatabase)
    {
        wxThePrintPaperDatabase = new wxPrintPaperDatabase;
        wxThePrintPaperDatabase->CreateDatabase();
    }
*/

    size_t      n = wxThePrintPaperDatabase->GetCount();
    wxString   *choices = new wxString [n];

    for (size_t i = 0; i < n; i++)
    {
        wxPrintPaperType *paper = wxThePrintPaperDatabase->Item(i);
        choices[i] = paper->GetName();
    }

    (void) new wxStaticText(this, wxPRINTID_STATIC, _("Paper size"), wxPoint(*x, *y));
    *y += 25;

    wxComboBox *choice = new wxComboBox( this,
                                         wxPRINTID_PAPERSIZE,
                                         _("Paper Size"),
                                         wxPoint(*x, *y),
                                         wxSize(300, wxDefaultCoord),
                                         n, choices );
    *y += 35;
    delete[] choices;

//    choice->SetSelection(sel);
    return choice;
}

void wxGenericPageSetupDialog::OnPrinter(wxCommandEvent& WXUNUSED(event))
{
    // We no longer query GetPrintMode, so we can eliminate the need
    // to call SetPrintMode.
    // This has the limitation that we can't explicitly call the PostScript
    // print setup dialog from the generic Page Setup dialog under Windows,
    // but since this choice would only happen when trying to do PostScript
    // printing under Windows (and only in 16-bit Windows which
    // doesn't have a Windows-specific page setup dialog) it's worth it.

    // First save the current settings, so the wxPrintData object is up to date.
    TransferDataFromWindow();

    // Transfer the current print settings from this dialog to the page setup dialog.

#if 0
    // Use print factory later

    wxPrintDialogData data;
    data = GetPageSetupData().GetPrintData();
    data.SetSetupDialog(true);
    wxPrintDialog printDialog(this, & data);
    printDialog.ShowModal();

    // Transfer the page setup print settings from the page dialog to this dialog again, in case
    // the page setup dialog changed something.
    GetPageSetupData().GetPrintData() = printDialog.GetPrintDialogData().GetPrintData();
    GetPageSetupData().CalculatePaperSizeFromId(); // Make sure page size reflects the id in wxPrintData

    // Now update the dialog in case the page setup dialog changed some of our settings.
    TransferDataToWindow();
#endif
}

#endif


text:
package com.zyeeda.framework.nosql.internal;

import org.apache.commons.configuration.Configuration;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.DB;
import com.mongodb.DBAddress;
import com.mongodb.Mongo;
import com.zyeeda.framework.config.ConfigurationService;
import com.zyeeda.framework.nosql.MongoDbService;
import com.zyeeda.framework.service.AbstractService;

@Marker(Primary.class)
@ServiceId("default-mongodb-service")
public class DefaultMongoDbServiceProvider extends AbstractService implements
		MongoDbService {

	private final static Logger logger = LoggerFactory.getLogger(DefaultMongoDbServiceProvider.class);

	private final static String HOST_KEY = "host";
	private final static String PORT_KEY = "port";
	private final static String SYSTEM_USERNAME_KEY = "systemUsername";
	private final static String SYSTEM_PASSWORD_KEY = "systemPassword";
	private final static String DEFAULT_DATABASE_NAME_KEY = "defaultDatabaseName";

	private final static String DEFAULT_DEFAULT_DATABASE_NAME = "zyeeda-framework";

	private ConfigurationService configSvc;

	private String host;
	private int port;
	private String systemUsername;
	private String defaultDatabaseName;

	private Configuration config;
	private Mongo mongo;

	public DefaultMongoDbServiceProvider(RegistryShutdownHub shutdownHub,
			@Primary ConfigurationService configSvc) {
		super(shutdownHub);

		this.configSvc = configSvc;

		Configuration config = this.getConfiguration(this.configSvc);
		this.init(config);
	}

	private void init(Configuration config) {
		this.config = config;

		this.host = config.getString(HOST_KEY, DBAddress.defaultHost());
		this.port = config.getInt(PORT_KEY, DBAddress.defaultPort());
		this.systemUsername = config.getString(SYSTEM_USERNAME_KEY);
		this.defaultDatabaseName = config.getString(DEFAULT_DATABASE_NAME_KEY, DEFAULT_DEFAULT_DATABASE_NAME);

		if (logger.isDebugEnabled()) {
			logger.debug("{} = {}", HOST_KEY, this.host);
			logger.debug("{} = {}", PORT_KEY, this.port);
			logger.debug("{} = {}", SYSTEM_USERNAME_KEY, this.systemUsername);
			logger.debug("{} = {}", SYSTEM_PASSWORD_KEY, "******");
			logger.debug("{} = {}", DEFAULT_DATABASE_NAME_KEY, this.defaultDatabaseName);
		}
	}

	@Override
	public void start() throws Exception {
		this.mongo = new Mongo(this.host, this.port);
		DB adminDb = this.mongo.getDB("admin");
		String systemPassword = this.config.getString(SYSTEM_PASSWORD_KEY);
		if (this.systemUsername != null && systemPassword != null) {
			adminDb.authenticate(this.systemUsername, systemPassword.toCharArray());
		}
	}

	@Override
	public void stop() {
		this.mongo.close();
	}

	@Override
	public Mongo getMongo() {
		return this.mongo;
	}

	@Override
	public DB getDefaultDatabase() {
		return this.getDatabase(this.defaultDatabaseName);
	}

	@Override
	public DB getDatabase(String name) {
		return this.mongo.getDB(name);
	}

}


text:
package org.camelcookbook.transactions.dao;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Utility class for accessing the messages table used in the database examples.
 */
public class MessageDao {

    private final JdbcTemplate jdbcTemplate;

    public MessageDao(DataSource dataSource) {
        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public int getMessageCount(String message) {
        return jdbcTemplate.queryForObject("select count(*) from messages where message = ?", Integer.class, message);
    }
}


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Article.slider_image'
        db.add_column(u'myblog_article', 'slider_image',
                      self.gf('django.db.models.fields.URLField')(default='static/light.jpg', max_length=200),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Article.slider_image'
        db.delete_column(u'myblog_article', 'slider_image')

    models = {
        u'myblog.article': {
            'Meta': {'object_name': 'Article'},
            'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['myblog.Author']"}),
            'comment': ('django.db.models.fields.TextField', [], {'default': "''", 'max_length': '300'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'image': ('django.db.models.fields.URLField', [], {'default': "'static/light.jpg'", 'max_length': '200'}),
            'pub_date': ('django.db.models.fields.DateTimeField', [], {}),
            'rating': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'slider_image': ('django.db.models.fields.URLField', [], {'default': "'static/light.jpg'", 'max_length': '200'}),
            'text': ('django.db.models.fields.TextField', [], {'max_length': '1000000000'}),
            'title': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '30'})
        },
        u'myblog.author': {
            'Meta': {'object_name': 'Author'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '30'})
        }
    }

    complete_apps = ['myblog']


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
	<style name="BT_spinner">
	    <item name="android:windowFrame">@null</item>
	    <item name="android:windowBackground">@android:color/transparent</item>
	    <item name="android:windowIsFloating">true</item>
	    <item name="android:windowContentOverlay">@null</item>
	    <item name="android:windowTitleStyle">@null</item>
	    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
	    <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
	    <item name="android:backgroundDimEnabled">false</item>
	    <item name="android:background">@android:color/transparent</item>
	</style>
</resources>


text:
Represents a ProductVariation.

## Model Reference

| Name       | Type   | Default | Description                            |
|------------|--------|---------|----------------------------------------|
| id         | int    |         | ID of the ProductVariation             |
| title      | string |         | Title of the ProductVariation          |
| price      | float  | 0.0     | Price of the ProductVariation          |
| price_nice | string | '$0.00' | Formatted string of product price      |
| sku        | string |         | InternalItemID of the ProductVariation |


text:
namespace exegesis {
namespace x86 {

// Adds the undocumented instruction FFREEP. For more information about the
// instruction see https://www.pagetable.com/?p=16.
absl::Status AddMissingFfreepInstruction(InstructionSetProto* instruction_set);

}  // namespace x86
}  // namespace exegesis

#endif  // EXEGESIS_X86_CLEANUP_INSTRUCTION_SET_MISSING_INSTRUCTIONS_H_


text:
class AddBranchToBuild < ActiveRecord::Migration[5.0]
  def change
    add_column :builds, :branch, :string
  end
end