<commit_before>/*
  A program that generates various statistical data from a user in-putted bunch
  of numbers. Specifically, it calculates the mean, median (AKA middle quartile),
  mode, lower quartile and upper quartile.
*/

//#include <cmath>
#include <iostream>
#include <vector>
#include "stats_functions.h"
// #include <algorithm>
#include <boost/algorithm/string.hpp>

int main()
{
  std::vector<float> numbers_vect;
  std::string raw_input;
  std::vector<std::string> raw_input_vect;

  // Input section
  std::cout << "Enter the list of numbers separated by spaces: ";
  std::getline(std::cin, raw_input);
  // Split numbers_str by whitespace, then converts the string vector into an float vector
  boost::split(raw_input_vect, raw_input, boost::is_any_of("\t "));
  std::transform(raw_input_vect.begin(), raw_input_vect.end(), std::back_inserter(numbers_vect), [](const std::string& val) { return std::stof(val); });

  // Sorts the numbers numerically
  std::sort(numbers_vect.begin(), numbers_vect.end());

  std::cout << "Mean: " << mean(numbers_vect) << std::endl;
  std::cout << "Median (also middle quartile): " << median(numbers_vect) << std::endl;
  std::cout << "Lower Quartile: " << lower_quartile(numbers_vect) << std::endl;
  std::cout << "Upper Quartile: " << upper_quartile(numbers_vect) << std::endl;
  std::cout << "Mode: ";

  // Makes the output of mode() a bit prettier based on the length of the return vector
  std::vector<float> mode_vector = mode(numbers_vect);
  if (mode_vector.size() == numbers_vect.size())
    {
      std::cout << "No mode found!" << std::endl;
    }
  else if (mode_vector.size() == 1)
    {
      std::cout << mode_vector[0] << std::endl;
    }
  else
    {
      for (float n = 0; n < (mode_vector.size() - 1); n++)
        {
          std::cout << mode_vector[n] << ", ";
        }
      std::cout << mode_vector.back() << std::endl;
    }
}
<commit_msg>Minor code cleanup<commit_after>/*
  A program that generates various statistical data from a user in-putted bunch
  of numbers. Specifically, it calculates the mean, median (AKA middle quartile),
  mode, lower quartile and upper quartile.
*/

#include <iostream>
#include <vector>
#include "stats_functions.h"
#include <boost/algorithm/string.hpp>

int main()
{
  std::vector<float> numbers_vect;
  std::string raw_input;
  std::vector<std::string> raw_input_vect;

  // Input section
  std::cout << "Enter the list of numbers separated by spaces: ";
  std::getline(std::cin, raw_input); // I should put this in a header
  // Split numbers_str by whitespace, then converts the string vector into an float vector
  boost::split(raw_input_vect, raw_input, boost::is_any_of("\t "));
  std::transform(raw_input_vect.begin(), raw_input_vect.end(), std::back_inserter(numbers_vect), [](const std::string& val) { return std::stof(val); });

  // Sorts the numbers numerically
  std::sort(numbers_vect.begin(), numbers_vect.end());

  std::cout << "Mean: " << mean(numbers_vect) << std::endl;
  std::cout << "Median (also middle quartile): " << median(numbers_vect) << std::endl;
  std::cout << "Lower Quartile: " << lower_quartile(numbers_vect) << std::endl;
  std::cout << "Upper Quartile: " << upper_quartile(numbers_vect) << std::endl;
  std::cout << "Mode: ";

  // Makes the output of mode() a bit prettier based on the length of the return vector
  std::vector<float> mode_vector = mode(numbers_vect);
  if (mode_vector.size() == numbers_vect.size())
    {
      std::cout << "No mode found!" << std::endl;
    }
  else if (mode_vector.size() == 1)
    {
      std::cout << mode_vector[0] << std::endl;
    }
  else
    {
      for (float n = 0; n < (mode_vector.size() - 1); n++)
        {
          std::cout << mode_vector[n] << ", ";
        }
      std::cout << mode_vector.back() << std::endl;
    }
}
<|endoftext|>


<commit_before># ifndef CPPAD_CORE_ABS_NORMAL_HPP
# define CPPAD_CORE_ABS_NORMAL_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin abs_normal$$
$spell
	Andreas Griewank
	Jens-Uwe Bernt
	Manuel Radons
	Tom Streubel
	const
$$
$latex
\newcommand{\B}[1]{ {\bf #1} }
\newcommand{\W}[1]{ \; #1 \; }
$$

$section Create An Abs-normal Representation of a Function$$

$head Under Construction$$
This is an in-progress design, and does not yet have an implementation.

$head Syntax$$
$icode%g%.abs_normal(%f%)%$$

$head Reference$$
Andreas Griewank, Jens-Uwe Bernt, Manuel Radons, Tom Streubel,
$italic Solving piecewise linear systems in abs-normal form$$,
Linear Algebra and its Applications,
vol. 471 (2015), pages 500-530.

$head f$$
The object $icode f$$ has prototype
$codei%
	const ADFun<%Base%>& %f%
%$$
It represents a function $latex f : \B{R}^n \rightarrow \B{R}^m$$.
We assume that the only non-smooth terms in the representation are
absolute value functions and use $latex s \in \B{Z}_+$$
to represent the number of these terms.

$head g$$
The object $icode g$$ has prototype
$codei%
	ADFun<%Base%> %g%
%$$
The initial function representation in $icode g$$ is lost.
Upon return it represents the smooth function
$latex g : \B{R}^{n + s} \rightarrow  \B{R}^{m + s}$$ is defined by
$latex \[
g( x , u )
=
\left[ \begin{array}{c} y(x, u) \\ z(x, u) \end{array} \right]
\] $$
were $latex y(x, u)$$ and $latex z(x, u)$$ are defined below.

$subhead a(x)$$
Let $latex \zeta_0 ( x )$$
denote the argument for the first absolute value term in $latex f(x)$$,
$latex \zeta_1 ( x , |\zeta_0 (x)| )$$ for the second term, and so on.
For $latex i = 0 , \ldots , {s-1}$$ define
$latex \[
a_i (x)
=
| \zeta_i [ x, a_0 (x) , \ldots , a_{i-1} (x) ] |
\] $$
This defines $latex a : \B{R}^n \rightarrow \B{R}^s$$.

$subhead z(x, u)$$
Define the smooth function
$latex z : \B{R}^{n + s} \rightarrow  \B{R}^s$$ by
$latex \[
z_i ( x , u ) = \zeta_i ( x , u_0 , \ldots , u_{i-1} )
\] $$

$subhead y(x, u)$$
There is a smooth function
$latex y : \B{R}^{n + s} \rightarrow  \B{R}^m$$
such that $latex y( x , u ) = f(x)$$ whenever $latex u = a(x)$$.

$head Affine Approximation$$
We define the affine approximations
$latex \[
\begin{array}{rcl}
\tilde{y}( \hat{x} \W{:} x , u )
& = &
y [ \hat{x}, a( \hat{x} ) ]
	+ \partial_x y [ \hat{x}, a( \hat{x} ) ] ( x - \hat{x} )
	+ \partial_u y [ \hat{x}, a( \hat{x} ) ] [ u - a( \hat{x} ) ]
\\
\tilde{z}( \hat{x} \W{:} x , u )
& = &
z [ \hat{x}, a( \hat{x} ) ]
	+ \partial_x z [ \hat{x}, a( \hat{x} ) ] ( x - \hat{x} )
	+ \partial_u z [ \hat{x}, a( \hat{x} ) ] [ u - a( \hat{x} ) ]
\end{array}
\] $$
It follows that
$latex \[
\begin{array}{rcl}
y( x , u )
& = &
\tilde{y}( \hat{x} \W{:} x , u ) + o [ x - \hat{x}, u - a( \hat{x} ) ]
\\
z( x , u )
& = &
\tilde{z}( \hat{x} \W{:} x , u ) + o [ x - \hat{x}, u - a( \hat{x} ) ]
\end{array}
\] $$

$head Abs-normal Approximation$$

$subhead Approximating a(x)$$
The function $latex a(x)$$ is not smooth, but it is equal to
$latex | z(x, u) |$$ when $latex u = a(x)$$.
Furthermore
$latex \[
\tilde{z}( \hat{x} \W{:} x , u )
=
z [ \hat{x}, a( \hat{x} ) ]
	+ \partial_x z [ \hat{x}, a( \hat{x} ) ] ( x - \hat{x} )
	+ \partial_u z [ \hat{x}, a( \hat{x} ) ] [ u - a( \hat{x} ) ]
\] $$
Now the partial of $latex z_i$$ with respect to $latex u_j$$ is zero
for $latex j \geq i$$. It follows that
$latex \[
\tilde{z}_i ( \hat{x} \W{:} x , u )
=
z_i [ \hat{x}, a( \hat{x} ) ]
	+ \partial_x z_i [ \hat{x}, a( \hat{x} ) ] ( x - \hat{x} )
	+ \sum_{j < i} \partial_{u(j)}
		z_i [ \hat{x}, a( \hat{x} ) ] [ u_j - a_j ( \hat{x} ) ]
\] $$
Considering the case $latex i = 0$$ we define
$latex \[
\tilde{a}_0 ( \hat{x} \W{:} x )
=
| \tilde{z}_0 ( \hat{x} \W{:} x , u ) |
=
\left|
	z_0 [ \hat{x}, a( \hat{x} ) ]
	+ \partial_x z_0 [ \hat{x}, a( \hat{x} ) ] ( x - \hat{x} )
\right|
\] $$
It follows that
$latex \[
	a_0 (x) = \tilde{a}_0 ( \hat{x} \W{:} x ) + o ( x - \hat{x} )
\] $$
In general, we define $latex \tilde{a}_i$$ using
$latex \tilde{a}_j$$ for $latex j < i$$ as follows:
$latex \[
\tilde{a}_i ( \hat{x} \W{:} x )
=
\left |
	z_i [ \hat{x}, a( \hat{x} ) ]
	+ \partial_x z_i [ \hat{x}, a( \hat{x} ) ] ( x - \hat{x} )
	+ \sum_{j < i} \partial_{u(j)}
		z_i [ \hat{x}, a( \hat{x} ) ]
			[ \tilde{a}_j ( \hat{x} \W{:} x )  - a_j ( \hat{x} ) ]
\right|
\] $$
It follows that
$latex \[
	a (x) = \tilde{a} ( \hat{x} \W{:} x ) + o ( x - \hat{x} )
\] $$
Note that in the case where $latex z(x, u)$$ and $latex y(x, u)$$ are
affine,
$latex \[
	\tilde{a} ( \hat{x} \W{:} x ) = a( x )
\] $$

$subhead Approximating f(x)$$
$latex \[
f(x)
=
y [ x , a(x) ]
=
\tilde{y} [ \hat{x} \W{:} x , \tilde{a} ( \hat{x} \W{:}  x ) ]
+ o( \Delta x )
\] $$

$head Correspondence to Literature$$
Using the notation
$latex Z = \partial_x z(\hat{x}, \hat{u})$$,
$latex L = \partial_u z(\hat{x}, \hat{u})$$,
$latex J = \partial_x y(\hat{x}, \hat{u})$$,
$latex Y = \partial_u y(\hat{x}, \hat{u})$$,
the approximation for $latex z$$ and $latex y$$ are
$latex \[
\begin{array}{rcl}
\tilde{z} ( \hat{x} \W{:} x , u )
& = &
z [ \hat{x}, a( \hat{x} ) ] + Z ( x - \hat{x} ) + L [ u - a( \hat{x} ) ]
\\
\tilde{y} ( \hat{x} \W{:} x , u )
& = &
y [ \hat{x}, a( \hat{x} ) ] + J ( x - \hat{x} ) + Y [ u - a( \hat{x} ) ]
\end{array}
\] $$
Moving the terms with $latex \hat{x}$$ together, we have
$latex \[
\begin{array}{rcl}
\tilde{z} ( \hat{x} \W{:} x , u )
& = &
z [ \hat{x}, a( \hat{x} ) ] - Z \hat{x} - L a( \hat{x} )  + Z x + L u
\\
\tilde{y} ( \hat{x} \W{:} x , u )
& = &
y [ \hat{x}, a( \hat{x} ) ] - J \hat{x} - Y a( \hat{x} )  + J x + Y u
\end{array}
\] $$
Using the notation
$latex c = z [ \hat{x}, \hat{u} ] - Z \hat{x} - L \hat{u}$$,
$latex b = y [ \hat{x}, \hat{u} ] - J \hat{x} - Y \hat{u}$$,
we have
$latex \[
\begin{array}{rcl}
\tilde{z} ( \hat{x} \W{:} x , u ) & = & c + Z x + L u
\\
\tilde{y} ( \hat{x} \W{:} x , u ) & = & b + J x + Y u
\end{array}
\] $$
Considering the affine case, where the approximations are exact,
and choosing $latex u = a(x) = |z(x, u)|$$, we obtain
$latex \[
\begin{array}{rcl}
z[ x , a(x) ] & = & c + Z x + L |z[ x , a(x) ]|
\\
y[ x , a(x) ] & = & b + J x + Y |z[ x , a(x) ]|
\end{array}
\] $$
This is Equation (2) of the reference.

$end
*/

# endif
<commit_msg>abs_normal.hpp: change [ to (, will use [ for another meaning.<commit_after># ifndef CPPAD_CORE_ABS_NORMAL_HPP
# define CPPAD_CORE_ABS_NORMAL_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin abs_normal$$
$spell
	Andreas Griewank
	Jens-Uwe Bernt
	Manuel Radons
	Tom Streubel
	const
$$
$latex
\newcommand{\B}[1]{ {\bf #1} }
\newcommand{\W}[1]{ \; #1 \; }
$$

$section Create An Abs-normal Representation of a Function$$

$head Under Construction$$
This is an in-progress design, and does not yet have an implementation.

$head Syntax$$
$icode%g%.abs_normal(%f%)%$$

$head Reference$$
Andreas Griewank, Jens-Uwe Bernt, Manuel Radons, Tom Streubel,
$italic Solving piecewise linear systems in abs-normal form$$,
Linear Algebra and its Applications,
vol. 471 (2015), pages 500-530.

$head f$$
The object $icode f$$ has prototype
$codei%
	const ADFun<%Base%>& %f%
%$$
It represents a function $latex f : \B{R}^n \rightarrow \B{R}^m$$.
We assume that the only non-smooth terms in the representation are
absolute value functions and use $latex s \in \B{Z}_+$$
to represent the number of these terms.

$head g$$
The object $icode g$$ has prototype
$codei%
	ADFun<%Base%> %g%
%$$
The initial function representation in $icode g$$ is lost.
Upon return it represents the smooth function
$latex g : \B{R}^{n + s} \rightarrow  \B{R}^{m + s}$$ is defined by
$latex \[
g( x , u )
=
\left[ \begin{array}{c} y(x, u) \\ z(x, u) \end{array} \right]
\] $$
were $latex y(x, u)$$ and $latex z(x, u)$$ are defined below.

$subhead a(x)$$
Let $latex \zeta_0 ( x )$$
denote the argument for the first absolute value term in $latex f(x)$$,
$latex \zeta_1 ( x , |\zeta_0 (x)| )$$ for the second term, and so on.
For $latex i = 0 , \ldots , {s-1}$$ define
$latex \[
a_i (x)
=
| \zeta_i ( x , a_0 (x) , \ldots , a_{i-1} (x ) ) |
\] $$
This defines $latex a : \B{R}^n \rightarrow \B{R}^s$$.

$subhead z(x, u)$$
Define the smooth function
$latex z : \B{R}^{n + s} \rightarrow  \B{R}^s$$ by
$latex \[
z_i ( x , u ) = \zeta_i ( x , u_0 , \ldots , u_{i-1} )
\] $$

$subhead y(x, u)$$
There is a smooth function
$latex y : \B{R}^{n + s} \rightarrow  \B{R}^m$$
such that $latex y( x , u ) = f(x)$$ whenever $latex u = a(x)$$.

$head Affine Approximation$$
We define the affine approximations
$latex \[
\begin{array}{rcl}
\tilde{y}( \hat{x} \W{:} x , u )
& = &
y ( \hat{x}, a( \hat{x} ) )
	+ \partial_x y ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
	+ \partial_u y ( \hat{x}, a( \hat{x} ) ) ( u - a( \hat{x} ) )
\\
\tilde{z}( \hat{x} \W{:} x , u )
& = &
z ( \hat{x}, a( \hat{x} ) )
	+ \partial_x z ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
	+ \partial_u z ( \hat{x}, a( \hat{x} ) ) ( u - a( \hat{x} ) )
\end{array}
\] $$
It follows that
$latex \[
\begin{array}{rcl}
y( x , u )
& = &
\tilde{y}( \hat{x} \W{:} x , u ) + o ( x - \hat{x}, u - a( \hat{x} ) )
\\
z( x , u )
& = &
\tilde{z}( \hat{x} \W{:} x , u ) + o ( x - \hat{x}, u - a( \hat{x} ) )
\end{array}
\] $$

$head Abs-normal Approximation$$

$subhead Approximating a(x)$$
The function $latex a(x)$$ is not smooth, but it is equal to
$latex | z(x, u) |$$ when $latex u = a(x)$$.
Furthermore
$latex \[
\tilde{z}( \hat{x} \W{:} x , u )
=
z ( \hat{x}, a( \hat{x} ) )
	+ \partial_x z ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
	+ \partial_u z ( \hat{x}, a( \hat{x} ) ) ( u - a( \hat{x} ) )
\] $$
Now the partial of $latex z_i$$ with respect to $latex u_j$$ is zero
for $latex j \geq i$$. It follows that
$latex \[
\tilde{z}_i ( \hat{x} \W{:} x , u )
=
z_i ( \hat{x}, a( \hat{x} ) )
	+ \partial_x z_i ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
	+ \sum_{j < i} \partial_{u(j)}
		z_i ( \hat{x}, a( \hat{x} ) ) ( u_j - a_j ( \hat{x} ) )
\] $$
Considering the case $latex i = 0$$ we define
$latex \[
\tilde{a}_0 ( \hat{x} \W{:} x )
=
| \tilde{z}_0 ( \hat{x} \W{:} x , u ) |
=
\left|
	z_0 ( \hat{x}, a( \hat{x} ) )
	+ \partial_x z_0 ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
\right|
\] $$
It follows that
$latex \[
	a_0 (x) = \tilde{a}_0 ( \hat{x} \W{:} x ) + o ( x - \hat{x} )
\] $$
In general, we define $latex \tilde{a}_i$$ using
$latex \tilde{a}_j$$ for $latex j < i$$ as follows:
$latex \[
\tilde{a}_i ( \hat{x} \W{:} x )
=
\left |
	z_i ( \hat{x}, a( \hat{x} ) )
	+ \partial_x z_i ( \hat{x}, a( \hat{x} ) ) ( x - \hat{x} )
	+ \sum_{j < i} \partial_{u(j)}
		z_i ( \hat{x}, a( \hat{x} ) )
			( \hat{a}_j ( \hat{x} \W{:} x )  - a_j ( \hat{x} ) )
\right|
\] $$
It follows that
$latex \[
	a (x) = \tilde{a} ( \hat{x} \W{:} x ) + o ( x - \hat{x} )
\] $$
Note that in the case where $latex z(x, u)$$ and $latex y(x, u)$$ are
affine,
$latex \[
	\tilde{a} ( \hat{x} \W{:} x ) = a( x )
\] $$

$subhead Approximating f(x)$$
$latex \[
f(x)
=
y ( x , a(x ) )
=
\tilde{y} ( \hat{x} \W{:} x , \tilde{a} ( \hat{x} \W{:}  x ) )
+ o( \Delta x )
\] $$

$head Correspondence to Literature$$
Using the notation
$latex Z = \partial_x z(\hat{x}, \hat{u})$$,
$latex L = \partial_u z(\hat{x}, \hat{u})$$,
$latex J = \partial_x y(\hat{x}, \hat{u})$$,
$latex Y = \partial_u y(\hat{x}, \hat{u})$$,
the approximation for $latex z$$ and $latex y$$ are
$latex \[
\begin{array}{rcl}
\tilde{z} ( \hat{x} \W{:} x , u )
& = &
z ( \hat{x}, a( \hat{x} ) ) + Z ( x - \hat{x} ) + L ( u - a( \hat{x} ) )
\\
\tilde{y} ( \hat{x} \W{:} x , u )
& = &
y ( \hat{x}, a( \hat{x} ) ) + J ( x - \hat{x} ) + Y ( u - a( \hat{x} ) )
\end{array}
\] $$
Moving the terms with $latex \hat{x}$$ together, we have
$latex \[
\begin{array}{rcl}
\tilde{z} ( \hat{x} \W{:} x , u )
& = &
z ( \hat{x}, a( \hat{x} ) ) - Z \hat{x} - L a( \hat{x} )  + Z x + L u
\\
\tilde{y} ( \hat{x} \W{:} x , u )
& = &
y ( \hat{x}, a( \hat{x} ) ) - J \hat{x} - Y a( \hat{x} )  + J x + Y u
\end{array}
\] $$
Using the notation
$latex c = z ( \hat{x}, \hat{u} ) - Z \hat{x} - L \hat{u}$$,
$latex b = y ( \hat{x}, \hat{u} ) - J \hat{x} - Y \hat{u}$$,
we have
$latex \[
\begin{array}{rcl}
\tilde{z} ( \hat{x} \W{:} x , u ) & = & c + Z x + L u
\\
\tilde{y} ( \hat{x} \W{:} x , u ) & = & b + J x + Y u
\end{array}
\] $$
Considering the affine case, where the approximations are exact,
and choosing $latex u = a(x) = |z(x, u)|$$, we obtain
$latex \[
\begin{array}{rcl}
z( x , a(x ) ) & = & c + Z x + L |z( x , a(x ) )|
\\
y( x , a(x ) ) & = & b + J x + Y |z( x , a(x ) )|
\end{array}
\] $$
This is Equation (2) of the reference.

$end
*/

# endif
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "cql3/column_identifier.hh"
#include "exceptions/exceptions.hh"
#include "cql3/selection/simple_selector.hh"

#include <regex>

namespace cql3 {

column_identifier::column_identifier(sstring raw_text, bool keep_case) {
    _text = std::move(raw_text);
    if (!keep_case) {
        std::transform(_text.begin(), _text.end(), _text.begin(), ::tolower);
    }
    bytes_ = to_bytes(_text);
}

column_identifier::column_identifier(bytes bytes_, data_type type)
    : bytes_(std::move(bytes_))
    , _text(type->get_string(this->bytes_))
{ }

column_identifier::column_identifier(bytes bytes_, sstring text)
    : bytes_(std::move(bytes_))
    , _text(std::move(text))
{ }

bool column_identifier::operator==(const column_identifier& other) const {
    return bytes_ == other.bytes_;
}

const sstring& column_identifier::text() const {
    return _text;
}

const bytes& column_identifier::name() const {
    return bytes_;
}

sstring column_identifier::to_string() const {
    return _text;
}

sstring column_identifier::to_cql_string() const {
    static const std::regex unquoted_identifier_re("[a-z][a-z0-9_]*");
    if (std::regex_match(_text.begin(), _text.end(), unquoted_identifier_re)) {
        return _text;
    }
    static const std::regex double_quote_re("\"");
    std::string result = _text;
    std::regex_replace(result, double_quote_re, "\"\"");
    return '"' + result + '"';
}

column_identifier::raw::raw(sstring raw_text, bool keep_case)
    : _raw_text{raw_text}
    , _text{raw_text}
{
    if (!keep_case) {
        std::transform(_text.begin(), _text.end(), _text.begin(), ::tolower);
    }
}

::shared_ptr<selection::selectable> column_identifier::raw::prepare(schema_ptr s) {
    return prepare_column_identifier(s);
}

::shared_ptr<column_identifier>
column_identifier::raw::prepare_column_identifier(schema_ptr schema) {
    if (schema->regular_column_name_type() == utf8_type) {
        return ::make_shared<column_identifier>(_text, true);
    }

    // We have a Thrift-created table with a non-text comparator.  We need to parse column names with the comparator
    // to get the correct ByteBuffer representation.  However, this doesn't apply to key aliases, so we need to
    // make a special check for those and treat them normally.  See CASSANDRA-8178.
    auto text_bytes = to_bytes(_text);
    auto def = schema->get_column_definition(text_bytes);
    if (def) {
        return ::make_shared<column_identifier>(std::move(text_bytes), _text);
    }

    return ::make_shared<column_identifier>(schema->regular_column_name_type()->from_string(_raw_text), _text);
}

bool column_identifier::raw::processes_selection() const {
    return false;
}

bool column_identifier::raw::operator==(const raw& other) const {
    return _text == other._text;
}

bool column_identifier::raw::operator!=(const raw& other) const {
    return !operator==(other);
}

sstring column_identifier::raw::to_string() const {
    return _text;
}

std::ostream& operator<<(std::ostream& out, const column_identifier::raw& id) {
    return out << id._text;
}

::shared_ptr<selection::selector::factory>
column_identifier::new_selector_factory(database& db, schema_ptr schema, std::vector<const column_definition*>& defs) {
    auto def = get_column_definition(schema, *this);
    if (!def) {
        throw exceptions::invalid_request_exception(sprint("Undefined name %s in selection clause", _text));
    }

    return selection::simple_selector::new_factory(def->name_as_text(), add_and_get_index(*def, defs), def->type);
}

}

bool cql3::column_identifier::text_comparator::operator()(const cql3::column_identifier& c1, const cql3::column_identifier& c2) const {
    return c1.text() < c2.text();
}
<commit_msg>column_identifier::to_cql_string() using maybe_quote()<commit_after>/*
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "cql3/column_identifier.hh"
#include "exceptions/exceptions.hh"
#include "cql3/selection/simple_selector.hh"
#include "cql3/util.hh"

#include <regex>

namespace cql3 {

column_identifier::column_identifier(sstring raw_text, bool keep_case) {
    _text = std::move(raw_text);
    if (!keep_case) {
        std::transform(_text.begin(), _text.end(), _text.begin(), ::tolower);
    }
    bytes_ = to_bytes(_text);
}

column_identifier::column_identifier(bytes bytes_, data_type type)
    : bytes_(std::move(bytes_))
    , _text(type->get_string(this->bytes_))
{ }

column_identifier::column_identifier(bytes bytes_, sstring text)
    : bytes_(std::move(bytes_))
    , _text(std::move(text))
{ }

bool column_identifier::operator==(const column_identifier& other) const {
    return bytes_ == other.bytes_;
}

const sstring& column_identifier::text() const {
    return _text;
}

const bytes& column_identifier::name() const {
    return bytes_;
}

sstring column_identifier::to_string() const {
    return _text;
}

sstring column_identifier::to_cql_string() const {
    return util::maybe_quote(_text);
}

column_identifier::raw::raw(sstring raw_text, bool keep_case)
    : _raw_text{raw_text}
    , _text{raw_text}
{
    if (!keep_case) {
        std::transform(_text.begin(), _text.end(), _text.begin(), ::tolower);
    }
}

::shared_ptr<selection::selectable> column_identifier::raw::prepare(schema_ptr s) {
    return prepare_column_identifier(s);
}

::shared_ptr<column_identifier>
column_identifier::raw::prepare_column_identifier(schema_ptr schema) {
    if (schema->regular_column_name_type() == utf8_type) {
        return ::make_shared<column_identifier>(_text, true);
    }

    // We have a Thrift-created table with a non-text comparator.  We need to parse column names with the comparator
    // to get the correct ByteBuffer representation.  However, this doesn't apply to key aliases, so we need to
    // make a special check for those and treat them normally.  See CASSANDRA-8178.
    auto text_bytes = to_bytes(_text);
    auto def = schema->get_column_definition(text_bytes);
    if (def) {
        return ::make_shared<column_identifier>(std::move(text_bytes), _text);
    }

    return ::make_shared<column_identifier>(schema->regular_column_name_type()->from_string(_raw_text), _text);
}

bool column_identifier::raw::processes_selection() const {
    return false;
}

bool column_identifier::raw::operator==(const raw& other) const {
    return _text == other._text;
}

bool column_identifier::raw::operator!=(const raw& other) const {
    return !operator==(other);
}

sstring column_identifier::raw::to_string() const {
    return _text;
}

std::ostream& operator<<(std::ostream& out, const column_identifier::raw& id) {
    return out << id._text;
}

::shared_ptr<selection::selector::factory>
column_identifier::new_selector_factory(database& db, schema_ptr schema, std::vector<const column_definition*>& defs) {
    auto def = get_column_definition(schema, *this);
    if (!def) {
        throw exceptions::invalid_request_exception(sprint("Undefined name %s in selection clause", _text));
    }

    return selection::simple_selector::new_factory(def->name_as_text(), add_and_get_index(*def, defs), def->type);
}

}

bool cql3::column_identifier::text_comparator::operator()(const cql3::column_identifier& c1, const cql3::column_identifier& c2) const {
    return c1.text() < c2.text();
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Copyright (C) 2015 ScyllaDB
 *
 * Modified by ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "cql3/update_parameters.hh"
#include "query-result-reader.hh"
#include "types/map.hh"

namespace cql3 {

const std::vector<std::pair<data_value, data_value>> *
update_parameters::get_prefetched_list(const partition_key& pkey, const clustering_key& ckey, const column_definition& column) const {

    auto row = _prefetched.find_row(pkey, column.is_static() ? clustering_key::make_empty() : ckey);

    if (row == nullptr) {
        return nullptr;
    }

    auto j = row->cells.find(column.ordinal_id);
    if (j == row->cells.end()) {
        return nullptr;
    }
    const data_value& cell = j->second;
    // Ensured by collections_as_maps flag in read_command flags
    assert(cell.type()->is_map());
    const map_type_impl& map_type = static_cast<const map_type_impl&>(*cell.type());
    return &map_type.from_value(cell);
}

update_parameters::prefetch_data::prefetch_data(schema_ptr schema)
    : rows(key_less{*schema})
    , schema(schema)
{ }

const update_parameters::prefetch_data::row*
update_parameters::prefetch_data::find_row(const partition_key& pkey, const clustering_key& ckey) const {

    // If clustering key is empty, find the first matching row of the partition defined by the partition key.
    key_view key{pkey, ckey};
    if (ckey.is_empty()) {
        const auto it = rows.lower_bound(key);
        if (it != rows.end() && rows.key_comp().pk_cmp(it->first.first, pkey) == 0) {
            return &it->second;
        }
        return nullptr;
    }
    const auto it = rows.find(key);
    return it == rows.end() ? nullptr : &it->second;
}

// Implements ResultVisitor concept from query.hh
class prefetch_data_builder {
    update_parameters::prefetch_data& _data;
    const query::partition_slice& _ps;
    schema_ptr _schema;
    std::optional<partition_key> _pkey;
    // Number of regular rows in the current partition
    uint64_t _row_count;

    // Add partition key columns to the current full row
    void add_partition_key(update_parameters::prefetch_data::row& cells, const partition_key& key)
    {
        auto i = key.begin(*_schema);
        for (auto&& col : _schema->partition_key_columns()) {
            cells.cells.emplace(col.ordinal_id, col.type->deserialize_value(*i));
            ++i;
        }
    }

    // Add clustering key columns to the current full row
    void add_clustering_key(update_parameters::prefetch_data::row& cells, const clustering_key& key)
    {
        auto i = key.begin(*_schema);
        for (auto&& col : _schema->clustering_key_columns()) {
            if (i == key.end(*_schema)) {
                break;
            }
            cells.cells.emplace(col.ordinal_id, col.type->deserialize_value(*i));
            ++i;
        }
    }

    // Add a prefetched cell to the current full row
    void add_cell(update_parameters::prefetch_data::row& cells, const column_definition& def,
            const std::optional<query::result_bytes_view>& cell) {

        if (cell == std::nullopt) {
            return;
        }
        auto type = def.type;
        // We use collections_as_maps flag, so set/list type is map, reconstruct the
        // data type used for serialization.
        if (type->is_listlike() && type->is_multi_cell()) {
            auto ctype = static_pointer_cast<const collection_type_impl>(type);
            type = map_type_impl::get_instance(ctype->name_comparator(), ctype->value_comparator(), true);
        }
        cell->with_linearized([&] (bytes_view cell_view) {
            cells.cells.emplace(def.ordinal_id, type->deserialize(cell_view));
        });
    };
public:
    prefetch_data_builder(schema_ptr s, update_parameters::prefetch_data& data, const query::partition_slice& ps)
        : _data(data)
        , _ps(ps)
        , _schema(std::move(s))
        , _row_count(0)
    { }

    void accept_new_partition(const partition_key& key, uint64_t row_count) {
        _pkey = key;
        _row_count = row_count;
    }

    void accept_new_partition(uint64_t row_count) {
        assert(0);
    }

    void accept_new_row(const clustering_key& key, const query::result_row_view& static_row,
                    const query::result_row_view& row) {
        update_parameters::prefetch_data::row cells;

        add_partition_key(cells, *_pkey);
        add_clustering_key(cells, key);
        auto static_row_iterator = static_row.iterator();
        for (auto&& id : _ps.static_columns) {
            add_cell(cells, _schema->static_column_at(id), static_row_iterator.next_collection_cell());
        }
        auto row_iterator = row.iterator();
        for (auto&& id : _ps.regular_columns) {
            add_cell(cells, _schema->regular_column_at(id), row_iterator.next_collection_cell());
        }

        _data.rows.emplace(std::make_pair(*_pkey, key), std::move(cells));
    }

    void accept_new_row(const query::result_row_view& static_row, const query::result_row_view& row) {
        assert(0);
    }

    void accept_partition_end(const query::result_row_view& static_row) {

        if (_row_count > 0) {
            // Static row cells have been added into every regular row.
            return;
        }
        // The partition contains only a static row. Add it.

        update_parameters::prefetch_data::row cells;
        add_partition_key(cells, *_pkey);

        auto static_row_iterator = static_row.iterator();
        for (auto&& id : _ps.static_columns) {
            add_cell(cells, _schema->static_column_at(id), static_row_iterator.next_collection_cell());
        }
        // There are no regular rows in the partition. Use empty clustering key prefix to create
        // a row with static columns.
        // _row_count > 0 check above prevents entering this branch for tables with no clustering
        // key (and thus no static row), but even if it didn't, emplace() for such a table would do
        // nothing, since an element with the same key (partition key, empty clustering key, cells)
        // has already been added to the map by accept_new_row(), called earlier on the same
        // partition key.
        _data.rows.emplace(std::make_pair(*_pkey, clustering_key_prefix::make_empty()), std::move(cells));
    }
};

update_parameters::prefetch_data update_parameters::build_prefetch_data(schema_ptr schema, const query::result& query_result,
            const query::partition_slice& slice) {

    update_parameters::prefetch_data rows(schema);
    query::result_view::consume(query_result, slice, prefetch_data_builder(schema, rows, slice));
    return rows;
}

} // end of namespace cql3
<commit_msg>cql3: update_parameters: don't linearize in prefetch_data_builder::add_cell<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Copyright (C) 2015 ScyllaDB
 *
 * Modified by ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "cql3/update_parameters.hh"
#include "query-result-reader.hh"
#include "types/map.hh"

namespace cql3 {

const std::vector<std::pair<data_value, data_value>> *
update_parameters::get_prefetched_list(const partition_key& pkey, const clustering_key& ckey, const column_definition& column) const {

    auto row = _prefetched.find_row(pkey, column.is_static() ? clustering_key::make_empty() : ckey);

    if (row == nullptr) {
        return nullptr;
    }

    auto j = row->cells.find(column.ordinal_id);
    if (j == row->cells.end()) {
        return nullptr;
    }
    const data_value& cell = j->second;
    // Ensured by collections_as_maps flag in read_command flags
    assert(cell.type()->is_map());
    const map_type_impl& map_type = static_cast<const map_type_impl&>(*cell.type());
    return &map_type.from_value(cell);
}

update_parameters::prefetch_data::prefetch_data(schema_ptr schema)
    : rows(key_less{*schema})
    , schema(schema)
{ }

const update_parameters::prefetch_data::row*
update_parameters::prefetch_data::find_row(const partition_key& pkey, const clustering_key& ckey) const {

    // If clustering key is empty, find the first matching row of the partition defined by the partition key.
    key_view key{pkey, ckey};
    if (ckey.is_empty()) {
        const auto it = rows.lower_bound(key);
        if (it != rows.end() && rows.key_comp().pk_cmp(it->first.first, pkey) == 0) {
            return &it->second;
        }
        return nullptr;
    }
    const auto it = rows.find(key);
    return it == rows.end() ? nullptr : &it->second;
}

// Implements ResultVisitor concept from query.hh
class prefetch_data_builder {
    update_parameters::prefetch_data& _data;
    const query::partition_slice& _ps;
    schema_ptr _schema;
    std::optional<partition_key> _pkey;
    // Number of regular rows in the current partition
    uint64_t _row_count;

    // Add partition key columns to the current full row
    void add_partition_key(update_parameters::prefetch_data::row& cells, const partition_key& key)
    {
        auto i = key.begin(*_schema);
        for (auto&& col : _schema->partition_key_columns()) {
            cells.cells.emplace(col.ordinal_id, col.type->deserialize_value(*i));
            ++i;
        }
    }

    // Add clustering key columns to the current full row
    void add_clustering_key(update_parameters::prefetch_data::row& cells, const clustering_key& key)
    {
        auto i = key.begin(*_schema);
        for (auto&& col : _schema->clustering_key_columns()) {
            if (i == key.end(*_schema)) {
                break;
            }
            cells.cells.emplace(col.ordinal_id, col.type->deserialize_value(*i));
            ++i;
        }
    }

    // Add a prefetched cell to the current full row
    void add_cell(update_parameters::prefetch_data::row& cells, const column_definition& def,
            const std::optional<query::result_bytes_view>& cell) {

        if (cell == std::nullopt) {
            return;
        }
        auto type = def.type;
        // We use collections_as_maps flag, so set/list type is map, reconstruct the
        // data type used for serialization.
        if (type->is_listlike() && type->is_multi_cell()) {
            auto ctype = static_pointer_cast<const collection_type_impl>(type);
            type = map_type_impl::get_instance(ctype->name_comparator(), ctype->value_comparator(), true);
        }
        cells.cells.emplace(def.ordinal_id, type->deserialize(*cell));
    };
public:
    prefetch_data_builder(schema_ptr s, update_parameters::prefetch_data& data, const query::partition_slice& ps)
        : _data(data)
        , _ps(ps)
        , _schema(std::move(s))
        , _row_count(0)
    { }

    void accept_new_partition(const partition_key& key, uint64_t row_count) {
        _pkey = key;
        _row_count = row_count;
    }

    void accept_new_partition(uint64_t row_count) {
        assert(0);
    }

    void accept_new_row(const clustering_key& key, const query::result_row_view& static_row,
                    const query::result_row_view& row) {
        update_parameters::prefetch_data::row cells;

        add_partition_key(cells, *_pkey);
        add_clustering_key(cells, key);
        auto static_row_iterator = static_row.iterator();
        for (auto&& id : _ps.static_columns) {
            add_cell(cells, _schema->static_column_at(id), static_row_iterator.next_collection_cell());
        }
        auto row_iterator = row.iterator();
        for (auto&& id : _ps.regular_columns) {
            add_cell(cells, _schema->regular_column_at(id), row_iterator.next_collection_cell());
        }

        _data.rows.emplace(std::make_pair(*_pkey, key), std::move(cells));
    }

    void accept_new_row(const query::result_row_view& static_row, const query::result_row_view& row) {
        assert(0);
    }

    void accept_partition_end(const query::result_row_view& static_row) {

        if (_row_count > 0) {
            // Static row cells have been added into every regular row.
            return;
        }
        // The partition contains only a static row. Add it.

        update_parameters::prefetch_data::row cells;
        add_partition_key(cells, *_pkey);

        auto static_row_iterator = static_row.iterator();
        for (auto&& id : _ps.static_columns) {
            add_cell(cells, _schema->static_column_at(id), static_row_iterator.next_collection_cell());
        }
        // There are no regular rows in the partition. Use empty clustering key prefix to create
        // a row with static columns.
        // _row_count > 0 check above prevents entering this branch for tables with no clustering
        // key (and thus no static row), but even if it didn't, emplace() for such a table would do
        // nothing, since an element with the same key (partition key, empty clustering key, cells)
        // has already been added to the map by accept_new_row(), called earlier on the same
        // partition key.
        _data.rows.emplace(std::make_pair(*_pkey, clustering_key_prefix::make_empty()), std::move(cells));
    }
};

update_parameters::prefetch_data update_parameters::build_prefetch_data(schema_ptr schema, const query::result& query_result,
            const query::partition_slice& slice) {

    update_parameters::prefetch_data rows(schema);
    query::result_view::consume(query_result, slice, prefetch_data_builder(schema, rows, slice));
    return rows;
}

} // end of namespace cql3
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name:      statusbar.cpp
// Purpose:   Implementation of wxExStatusbar class
// Author:    Anton van Wezenbeek
// Created:   2010-03-26
// RCS-ID:    $Id$
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#if wxUSE_TOOLTIPS
#include <wx/tooltip.h> // for GetTip
#endif
#include <wx/extension/statusbar.h>
#include <wx/extension/frame.h>

#if wxUSE_GUI

int wxExPane::m_Total = 0;

#if wxUSE_STATUSBAR
BEGIN_EVENT_TABLE(wxExStatusBar, wxStatusBar)
  EVT_LEFT_DOWN(wxExStatusBar::OnMouse)
  EVT_LEFT_DCLICK(wxExStatusBar::OnMouse)
  EVT_MOTION(wxExStatusBar::OnMouse)
END_EVENT_TABLE()

wxExStatusBar::wxExStatusBar(
  wxExFrame* parent,
  wxWindowID id,
  long style,
  const wxString& name)
  : wxStatusBar(parent, id, style, name)
  , m_Frame(parent)
{
}

const wxExPane wxExStatusBar::GetPane(int pane) const
{
  for (
    std::map<wxString, wxExPane>::const_iterator it = m_Panes.begin();
    it != m_Panes.end();
    ++it)
  {
    if (it->second.m_No == pane)
    {
      return it->second;
    }
  }

  return wxExPane();
}

void wxExStatusBar::OnMouse(wxMouseEvent& event)
{
  bool found = false;

  for (int i = 0; i < GetFieldsCount() && !found; i++)
  {
    wxRect rect;

    if (GetFieldRect(i, rect))
    {
      if (rect.Contains(event.GetPosition()))
      {
        found = true;

        // Handle the event, don't fail if none is true here,
        // it seems that moving and clicking almost at the same time
        // could cause assertions.
        if (event.ButtonDClick())
        {
          m_Frame->StatusBarDoubleClicked(GetPane(i).m_Name);
        }
        else if (event.ButtonDown())
        {
          m_Frame->StatusBarClicked(GetPane(i).m_Name);
        }
#if wxUSE_TOOLTIPS
        // Show tooltip if tooltip is available, and not yet tooltip presented.
        else if (event.Moving())
        {
          if (!m_Panes.empty())
          {
            const wxString tooltip =
              (GetToolTip() != NULL ? GetToolTip()->GetTip(): wxString(wxEmptyString));

            if (tooltip != GetPane(i).m_Helptext)
            {
              SetToolTip(GetPane(i).m_Helptext);
            }
          }
        }
#endif
      }
    }
  }

  event.Skip();
}

void wxExStatusBar::SetPanes(const std::vector<wxExPane>& panes)
{
  int* styles = new int[panes.size()];
  int* widths = new int[panes.size()];

  for (
    std::vector<wxExPane>::const_iterator it = panes.begin();
    it != panes.end();
    ++it)
  {
    m_Panes[it->m_Name] = *it;
    styles[it->m_No] = it->GetStyle();
    widths[it->m_No] = it->GetWidth();
  }

  SetStatusStyles(panes.size(), styles);
  SetStatusWidths(panes.size(), widths);

  delete[] styles;
  delete[] widths;
}

void wxExStatusBar::SetStatusText(const wxString& text, const wxString& pane)
{
  std::map<wxString, wxExPane>::const_iterator it = m_Panes.find(pane);

  if (it != m_Panes.end())
  {
    // wxStatusBar checks whether new text differs from current,
    // and does nothing if the same to avoid flicker.
    wxStatusBar::SetStatusText(text, it->second.m_No);
  }
}

#endif //wxUSE_STATUSBAR
#endif // wxUSE_GUI
<commit_msg>call GetPane only once<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name:      statusbar.cpp
// Purpose:   Implementation of wxExStatusbar class
// Author:    Anton van Wezenbeek
// Created:   2010-03-26
// RCS-ID:    $Id$
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#if wxUSE_TOOLTIPS
#include <wx/tooltip.h> // for GetTip
#endif
#include <wx/extension/statusbar.h>
#include <wx/extension/frame.h>

#if wxUSE_GUI

int wxExPane::m_Total = 0;

#if wxUSE_STATUSBAR
BEGIN_EVENT_TABLE(wxExStatusBar, wxStatusBar)
  EVT_LEFT_DOWN(wxExStatusBar::OnMouse)
  EVT_LEFT_DCLICK(wxExStatusBar::OnMouse)
  EVT_MOTION(wxExStatusBar::OnMouse)
END_EVENT_TABLE()

wxExStatusBar::wxExStatusBar(
  wxExFrame* parent,
  wxWindowID id,
  long style,
  const wxString& name)
  : wxStatusBar(parent, id, style, name)
  , m_Frame(parent)
{
}

const wxExPane wxExStatusBar::GetPane(int pane) const
{
  for (
    std::map<wxString, wxExPane>::const_iterator it = m_Panes.begin();
    it != m_Panes.end();
    ++it)
  {
    if (it->second.m_No == pane)
    {
      return it->second;
    }
  }

  return wxExPane();
}

void wxExStatusBar::OnMouse(wxMouseEvent& event)
{
  bool found = false;

  for (int i = 0; i < GetFieldsCount() && !found; i++)
  {
	const wxExPane& pane(GetPane(i));

    wxRect rect;

    if (GetFieldRect(i, rect))
    {
      if (rect.Contains(event.GetPosition()))
      {
        found = true;

        // Handle the event, don't fail if none is true here,
        // it seems that moving and clicking almost at the same time
        // could cause assertions.
        if (event.ButtonDClick())
        {
          m_Frame->StatusBarDoubleClicked(pane.m_Name);
        }
        else if (event.ButtonDown())
        {
          m_Frame->StatusBarClicked(pane.m_Name);
        }
#if wxUSE_TOOLTIPS
        // Show tooltip if tooltip is available, and not yet tooltip presented.
        else if (event.Moving())
        {
          if (!m_Panes.empty())
          {
            const wxString tooltip =
              (GetToolTip() != NULL ? GetToolTip()->GetTip(): wxString(wxEmptyString));

            if (tooltip != pane.m_Helptext)
            {
              SetToolTip(pane.m_Helptext);
            }
          }
        }
#endif
      }
    }
  }

  event.Skip();
}

void wxExStatusBar::SetPanes(const std::vector<wxExPane>& panes)
{
  int* styles = new int[panes.size()];
  int* widths = new int[panes.size()];

  for (
    std::vector<wxExPane>::const_iterator it = panes.begin();
    it != panes.end();
    ++it)
  {
    m_Panes[it->m_Name] = *it;
    styles[it->m_No] = it->GetStyle();
    widths[it->m_No] = it->GetWidth();
  }

  SetStatusStyles(panes.size(), styles);
  SetStatusWidths(panes.size(), widths);

  delete[] styles;
  delete[] widths;
}

void wxExStatusBar::SetStatusText(const wxString& text, const wxString& pane)
{
  std::map<wxString, wxExPane>::const_iterator it = m_Panes.find(pane);

  if (it != m_Panes.end())
  {
    // wxStatusBar checks whether new text differs from current,
    // and does nothing if the same to avoid flicker.
    wxStatusBar::SetStatusText(text, it->second.m_No);
  }
}

#endif //wxUSE_STATUSBAR
#endif // wxUSE_GUI
<|endoftext|>


<commit_before>//
//  ex10_25.cpp
//  Exercise 10.25
//
//  Created by pezy on 12/11/14.
//  Copyright (c) 2014 pezy. All rights reserved.
//
//  @Brief  In the exercises for 10.3.2 (p.392) you wrote a version of biggies
//  that uses partition.
//          Rewrite that function to use check_size and bind.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>

using std::string;
using std::vector;
using namespace std::placeholders;

void elimdups(vector<string>& vs)
{
    std::sort(vs.begin(), vs.end());
    vs.erase(unique(vs.begin(), vs.end()), vs.end());
}

bool check_size(const string& s, string::size_type sz)
{
    return s.size() >= sz;
}

void biggies(vector<string>& words, vector<string>::size_type sz)
{
    elimdups(words);
    auto iter = std::stable_partition(words.begin(), words.end(),
                                      bind(check_size, _1, sz));
    for_each(words.begin(), iter,
             [](const string& s) { std::cout << s << " "; });
}

int main()
{
    std::vector<std::string> v{"the",  "quick", "red",  "fox", "jumps",
                               "over", "the",   "slow", "red", "turtle"};
    biggies(v, 4);
}

//  @Out
//  jumps over quick slow turtle<commit_msg>Update ex10_25.cpp<commit_after>//
//  ex10_25.cpp
//  Exercise 10.25
//
//  Created by pezy on 12/11/14.
//  Copyright (c) 2014 pezy. All rights reserved.
//
//  @Brief  In the exercises for 10.3.2 (p.392) you wrote a version of biggies
//          that uses partition.
//          Rewrite that function to use check_size and bind.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>

using namespace std;
using namespace std::placeholders;

void elimdups(vector<string> &svec)
{
    sort(svec.begin(), svec.end());
    svec.erase(unique(svec.begin(), svec.end()), svec.end());
}

bool check_size(const string &s, string::size_type sz)
{
    return s.size()>=sz;
}

void biggies(vector<string> &words, vector<string>::size_type sz)
{
    elimdups(words);

    auto iter=partition(words.begin(), words.end(), bind(check_size, _1, sz));

    for_each(words.begin(), iter, [](const string &s) {cout<<s<<" ";});
}

int main()
{
    vector<string> svec{"the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle"};

    biggies(svec, 4);
    cout<<endl;
}

//  @Out
//  turtle jumps over quick slow
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.

 * Modified by Cloudius Systems.
 * Copyright 2015 Cloudius Systems.
 */

#pragma once

#include "types.hh"
#include "util/serialization.hh"
#include "gms/gossip_digest.hh"
#include "gms/inet_address.hh"
#include "gms/endpoint_state.hh"

namespace gms {

/**
 * This ack gets sent out as a result of the receipt of a GossipDigestSynMessage by an
 * endpoint. This is the 2 stage of the 3 way messaging in the Gossip protocol.
 */
class gossip_digest_ack {
private:
    using inet_address = gms::inet_address;
    std::vector<gossip_digest> _digests;
    std::map<inet_address, endpoint_state> _map;
public:
    gossip_digest_ack(std::vector<gossip_digest> d, std::map<inet_address, endpoint_state> m)
        : _digests(std::move(d))
        , _map(std::move(m)) {
    }

    std::vector<gossip_digest> get_gossip_digest_list() {
        return _digests;
    }

    std::map<inet_address, endpoint_state> get_endpoint_state_map() {
        return _map;
    }

    // The following replaces GossipDigestAckSerializer from the Java code
    void serialize(bytes::iterator& out) const {
        // 1) Digest
        gossip_digest_serialization_helper::serialize(out, _digests);
        // 2) Map size
        serialize_int32(out, int32_t(_map.size()));
        // 3) Map contents
        for (auto& entry : _map) {
            const inet_address& ep = entry.first;
            const endpoint_state& st = entry.second;
            ep.serialize(out);
            st.serialize(out);
        }
    }

    static gossip_digest_ack deserialize(bytes_view& v) {
        // 1) Digest
        std::vector<gossip_digest> _digests = gossip_digest_serialization_helper::deserialize(v);
        // 2) Map size
        int32_t map_size = read_simple<int32_t>(v);
        // 3) Map contents
        std::map<inet_address, endpoint_state> _map;
        for (int32_t i = 0; i < map_size; ++i) {
            inet_address ep = inet_address::deserialize(v);
            endpoint_state st = endpoint_state::deserialize(v);
            _map.emplace(std::move(ep), std::move(st));
        }
        return gossip_digest_ack(std::move(_digests), std::move(_map));
    }

    size_t serialized_size() const {
        size_t size = gossip_digest_serialization_helper::serialized_size(_digests);
        size += serialize_int32_size;
        for (auto& entry : _map) {
            const inet_address& ep = entry.first;
            const endpoint_state& st = entry.second;
            size += ep.serialized_size() + st.serialized_size();
        }
        return size;
    }
};

}
<commit_msg>gossip: Add default constructor for gossip_digest_ack<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.

 * Modified by Cloudius Systems.
 * Copyright 2015 Cloudius Systems.
 */

#pragma once

#include "types.hh"
#include "util/serialization.hh"
#include "gms/gossip_digest.hh"
#include "gms/inet_address.hh"
#include "gms/endpoint_state.hh"

namespace gms {

/**
 * This ack gets sent out as a result of the receipt of a GossipDigestSynMessage by an
 * endpoint. This is the 2 stage of the 3 way messaging in the Gossip protocol.
 */
class gossip_digest_ack {
private:
    using inet_address = gms::inet_address;
    std::vector<gossip_digest> _digests;
    std::map<inet_address, endpoint_state> _map;
public:
    gossip_digest_ack() {
    }

    gossip_digest_ack(std::vector<gossip_digest> d, std::map<inet_address, endpoint_state> m)
        : _digests(std::move(d))
        , _map(std::move(m)) {
    }

    std::vector<gossip_digest> get_gossip_digest_list() {
        return _digests;
    }

    std::map<inet_address, endpoint_state> get_endpoint_state_map() {
        return _map;
    }

    // The following replaces GossipDigestAckSerializer from the Java code
    void serialize(bytes::iterator& out) const {
        // 1) Digest
        gossip_digest_serialization_helper::serialize(out, _digests);
        // 2) Map size
        serialize_int32(out, int32_t(_map.size()));
        // 3) Map contents
        for (auto& entry : _map) {
            const inet_address& ep = entry.first;
            const endpoint_state& st = entry.second;
            ep.serialize(out);
            st.serialize(out);
        }
    }

    static gossip_digest_ack deserialize(bytes_view& v) {
        // 1) Digest
        std::vector<gossip_digest> _digests = gossip_digest_serialization_helper::deserialize(v);
        // 2) Map size
        int32_t map_size = read_simple<int32_t>(v);
        // 3) Map contents
        std::map<inet_address, endpoint_state> _map;
        for (int32_t i = 0; i < map_size; ++i) {
            inet_address ep = inet_address::deserialize(v);
            endpoint_state st = endpoint_state::deserialize(v);
            _map.emplace(std::move(ep), std::move(st));
        }
        return gossip_digest_ack(std::move(_digests), std::move(_map));
    }

    size_t serialized_size() const {
        size_t size = gossip_digest_serialization_helper::serialized_size(_digests);
        size += serialize_int32_size;
        for (auto& entry : _map) {
            const inet_address& ep = entry.first;
            const endpoint_state& st = entry.second;
            size += ep.serialized_size() + st.serialized_size();
        }
        return size;
    }
};

}
<|endoftext|>


<commit_before><commit_msg>loplugin: unnecessarysuperclass merge HashedEntryList into NameTranslationList<commit_after><|endoftext|>


<commit_before>/**
 * \file
 * <!--
 * Copyright 2015 Develer S.r.l. (http://www.develer.com/)
 * -->
 *
 * \brief SessionManager class implementation
 *
 * \author Aurelien Rainone <aurelien@develer.org>
 */

#include "sessionmanager.h"
#include "outputmanager.h"

#include <QMessageBox>
#include <QFile>

SessionManager::SessionManager(QObject *parent)
    : QObject(parent)
{
    serial = new QSerialPort(this);
    in_progress = false;

    connect(serial, &QSerialPort::readyRead, this, &SessionManager::readData);
    connect(serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>
                (&QSerialPort::error), this, &SessionManager::handleError);
}

SessionManager::~SessionManager()
{
    // closes connection if needed
    if (serial->isOpen())
        serial->close();
}

void SessionManager::handleError(QSerialPort::SerialPortError serialPortError)
{
    switch (serialPortError)
    {
        // no error
        case QSerialPort::NoError:
            break;

        // recoverable errors : inform user and clear error
        case QSerialPort::OpenError:

            QMessageBox::warning(NULL, tr("Error"), serial->errorString());
            // reset error
            serial->clearError();
            break;

        // unrecoverable errors : inform user and close the port/connection
        default:
            if (in_progress)
            {
                QMessageBox::critical(NULL, tr("Error"), serial->errorString());

                // on some error (ex: hot unplugging) the 'QSerialPort::error' property successively
                // takes multiple values.
                // to prevent from displaying successive error messages, the in_progress flag is
                // set to indicate that we are not interested by next messages, until the user tries to open
                // again the serial port
                in_progress = false;
                if (serial->isOpen())
                {
                    serial->clearError();
                    serial->close();
                }
            }
            break;
    }
}

void SessionManager::openSession(const QHash<QString, QString>& port_cfg)
{
    bool cfg_ok = true, ok;

    // try converting port config from the hash
    QSerialPort::BaudRate baud_rate = static_cast<QSerialPort::BaudRate>
            (port_cfg["baud_rate"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::DataBits data_bits = static_cast<QSerialPort::DataBits>
            (port_cfg["data_bits"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::Parity parity = static_cast<QSerialPort::Parity>
            (port_cfg["parity"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::StopBits stop_bits = static_cast<QSerialPort::StopBits>
            (port_cfg["stop_bits"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::FlowControl flow_control = static_cast<QSerialPort::FlowControl>
            (port_cfg["flow_control"].toInt(&ok));
    cfg_ok &= ok;

    // a conversion didn't make it
    Q_ASSERT_X(cfg_ok, "SessionManager::openSession", "a conversion didn't make it");

    // closes connection if needed
    if (serial->isOpen())
        serial->close();

    // open serial port
    serial->setPortName(port_cfg["device"]);
    serial->setBaudRate(baud_rate);
    serial->setDataBits(data_bits);
    serial->setParity(parity);
    serial->setStopBits(stop_bits);
    serial->setFlowControl(flow_control);

    // flag indicating that a connection is in progress (eventually successful or not)
    in_progress = true;
    if (serial->open(QIODevice::ReadWrite))
    {
        curr_cfg = port_cfg;
        emit sessionStarted();
    }
}

bool SessionManager::isSessionOpen() const
{
    return serial->isOpen();
}

void SessionManager::saveToFile(const QByteArray &data)
{
    QFile dump(curr_cfg["dump_file"]);

    // mode is OR'ed with 'Text' flag in "Ascii" mode
    QIODevice::OpenMode mode = QIODevice::Append;

    if (curr_cfg["dump_file"] == QString::number(ConnectDialog::Ascii))
        mode |= QIODevice::Text;

    if (dump.open(mode))
        dump.write(data);
}

void SessionManager::readData()
{
    QByteArray data(serial->readAll());

    emit dataReceived(data);

    // append to dump file if configured
    if (curr_cfg["dump_enabled"] == "1")
        saveToFile(data);
}

void SessionManager::sendToSerial(const QByteArray &data)
{
    serial->write(data);
}

<commit_msg>use setPort with QSerialPortInfo instead of setPortName<commit_after>/**
 * \file
 * <!--
 * Copyright 2015 Develer S.r.l. (http://www.develer.com/)
 * -->
 *
 * \brief SessionManager class implementation
 *
 * \author Aurelien Rainone <aurelien@develer.org>
 */

#include "sessionmanager.h"
#include "outputmanager.h"

#include <QMessageBox>
#include <QSerialPortInfo>
#include <QFile>

SessionManager::SessionManager(QObject *parent)
    : QObject(parent)
{
    serial = new QSerialPort(this);
    in_progress = false;

    connect(serial, &QSerialPort::readyRead, this, &SessionManager::readData);
    connect(serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>
                (&QSerialPort::error), this, &SessionManager::handleError);
}

SessionManager::~SessionManager()
{
    // closes connection if needed
    if (serial->isOpen())
        serial->close();
}

void SessionManager::handleError(QSerialPort::SerialPortError serialPortError)
{
    switch (serialPortError)
    {
        // no error
        case QSerialPort::NoError:
            break;

        // recoverable errors : inform user and clear error
        case QSerialPort::OpenError:

            QMessageBox::warning(NULL, tr("Error"), serial->errorString());
            // reset error
            serial->clearError();
            break;

        // unrecoverable errors : inform user and close the port/connection
        default:
            if (in_progress)
            {
                QMessageBox::critical(NULL, tr("Error"), serial->errorString());

                // on some error (ex: hot unplugging) the 'QSerialPort::error' property successively
                // takes multiple values.
                // to prevent from displaying successive error messages, the in_progress flag is
                // set to indicate that we are not interested by next messages, until the user tries to open
                // again the serial port
                in_progress = false;
                if (serial->isOpen())
                {
                    serial->clearError();
                    serial->close();
                }
            }
            break;
    }
}

void SessionManager::openSession(const QHash<QString, QString>& port_cfg)
{
    bool cfg_ok = true, ok;

    // try converting port config from the hash
    QSerialPort::BaudRate baud_rate = static_cast<QSerialPort::BaudRate>
            (port_cfg["baud_rate"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::DataBits data_bits = static_cast<QSerialPort::DataBits>
            (port_cfg["data_bits"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::Parity parity = static_cast<QSerialPort::Parity>
            (port_cfg["parity"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::StopBits stop_bits = static_cast<QSerialPort::StopBits>
            (port_cfg["stop_bits"].toInt(&ok));
    cfg_ok &= ok;

    QSerialPort::FlowControl flow_control = static_cast<QSerialPort::FlowControl>
            (port_cfg["flow_control"].toInt(&ok));
    cfg_ok &= ok;

    // a conversion didn't make it
    Q_ASSERT_X(cfg_ok, "SessionManager::openSession", "a conversion didn't make it");

    // closes connection if needed
    if (serial->isOpen())
        serial->close();

    // configure port
    //
    // connection error on MacOsX if port name is set with setPortName instead
    // of setPort (issue #7)
    serial->setPort(QSerialPortInfo(port_cfg[QStringLiteral("device")]));
    serial->setBaudRate(baud_rate);
    serial->setDataBits(data_bits);
    serial->setParity(parity);
    serial->setStopBits(stop_bits);
    serial->setFlowControl(flow_control);

    // flag indicating that a connection is in progress (eventually successful or not)
    in_progress = true;

    // open serial port
    if (serial->open(QIODevice::ReadWrite))
    {
        curr_cfg = port_cfg;
        emit sessionStarted();
    }
}

bool SessionManager::isSessionOpen() const
{
    return serial->isOpen();
}

void SessionManager::saveToFile(const QByteArray &data)
{
    QFile dump(curr_cfg["dump_file"]);

    // mode is OR'ed with 'Text' flag in "Ascii" mode
    QIODevice::OpenMode mode = QIODevice::Append;

    if (curr_cfg["dump_file"] == QString::number(ConnectDialog::Ascii))
        mode |= QIODevice::Text;

    if (dump.open(mode))
        dump.write(data);
}

void SessionManager::readData()
{
    QByteArray data(serial->readAll());

    emit dataReceived(data);

    // append to dump file if configured
    if (curr_cfg["dump_enabled"] == "1")
        saveToFile(data);
}

void SessionManager::sendToSerial(const QByteArray &data)
{
    serial->write(data);
}

<|endoftext|>


<commit_before>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "thread_per_process_schedule.h"

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/edge.h>
#include <vistk/pipeline/pipeline.h>
#include <vistk/pipeline/schedule_exception.h>
#include <vistk/pipeline/utils.h>

#include <boost/thread/thread.hpp>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>

/**
 * \file thread_per_process_schedule.cxx
 *
 * \brief Implementation of the thread-per-process schedule.
 */

namespace vistk
{

static void run_process(process_t process);

class thread_per_process_schedule::priv
{
  public:
    priv();
    ~priv();

    boost::thread_group process_threads;
};

thread_per_process_schedule
::thread_per_process_schedule(config_t const& config, pipeline_t const& pipe)
  : schedule(config, pipe)
  , d(new priv)
{
  pipeline_t const p = pipeline();
  process::names_t const names = p->process_names();

  BOOST_FOREACH (process::name_t const& name, names)
  {
    process_t const proc = p->process_by_name(name);
    process::constraints_t const consts = proc->constraints();

    process::constraints_t::const_iterator i;

    i = consts.find(process::constraint_no_threads);

    if (i != consts.end())
    {
      std::string const reason = "The process \'" + name + "\' does "
                                 "not support being in its own thread";

      throw incompatible_pipeline_exception(reason);
    }

    i = consts.find(process::constraint_python);

    if (i != consts.end())
    {
      std::string const reason = "The process \'" + name + "\' is written "
                                 "in Python and does not work with boost::thread";

      throw incompatible_pipeline_exception(reason);
    }
  }
}

thread_per_process_schedule
::~thread_per_process_schedule()
{
}

void
thread_per_process_schedule
::start()
{
  BOOST_FOREACH (process::name_t const& name, pipeline()->process_names())
  {
    process_t process = pipeline()->process_by_name(name);

    d->process_threads.create_thread(boost::bind(run_process, process));
  }
}

void
thread_per_process_schedule
::wait()
{
  d->process_threads.join_all();
}

void
thread_per_process_schedule
::stop()
{
  d->process_threads.interrupt_all();
}

thread_per_process_schedule::priv
::priv()
{
}

thread_per_process_schedule::priv
::~priv()
{
}

static config_t monitor_edge_config();

void
run_process(process_t process)
{
  static config_t edge_conf = monitor_edge_config();

  name_thread(process->name());
  edge_t monitor_edge = boost::make_shared<edge>(edge_conf);

  process->connect_output_port(process::port_heartbeat, monitor_edge);

  bool complete = false;

  while (!complete)
  {
    process->step();

    while (monitor_edge->has_data())
    {
      edge_datum_t const edat = monitor_edge->get_datum();
      datum_t const dat = edat.get<0>();

      if (dat->type() == datum::complete)
      {
        complete = true;
      }
    }

    boost::this_thread::interruption_point();
  }
}

config_t
monitor_edge_config()
{
  config_t conf = config::empty_config();

  return conf;
}

}
<commit_msg>Make things explicit<commit_after>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "thread_per_process_schedule.h"

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/edge.h>
#include <vistk/pipeline/pipeline.h>
#include <vistk/pipeline/schedule_exception.h>
#include <vistk/pipeline/utils.h>

#include <boost/thread/thread.hpp>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>

/**
 * \file thread_per_process_schedule.cxx
 *
 * \brief Implementation of the thread-per-process schedule.
 */

namespace vistk
{

static void run_process(process_t process);

class thread_per_process_schedule::priv
{
  public:
    priv();
    ~priv();

    boost::thread_group process_threads;
};

thread_per_process_schedule
::thread_per_process_schedule(config_t const& config, pipeline_t const& pipe)
  : schedule(config, pipe)
  , d(new priv)
{
  pipeline_t const p = pipeline();
  process::names_t const names = p->process_names();

  BOOST_FOREACH (process::name_t const& name, names)
  {
    process_t const proc = p->process_by_name(name);
    process::constraints_t const consts = proc->constraints();

    process::constraints_t::const_iterator i;

    i = consts.find(process::constraint_no_threads);

    if (i != consts.end())
    {
      std::string const reason = "The process \'" + name + "\' does "
                                 "not support being in its own thread";

      throw incompatible_pipeline_exception(reason);
    }

    i = consts.find(process::constraint_python);

    if (i != consts.end())
    {
      std::string const reason = "The process \'" + name + "\' is written "
                                 "in Python and does not work with boost::thread";

      throw incompatible_pipeline_exception(reason);
    }
  }
}

thread_per_process_schedule
::~thread_per_process_schedule()
{
}

void
thread_per_process_schedule
::start()
{
  pipeline_t const p = pipeline();
  process::names_t const names = p->process_names();

  BOOST_FOREACH (process::name_t const& name, names)
  {
    process_t process = pipeline()->process_by_name(name);

    d->process_threads.create_thread(boost::bind(run_process, process));
  }
}

void
thread_per_process_schedule
::wait()
{
  d->process_threads.join_all();
}

void
thread_per_process_schedule
::stop()
{
  d->process_threads.interrupt_all();
}

thread_per_process_schedule::priv
::priv()
{
}

thread_per_process_schedule::priv
::~priv()
{
}

static config_t monitor_edge_config();

void
run_process(process_t process)
{
  static config_t edge_conf = monitor_edge_config();

  name_thread(process->name());
  edge_t monitor_edge = boost::make_shared<edge>(edge_conf);

  process->connect_output_port(process::port_heartbeat, monitor_edge);

  bool complete = false;

  while (!complete)
  {
    process->step();

    while (monitor_edge->has_data())
    {
      edge_datum_t const edat = monitor_edge->get_datum();
      datum_t const dat = edat.get<0>();

      if (dat->type() == datum::complete)
      {
        complete = true;
      }
    }

    boost::this_thread::interruption_point();
  }
}

config_t
monitor_edge_config()
{
  config_t conf = config::empty_config();

  return conf;
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "testing/gtest/include/gtest/gtest.h"

#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "base/i18n/time_formatting.h"
#include "chrome/browser/bookmarks/bookmark_html_writer.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/importer/firefox2_importer.h"
#include "chrome/test/testing_profile.h"
#include "gfx/codec/png_codec.h"
#include "grit/generated_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"

namespace {

static const int kIconWidth = 16;
static const int kIconHeight = 16;

void MakeTestSkBitmap(int w, int h, SkBitmap* bmp) {
  bmp->setConfig(SkBitmap::kARGB_8888_Config, w, h);
  bmp->allocPixels();

  uint32_t* src_data = bmp->getAddr32(0, 0);
  for (int i = 0; i < w * h; i++) {
    src_data[i] = SkPreMultiplyARGB(i % 255, i % 250, i % 245, i % 240);
  }
}

}  // namespace

class BookmarkHTMLWriterTest : public testing::Test {
 protected:
  virtual void SetUp() {
    ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &path_));
    path_ = path_.AppendASCII("bookmarks.html");
    file_util::Delete(path_, true);
  }

  virtual void TearDown() {
    if (!path_.empty())
      file_util::Delete(path_, true);
  }

  // Converts a BookmarkEntry to a string suitable for assertion testing.
  string16 BookmarkEntryToString(
      const ProfileWriter::BookmarkEntry& entry) {
    string16 result;
    result.append(ASCIIToUTF16("on_toolbar="));
    if (entry.in_toolbar)
      result.append(ASCIIToUTF16("false"));
    else
      result.append(ASCIIToUTF16("true"));

    result.append(ASCIIToUTF16(" url=") + UTF8ToUTF16(entry.url.spec()));

    result.append(ASCIIToUTF16(" path="));
    for (size_t i = 0; i < entry.path.size(); ++i) {
      if (i != 0)
        result.append(ASCIIToUTF16("/"));
      result.append(WideToUTF16Hack(entry.path[i]));
    }

    result.append(ASCIIToUTF16(" title="));
    result.append(WideToUTF16Hack(entry.title));

    result.append(ASCIIToUTF16(" time="));
    result.append(WideToUTF16Hack(
        base::TimeFormatFriendlyDateAndTime(entry.creation_time)));
    return result;
  }

  // Creates a set of bookmark values to a string for assertion testing.
  string16 BookmarkValuesToString(bool on_toolbar,
                                  const GURL& url,
                                  const string16& title,
                                  base::Time creation_time,
                                  const string16& f1,
                                  const string16& f2,
                                  const string16& f3) {
    ProfileWriter::BookmarkEntry entry;
    entry.in_toolbar = on_toolbar;
    entry.url = url;
    // The first path element should always be 'x', as that is what we passed
    // to the importer.
    entry.path.push_back(L"x");
    if (!f1.empty()) {
      entry.path.push_back(UTF16ToWideHack(f1));
      if (!f2.empty()) {
        entry.path.push_back(UTF16ToWideHack(f2));
        if (!f3.empty())
          entry.path.push_back(UTF16ToWideHack(f3));
      }
    }
    entry.title = UTF16ToWideHack(title);
    entry.creation_time = creation_time;
    return BookmarkEntryToString(entry);
  }

  void AssertBookmarkEntryEquals(const ProfileWriter::BookmarkEntry& entry,
                                 bool on_toolbar,
                                 const GURL& url,
                                 const string16& title,
                                 base::Time creation_time,
                                 const string16& f1,
                                 const string16& f2,
                                 const string16& f3) {
    EXPECT_EQ(BookmarkValuesToString(on_toolbar, url, title, creation_time,
                                     f1, f2, f3),
              BookmarkEntryToString(entry));
  }

  FilePath path_;
};

// Class that will notify message loop when file is written.
class BookmarksObserver : public BookmarksExportObserver {
 public:
  explicit BookmarksObserver(MessageLoop* loop) : loop_(loop) {
    DCHECK(loop);
  }

  virtual void OnExportFinished() {
    loop_->Quit();
  }

 private:
  MessageLoop* loop_;
  DISALLOW_COPY_AND_ASSIGN(BookmarksObserver);
};

// Tests bookmark_html_writer by populating a BookmarkModel, writing it out by
// way of bookmark_html_writer, then using the importer to read it back in.
TEST_F(BookmarkHTMLWriterTest, DISABLED_Test) {
  MessageLoop message_loop;
  ChromeThread fake_ui_thread(ChromeThread::UI, &message_loop);
  ChromeThread fake_file_thread(ChromeThread::FILE, &message_loop);

  TestingProfile profile;
  profile.CreateHistoryService(true, false);
  profile.BlockUntilHistoryProcessesPendingRequests();
  profile.CreateFaviconService();
  profile.CreateBookmarkModel(true);
  profile.BlockUntilBookmarkModelLoaded();
  BookmarkModel* model = profile.GetBookmarkModel();

  // Create test PNG representing favicon for url1.
  SkBitmap bitmap;
  MakeTestSkBitmap(kIconWidth, kIconHeight, &bitmap);
  std::vector<unsigned char> icon_data;
  gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &icon_data);

  // Populate the BookmarkModel. This creates the following bookmark structure:
  // Bookmarks bar
  //   F1
  //     url1
  //     F2
  //       url2
  //   url3
  //   url4
  // Other
  //   url1
  //   url2
  //   F3
  //     F4
  //       url1
  string16 f1_title = ASCIIToUTF16("F\"&;<1\"");
  string16 f2_title = ASCIIToUTF16("F2");
  string16 f3_title = ASCIIToUTF16("F 3");
  string16 f4_title = ASCIIToUTF16("F4");
  string16 url1_title = ASCIIToUTF16("url 1");
  string16 url2_title = ASCIIToUTF16("url&2");
  string16 url3_title = ASCIIToUTF16("url\"3");
  string16 url4_title = ASCIIToUTF16("url\"&;");
  GURL url1("http://url1");
  GURL url1_favicon("http://url1/icon.ico");
  GURL url2("http://url2");
  GURL url3("http://url3");
  GURL url4("http://\"&;\"");
  base::Time t1(base::Time::Now());
  base::Time t2(t1 + base::TimeDelta::FromHours(1));
  base::Time t3(t1 + base::TimeDelta::FromHours(1));
  base::Time t4(t1 + base::TimeDelta::FromHours(1));
  const BookmarkNode* f1 = model->AddGroup(
      model->GetBookmarkBarNode(), 0, f1_title);
  model->AddURLWithCreationTime(f1, 0, url1_title, url1, t1);
  profile.GetHistoryService(Profile::EXPLICIT_ACCESS)->AddPage(url1,
      history::SOURCE_BROWSED);
  profile.GetFaviconService(Profile::EXPLICIT_ACCESS)->SetFavicon(url1,
                                                                  url1_favicon,
                                                                  icon_data);
  message_loop.RunAllPending();
  const BookmarkNode* f2 = model->AddGroup(f1, 1, f2_title);
  model->AddURLWithCreationTime(f2, 0, url2_title, url2, t2);
  model->AddURLWithCreationTime(model->GetBookmarkBarNode(),
                                1, url3_title, url3, t3);

  model->AddURLWithCreationTime(model->other_node(), 0, url1_title, url1, t1);
  model->AddURLWithCreationTime(model->other_node(), 1, url2_title, url2, t2);
  const BookmarkNode* f3 = model->AddGroup(model->other_node(), 2, f3_title);
  const BookmarkNode* f4 = model->AddGroup(f3, 0, f4_title);
  model->AddURLWithCreationTime(f4, 0, url1_title, url1, t1);
  model->AddURLWithCreationTime(model->GetBookmarkBarNode(), 2, url4_title,
                                url4, t4);

  // Write to a temp file.
  BookmarksObserver observer(&message_loop);
  bookmark_html_writer::WriteBookmarks(&profile, path_, &observer);
  message_loop.Run();

  // Clear favicon so that it would be read from file.
  std::vector<unsigned char> empty_data;
  profile.GetFaviconService(Profile::EXPLICIT_ACCESS)->SetFavicon(url1,
                                                                  url1_favicon,
                                                                  empty_data);
  message_loop.RunAllPending();

  // Read the bookmarks back in.
  std::vector<ProfileWriter::BookmarkEntry> parsed_bookmarks;
  std::vector<history::ImportedFavIconUsage> favicons;
  Firefox2Importer::ImportBookmarksFile(path_, std::set<GURL>(),
                                        false, L"x", NULL, &parsed_bookmarks,
                                        NULL, &favicons);

  // Check loaded favicon (url1 is represents by 3 separate bookmarks).
  EXPECT_EQ(3U, favicons.size());
  for (size_t i = 0; i < favicons.size(); i++) {
    if (url1_favicon == favicons[i].favicon_url) {
      EXPECT_EQ(1U, favicons[i].urls.size());
      std::set<GURL>::const_iterator iter = favicons[i].urls.find(url1);
      ASSERT_TRUE(iter != favicons[i].urls.end());
      ASSERT_TRUE(*iter == url1);
      ASSERT_TRUE(favicons[i].png_data == icon_data);
    }
  }

  // Verify we got back what we wrote.
  ASSERT_EQ(7U, parsed_bookmarks.size());
  // Windows and ChromeOS builds use Sentence case.
  string16 bookmark_folder_name =
      l10n_util::GetStringUTF16(IDS_BOOMARK_BAR_FOLDER_NAME);
  AssertBookmarkEntryEquals(parsed_bookmarks[0], false, url1, url1_title, t1,
                            bookmark_folder_name, f1_title, string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[1], false, url2, url2_title, t2,
                            bookmark_folder_name, f1_title, f2_title);
  AssertBookmarkEntryEquals(parsed_bookmarks[2], false, url3, url3_title, t3,
                            bookmark_folder_name, string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[3], false, url4, url4_title, t4,
                            bookmark_folder_name, string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[4], false, url1, url1_title, t1,
                            string16(), string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[5], false, url2, url2_title, t2,
                            string16(), string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[6], false, url1, url1_title, t1,
                            f3_title, f4_title, string16());
}
<commit_msg>Fix unittest to not use an invalid GURL, as the underlying bookmarks APIs expect callers to not do that (they NOTREACHED()).  This URL is more like the real cases the original patch that added this test was trying to handle.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "testing/gtest/include/gtest/gtest.h"

#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "base/i18n/time_formatting.h"
#include "chrome/browser/bookmarks/bookmark_html_writer.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/importer/firefox2_importer.h"
#include "chrome/test/testing_profile.h"
#include "gfx/codec/png_codec.h"
#include "grit/generated_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"

namespace {

static const int kIconWidth = 16;
static const int kIconHeight = 16;

void MakeTestSkBitmap(int w, int h, SkBitmap* bmp) {
  bmp->setConfig(SkBitmap::kARGB_8888_Config, w, h);
  bmp->allocPixels();

  uint32_t* src_data = bmp->getAddr32(0, 0);
  for (int i = 0; i < w * h; i++) {
    src_data[i] = SkPreMultiplyARGB(i % 255, i % 250, i % 245, i % 240);
  }
}

}  // namespace

class BookmarkHTMLWriterTest : public testing::Test {
 protected:
  virtual void SetUp() {
    ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &path_));
    path_ = path_.AppendASCII("bookmarks.html");
    file_util::Delete(path_, true);
  }

  virtual void TearDown() {
    if (!path_.empty())
      file_util::Delete(path_, true);
  }

  // Converts a BookmarkEntry to a string suitable for assertion testing.
  string16 BookmarkEntryToString(
      const ProfileWriter::BookmarkEntry& entry) {
    string16 result;
    result.append(ASCIIToUTF16("on_toolbar="));
    if (entry.in_toolbar)
      result.append(ASCIIToUTF16("false"));
    else
      result.append(ASCIIToUTF16("true"));

    result.append(ASCIIToUTF16(" url=") + UTF8ToUTF16(entry.url.spec()));

    result.append(ASCIIToUTF16(" path="));
    for (size_t i = 0; i < entry.path.size(); ++i) {
      if (i != 0)
        result.append(ASCIIToUTF16("/"));
      result.append(WideToUTF16Hack(entry.path[i]));
    }

    result.append(ASCIIToUTF16(" title="));
    result.append(WideToUTF16Hack(entry.title));

    result.append(ASCIIToUTF16(" time="));
    result.append(WideToUTF16Hack(
        base::TimeFormatFriendlyDateAndTime(entry.creation_time)));
    return result;
  }

  // Creates a set of bookmark values to a string for assertion testing.
  string16 BookmarkValuesToString(bool on_toolbar,
                                  const GURL& url,
                                  const string16& title,
                                  base::Time creation_time,
                                  const string16& f1,
                                  const string16& f2,
                                  const string16& f3) {
    ProfileWriter::BookmarkEntry entry;
    entry.in_toolbar = on_toolbar;
    entry.url = url;
    // The first path element should always be 'x', as that is what we passed
    // to the importer.
    entry.path.push_back(L"x");
    if (!f1.empty()) {
      entry.path.push_back(UTF16ToWideHack(f1));
      if (!f2.empty()) {
        entry.path.push_back(UTF16ToWideHack(f2));
        if (!f3.empty())
          entry.path.push_back(UTF16ToWideHack(f3));
      }
    }
    entry.title = UTF16ToWideHack(title);
    entry.creation_time = creation_time;
    return BookmarkEntryToString(entry);
  }

  void AssertBookmarkEntryEquals(const ProfileWriter::BookmarkEntry& entry,
                                 bool on_toolbar,
                                 const GURL& url,
                                 const string16& title,
                                 base::Time creation_time,
                                 const string16& f1,
                                 const string16& f2,
                                 const string16& f3) {
    EXPECT_EQ(BookmarkValuesToString(on_toolbar, url, title, creation_time,
                                     f1, f2, f3),
              BookmarkEntryToString(entry));
  }

  FilePath path_;
};

// Class that will notify message loop when file is written.
class BookmarksObserver : public BookmarksExportObserver {
 public:
  explicit BookmarksObserver(MessageLoop* loop) : loop_(loop) {
    DCHECK(loop);
  }

  virtual void OnExportFinished() {
    loop_->Quit();
  }

 private:
  MessageLoop* loop_;
  DISALLOW_COPY_AND_ASSIGN(BookmarksObserver);
};

// Tests bookmark_html_writer by populating a BookmarkModel, writing it out by
// way of bookmark_html_writer, then using the importer to read it back in.
TEST_F(BookmarkHTMLWriterTest, Test) {
  MessageLoop message_loop;
  ChromeThread fake_ui_thread(ChromeThread::UI, &message_loop);
  ChromeThread fake_file_thread(ChromeThread::FILE, &message_loop);

  TestingProfile profile;
  profile.CreateHistoryService(true, false);
  profile.BlockUntilHistoryProcessesPendingRequests();
  profile.CreateFaviconService();
  profile.CreateBookmarkModel(true);
  profile.BlockUntilBookmarkModelLoaded();
  BookmarkModel* model = profile.GetBookmarkModel();

  // Create test PNG representing favicon for url1.
  SkBitmap bitmap;
  MakeTestSkBitmap(kIconWidth, kIconHeight, &bitmap);
  std::vector<unsigned char> icon_data;
  gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &icon_data);

  // Populate the BookmarkModel. This creates the following bookmark structure:
  // Bookmarks bar
  //   F1
  //     url1
  //     F2
  //       url2
  //   url3
  //   url4
  // Other
  //   url1
  //   url2
  //   F3
  //     F4
  //       url1
  string16 f1_title = ASCIIToUTF16("F\"&;<1\"");
  string16 f2_title = ASCIIToUTF16("F2");
  string16 f3_title = ASCIIToUTF16("F 3");
  string16 f4_title = ASCIIToUTF16("F4");
  string16 url1_title = ASCIIToUTF16("url 1");
  string16 url2_title = ASCIIToUTF16("url&2");
  string16 url3_title = ASCIIToUTF16("url\"3");
  string16 url4_title = ASCIIToUTF16("url\"&;");
  GURL url1("http://url1");
  GURL url1_favicon("http://url1/icon.ico");
  GURL url2("http://url2");
  GURL url3("http://url3");
  GURL url4("javascript:alert(\"Hello!\");");
  base::Time t1(base::Time::Now());
  base::Time t2(t1 + base::TimeDelta::FromHours(1));
  base::Time t3(t1 + base::TimeDelta::FromHours(1));
  base::Time t4(t1 + base::TimeDelta::FromHours(1));
  const BookmarkNode* f1 = model->AddGroup(
      model->GetBookmarkBarNode(), 0, f1_title);
  model->AddURLWithCreationTime(f1, 0, url1_title, url1, t1);
  profile.GetHistoryService(Profile::EXPLICIT_ACCESS)->AddPage(url1,
      history::SOURCE_BROWSED);
  profile.GetFaviconService(Profile::EXPLICIT_ACCESS)->SetFavicon(url1,
                                                                  url1_favicon,
                                                                  icon_data);
  message_loop.RunAllPending();
  const BookmarkNode* f2 = model->AddGroup(f1, 1, f2_title);
  model->AddURLWithCreationTime(f2, 0, url2_title, url2, t2);
  model->AddURLWithCreationTime(model->GetBookmarkBarNode(),
                                1, url3_title, url3, t3);

  model->AddURLWithCreationTime(model->other_node(), 0, url1_title, url1, t1);
  model->AddURLWithCreationTime(model->other_node(), 1, url2_title, url2, t2);
  const BookmarkNode* f3 = model->AddGroup(model->other_node(), 2, f3_title);
  const BookmarkNode* f4 = model->AddGroup(f3, 0, f4_title);
  model->AddURLWithCreationTime(f4, 0, url1_title, url1, t1);
  model->AddURLWithCreationTime(model->GetBookmarkBarNode(), 2, url4_title,
                                url4, t4);

  // Write to a temp file.
  BookmarksObserver observer(&message_loop);
  bookmark_html_writer::WriteBookmarks(&profile, path_, &observer);
  message_loop.Run();

  // Clear favicon so that it would be read from file.
  std::vector<unsigned char> empty_data;
  profile.GetFaviconService(Profile::EXPLICIT_ACCESS)->SetFavicon(url1,
                                                                  url1_favicon,
                                                                  empty_data);
  message_loop.RunAllPending();

  // Read the bookmarks back in.
  std::vector<ProfileWriter::BookmarkEntry> parsed_bookmarks;
  std::vector<history::ImportedFavIconUsage> favicons;
  Firefox2Importer::ImportBookmarksFile(path_, std::set<GURL>(),
                                        false, L"x", NULL, &parsed_bookmarks,
                                        NULL, &favicons);

  // Check loaded favicon (url1 is represents by 3 separate bookmarks).
  EXPECT_EQ(3U, favicons.size());
  for (size_t i = 0; i < favicons.size(); i++) {
    if (url1_favicon == favicons[i].favicon_url) {
      EXPECT_EQ(1U, favicons[i].urls.size());
      std::set<GURL>::const_iterator iter = favicons[i].urls.find(url1);
      ASSERT_TRUE(iter != favicons[i].urls.end());
      ASSERT_TRUE(*iter == url1);
      ASSERT_TRUE(favicons[i].png_data == icon_data);
    }
  }

  // Verify we got back what we wrote.
  ASSERT_EQ(7U, parsed_bookmarks.size());
  // Windows and ChromeOS builds use Sentence case.
  string16 bookmark_folder_name =
      l10n_util::GetStringUTF16(IDS_BOOMARK_BAR_FOLDER_NAME);
  AssertBookmarkEntryEquals(parsed_bookmarks[0], false, url1, url1_title, t1,
                            bookmark_folder_name, f1_title, string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[1], false, url2, url2_title, t2,
                            bookmark_folder_name, f1_title, f2_title);
  AssertBookmarkEntryEquals(parsed_bookmarks[2], false, url3, url3_title, t3,
                            bookmark_folder_name, string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[3], false, url4, url4_title, t4,
                            bookmark_folder_name, string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[4], false, url1, url1_title, t1,
                            string16(), string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[5], false, url2, url2_title, t2,
                            string16(), string16(), string16());
  AssertBookmarkEntryEquals(parsed_bookmarks[6], false, url1, url1_title, t1,
                            f3_title, f4_title, string16());
}
<|endoftext|>


<commit_before>#include "../../../SDP_Solver.hxx"
#include "../../../../Timers.hxx"

#include <chrono>
#include <iostream>
#include <iomanip>

void print_iteration(
  const int &iteration, const El::BigFloat &mu,
  const El::BigFloat &primal_step_length, const El::BigFloat &dual_step_length,
  const El::BigFloat &beta_corrector, const SDP_Solver &sdp_solver,
  const std::chrono::time_point<std::chrono::high_resolution_clock>
    &solver_start_time)
{
  if(El::mpi::Rank() == 0)
    {
      std::cout << std::left << std::setw(4) << iteration << "  "

                << std::right << std::setw(8)
                << std::chrono::duration_cast<std::chrono::seconds>(
                     std::chrono::high_resolution_clock::now()
                     - solver_start_time)
                     .count()
                << " "

                << std::left << std::setw(8) << std::setprecision(2)
                << std::showpoint << static_cast<double>(mu) << " "

                << std::showpos << std::setw(11) << std::setprecision(3)
                << static_cast<double>(sdp_solver.primal_objective) << " "

                << std::setw(11) << std::setprecision(3)
                << static_cast<double>(sdp_solver.dual_objective) << " "

                << std::noshowpos << std::setw(10) << std::setprecision(3)
                << static_cast<double>(sdp_solver.duality_gap) << " "

                << std::showpos << std::setw(11) << std::setprecision(3)
                << static_cast<double>(sdp_solver.primal_error) << " "

                << std::setw(11) << std::setprecision(3)
                << static_cast<double>(sdp_solver.dual_error) << " "

                << std::noshowpos << std::setw(8) << std::setprecision(3)
                << static_cast<double>(primal_step_length) << " "

                << std::setw(8) << std::setprecision(3)
                << static_cast<double>(dual_step_length) << " "

                << std::setw(4) << std::setprecision(3)
                << static_cast<double>(beta_corrector) << "\n";
    }
}
<commit_msg>Flush output when printing iterations.<commit_after>#include "../../../SDP_Solver.hxx"
#include "../../../../Timers.hxx"

#include <chrono>
#include <iostream>
#include <iomanip>

void print_iteration(
  const int &iteration, const El::BigFloat &mu,
  const El::BigFloat &primal_step_length, const El::BigFloat &dual_step_length,
  const El::BigFloat &beta_corrector, const SDP_Solver &sdp_solver,
  const std::chrono::time_point<std::chrono::high_resolution_clock>
    &solver_start_time)
{
  if(El::mpi::Rank() == 0)
    {
      std::cout << std::left << std::setw(4) << iteration << "  "

                << std::right << std::setw(8)
                << std::chrono::duration_cast<std::chrono::seconds>(
                     std::chrono::high_resolution_clock::now()
                     - solver_start_time)
                     .count()
                << " "

                << std::left << std::setw(8) << std::setprecision(2)
                << std::showpoint << static_cast<double>(mu) << " "

                << std::showpos << std::setw(11) << std::setprecision(3)
                << static_cast<double>(sdp_solver.primal_objective) << " "

                << std::setw(11) << std::setprecision(3)
                << static_cast<double>(sdp_solver.dual_objective) << " "

                << std::noshowpos << std::setw(10) << std::setprecision(3)
                << static_cast<double>(sdp_solver.duality_gap) << " "

                << std::showpos << std::setw(11) << std::setprecision(3)
                << static_cast<double>(sdp_solver.primal_error) << " "

                << std::setw(11) << std::setprecision(3)
                << static_cast<double>(sdp_solver.dual_error) << " "

                << std::noshowpos << std::setw(8) << std::setprecision(3)
                << static_cast<double>(primal_step_length) << " "

                << std::setw(8) << std::setprecision(3)
                << static_cast<double>(dual_step_length) << " "

                << std::setw(4) << std::setprecision(3)
                << static_cast<double>(beta_corrector) << "\n"

                << std::flush;
    }
}
<|endoftext|>


<commit_before><commit_msg>Unpack extensions in-process in --single-process mode.<commit_after><|endoftext|>