text:
from __future__ import unicode_literals

import unittest

from pymatgen import Composition
from pymatgen.analysis.reaction_calculator import Reaction, BalancedReaction, \
    ReactionError, ComputedReaction
from pymatgen.entries.computed_entries import ComputedEntry

class ReactionTest(unittest.TestCase):
    def test_init(self):
        reactants = [Composition("Fe"),
                     Composition("O2")]
        products = [Composition("Fe2O3")]
        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn), "2 Fe + 1.5 O2 -> Fe2O3")
        self.assertEqual(rxn.normalized_repr, "4 Fe + 3 O2 -> 2 Fe2O3")

        d = rxn.as_dict()
        rxn = Reaction.from_dict(d)
        repr, factor = rxn.normalized_repr_and_factor()
        self.assertEqual(repr, "4 Fe + 3 O2 -> 2 Fe2O3")
        self.assertAlmostEqual(factor, 2)

        reactants = [Composition("FePO4"), Composition('Mn')]
        products = [Composition("FePO4"), Composition('Xe')]
        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn), "FePO4 -> FePO4")

        products = [Composition("Ti2 O4"), Composition("O1")]
        reactants = [Composition("Ti1 O2")]
        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn), "2 TiO2 -> 2 TiO2")

        reactants = [Composition("FePO4"), Composition("Li")]
        products = [Composition("LiFePO4")]
        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn), "FePO4 + Li -> LiFePO4")

        reactants = [Composition("MgO")]
        products = [Composition("MgO")]

        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn), "MgO -> MgO")

        reactants = [Composition("Mg")]
        products = [Composition("Mg")]

        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn), "Mg -> Mg")

        reactants = [Composition("FePO4"), Composition("LiPO3")]
        products = [Composition("LiFeP2O7")]

        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn),
                         "FePO4 + LiPO3 -> LiFeP2O7")

        reactants = [Composition("Na"), Composition("K2O")]
        products = [Composition("Na2O"), Composition("K")]
        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn),
                         "2 Na + K2O -> Na2O + 2 K")

        # Test for an old bug which has a problem when excess product is
        # defined.
        products = [Composition("FePO4"), Composition("O")]
        reactants = [Composition("FePO4")]
        rxn = Reaction(reactants, products)

        self.assertEqual(str(rxn), "FePO4 -> FePO4")

        products = list(map(Composition, ['LiCrO2', 'La8Ti8O12', 'O2']))
        reactants = [Composition('LiLa3Ti3CrO12')]
        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn),
                         "LiLa3Ti3CrO12 -> LiCrO2 + 1.5 La2Ti2O3 + 2.75 O2")

    def test_rank(self):
        reactants = [Composition("La2Zr2O7"), Composition("LiCoO2")]
        products = [Composition("La2O3"),
                    Composition("Co2O3"),
                    Composition("Li2ZrO3"),
                    Composition("Li2O")]

        self.assertEqual(str(Reaction(reactants, products)),
                         "La2Zr2O7 + 2 LiCoO2 + Li2O -> "
                         "La2O3 + Co2O3 + 2 Li2ZrO3")

        reactants = [Composition("La2O3"), Composition("Co2O3"),
                     Composition("Li2ZrO3")]
        products = [Composition("Li2O"), Composition("La2Zr2O7"),
                    Composition("Li3CoO3")]
        self.assertEqual(str(Reaction(reactants, products)),
                         "La2O3 + 0.3333 Co2O3 + 2 Li2ZrO3 -> "
                         "Li2O + La2Zr2O7 + 0.6667 Li3CoO3")

        reactants = [Composition("La2O3"), Composition("Co2O3"),
                     Composition("Li2ZrO3")]
        products = [Composition("Xe"), Composition("Li2O"),
                    Composition("La2Zr2O7"),
                    Composition("Li3CoO3")]
        self.assertEqual(str(Reaction(reactants, products)),
                         "La2O3 + 0.3333 Co2O3 + 2 Li2ZrO3 -> "
                         "Li2O + La2Zr2O7 + 0.6667 Li3CoO3")

        reactants = [Composition("La2O3"), Composition("Co2O3"),
                     Composition("Li2ZrO3")]
        products = [Composition("Xe"), Composition("Li2O"),
                    Composition("La2Zr2O7"),
                    Composition("Li3CoO3"), Composition("XeNe")]
        self.assertEqual(str(Reaction(reactants, products)),
                         "La2O3 + 0.3333 Co2O3 + 2 Li2ZrO3 -> "
                         "Li2O + La2Zr2O7 + 0.6667 Li3CoO3")

        reactants = [Composition("LiCoO2")]
        products = [Composition("La2O3"), Composition("Co2O3"),
                    Composition("Li2O1"), Composition("Li1F1"),
                    Composition("Co1F3")]
        self.assertEqual(str(Reaction(reactants, products)),
                         "2 LiCoO2 -> Co2O3 + Li2O")

        # this test can fail because of numerical rank calculation issues
        reactants = [Composition("LiCoO2"), Composition("Li2O1")]
        products = [Composition("ZrF4"), Composition("Co2O3")]
        self.assertEqual(str(Reaction(reactants, products)),
                         '2 LiCoO2 -> Li2O + Co2O3')

    def test_singular_case(self):
        rxn = Reaction([Composition('XeMn'), Composition("Li")],
                       [Composition("S"), Composition("LiS2"),
                        Composition('FeCl')])
        self.assertEqual(str(rxn), '0.5 LiS2 -> 0.5 Li + S')

    def test_overdetermined(self):
        self.assertRaises(ReactionError, Reaction, [Composition("Li")],
                          [Composition("LiO2")])

    def test_scientific_notation(self):
        products = [Composition("FePO3.9999"), Composition("O2")]
        reactants = [Composition("FePO4")]
        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn), "FePO4 -> Fe1P1O3.9999 + 5e-05 O2")
        self.assertEqual(rxn, Reaction.from_string(str(rxn)))

        rxn2 = Reaction.from_string("FePO4 + 20 CO -> 1e1 O2 + Fe1P1O4 + 20 C")
        self.assertEqual(str(rxn2), "20 CO -> 10 O2 + 20 C")

    def test_equals(self):
        reactants = [Composition("Fe"),
                     Composition("O2")]
        products = [Composition("Fe2O3")]
        rxn = Reaction(reactants, products)
        reactants = [Composition("O2"), Composition("Fe")]
        products = [Composition("Fe2O3")]
        rxn2 = Reaction(reactants, products)
        self.assertTrue(rxn == rxn2)

    def test_normalize_to(self):
        products = [Composition("Fe"), Composition("O2")]
        reactants = [Composition("Fe2O3")]
        rxn = Reaction(reactants, products)
        rxn.normalize_to(Composition("Fe"), 3)
        self.assertEqual(str(rxn), "1.5 Fe2O3 -> 3 Fe + 2.25 O2")

    def test_calculate_energy(self):
        reactants = [Composition("MgO"), Composition("Al2O3")]
        products = [Composition("MgAl2O4")]
        energies = {Composition("MgO"): -0.1, Composition("Al2O3"): -0.2,
                    Composition("MgAl2O4"): -0.5}
        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn),
                         "MgO + Al2O3 -> MgAl2O4")
        self.assertEqual(rxn.normalized_repr, "MgO + Al2O3 -> MgAl2O4")
        self.assertAlmostEqual(rxn.calculate_energy(energies), -0.2, 5)

    def test_as_entry(self):
        reactants = [Composition("MgO"), Composition("Al2O3")]
        products = [Composition("MgAl2O4")]
        energies = {Composition("MgO"): -0.1, Composition("Al2O3"): -0.2,
                    Composition("MgAl2O4"): -0.5}
        rxn = Reaction(reactants, products)
        entry = rxn.as_entry(energies)
        self.assertEqual(entry.name,
                         "MgO + Al2O3 -> MgAl2O4")
        self.assertAlmostEqual(entry.energy, -0.2, 5)

        products = [Composition("Fe"), Composition("O2")]
        reactants = [Composition("Fe2O3")]
        rxn = Reaction(reactants, products)
        energies = {Composition("Fe"): 0, Composition("O2"): 0,
                    Composition("Fe2O3"): 0.5}
        entry = rxn.as_entry(energies)
        self.assertEqual(entry.composition, Composition("Fe1.0 O1.5"))
        self.assertAlmostEqual(entry.energy, -0.25, 5)

    def test_products_reactants(self):
        reactants = [Composition("Li3Fe2(PO4)3"), Composition("Fe2O3"),
                     Composition("O2")]
        products = [Composition("LiFePO4")]
        energies = {Composition("Li3Fe2(PO4)3"): -0.1,
                    Composition("Fe2O3"): -0.2,
                    Composition("O2"): -0.2,
                    Composition("LiFePO4"): -0.5}
        rxn = Reaction(reactants, products)

        self.assertIn(Composition("O2"), rxn.products, "O not in products!")
        self.assertIn(Composition("Li3Fe2(PO4)3"), rxn.reactants,
                      "Li3Fe2(PO4)4 not in reactants!")
        self.assertEqual(str(rxn),
                         "0.3333 Li3Fe2(PO4)3 + 0.1667 Fe2O3 -> 0.25 O2 + LiFePO4")
        self.assertEqual(rxn.normalized_repr,
                         "4 Li3Fe2(PO4)3 + 2 Fe2O3 -> 3 O2 + 12 LiFePO4")
        self.assertAlmostEqual(rxn.calculate_energy(energies), -0.48333333, 5)

    def test_to_from_dict(self):
        reactants = [Composition("Fe"), Composition("O2")]
        products = [Composition("Fe2O3")]
        rxn = Reaction(reactants, products)
        d = rxn.as_dict()
        rxn = Reaction.from_dict(d)
        self.assertEqual(rxn.normalized_repr, "4 Fe + 3 O2 -> 2 Fe2O3")

    def test_underdetermined(self):
        reactants = [Composition("Fe"), Composition("O2")]
        products = [Composition("Fe"), Composition("O2")]
        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn), "Fe + O2 -> Fe + O2")

        reactants = [Composition("Fe"),
                     Composition("O2"),
                     Composition("Na"),
                     Composition("Li"),
                     Composition("Cl")]
        products = [Composition("FeO2"), Composition("NaCl"),
                    Composition("Li2Cl2")]
        rxn = Reaction(reactants, products)
        self.assertEqual(str(rxn),
                         "Fe + O2 + Na + 2 Li + 1.5 Cl2 -> FeO2 + NaCl + 2 LiCl")

        reactants = [Composition("Fe"),
                     Composition("Na"),
                     Composition("Li2O"),
                     Composition("Cl")]
        products = [Composition("LiCl"), Composition("Na2O"),
                    Composition("Xe"), Composition("FeCl"), Composition("Mn")]
        rxn = Reaction(reactants, products)
        # this cant normalize to 1 LiCl + 1 Na2O (not enough O), so chooses LiCl and FeCl
        self.assertEqual(str(rxn),
                         "Fe + Na + 0.5 Li2O + Cl2 -> LiCl + 0.5 Na2O + FeCl")

    def test_underdetermined_reactants(self):
        reactants = [Composition("Li"),
                     Composition("Cl"),
                     Composition("Cl")]
        products = [Composition("LiCl")]
        self.assertRaisesRegexp(ReactionError, "underdetermined", Reaction,
                               reactants, products)

        reactants = [Composition("LiMnCl3"),
                     Composition("LiCl"),
                     Composition("MnCl2")]
        products = [Composition("Li2MnCl4")]
        self.assertRaisesRegexp(ReactionError, "underdetermined", Reaction,
                               reactants, products)

class BalancedReactionTest(unittest.TestCase):
    def test_init(self):
        rct = {Composition('K2SO4'): 3, Composition('Na2S'): 1,
               Composition('Li'): 24}
        prod = {Composition('KNaS'): 2, Composition('K2S'): 2,
                Composition('Li2O'): 12}
        rxn = BalancedReaction(rct, prod)
        self.assertIsNotNone(str(rxn))

        # Test unbalanced exception
        rct = {Composition('K2SO4'): 1,
               Composition('Na2S'): 1, Composition('Li'): 24}
        prod = {Composition('KNaS'): 2, Composition('K2S'): 2,
                Composition('Li2O'): 12}
        self.assertRaises(ReactionError, BalancedReaction, rct, prod)

    def test_to_from_dict(self):
        rct = {Composition('K2SO4'): 3,
               Composition('Na2S'): 1, Composition('Li'): 24}
        prod = {Composition('KNaS'): 2, Composition('K2S'): 2,
                Composition('Li2O'): 12}
        rxn = BalancedReaction(rct, prod)
        d = rxn.as_dict()
        new_rxn = BalancedReaction.from_dict(d)
        for comp in new_rxn.all_comp:
            self.assertEqual(new_rxn.get_coeff(comp), rxn.get_coeff(comp))

    def test_from_string(self):
        rxn = BalancedReaction({Composition("Li"): 4, Composition("O2"): 1},
                               {Composition("Li2O"): 2})
        self.assertEqual(rxn,
                         BalancedReaction.from_string("4 Li + O2 -> 2Li2O"))

        rxn = BalancedReaction({Composition("Li(NiO2)3"): 1},
                               {Composition("O2"): 0.5,
                                Composition("Li(NiO2)2"): 1,
                                Composition("NiO"): 1})

        self.assertEqual(rxn,
                         BalancedReaction.from_string(
                             "1.000 Li(NiO2)3 -> 0.500 O2 + 1.000 Li(NiO2)2 + 1.000 NiO"))

    def test_remove_spectator_species(self):
        rxn = BalancedReaction(
            {Composition("Li"): 4, Composition("O2"): 1, Composition('Na'): 1},
            {Composition("Li2O"): 2, Composition('Na'): 1})

        self.assertTrue(Composition('Na') not in rxn.all_comp)

class ComputedReactionTest(unittest.TestCase):
    def setUp(self):
        d = [{"correction": 0.0, "data": {}, "energy": -108.56492362,
              "parameters": {}, "composition": {"Li": 54}},
             {"correction": 0.0, "data": {}, "energy": -577.94689128,
              "parameters": {}, "composition": {"O": 32, "Li": 64}},
             {"correction": 0.0, "data": {}, "energy": -17.02844794,
              "parameters": {}, "composition": {"O": 2}},
             {"correction": 0.0, "data": {}, "energy": -959.64693323,
              "parameters": {}, "composition": {"O": 72, "Li": 72}}]
        entries = []
        for e in d:
            entries.append(ComputedEntry.from_dict(e))
        rcts = list(
            filter(lambda e: e.composition.reduced_formula in ["Li", "O2"],
                   entries))
        prods = list(filter(lambda e: e.composition.reduced_formula == "Li2O2",
                            entries))

        self.rxn = ComputedReaction(rcts, prods)

    def test_calculated_reaction_energy(self):
        self.assertAlmostEqual(self.rxn.calculated_reaction_energy,
                               - 5.60748821935)

    def test_init(self):
        self.assertEqual(str(self.rxn), "O2 + 2 Li -> Li2O2")

    def test_to_from_dict(self):
        d = self.rxn.as_dict()
        new_rxn = ComputedReaction.from_dict(d)
        self.assertEqual(str(new_rxn), "O2 + 2 Li -> Li2O2")

    def test_all_entries(self):
        for c, e in zip(self.rxn.coeffs, self.rxn.all_entries):
            if c > 0:
                self.assertEqual(e.composition.reduced_formula, "Li2O2")
                self.assertAlmostEqual(e.energy, -959.64693323)

if __name__ == '__main__':
    unittest.main()


text:
package saltchannel.util;

public class SystemClockTimeKeeper implements TimeKeeper {
    private boolean isInited = false;
    private long t0;

    @Override
    public int getFirstTime() {
        t0 = System.currentTimeMillis();
        isInited = true;
        return 1;
    }

    @Override
    public int getTime() {
        if (!isInited) throw new IllegalStateException("call getFirstTime first");
        long diff = System.currentTimeMillis() - t0;
        int result = (int) diff;
        if (result  < 0) {
            result = Integer.MAX_VALUE;
        }
        return result;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.openhds.webservice.resources;

import org.openhds.controller.service.RoundService;
import org.openhds.domain.model.wrappers.Rounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/rounds")
public class RoundResource {

    private RoundService roundService;

    @Autowired
    public RoundResource(RoundService roundService) {
        this.roundService = roundService;
    }

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public Rounds getLastRound() {
        Rounds rounds = new Rounds();
        rounds.setRounds(roundService.getLastRound());
        return rounds;
    }

}


text:
namespace lldb_private {

typedef std::pair<int, std::string> OptionArgValue;
typedef std::pair<std::string, OptionArgValue> OptionArgPair;
typedef std::vector<OptionArgPair> OptionArgVector;
typedef std::shared_ptr<OptionArgVector> OptionArgVectorSP;

struct OptionArgElement
{
    enum {
        eUnrecognizedArg = -1,
        eBareDash = -2,
        eBareDoubleDash = -3
    };

    OptionArgElement (int defs_index, int pos, int arg_pos) :
        opt_defs_index(defs_index),
        opt_pos (pos),
        opt_arg_pos (arg_pos)
    {
    }

    int opt_defs_index;
    int opt_pos;
    int opt_arg_pos;
};

typedef std::vector<OptionArgElement> OptionElementVector;

//----------------------------------------------------------------------
/// @class Args Args.h "lldb/Interpreter/Args.h"
/// @brief A command line argument class.
///
/// The Args class is designed to be fed a command line. The
/// command line is copied into an internal buffer and then split up
/// into arguments. Arguments are space delimited if there are no quotes
/// (single, double, or backtick quotes) surrounding the argument. Spaces
/// can be escaped using a \ character to avoid having to surround an
/// argument that contains a space with quotes.
//----------------------------------------------------------------------
class Args
{
public:

    //------------------------------------------------------------------
    /// Construct with an option command string.
    ///
    /// @param[in] command
    ///     A NULL terminated command that will be copied and split up
    ///     into arguments.
    ///
    /// @see Args::SetCommandString(const char *)
    //------------------------------------------------------------------
    Args (const char *command = NULL);

    Args (const char *command, size_t len);

    Args (const Args &rhs);

    const Args &
    operator= (const Args &rhs);

    //------------------------------------------------------------------
    /// Destructor.
    //------------------------------------------------------------------
    ~Args();

    //------------------------------------------------------------------
    /// Dump all arguments to the stream \a s.
    ///
    /// @param[in] s
    ///     The stream to which to dump all arguments in the argument
    ///     vector.
    //------------------------------------------------------------------
    void
    Dump (Stream *s);

    //------------------------------------------------------------------
    /// Sets the command string contained by this object.
    ///
    /// The command string will be copied and split up into arguments
    /// that can be accessed via the accessor functions.
    ///
    /// @param[in] command
    ///     A NULL terminated command that will be copied and split up
    ///     into arguments.
    ///
    /// @see Args::GetArgumentCount() const
    /// @see Args::GetArgumentAtIndex (size_t) const
    /// @see Args::GetArgumentVector ()
    /// @see Args::Shift ()
    /// @see Args::Unshift (const char *)
    //------------------------------------------------------------------
    void
    SetCommandString (const char *command);

    void
    SetCommandString (const char *command, size_t len);

    bool
    GetCommandString (std::string &command) const;

    bool
    GetQuotedCommandString (std::string &command) const;

    //------------------------------------------------------------------
    /// Gets the number of arguments left in this command object.
    ///
    /// @return
    ///     The number or arguments in this object.
    //------------------------------------------------------------------
    size_t
    GetArgumentCount () const;

    //------------------------------------------------------------------
    /// Gets the NULL terminated C string argument pointer for the
    /// argument at index \a idx.
    ///
    /// @return
    ///     The NULL terminated C string argument pointer if \a idx is a
    ///     valid argument index, NULL otherwise.
    //------------------------------------------------------------------
    const char *
    GetArgumentAtIndex (size_t idx) const;

    char
    GetArgumentQuoteCharAtIndex (size_t idx) const;

    //------------------------------------------------------------------
    /// Gets the argument vector.
    ///
    /// The value returned by this function can be used by any function
    /// that takes and vector. The return value is just like \a argv
    /// in the standard C entry point function:
    ///     \code
    ///         int main (int argc, const char **argv);
    ///     \endcode
    ///
    /// @return
    ///     An array of NULL terminated C string argument pointers that
    ///     also has a terminating NULL C string pointer
    //------------------------------------------------------------------
    char **
    GetArgumentVector ();

    //------------------------------------------------------------------
    /// Gets the argument vector.
    ///
    /// The value returned by this function can be used by any function
    /// that takes and vector. The return value is just like \a argv
    /// in the standard C entry point function:
    ///     \code
    ///         int main (int argc, const char **argv);
    ///     \endcode
    ///
    /// @return
    ///     An array of NULL terminate C string argument pointers that
    ///     also has a terminating NULL C string pointer
    //------------------------------------------------------------------
    const char **
    GetConstArgumentVector () const;

    //------------------------------------------------------------------
    /// Appends a new argument to the end of the list argument list.
    ///
    /// @param[in] arg_cstr
    ///     The new argument as a NULL terminated C string.
    ///
    /// @param[in] quote_char
    ///     If the argument was originally quoted, put in the quote char here.
    ///
    /// @return
    ///     The NULL terminated C string of the copy of \a arg_cstr.
    //------------------------------------------------------------------
    const char *
    AppendArgument (const char *arg_cstr, char quote_char = '\0');

    void
    AppendArguments (const Args &rhs);

    void
    AppendArguments (const char **argv);

    //------------------------------------------------------------------
    /// Insert the argument value at index \a idx to \a arg_cstr.
    ///
    /// @param[in] idx
    ///     The index of where to insert the argument.
    ///
    /// @param[in] arg_cstr
    ///     The new argument as a NULL terminated C string.
    ///
    /// @param[in] quote_char
    ///     If the argument was originally quoted, put in the quote char here.
    ///
    /// @return
    ///     The NULL terminated C string of the copy of \a arg_cstr.
    //------------------------------------------------------------------
    const char *
    InsertArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char = '\0');

    //------------------------------------------------------------------
    /// Replaces the argument value at index \a idx to \a arg_cstr
    /// if \a idx is a valid argument index.
    ///
    /// @param[in] idx
    ///     The index of the argument that will have its value replaced.
    ///
    /// @param[in] arg_cstr
    ///     The new argument as a NULL terminated C string.
    ///
    /// @param[in] quote_char
    ///     If the argument was originally quoted, put in the quote char here.
    ///
    /// @return
    ///     The NULL terminated C string of the copy of \a arg_cstr if
    ///     \a idx was a valid index, NULL otherwise.
    //------------------------------------------------------------------
    const char *
    ReplaceArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char = '\0');

    //------------------------------------------------------------------
    /// Deletes the argument value at index
    /// if \a idx is a valid argument index.
    ///
    /// @param[in] idx
    ///     The index of the argument that will have its value replaced.
    ///
    //------------------------------------------------------------------
    void
    DeleteArgumentAtIndex (size_t idx);

    //------------------------------------------------------------------
    /// Sets the argument vector value, optionally copying all
    /// arguments into an internal buffer.
    ///
    /// Sets the arguments to match those found in \a argv. All argument
    /// strings will be copied into an internal buffers.
    //
    //  FIXME: Handle the quote character somehow.
    //------------------------------------------------------------------
    void
    SetArguments (size_t argc, const char **argv);

    void
    SetArguments (const char **argv);

    //------------------------------------------------------------------
    /// Shifts the first argument C string value of the array off the
    /// argument array.
    ///
    /// The string value will be freed, so a copy of the string should
    /// be made by calling Args::GetArgumentAtIndex (size_t) const
    /// first and copying the returned value before calling
    /// Args::Shift().
    ///
    /// @see Args::GetArgumentAtIndex (size_t) const
    //------------------------------------------------------------------
    void
    Shift ();

    //------------------------------------------------------------------
    /// Inserts a class owned copy of \a arg_cstr at the beginning of
    /// the argument vector.
    ///
    /// A copy \a arg_cstr will be made.
    ///
    /// @param[in] arg_cstr
    ///     The argument to push on the front the the argument stack.
    ///
    /// @param[in] quote_char
    ///     If the argument was originally quoted, put in the quote char here.
    ///
    /// @return
    ///     A pointer to the copy of \a arg_cstr that was made.
    //------------------------------------------------------------------
    const char *
    Unshift (const char *arg_cstr, char quote_char = '\0');

    //------------------------------------------------------------------
    /// Parse the arguments in the contained arguments.
    ///
    /// The arguments that are consumed by the argument parsing process
    /// will be removed from the argument vector. The arguements that
    /// get processed start at the second argument. The first argument
    /// is assumed to be the command and will not be touched.
    ///
    /// @see class Options
    //------------------------------------------------------------------
    Error
    ParseOptions (Options &options);

    size_t
    FindArgumentIndexForOption (Option *long_options, int long_options_index);

    bool
    IsPositionalArgument (const char *arg);

    // The following works almost identically to ParseOptions, except that no option is required to have arguments,
    // and it builds up the option_arg_vector as it parses the options.

    void
    ParseAliasOptions (Options &options, CommandReturnObject &result, OptionArgVector *option_arg_vector,
                       std::string &raw_input_line);

    void
    ParseArgsForCompletion (Options &options, OptionElementVector &option_element_vector, uint32_t cursor_index);

    //------------------------------------------------------------------
    // Clear the arguments.
    //
    // For re-setting or blanking out the list of arguments.
    //------------------------------------------------------------------
    void
    Clear ();

    static const char *
    StripSpaces (std::string &s,
                 bool leading = true,
                 bool trailing = true,
                 bool return_null_if_empty = true);

    static int32_t
    StringToSInt32 (const char *s, int32_t fail_value = 0, int base = 0, bool *success_ptr = NULL);

    static uint32_t
    StringToUInt32 (const char *s, uint32_t fail_value = 0, int base = 0, bool *success_ptr = NULL);

    static int64_t
    StringToSInt64 (const char *s, int64_t fail_value = 0, int base = 0, bool *success_ptr = NULL);

    static uint64_t
    StringToUInt64 (const char *s, uint64_t fail_value = 0, int base = 0, bool *success_ptr = NULL);

    static bool
    UInt64ValueIsValidForByteSize (uint64_t uval64, size_t total_byte_size)
    {
        if (total_byte_size > 8)
            return false;

        if (total_byte_size == 8)
            return true;

        const uint64_t max = ((uint64_t)1 << (uint64_t)(total_byte_size * 8)) - 1;
        return uval64 <= max;
    }

    static bool
    SInt64ValueIsValidForByteSize (int64_t sval64, size_t total_byte_size)
    {
        if (total_byte_size > 8)
            return false;

        if (total_byte_size == 8)
            return true;

        const int64_t max = ((int64_t)1 << (uint64_t)(total_byte_size * 8 - 1)) - 1;
        const int64_t min = ~(max);
        return min <= sval64 && sval64 <= max;
    }

    static lldb::addr_t
    StringToAddress (const ExecutionContext *exe_ctx,
                     const char *s,
                     lldb::addr_t fail_value,
                     Error *error);

    static bool
    StringToBoolean (const char *s, bool fail_value, bool *success_ptr);

    static int64_t
    StringToOptionEnum (const char *s, OptionEnumValueElement *enum_values, int32_t fail_value, Error &error);

    static lldb::ScriptLanguage
    StringToScriptLanguage (const char *s, lldb::ScriptLanguage fail_value, bool *success_ptr);

    static Error
    StringToFormat (const char *s,
                    lldb::Format &format,
                    size_t *byte_size_ptr); // If non-NULL, then a byte size can precede the format character

    static lldb::Encoding
    StringToEncoding (const char *s,
                      lldb::Encoding fail_value = lldb::eEncodingInvalid);

    static uint32_t
    StringToGenericRegister (const char *s);

    static const char *
    StringToVersion (const char *s, uint32_t &major, uint32_t &minor, uint32_t &update);

    static const char *
    GetShellSafeArgument (const char *unsafe_arg, std::string &safe_arg);

    // EncodeEscapeSequences will change the textual representation of common
    // escape sequences like "\n" (two characters) into a single '\n'. It does
    // this for all of the supported escaped sequences and for the \0ooo (octal)
    // and \xXX (hex). The resulting "dst" string will contain the character
    // versions of all supported escape sequences. The common supported escape
    // sequences are: "\a", "\b", "\f", "\n", "\r", "\t", "\v", "\'", "\"", "\\".

    static void
    EncodeEscapeSequences (const char *src, std::string &dst);

    // ExpandEscapeSequences will change a string of possibly non-printable
    // characters and expand them into text. So '\n' will turn into two chracters
    // like "\n" which is suitable for human reading. When a character is not
    // printable and isn't one of the common in escape sequences listed in the
    // help for EncodeEscapeSequences, then it will be encoded as octal. Printable
    // characters are left alone.
    static void
    ExpandEscapedCharacters (const char *src, std::string &dst);

    // This one isn't really relevant to Arguments per se, but we're using the Args as a
    // general strings container, so...
    void
    LongestCommonPrefix (std::string &common_prefix);

protected:
    //------------------------------------------------------------------
    // Classes that inherit from Args can see and modify these
    //------------------------------------------------------------------
    typedef std::list<std::string> arg_sstr_collection;
    typedef std::vector<const char *> arg_cstr_collection;
    typedef std::vector<char> arg_quote_char_collection;
    arg_sstr_collection m_args;
    arg_cstr_collection m_argv; ///< The current argument vector.
    arg_quote_char_collection m_args_quote_char;

    void
    UpdateArgsAfterOptionParsing ();

    void
    UpdateArgvFromArgs ();
};

} // namespace lldb_private

#endif  // liblldb_Command_h_


text:
var SearchApp = Backbone.Router.extend({
  initialize: function() {
    window.App = this;

    _.bindAll(this, "search", "jobs", "signedIn", "maps", "service");

    this.events = _.extend({}, Backbone.Events);
    this.events.bind("service:login", this.signedIn);

    this.searchView = new SearchView();
    this.jobsView = new JobManagerView();
    this.mapView = new MapView();
    this.navBarView = new NavBarView({el: "#navbar"});

    this.navBarView.render();
    this.searchView.render();
    this.jobsView.render();
  },

  routes: {
    "" : "search",
    "search" : "search",
    "jobs": "jobs",
    "maps": "maps"
  },

  signedIn: function(service) {
    this.svc = service;
    this.jobsView.jobs.continuousFetch();
  },

  service: function() {
    if (this.svc) {
      return this.svc;
    }

    var view = new SigninView();
    view.show();

    return false;
  },

  search : function() {
    this.setNavigationHighlight("search");

    $("#content").detach();
    $("#content-container").append(this.searchView.el);
  },

  jobs : function() {
    this.setNavigationHighlight("jobs");

    $("#content").detach();
    $("#content-container").append(this.jobsView.el);
  },

  maps: function() {
    this.setNavigationHighlight("maps");

    $("#content").detach();
    $("#content-container").append(this.mapView.el);
    this.mapView.render();
  },

  setNavigationHighlight: function(view) {
    $("#navbar li").each(function(index, elem) {
      $(elem).removeClass("active");

      var href = $(elem).children("a").attr("href") || "";
      if (href.substring(1) === view) {
        $(elem).addClass("active");
      }
    });
  }
});

$(document).ready(function() {
  process.nextTick(function() {
    var app = new SearchApp();
    Backbone.history.start();
  });
});


text:
/*!
 * \file
 * \brief Flush and finish tests.
 *//*--------------------------------------------------------------------*/

#include "es3fFlushFinishTests.hpp"

#include "gluRenderContext.hpp"
#include "gluObjectWrapper.hpp"
#include "gluShaderProgram.hpp"
#include "gluDrawUtil.hpp"

#include "glsCalibration.hpp"

#include "tcuTestLog.hpp"
#include "tcuRenderTarget.hpp"
#include "tcuCPUWarmup.hpp"

#include "glwEnums.hpp"
#include "glwFunctions.hpp"

#include "deRandom.hpp"
#include "deStringUtil.hpp"
#include "deClock.h"
#include "deThread.h"
#include "deMath.h"

#include <algorithm>

namespace deqp
{
namespace gles3
{
namespace Functional
{

using std::vector;
using std::string;
using tcu::TestLog;
using tcu::Vec2;
using deqp::gls::theilSenLinearRegression;
using deqp::gls::LineParameters;

namespace
{

enum
{
	MAX_VIEWPORT_SIZE			= 256,
	MAX_SAMPLE_DURATION_US		= 150*1000,
	WAIT_TIME_MS				= 200,
	MIN_DRAW_CALL_COUNT			= 10,
	MAX_DRAW_CALL_COUNT			= 1<<20,
	MAX_SHADER_ITER_COUNT		= 1<<10,
	NUM_SAMPLES					= 50,
	NUM_VERIFICATION_SAMPLES	= 3,
	MAX_CALIBRATION_ATTEMPTS	= 5
};

DE_STATIC_ASSERT(MAX_SAMPLE_DURATION_US < 1000*WAIT_TIME_MS);

const float		NO_CORR_COEF_THRESHOLD				= 0.1f;
const float		FLUSH_COEF_THRESHOLD				= 0.2f;
const float		CORRELATED_COEF_THRESHOLD			= 0.5f;
const float		CALIBRATION_VERIFICATION_THRESHOLD	= 0.10f;	// Rendering time needs to be within 10% of MAX_SAMPLE_DURATION_US

static void busyWait (int milliseconds)
{
	const deUint64	startTime	= deGetMicroseconds();
	float			v			= 2.0f;

	for (;;)
	{
		for (int i = 0; i < 10; i++)
			v = deFloatSin(v);

		if (deGetMicroseconds()-startTime >= deUint64(1000*milliseconds))
			break;
	}
}

class CalibrationFailedException : public std::runtime_error
{
public:
	CalibrationFailedException (const std::string& reason) : std::runtime_error(reason) {}
};

class FlushFinishCase : public TestCase
{
public:
	enum ExpectedBehavior
	{
		EXPECT_COEF_LESS_THAN = 0,
		EXPECT_COEF_GREATER_THAN,
	};

							FlushFinishCase		(Context&			context,
												 const char*		name,
												 const char*		description,
												 ExpectedBehavior	waitBehavior,
												 float				waitThreshold,
												 ExpectedBehavior	readBehavior,
												 float				readThreshold);
							~FlushFinishCase	(void);

	void					init				(void);
	void					deinit				(void);
	IterateResult			iterate				(void);

	struct Sample
	{
		int			numDrawCalls;
		deUint64	submitTime;
		deUint64	waitTime;
		deUint64	readPixelsTime;
	};

	struct CalibrationParams
	{
		int			numItersInShader;
		int			maxDrawCalls;
	};

protected:
	virtual void			waitForGL			(void) = 0;

private:
							FlushFinishCase		(const FlushFinishCase&);
	FlushFinishCase&		operator=			(const FlushFinishCase&);

	CalibrationParams		calibrate			(void);
	void					verifyCalibration	(const CalibrationParams& params);

	void					analyzeResults		(const std::vector<Sample>& samples, const CalibrationParams& calibrationParams);

	void					setupRenderState	(void);
	void					setShaderIterCount	(int numIters);
	void					render				(int numDrawCalls);
	void					readPixels			(void);

	const ExpectedBehavior	m_waitBehavior;
	const float				m_waitThreshold;
	const ExpectedBehavior	m_readBehavior;
	const float				m_readThreshold;

	glu::ShaderProgram*		m_program;
	int						m_iterCountLoc;
};

FlushFinishCase::FlushFinishCase (Context& context, const char* name, const char* description, ExpectedBehavior waitBehavior, float waitThreshold, ExpectedBehavior readBehavior, float readThreshold)
	: TestCase			(context, name, description)
	, m_waitBehavior	(waitBehavior)
	, m_waitThreshold	(waitThreshold)
	, m_readBehavior	(readBehavior)
	, m_readThreshold	(readThreshold)
	, m_program			(DE_NULL)
	, m_iterCountLoc	(0)
{
}

FlushFinishCase::~FlushFinishCase (void)
{
	FlushFinishCase::deinit();
}

void FlushFinishCase::init (void)
{
	DE_ASSERT(!m_program);

	m_program = new glu::ShaderProgram(m_context.getRenderContext(),
		glu::ProgramSources()
			<< glu::VertexSource(
				"#version 300 es\n"
				"in highp vec4 a_position;\n"
				"out highp vec4 v_coord;\n"
				"void main (void)\n"
				"{\n"
				"	gl_Position = a_position;\n"
				"	v_coord = a_position;\n"
				"}\n")
			<< glu::FragmentSource(
				"#version 300 es\n"
				"uniform highp int u_numIters;\n"
				"in highp vec4 v_coord;\n"
				"out mediump vec4 o_color;\n"
				"void main (void)\n"
				"{\n"
				"	highp vec4 color = v_coord;\n"
				"	for (int i = 0; i < u_numIters; i++)\n"
				"		color = sin(color);\n"
				"	o_color = color;\n"
				"}\n"));

	if (!m_program->isOk())
	{
		m_testCtx.getLog() << *m_program;
		delete m_program;
		m_program = DE_NULL;
		TCU_FAIL("Compile failed");
	}

	m_iterCountLoc = m_context.getRenderContext().getFunctions().getUniformLocation(m_program->getProgram(), "u_numIters");
	TCU_CHECK(m_iterCountLoc >= 0);
}

void FlushFinishCase::deinit (void)
{
	delete m_program;
	m_program = DE_NULL;
}

tcu::TestLog& operator<< (tcu::TestLog& log, const FlushFinishCase::Sample& sample)
{
	log << TestLog::Message << sample.numDrawCalls << " calls:\t" << sample.submitTime << " us submit,\t" << sample.waitTime << " us wait,\t" << sample.readPixelsTime << " us read" << TestLog::EndMessage;
	return log;
}

void FlushFinishCase::setupRenderState (void)
{
	const glw::Functions&	gl				= m_context.getRenderContext().getFunctions();
	const int				posLoc			= gl.getAttribLocation(m_program->getProgram(), "a_position");
	const int				viewportW		= de::min<int>(m_context.getRenderTarget().getWidth(), MAX_VIEWPORT_SIZE);
	const int				viewportH		= de::min<int>(m_context.getRenderTarget().getHeight(), MAX_VIEWPORT_SIZE);

	static const float s_positions[] =
	{
		-1.0f, -1.0f,
		+1.0f, -1.0f,
		-1.0f, +1.0f,
		+1.0f, +1.0f
	};

	TCU_CHECK(posLoc >= 0);

	gl.viewport(0, 0, viewportW, viewportH);
	gl.useProgram(m_program->getProgram());
	gl.enableVertexAttribArray(posLoc);
	gl.vertexAttribPointer(posLoc, 2, GL_FLOAT, GL_FALSE, 0, &s_positions[0]);
	gl.enable(GL_BLEND);
	gl.blendFunc(GL_ONE, GL_ONE);
	gl.blendEquation(GL_FUNC_ADD);
	GLU_EXPECT_NO_ERROR(gl.getError(), "Failed to set up render state");
}

void FlushFinishCase::setShaderIterCount (int numIters)
{
	const glw::Functions&	gl	= m_context.getRenderContext().getFunctions();
	gl.uniform1i(m_iterCountLoc, numIters);
}

void FlushFinishCase::render (int numDrawCalls)
{
	const glw::Functions&	gl	= m_context.getRenderContext().getFunctions();

	const deUint8 indices[] = { 0, 1, 2, 2, 1, 3 };

	gl.clear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);

	for (int ndx = 0; ndx < numDrawCalls; ndx++)
		gl.drawElements(GL_TRIANGLES, DE_LENGTH_OF_ARRAY(indices), GL_UNSIGNED_BYTE, &indices[0]);
}

void FlushFinishCase::readPixels (void)
{
	const glw::Functions&	gl		= m_context.getRenderContext().getFunctions();
	deUint8					tmp[4];

	gl.readPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &tmp);
}

FlushFinishCase::CalibrationParams FlushFinishCase::calibrate (void)
{
	tcu::ScopedLogSection		section				(m_testCtx.getLog(), "CalibrationInfo", "Calibration info");
	CalibrationParams			params;

	// Step 1: find iteration count that results in rougly 1/10th of target maximum sample duration.
	{
		const deUint64		targetDurationUs		= MAX_SAMPLE_DURATION_US/100;
		deUint64			prevDuration			= 0;
		int					prevIterCount			= 1;
		int					curIterCount			= 1;

		m_testCtx.getLog() << TestLog::Message << "Calibrating shader iteration count, target duration = " << targetDurationUs << " us" << TestLog::EndMessage;

		for (;;)
		{
			deUint64 curDuration;

			setShaderIterCount(curIterCount);
			render(1); // \note Submit time is ignored

			{
				const deUint64 startTime = deGetMicroseconds();
				readPixels();
				curDuration = deGetMicroseconds()-startTime;
			}

			m_testCtx.getLog() << TestLog::Message << "Duration with " << curIterCount << " iterations = " << curDuration << " us" << TestLog::EndMessage;

			if (curDuration > targetDurationUs)
			{
				if (curIterCount > 1)
				{
					// Compute final count by using linear estimation.
					const float		a		= float(curDuration - prevDuration) / float(curIterCount - prevIterCount);
					const float		b		= float(prevDuration) - a*float(prevIterCount);
					const float		est		= (float(targetDurationUs) - b) / a;

					curIterCount = de::clamp(deFloorFloatToInt32(est), 1, int(MAX_SHADER_ITER_COUNT));
				}
				// else: Settle on 1.

				break;
			}
			else if (curIterCount >= MAX_SHADER_ITER_COUNT)
				break; // Settle on maximum.
			else
			{
				prevIterCount	= curIterCount;
				prevDuration	= curDuration;
				curIterCount	= curIterCount*2;
			}
		}

		params.numItersInShader = curIterCount;

		m_testCtx.getLog() << TestLog::Integer("ShaderIterCount", "Shader iteration count", "", QP_KEY_TAG_NONE, params.numItersInShader);
	}

	// Step 2: Find draw call count that results in desired maximum time.
	{
		deUint64			prevDuration			= 0;
		int					prevDrawCount			= 1;
		int					curDrawCount			= 1;

		m_testCtx.getLog() << TestLog::Message << "Calibrating maximum draw call count, target duration = " << int(MAX_SAMPLE_DURATION_US) << " us" << TestLog::EndMessage;

		setShaderIterCount(params.numItersInShader);

		for (;;)
		{
			deUint64 curDuration;

			render(curDrawCount); // \note Submit time is ignored

			{
				const deUint64 startTime = deGetMicroseconds();
				readPixels();
				curDuration = deGetMicroseconds()-startTime;
			}

			m_testCtx.getLog() << TestLog::Message << "Duration with " << curDrawCount << " draw calls = " << curDuration << " us" << TestLog::EndMessage;

			if (curDuration > MAX_SAMPLE_DURATION_US)
			{
				if (curDrawCount > 1)
				{
					// Compute final count by using linear estimation.
					const float		a		= float(curDuration - prevDuration) / float(curDrawCount - prevDrawCount);
					const float		b		= float(prevDuration) - a*float(prevDrawCount);
					const float		est		= (float(MAX_SAMPLE_DURATION_US) - b) / a;

					curDrawCount = de::clamp(deFloorFloatToInt32(est), 1, int(MAX_DRAW_CALL_COUNT));
				}
				// else: Settle on 1.

				break;
			}
			else if (curDrawCount >= MAX_DRAW_CALL_COUNT)
				break; // Settle on maximum.
			else
			{
				prevDrawCount	= curDrawCount;
				prevDuration	= curDuration;
				curDrawCount	= curDrawCount*2;
			}
		}

		params.maxDrawCalls = curDrawCount;

		m_testCtx.getLog() << TestLog::Integer("MaxDrawCalls", "Maximum number of draw calls", "", QP_KEY_TAG_NONE, params.maxDrawCalls);
	}

	// Sanity check.
	if (params.maxDrawCalls < MIN_DRAW_CALL_COUNT)
		throw CalibrationFailedException("Calibration failed, maximum draw call count is too low");

	return params;
}

void FlushFinishCase::verifyCalibration (const CalibrationParams& params)
{
	setShaderIterCount(params.numItersInShader);

	for (int sampleNdx = 0; sampleNdx < NUM_VERIFICATION_SAMPLES; sampleNdx++)
	{
		deUint64 readStartTime;

		render(params.maxDrawCalls);

		readStartTime = deGetMicroseconds();
		readPixels();

		{
			const deUint64	renderDuration	= deGetMicroseconds()-readStartTime;
			const float		relativeDelta	= float(double(renderDuration) / double(MAX_SAMPLE_DURATION_US)) - 1.0f;

			if (!de::inBounds(relativeDelta, -CALIBRATION_VERIFICATION_THRESHOLD, CALIBRATION_VERIFICATION_THRESHOLD))
			{
				std::ostringstream msg;
				msg << "ERROR: Unstable performance, got " << renderDuration << " us read time, "
					<< de::floatToString(relativeDelta*100.0f, 1) << "% diff to estimated " << (int)MAX_SAMPLE_DURATION_US << " us";
				throw CalibrationFailedException(msg.str());
			}
		}
	}
}

struct CompareSampleDrawCount
{
	bool operator() (const FlushFinishCase::Sample& a, const FlushFinishCase::Sample& b) const { return a.numDrawCalls < b.numDrawCalls; }
};

std::vector<Vec2> getPointsFromSamples (const std::vector<FlushFinishCase::Sample>& samples, const deUint64 FlushFinishCase::Sample::*field)
{
	vector<Vec2> points(samples.size());

	for (size_t ndx = 0; ndx < samples.size(); ndx++)
		points[ndx] = Vec2(float(samples[ndx].numDrawCalls), float(samples[ndx].*field));

	return points;
}

template<typename T>
T getMaximumValue (const std::vector<FlushFinishCase::Sample>& samples, const T FlushFinishCase::Sample::*field)
{
	DE_ASSERT(!samples.empty());

	T maxVal = samples[0].*field;

	for (size_t ndx = 1; ndx < samples.size(); ndx++)
		maxVal = de::max(maxVal, samples[ndx].*field);

	return maxVal;
}

void FlushFinishCase::analyzeResults (const std::vector<Sample>& samples, const CalibrationParams& calibrationParams)
{
	const vector<Vec2>		waitTimes		= getPointsFromSamples(samples, &Sample::waitTime);
	const vector<Vec2>		readTimes		= getPointsFromSamples(samples, &Sample::readPixelsTime);
	const LineParameters	waitLine		= theilSenLinearRegression(waitTimes);
	const LineParameters	readLine		= theilSenLinearRegression(readTimes);
	const float				normWaitCoef	= waitLine.coefficient * float(calibrationParams.maxDrawCalls) / float(MAX_SAMPLE_DURATION_US);
	const float				normReadCoef	= readLine.coefficient * float(calibrationParams.maxDrawCalls) / float(MAX_SAMPLE_DURATION_US);
	bool					allOk			= true;

	{
		tcu::ScopedLogSection	section			(m_testCtx.getLog(), "Samples", "Samples");
		vector<Sample>			sortedSamples	(samples.begin(), samples.end());

		std::sort(sortedSamples.begin(), sortedSamples.end(), CompareSampleDrawCount());

		for (vector<Sample>::const_iterator iter = sortedSamples.begin(); iter != sortedSamples.end(); ++iter)
			m_testCtx.getLog() << *iter;
	}

	m_testCtx.getLog() << TestLog::Float("WaitCoefficient",				"Wait coefficient", "", QP_KEY_TAG_NONE, waitLine.coefficient)
					   << TestLog::Float("ReadCoefficient",				"Read coefficient", "", QP_KEY_TAG_NONE, readLine.coefficient)
					   << TestLog::Float("NormalizedWaitCoefficient",	"Normalized wait coefficient", "", QP_KEY_TAG_NONE, normWaitCoef)
					   << TestLog::Float("NormalizedReadCoefficient",	"Normalized read coefficient", "", QP_KEY_TAG_NONE, normReadCoef);

	{
		const bool		waitCorrelated		= normWaitCoef > CORRELATED_COEF_THRESHOLD;
		const bool		readCorrelated		= normReadCoef > CORRELATED_COEF_THRESHOLD;
		const bool		waitNotCorr			= normWaitCoef < NO_CORR_COEF_THRESHOLD;
		const bool		readNotCorr			= normReadCoef < NO_CORR_COEF_THRESHOLD;

		if (waitCorrelated || waitNotCorr)
			m_testCtx.getLog() << TestLog::Message << "Wait time is" << (waitCorrelated ? "" : " NOT") << " correlated to rendering workload size." << TestLog::EndMessage;
		else
			m_testCtx.getLog() << TestLog::Message << "Warning: Wait time correlation to rendering workload size is unclear." << TestLog::EndMessage;

		if (readCorrelated || readNotCorr)
			m_testCtx.getLog() << TestLog::Message << "Read time is" << (readCorrelated ? "" : " NOT") << " correlated to rendering workload size." << TestLog::EndMessage;
		else
			m_testCtx.getLog() << TestLog::Message << "Warning: Read time correlation to rendering workload size is unclear." << TestLog::EndMessage;
	}

	for (int ndx = 0; ndx < 2; ndx++)
	{
		const float				coef		= ndx == 0 ? normWaitCoef : normReadCoef;
		const char*				name		= ndx == 0 ? "wait" : "read";
		const ExpectedBehavior	behavior	= ndx == 0 ? m_waitBehavior : m_readBehavior;
		const float				threshold	= ndx == 0 ? m_waitThreshold : m_readThreshold;
		const bool				isOk		= behavior == EXPECT_COEF_GREATER_THAN	? coef > threshold :
											  behavior == EXPECT_COEF_LESS_THAN		? coef < threshold : false;
		const char*				cmpName		= behavior == EXPECT_COEF_GREATER_THAN	? "greater than" :
											  behavior == EXPECT_COEF_LESS_THAN		? "less than" : DE_NULL;

		if (!isOk)
		{
			m_testCtx.getLog() << TestLog::Message << "ERROR: Expected " << name << " coefficient to be " << cmpName << " " << threshold << TestLog::EndMessage;
			allOk = false;
		}
	}

	m_testCtx.setTestResult(allOk ? QP_TEST_RESULT_PASS	: QP_TEST_RESULT_FAIL,
							allOk ? "Pass"				: "Suspicious performance behavior");
}

FlushFinishCase::IterateResult FlushFinishCase::iterate (void)
{
	vector<Sample>		samples		(NUM_SAMPLES);
	CalibrationParams	params;

	tcu::warmupCPU();

	setupRenderState();

	// Do one full render cycle.
	{
		setShaderIterCount(1);
		render(1);
		readPixels();
	}

	// Calibrate.
	for (int calibrationRoundNdx = 0; /* until done */; calibrationRoundNdx++)
	{
		try
		{
			m_testCtx.touchWatchdog();
			params = calibrate();
			verifyCalibration(params);
			break;
		}
		catch (const CalibrationFailedException& e)
		{
			m_testCtx.getLog() << e;

			if (calibrationRoundNdx < MAX_CALIBRATION_ATTEMPTS)
			{
				m_testCtx.getLog() << TestLog::Message
								   << "Retrying calibration (" << (calibrationRoundNdx+1) << " / " << (int)MAX_CALIBRATION_ATTEMPTS << ")"
								   << TestLog::EndMessage;
			}
			else
			{
				m_testCtx.setTestResult(QP_TEST_RESULT_COMPATIBILITY_WARNING, e.what());
				return STOP;
			}
		}
	}

	// Do measurement.
	{
		de::Random	rnd		(123);

		setShaderIterCount(params.numItersInShader);

		for (size_t ndx = 0; ndx < samples.size(); ndx++)
		{
			const int		drawCallCount	= rnd.getInt(1, params.maxDrawCalls);
			const deUint64	submitStartTime	= deGetMicroseconds();
			deUint64		waitStartTime;
			deUint64		readStartTime;
			deUint64		readFinishTime;

			render(drawCallCount);

			waitStartTime = deGetMicroseconds();
			waitForGL();

			readStartTime = deGetMicroseconds();
			readPixels();
			readFinishTime = deGetMicroseconds();

			samples[ndx].numDrawCalls	= drawCallCount;
			samples[ndx].submitTime		= waitStartTime-submitStartTime;
			samples[ndx].waitTime		= readStartTime-waitStartTime;
			samples[ndx].readPixelsTime	= readFinishTime-readStartTime;

			m_testCtx.touchWatchdog();
		}
	}

	// Analyze - sets test case result.
	analyzeResults(samples, params);

	return STOP;
}

class WaitOnlyCase : public FlushFinishCase
{
public:
	WaitOnlyCase (Context& context)
		: FlushFinishCase(context, "wait", "Wait only", EXPECT_COEF_LESS_THAN, NO_CORR_COEF_THRESHOLD, EXPECT_COEF_GREATER_THAN, -1000.0f /* practically nothing is expected */)
	{
	}

	void init (void)
	{
		m_testCtx.getLog() << TestLog::Message << int(WAIT_TIME_MS) << " ms busy wait" << TestLog::EndMessage;
		FlushFinishCase::init();
	}

protected:
	void waitForGL (void)
	{
		busyWait(WAIT_TIME_MS);
	}
};

class FlushOnlyCase : public FlushFinishCase
{
public:
	FlushOnlyCase (Context& context)
		: FlushFinishCase(context, "flush", "Flush only", EXPECT_COEF_LESS_THAN, FLUSH_COEF_THRESHOLD, EXPECT_COEF_GREATER_THAN, CORRELATED_COEF_THRESHOLD)
	{
	}

	void init (void)
	{
		m_testCtx.getLog() << TestLog::Message << "Single call to glFlush()" << TestLog::EndMessage;
		FlushFinishCase::init();
	}

protected:
	void waitForGL (void)
	{
		m_context.getRenderContext().getFunctions().flush();
	}
};

class FlushWaitCase : public FlushFinishCase
{
public:
	FlushWaitCase (Context& context)
		: FlushFinishCase(context, "flush_wait", "Wait after flushing", EXPECT_COEF_LESS_THAN, FLUSH_COEF_THRESHOLD, EXPECT_COEF_LESS_THAN, NO_CORR_COEF_THRESHOLD)
	{
	}

	void init (void)
	{
		m_testCtx.getLog() << TestLog::Message << "glFlush() followed by " << int(WAIT_TIME_MS) << " ms busy wait" << TestLog::EndMessage;
		FlushFinishCase::init();
	}

protected:
	void waitForGL (void)
	{
		m_context.getRenderContext().getFunctions().flush();
		busyWait(WAIT_TIME_MS);
	}
};

class FinishOnlyCase : public FlushFinishCase
{
public:
	FinishOnlyCase (Context& context)
		: FlushFinishCase(context, "finish", "Finish only", EXPECT_COEF_GREATER_THAN, CORRELATED_COEF_THRESHOLD, EXPECT_COEF_LESS_THAN, NO_CORR_COEF_THRESHOLD)
	{
	}

	void init (void)
	{
		m_testCtx.getLog() << TestLog::Message << "Single call to glFinish()" << TestLog::EndMessage;
		FlushFinishCase::init();
	}

protected:
	void waitForGL (void)
	{
		m_context.getRenderContext().getFunctions().finish();
	}
};

class FinishWaitCase : public FlushFinishCase
{
public:
	FinishWaitCase (Context& context)
		: FlushFinishCase(context, "finish_wait", "Finish and wait", EXPECT_COEF_GREATER_THAN, CORRELATED_COEF_THRESHOLD, EXPECT_COEF_LESS_THAN, NO_CORR_COEF_THRESHOLD)
	{
	}

	void init (void)
	{
		m_testCtx.getLog() << TestLog::Message << "glFinish() followed by " << int(WAIT_TIME_MS) << " ms busy wait" << TestLog::EndMessage;
		FlushFinishCase::init();
	}

protected:
	void waitForGL (void)
	{
		m_context.getRenderContext().getFunctions().finish();
		busyWait(WAIT_TIME_MS);
	}
};

} // anonymous

FlushFinishTests::FlushFinishTests (Context& context)
	: TestCaseGroup(context, "flush_finish", "Flush and Finish tests")
{
}

FlushFinishTests::~FlushFinishTests (void)
{
}

void FlushFinishTests::init (void)
{
	addChild(new WaitOnlyCase	(m_context));
	addChild(new FlushOnlyCase	(m_context));
	addChild(new FlushWaitCase	(m_context));
	addChild(new FinishOnlyCase	(m_context));
	addChild(new FinishWaitCase	(m_context));
}

} // Functional
} // gles3
} // deqp


text:
package com.vadim.ok.portmapper.statistics;

import com.vadim.ok.logging.LoggerHelper;
import com.vadim.ok.portmapper.tasks.TaskExecutionStatistics;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;

class TaskExecutionStatisticsAggregator implements Callable<Integer> {
    private static final Logger logger = LoggerHelper.getLogger(TaskExecutionStatisticsAggregator.class);

    private TotalExecutionStatistics totalExecutionStatistics;

    public TaskExecutionStatisticsAggregator(TotalExecutionStatistics totalExecutionStatistics) {
        this.totalExecutionStatistics = totalExecutionStatistics;
    }

    @Override
    public Integer call() throws Exception {
        logger.info("start");

        int freeCellsCount = 0;

        for (int i = 0; i < totalExecutionStatistics.taskExecutionStatisticsHolderBuffer.length; ++i) {
            Future<TaskExecutionStatistics> taskExecutionStatistics = totalExecutionStatistics.taskExecutionStatisticsHolderBuffer[i];

            if (taskExecutionStatistics.isDone()) {
                try {
                    totalExecutionStatistics.totalTransmittedBytesFromClientToTargetCount +=
                            taskExecutionStatistics.get().getTransmittedBytesFromClientToTargetCount();
                    totalExecutionStatistics.totalTransmittedBytesFromTargetToClientCount +=
                            taskExecutionStatistics.get().getTransmittedBytesFromTargetToClientCount();

                    totalExecutionStatistics.byteBufferCapacity = taskExecutionStatistics.get().getByteBufferCapacity();
                } catch (InterruptedException e) {
                    logger.log(Level.WARNING, "Accept task was interrupted during execution", e);
                } catch (ExecutionException e) {
                    Throwable cause = e.getCause();
                    logger.log(Level.WARNING, "Accept task failed", cause);
                } finally {
                    totalExecutionStatistics.taskExecutionStatisticsHolderBuffer[i] = null;
                    freeCellsCount++;
                }
            }
        }

        logger.info("finish");

        return freeCellsCount;
    }
}


text: Three column grid.


text:
namespace orpg
{
   template <typename T>
   [[nodiscard]] auto read_from_json(std::filesystem::path const& filename) noexcept -> T
   {
      T result;
      try {
         std::ifstream ifs{filename};
         const auto j = nlohmann::json::parse(ifs);
         result = j.get<T>();
      } catch (...) {
         spdlog::warn("failed to open and parse: {} \n -> use default", filename.string());
      }
      return result;
   }
} // namespace orpg


text:
[Passport](http://passportjs.org/) strategies for authenticating with [Google](http://www.google.com/)
using OAuth 1.0a and OAuth 2.0.

This module lets you authenticate using Google in your Node.js applications.
By plugging into Passport, Google authentication can be easily and
unobtrusively integrated into any application or framework that supports
[Connect](http://www.senchalabs.org/connect/)-style middleware, including
[Express](http://expressjs.com/).

## Install

    $ npm install passport-google-oauth

## Usage of OAuth 1.0

#### Configure Strategy

The Google OAuth 1.0 authentication strategy authenticates users using a Google
account and OAuth tokens.  The strategy requires a `verify` callback, which
accepts these credentials and calls `done` providing a user, as well as `options`
specifying a consumer key, consumer secret, and callback URL.

    var GoogleStrategy = require('passport-google-oauth').OAuthStrategy;

    passport.use(new GoogleStrategy({
        consumerKey: GOOGLE_CONSUMER_KEY,
        consumerSecret: GOOGLE_CONSUMER_SECRET,
        callbackURL: "http://127.0.0.1:3000/auth/google/callback"
      },
      function(token, tokenSecret, profile, done) {
        User.findOrCreate({ googleId: profile.id }, function (err, user) {
          return done(err, user);
        });
      }
    ));

#### Authenticate Requests

Use `passport.authenticate()`, specifying the `'google'` strategy, to
authenticate requests.

For example, as route middleware in an [Express](http://expressjs.com/)
application:

    app.get('/auth/google',
      passport.authenticate('google', { scope: 'https://www.google.com/m8/feeds' }));

    app.get('/auth/google/callback',
      passport.authenticate('google', { failureRedirect: '/login' }),
      function(req, res) {
        // Successful authentication, redirect home.
        res.redirect('/');
      });

## Usage of OAuth 2.0

#### Configure Strategy

The Google OAuth 2.0 authentication strategy authenticates users using a Google
account and OAuth 2.0 tokens.  The strategy requires a `verify` callback, which
accepts these credentials and calls `done` providing a user, as well as
`options` specifying a client ID, client secret, and callback URL.

    var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

    passport.use(new GoogleStrategy({
        clientID: GOOGLE_CLIENT_ID,
        clientSecret: GOOGLE_CLIENT_SECRET,
        callbackURL: "http://127.0.0.1:3000/auth/google/callback"
      },
      function(accessToken, refreshToken, profile, done) {
        User.findOrCreate({ googleId: profile.id }, function (err, user) {
          return done(err, user);
        });
      }
    ));

#### Authenticate Requests

Use `passport.authenticate()`, specifying the `'google'` strategy, to
authenticate requests.

For example, as route middleware in an [Express](http://expressjs.com/)
application:

    app.get('/auth/google',
      passport.authenticate('google'));

    app.get('/auth/google/callback',
      passport.authenticate('google', { failureRedirect: '/login' }),
      function(req, res) {
        // Successful authentication, redirect home.
        res.redirect('/');
      });

## Examples

For a complete, working example, refer to the [OAuth 1.0 example](https://github.com/jaredhanson/passport-google-oauth/tree/master/examples/oauth)
and the [OAuth 2.0 example](https://github.com/jaredhanson/passport-google-oauth/tree/master/examples/oauth2).

## Tests

    $ npm install --dev
    $ make test

[![Build Status](https://secure.travis-ci.org/jaredhanson/passport-google-oauth.png)](http://travis-ci.org/jaredhanson/passport-google-oauth)

## Credits

  - [Jared Hanson](http://github.com/jaredhanson)

## License

[The MIT License](http://opensource.org/licenses/MIT)

Copyright (c) 2012-2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)>


text:
<!DOCTYPE html>

  <meta name="project_path" value="/web/tools/workbox/_project.yaml" />
  <meta name="book_path" value="/web/tools/workbox/_book.yaml" />
  <meta name="gtm_var" data-key="docType" data-value="reference">
  <title>Namespace: strategies</title>
  <link href="jsdoc.css" rel="stylesheet">

workbox.<wbr>strategies

namespace   static

              Version
              v3.2.0

There are common caching strategies that most service workers will need and use. This module provides simple implementations of these strategies.

Classes

CacheFirst

An implementation of a cache-first request strategy.

A cache first strategy is useful for assets that have been revisioned, such as URLs like /styles/example.a8f5f1.css, since they can be cached for long periods of time.

CacheOnly

An implementation of a
                cache-only request strategy.

This class is useful if you want to take advantage of any Workbox plugins.

NetworkFirst

An implementation of a
                network first request strategy.

By default, this strategy will cache responses with a 200 status code as well as opaque responses. Opaque responses are are cross-origin requests
                where the response doesn't support CORS.

NetworkOnly

An implementation of a
                network-only request strategy.

This class is useful if you want to take advantage of any Workbox plugins.

StaleWhileRevalidate

An implementation of a
                stale-while-revalidate request strategy.

Resources are requested from both the cache and the network in parallel. The strategy will respond with the cached version if available, otherwise wait for the network response. The cache is updated with the network response with each successful
                request.

By default, this strategy will cache responses with a 200 status code as well as opaque responses. Opaque responses are are cross-origin requests
                where the response doesn't support CORS.

Methods

cacheFirst

static

 cacheFirst(options)

Parameter

options

workbox.strategies.StrategyOptions

cacheOnly

static

 cacheOnly(options)

Parameter

options

workbox.strategies.StrategyOptions

networkFirst

static

 networkFirst(options)

Parameter

options

workbox.strategies.StrategyOptions

networkOnly

static

 networkOnly(options)

Parameter

options

workbox.strategies.StrategyOptions

staleWhileRevalidate

static

 staleWhileRevalidate(options)

Parameter

options

workbox.strategies.StrategyOptions

Abstract type

StrategyOptions

static

Object

Properties

Parameter

cacheName

String

Name of cache to use for caching (both lookup and updating).

cacheExpiration

Object

Defining this object will add a cache expiration plugins to this strategy.

Values in cacheExpiration have the following properties:

Parameter

maxEntries

Number

The maximum number of entries to store in a cache.

maxAgeSeconds

Number

The maximum lifetime of a request to stay in the cache before it's removed.


text:
package sualma.writer;

import org.junit.Test;
import static org.junit.Assert.*;
import sualma.model.*;
import sualma.parser.Parser;
import sualma.util.ObjFactory;

/**
 * @author wijnand.schepens@gmail.com
 */
public class SimpleWriterTest extends ObjFactory
{
    Parser parser = new Parser();

    @Test
    public void TestNum()
    {
        Obj obj = num(123);

        String text = SimpleWriter.toString(obj);

        assertEquals("123", text);

        assertEquals(obj, parser.parse(text)); // roundtrip
    }

    @Test
    public void TestName()
    {
        Obj obj = name("abc");

        String text = SimpleWriter.toString(obj);

        assertEquals("abc", text);

        assertEquals(obj, parser.parse(text)); // roundtrip
    }

    @Test
    public void TestBool()
    {
        Obj obj = True;

        String text = SimpleWriter.toString(obj);

        assertEquals("true", text);

        assertEquals(obj, parser.parse(text)); // roundtrip
    }

    @Test
    public void TestStr()
    {
        Obj obj = str("abc");

        String text = SimpleWriter.toString(obj);

        assertEquals("\"abc\"", text);

        assertEquals(obj, parser.parse(text)); // roundtrip
    }

    @Test
    public void TestEmptyList()
    {
        Obj obj = list();

        String text = SimpleWriter.toString(obj);

        assertEquals("()", text);

        assertEquals(obj, parser.parse(text)); // roundtrip
    }

    @Test
    public void TestOneElementList()
    {
        Obj obj = list(num(123));

        String text = SimpleWriter.toString(obj);

        assertEquals("( 123, )", text);
    }

    @Test
    public void TestTwoElementList()
    {
        Obj obj = list(num(123), name("abc"));

        String text = SimpleWriter.toString(obj);

        assertEquals("( 123, abc )", text);

        assertEquals(obj, parser.parse(text)); // roundtrip
    }

    @Test
    public void TestCall()
    {
        Obj obj = call(name("f"), num(123));

        String text = SimpleWriter.toString(obj);

        assertEquals("( f 123 )", text);

        assertEquals(obj, parser.parse(text)); // roundtrip
    }

}


text:
@include("plantillas.secadmin.doctype")

@include("plantillas.secadmin.head")

    @include("plantillas.general.cabecera_nav")

    @include("plantillas.secperfil.sidebar")

                @section("nombre_pagina")
                {{  "Perfil de Usuario" }}
                @show

                @yield("guia_navegacion")

            @yield("contenido")

    @include("plantillas.secadmin.footer")

    @include("plantillas.secadmin.controlsidebar")

@include("plantillas.secadmin.footerjs")
@yield("extra_js")