text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>list_of Reference</title>
<link rel="stylesheet" href="../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Bimap">
<link rel="up" href="../reference.html" title="Reference">
<link rel="prev" href="unordered_set_of_reference.html" title="unordered_set_of Reference">
<link rel="next" href="vector_of_reference.html" title="vector_of Reference">

Home
Libraries
People
FAQ
More

list_of Reference

Header
        "boost/bimap/list_of.hpp" synopsis

list_of
        Views

Complexity
          signature

Instantiation
          types

Constructors,
          copy and assignment

Capacity
          operations

Modifiers

List
          operations

Rearrange
          operations

Serialization

Header
        "boost/bimap/list_of.hpp" synopsis

namespace boost {
namespace bimaps {

template< class KeyType >
struct list_of;

struct list_of_relation;

} // namespace bimap
} // namespace boost

list_of
        Views

Complexity
          signature

Instantiation
          types

Constructors,
          copy and assignment

Capacity
          operations

Modifiers

List
          operations

Rearrange
          operations

Serialization

          A list_of set view is a std::list signature compatible interface to the
          underlying heap of elements contained in a bimap.

          If you look the bimap by a side, you will use a map view and if you looked
          it as a whole you will be using a set view.

          Elements in a list_of view are by default sorted according to their order
          of insertion: this means that new elements inserted through a different
          view of the bimap are appended
          to the end of the list_of view. Additionally, the view allows for free
          reordering of elements in the same vein as std::list
          does. Validity of iterators and references to elements is preserved in
          all operations.

          There are a number of differences with respect to std::lists:

              list_of views are not Assignable
              (like any other view.)

              Unlike as in std::list, insertions into a list_of view
              may fail due to clashings with other views. This alters the semantics
              of the operations provided with respect to their analogues in std::list.

              Elements in a list_of view are not mutable, and can only be changed
              by means of replace
              and modify member functions.

          Having these restrictions into account, list_of views are models of Reversible Container,
          Front
          Insertion Sequence and Back
          Insertion Sequence. We only provide descriptions of those types
          and operations that are either not present in the concepts modeled or do
          not exactly conform to the requirements for these types of containers.

namespace boost {
namespace bimaps {
namespace views {

template< -implementation defined parameter list- >
class -implementation defined view name-
{
    public:

    // types

    typedef -unspecified- value_type;
    typedef -unspecified- allocator_type;
    typedef -unspecified- reference;
    typedef -unspecified- const_reference;
    typedef -unspecified- iterator;
    typedef -unspecified- const_iterator;
    typedef -unspecified- size_type;
    typedef -unspecified- difference_type;
    typedef -unspecified- pointer;
    typedef -unspecified- const_pointer;
    typedef -unspecified- reverse_iterator;
    typedef -unspecified- const_reverse_iterator;

    typedef -unspecified- info_type;

    // construct/copy/destroy

    this_type & operator=(const this_type & x);

    template< class InputIterator >
    void assign(InputIterator first, InputIterator last);

    void assign(size_type n, const value_type & value);

    allocator_type get_allocator() const;

    // iterators

    iterator               begin();
    const_iterator         begin() const;

    iterator               end();
    const_iterator         end() const;

    reverse_iterator       rbegin();
    const_reverse_iterator rbegin() const;

    reverse_iterator       rend();
    const_reverse_iterator rend() const;

    // capacity

    bool      empty() const;

    size_type size() const;

    size_type max_size() const;

    void resize(size_type n, const value_type & x = value_type());

    // access

    const_reference front() const;
    const_reference back() const;

    // modifiers

    std::pair<iterator,bool> push_front(const value_type & x);
    void                     pop_front();

    std::pair<iterator,bool> push_back(const value_type & x);
    void                     pop_back();

    std::pair<iterator,bool> insert(iterator position, const value_type & x);

    void insert(iterator position, size_type n, const value_type & x);

    template< class InputIterator >
    void insert(iterator position, InputIterator first, InputIterator last);

    iterator erase(iterator position);
    iterator erase(iterator first, iterator last);

    bool replace(iterator position, const value_type & x);

    // Only in map views
    // {

      typedef -unspecified- key_type;
      typedef -unspecified- mapped_type;
      typedef -unspecified- mapped_type; // Equal to mapped_type

      template< class CompatibleKey >
      bool replace_key(iterator position, const CompatibleKey & x);

      template< class CompatibleData >
      bool replace_data(iterator position, const CompatibleData & x);

      template< class KeyModifier >
      bool modify_key(iterator position, KeyModifier mod);

      template< class DataModifier >
      bool modify_data(iterator position, DataModifier mod);

    // }

    void clear();

    // list operations

    void splice(iterator position, this_type & x);
    void splice(iterator position, this_type & x, iterator i);
    void splice(
        iterator position, this_type & x, iterator first, iterator last);

    void remove(const value_type & value);

    template< class Predicate >
    void remove_if(Predicate pred);

    void unique();

    template< class BinaryPredicate >
    void unique(BinaryPredicate binary_pred);

    void merge(this_type & x);

    template< class Compare >
    void merge(this_type & x,Compare comp);

    void sort();

    template< class Compare >
    void sort(Compare comp);

    void reverse();

    // rearrange operations

    void relocate(iterator position, iterator i);
    void relocate(iterator position, iterator first, iterator last);

}

// view comparison

bool operator==(const this_type & v1, const this_type & v2 );
bool operator< (const this_type & v1, const this_type & v2 );
bool operator!=(const this_type & v1, const this_type & v2 );
bool operator> (const this_type & v1, const this_type & v2 );
bool operator>=(const this_type & v1, const this_type & v2 );
bool operator<=(const this_type & v1, const this_type & v2 );

} // namespace views
} // namespace bimap
} // namespace boost

          In the case of a bimap< list_of<Left>, ... >

          In the set view:

typedef signature-compatible with relation< Left, ... > key_type;
typedef signature-compatible with relation< Left, ... > value_type;

          In the left map view:

typedef  Left  key_type;
typedef  ...   mapped_type;

typedef signature-compatible with std::pair< Left, ... > value_type;

          In the right map view:

typedef  ...  key_type;
typedef  Left mapped_type;

typedef signature-compatible with std::pair< ... , Left > value_type;

Complexity
          signature

            Here and in the descriptions of operations of list_of
            views, we adopt the scheme outlined in the complexity
            signature section. The complexity signature of a list_of view is:

                copying: c(n) = n * log(n),

                insertion: i(n) = 1
                (constant),

                hinted insertion: h(n) = 1 (constant),

                deletion: d(n) = 1
                (constant),

                replacement: r(n) = 1
                (constant),

                modifying: m(n) = 1
                (constant).

Instantiation
          types

            list_of views are instantiated
            internally to bimap and
            specified by means of the collection type specifiers and the bimap itself.
            Instantiations are dependent on the following types:

                Value from list_of,

                Allocator from bimap,

Constructors,
          copy and assignment

            As explained in the view concepts section, views do not have public constructors
            or destructors. Assignment, on the other hand, is provided.

this_type & operator=(const this_type & x);

                Effects:  a
                = b; where a and b are the bimap objects to which *this
                and x belong, respectively.

                Returns:  *this.

template< class InputIterator >
void assign(InputIterator first, InputIterator last);

                Requires:  InputIterator
                is a model of Input
                Iterator over elements of type value_type
                or a type convertible to value_type.
                first and last are not iterators into any views of the bimap to which this view belongs.
                last is reachable
                from first.

                Effects:  clear(); insert(end(),first,last);

void assign(size_type n, const value_type & value);

                Effects:  clear(); for(size_type
                i =
                0;
                i <
                n ;
                ++n) push_back(v);

Capacity
          operations

void resize(size_type n,const value_type& x=value_type());

                Effects:  if( n > size() ) insert(end(),
                n -
                size(),
                x);
                else if( n < size() ) {  iterator
                it =
                begin();
                 std::advance(it, n);
                 erase(it, end());
                }

                Note: If an expansion is requested,
                the size of the view is not guaranteed to be n after this operation
                (other views may ban insertions.)

Modifiers

std::pair<iterator,bool> push_front(const value_type& x);

                Effects: Inserts x
                at the beginning of the sequence if no other views of the bimap bans the insertion.

                Returns: The return value is a pair
                p. p.second is true
                if and only if insertion took place. On successful insertion, p.first points to the element inserted;
                otherwise, p.first points to an element that
                caused the insertion to be banned. Note that more than one element
                can be causing insertion not to be allowed.

                Complexity:
                O(I(n)).

                Exception safety: Strong.

std::pair<iterator,bool> push_back(const value_type & x);

                Effects: Inserts x
                at the end of the sequence if no other views of the bimap bans the insertion.

                Returns: The return value is a pair
                p. p.second is true
                if and only if insertion took place. On successful insertion, p.first points to the element inserted;
                otherwise, p.first points to an element that
                caused the insertion to be banned. Note that more than one element
                can be causing insertion not to be allowed.

                Complexity:
                O(I(n)).

                Exception safety: Strong.

std::pair<iterator,bool> insert(iterator position, const value_type & x);

                Requires:  position
                is a valid iterator
                of the view.

                Effects: Inserts x
                before position if insertion is allowed by all other views of the
                bimap.

                Returns: The return value is a pair
                p. p.second is true
                if and only if insertion took place. On successful insertion, p.first points to the element inserted;
                otherwise, p.first points to an element that
                caused the insertion to be banned. Note that more than one element
                can be causing insertion not to be allowed.

                Complexity:
                O(I(n)).

                Exception safety: Strong.

void insert(iterator position, size_type n, const value_type & x);

                Requires:  position
                is a valid iterator
                of the view.

                Effects:  for(size_type
                i =
                0;
                i <
                n;
                ++i) insert(position, x);

template< class InputIterator>
void insert(iterator position,InputIterator first,InputIterator last);

                Requires:  position
                is a valid iterator
                of the view. InputIterator
                is a model of Input
                Iterator over elements of type value_type.
                first and last are not iterators into any
                view of the bimap
                to which this view belongs. last
                is reachable from first.

                Effects:  while(first
                != last) insert(position, *first++);

                Complexity:
                O(m*I(n+m)), where m is the number of elements in [first,last).

                Exception safety: Basic.

iterator erase(iterator position);

                Requires:  position
                is a valid dereferenceable iterator
                of the view.

                Effects: Deletes the element pointed
                to by position.

                Returns: An iterator pointing to
                the element immediately following the one that was deleted, or end()
                if no such element exists.

                Complexity:
                O(D(n)).

                Exception safety: nothrow.

iterator erase(iterator first, iterator last);

                Requires:  [first,last)
                is a valid range of the view.

                Effects: Deletes the elements in
                [first,last).

                Returns:  last.

                Complexity:
                O(m*D(n)), where m is the number of elements in [first,last).

                Exception safety: nothrow.

bool replace(iterator position,const value_type& x);

                Requires:  position
                is a valid dereferenceable iterator of the view.

                Effects: Assigns the value x to the element pointed to by
                position into the
                bimap to which the
                view belongs if replacing is allowed by all other views of the bimap.

                Postconditions: Validity of position is preserved in all cases.

                Returns:  true
                if the replacement took place, false
                otherwise.

                Complexity:
                O(R(n)).

                Exception safety: Strong. If an
                exception is thrown by some user-provided operation the bimap to which the view belongs
                remains in its original state.

template< class CompatibleKey >
bool replace_key(iterator position, const CompatibleKey & x);

                Requires:  position
                is a valid dereferenceable iterator of the set view. CompatibleKey can be assigned to
                key_type.

                Effects: Assigns the value x to e.first,
                where e is the element
                pointed to by position
                into the bimap to
                which the set view belongs if replacing is allowed by all other views
                of the bimap.

                Postconditions: Validity of position
                is preserved in all cases.

                Returns:  true
                if the replacement took place, false
                otherwise.

                Complexity:
                O(R(n)).

                Exception safety: Strong. If an
                exception is thrown by some user-provided operation, the bimap to which the set view belongs
                remains in its original state.

template< class CompatibleData >
bool replace_data(iterator position, const CompatibleData & x);

                Requires:  position
                is a valid dereferenceable iterator of the set view. CompatibleKey can be assigned to
                mapped_type.

                Effects: Assigns the value x to e.second,
                where e is the element
                pointed to by position
                into the bimap to
                which the set view belongs if replacing is allowed by all other views
                of the bimap.

                Postconditions: Validity of position
                is preserved in all cases.

                Returns:  true
                if the replacement took place, false
                otherwise.

                Complexity:
                O(R(n)).

                Exception safety: Strong. If an
                exception is thrown by some user-provided operation, the bimap to which the set view belongs
                remains in its original state.

template< class KeyModifier >
bool modify_key(iterator position, KeyModifier mod);

                Requires:  KeyModifier
                is a model of Unary
                Function accepting arguments of type: key_type&; position
                is a valid dereferenceable iterator of the view.

                Effects: Calls mod(e.first) where e is the element pointed to
                by position and rearranges *position into all the views of
                the bimap. If the
                rearrangement fails, the element is erased. It is successful if the
                rearrangement is allowed by all other views of the bimap.

                Postconditions: Validity of position is preserved if the operation
                succeeds.

                Returns:  true
                if the operation succeeded, false
                otherwise.

                Complexity:
                O(M(n)).

                Exception safety: Basic. If an exception
                is thrown by some user-provided operation (except possibly mod),
                then the element pointed to by position is erased.

                Note: Only provided for map views.

template< class DataModifier >
bool modify_data(iterator position, DataModifier mod);

                Requires:  DataModifier
                is a model of Unary
                Function accepting arguments of type: mapped_type&; position
                is a valid dereferenceable iterator of the view.

                Effects: Calls mod(e.second) where e is the element pointed to
                by position and rearranges *position into all the views of
                the bimap. If the
                rearrangement fails, the element is erased. It is successful if the
                rearrangement is allowed by all other views of the bimap.

                Postconditions: Validity of position is preserved if the operation
                succeeds.

                Returns:  true
                if the operation succeeded, false
                otherwise.

                Complexity:
                O(M(n)).

                Exception safety: Basic. If an exception
                is thrown by some user-provided operation (except possibly mod),
                then the element pointed to by position is erased.

                Note: Only provided for map views.

List
          operations

            list_of views provide
            the full set of list operations found in std::list;
            the semantics of these member functions, however, differ from that of
            std::list in some cases as insertions might
            not succeed due to banning by other views. Similarly, the complexity
            of the operations may depend on the other views belonging to the same
            bimap.

void splice(iterator position, this_type & x);

                Requires:  position
                is a valid iterator of the view. &x!=this.

                Effects: Inserts the contents of
                x before position,
                in the same order as they were in x.
                Those elements successfully inserted are erased from x.

                Complexity:
                O(x.size()*I(n+x.size())
                + x.size()*D(x.size())).

                Exception safety: Basic.

void splice(iterator position, this_type & x,iterator i);

                Requires:  position
                is a valid iterator of the view. i
                is a valid dereferenceable iterator x.

                Effects: Inserts the element pointed
                to by i before position:
                if insertion is successful, the element is erased from x. In the special case &x==this,
                no copy or deletion is performed, and the operation is always successful.
                If position==i, no operation is performed.

                Postconditions: If &x==this,
                no iterator or reference is invalidated.

                Complexity:
                If &x==this,
                constant; otherwise O(I(n) + D(n)).

                Exception safety: If &x==this,
                nothrow; otherwise, strong.

void splice(iterator position, this_type & x, iterator first, iterator last);

                Requires:  position
                is a valid iterator of the view. first
                and last are valid
                iterators of x. last
                is reachable from first.
                position is not in the range [first,last).

                Effects: For each element in the
                range [first,last), insertion is tried before position;
                if the operation is successful, the element is erased from x. In
                the special case &x==this, no copy or deletion is performed,
                and insertions are always successful.

                Postconditions: If &x==this,
                no iterator or reference is invalidated.

                Complexity:
                If &x==this,
                constant; otherwise O(m*I(n+m) + m*D(x.size())) where m is the number
                of elements in [first,last).

                Exception safety: If &x==this,
                nothrow; otherwise, basic.

void remove(const value_type & value);

                Effects: Erases all elements of
                the view which compare equal to value.

                Complexity:
                O(n + m*D(n)), where m is the number of elements erased.

                Exception safety: Basic.

template< class Predicate >
void remove_if(Predicate pred);

                Effects: Erases all elements x of the view for which pred(x)
                holds.

                Complexity:
                O(n + m*D(n)), where m is the number of elements erased.

                Exception safety: Basic.

void unique();

                Effects: Eliminates all but the
                first element from every consecutive group of equal elements referred
                to by the iterator i
                in the range [first+1,last) for which *i==*(i-1).

                Complexity:
                O(n + m*D(n)), where m is the number of elements erased.

                Exception safety: Basic.

template< class BinaryPredicate >
void unique(BinaryPredicate binary_pred);

                Effects: Eliminates all but the
                first element from every consecutive group of elements referred to
                by the iterator i in the range [first+1,last) for which binary_pred(*i,*(i-1))
                holds.

                Complexity:
                O(n + m*D(n)), where m is the number of elements erased.

                Exception safety: Basic.

void merge(this_type & x);

                Requires:  std::less<value_type> is a Strict
                Weak Ordering over value_type.
                Both the view and x
                are sorted according to std::less<value_type>.

                Effects: Attempts to insert every
                element of x into
                the corresponding position of the view (according to the order).
                Elements successfully inserted are erased from x.
                The resulting sequence is stable, i.e. equivalent elements of either
                container preserve their relative position. In the special case
                &x==this,
                no operation is performed.

                Postconditions: Elements in the
                view and remaining elements in x
                are sorted. Validity of iterators to the view and of non-erased elements
                of x references is
                preserved.

                Complexity:
                If &x==this,
                constant; otherwise O(n + x.size()*I(n+x.size()) + x.size()*D(x.size())).

                Exception safety: If &x==this,
                nothrow; otherwise, basic.

template< class Compare >
void merge(this_type & x, Compare comp);

                Requires: Compare is a Strict
                Weak Ordering over value_type.
                Both the view and x
                are sorted according to comp.

                Effects: Attempts to insert every
                element of x into
                the corresponding position of the view (according to comp). Elements successfully inserted
                are erased from x.
                The resulting sequence is stable, i.e. equivalent elements of either
                container preserve their relative position. In the special case
                &x==this,
                no operation is performed.

                Postconditions: Elements in the
                view and remaining elements in x
                are sorted according to comp.
                Validity of iterators to the view and of non-erased elements of
                x references is preserved.

                Complexity:
                If &x==this,
                constant; otherwise O(n + x.size()*I(n+x.size()) + x.size()*D(x.size())).

                Exception safety: If &x==this,
                nothrow; otherwise, basic.

void sort();

                Requires:  std::less<value_type> is a Strict
                Weak Ordering over value_type.

                Effects: Sorts the view according
                to std::less<value_type>.
                The sorting is stable, i.e. equivalent elements preserve their relative
                position.

                Postconditions: Validity of iterators
                and references is preserved.

                Complexity: O(n*log(n)).

                Exception safety: nothrow if std::less<value_type>
                does not throw; otherwise, basic.

template< typename Compare >
void sort(Compare comp);

                Requires: Compare is a Strict
                Weak Ordering over value_type.

                Effects: Sorts the view according
                to comp. The sorting is stable, i.e. equivalent elements preserve
                their relative position.

                Postconditions: Validity of iterators
                and references is preserved.

                Complexity: O(n*log(n)).

                Exception safety: nothrow if comp
                does not throw; otherwise, basic.

void reverse();

                Effects: Reverses the order of the
                elements in the view.

                Postconditions: Validity of iterators
                and references is preserved.

                Complexity: O(n).

                Exception safety: nothrow.

Rearrange
          operations

            These operations, without counterpart in std::list
            (although splice provides partially overlapping functionality), perform
            individual and global repositioning of elements inside the index.

void relocate(iterator position, iterator i);

                Requires:  position
                is a valid iterator of the view. i
                is a valid dereferenceable iterator of the view.

                Effects: Inserts the element pointed
                to by i before position. If position==i,
                no operation is performed.

                Postconditions: No iterator or reference
                is invalidated.

                Complexity: Constant.

                Exception safety: nothrow.

void relocate(iterator position, iterator first, iterator last);

                Requires:  position
                is a valid iterator of the view. first
                and last are valid
                iterators of the view. last
                is reachable from first.
                position is not in
                the range [first,last).

                Effects: The range of elements
                [first,last) is repositioned just before position.

                Postconditions: No iterator or reference
                is invalidated.

                Complexity: Constant.

                Exception safety: nothrow.

Serialization

            Views cannot be serialized on their own, but only as part of the bimap into which they are embedded.
            In describing the additional preconditions and guarantees associated
            to list_of views with
            respect to serialization of their embedding containers, we use the concepts
            defined in the bimap
            serialization section.

            Operation: saving of a bimap b to an output archive (XML archive)
            ar.

                Requires: No additional requirements
                to those imposed by the container.

            Operation: loading of a bimap b' from an input archive (XML
            archive) ar.

                Requires: No additional requirements
                to those imposed by the container. Postconditions:
                On successful loading, each of the elements of [begin(),
                end())
                is a restored copy of the corresponding element in [m.get<i>().begin(), m.get<i>().end()), where i
                is the position of the list_of
                view in the container.

            Operation: saving of an iterator or const_iterator
            it to an output archive (XML archive) ar.

                Requires:  it
                is a valid iterator of the view. The associated bimap
                has been previously saved.

            Operation: loading of an iterator or const_iterator
            it' from an input archive (XML
            archive) ar.

                Postconditions: On successful loading,
                if it was dereferenceable then *it' is the restored copy of *it,
                otherwise it'
                == end().

                Note: It is allowed that it be a const_iterator
                and the restored it'
                an iterator, or viceversa.

Copyright © 2006-2012 Matias Capeletto

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace Managed3D.Rendering.OpenGL
{
    /// <summary>
    /// Provides a managed wrapper around the native OpenGL Extension Wrangler library.
    /// </summary>
    public static class GLEW
    {

    }
}

redpajama_set_name: RedPajamaGithub


text:
import os
import sys
import commands
from optparse import OptionParser

def get_run_number(input_list):
    with open(input_list,'r') as f:
        for line in f:
            return line.split('/')[-2].split('.')[2][2:]

usage="usage: "+sys.argv[0]+" input.list outDir"
parser = OptionParser(usage, version="0.1")
parser.add_option("--filesPerJob", default=1, dest="files_per_job",
                  help="files per job")
options,args = parser.parse_args()

workdir=os.getcwd()
zz4lDir=os.getenv("MonoJetCodeDir")
outdir=workdir

#config the job
maxFile = options.files_per_job

if len(args) > 1:
    myFileList = args[0]
    outdirname = args[1]
else:
    print usage
    exit(1)

print "max file(s) per job: ",maxFile
print "file list: ",myFileList
print "out put directory: ",outdirname
#print "Number of events per thread: ",nevents

prefix_name = myFileList.split('.')[0]

outdir = workdir+"/"+outdirname
os.system('mkdir -vp ./Lists')
split_cmd = '/afs/cern.ch/user/x/xju/tool/splitFile.py\
        ./Lists --list='+ myFileList + ' --nFiles='+str(maxFile)+\
        " --prefix="+prefix_name

status,output=commands.getstatusoutput(split_cmd)
print output

totalJobs = int(output.split(':')[5])
goodjobs = []
badjobs = []
for job in  range(totalJobs):
    inputlist = workdir+"/Lists/"+prefix_name+"_n"+str(job)+'.list'
    #run_number = get_run_number(inputlist)
    outname = myFileList+"_"+str(job)+".root"
    run_cmd = zz4lDir+"/MonoJet/bsubs/run_smear.sh "+\
            outdirname+" "+inputlist+" "+outname
            #outdirname+" "+inputlist+" "+run_number+" "+outname+" "+str(nevents)
    #print run_cmd
    #-G u_zp -q 8nh for atlas sources
    #-G ATLASWISC_GEN -q wisc for wisconsin sources
    #continue
    bsubs_cmd = "bsub -G ATLASWISC_GEN -q wisc  -R 'pool>4000' -C 0 -o" + \
            workdir+ "/output "+ run_cmd

    status,output=commands.getstatusoutput(bsubs_cmd)
    if status != 0:
        badjobs.append(0)
    else:
        goodjobs.append(1)

print "Good jobs: "+ str(len(goodjobs))+", "+str(len(badjobs))+" failed!"


text:
exports.config = {
  // ----- How to setup Selenium
  // There are three ways to specify how to use Selenium. Specify one of the
  // following:
  // 1. seleniumServerJar - to start Selenium Standalone locally.
  // 2. seleniumAddress - to connect to a Selenium server which is already
  //     running.
  // 3. sauceUser/sauceKey - to use remote Selenium servers via SauceLabs.

  // The location of the selenium standalone server .jar file.
  seleniumServerJar: './selenium/selenium-server-standalone-2.33.0.jar',
  // The port to start the selenium server on, or null if the server should
  // find its own unused port.
  seleniumPort: null,
  // Chromedriver location is used to help the selenium standalone server
  // find chromedriver. This will be passed to the selenium jar as
  // the system property webdriver.chrome.driver. If null, selenium will
  // attempt to find chromedriver using PATH.
  chromeDriver: './selenium/chromedriver',
  // Additional command line options to pass to selenium. For example,
  // if  you need to change the browser timeout, use
  // seleniumArgs: [-browserTimeout=60],
  seleniumArgs: [],

  // If sauceUser and sauceKey are specified, seleniumServerJar will be ignored.
  sauceUser: null,
  sauceKey: null,

  // The address of a running selenium server.
  seleniumAddress: 'http://localhost:4444/wd/hub',

  // Spec patterns are relative to the current working directly when
  // protractor is called.
  specs: ['spec/testAppSpec.js'],

  // ----- Capabilities to be passed to the webdriver instance.
  // For a full list of available capabilities, see
  // https://code.google.com/p/selenium/wiki/DesiredCapabilities
  capabilities: {
    'browserName': 'chrome'
  },

  // A base URL for your application under test. Calls to protractor.get()
  // with relative paths will be prepended with this.
  baseUrl: 'http://localhost:8000',

  // ----- Options to be passed to minijasminenode.
  jasmineNodeOpts: {
    // onComplete will be called before the driver quits.
    onComplete: null,
    isVerbose: false,
    showColors: true,
    includeStackTrace: true
  }
};


text:
<?php
/**
 * This file is part of the vardius/user-bundle package.
 *
 * Created by Rafał Lorenz <vardius@gmail.com>.
 */

namespace Vardius\Bundle\UserBundle\Event;

/**
 * RegisterEvents
 *
 * @author Rafał Lorenz <vardius@gmail.com>
 */
final class RegisterEvents
{
    /**
     * The vardius_user.register.pre_persist event is thrown each time an user is registered
     *
     * The event listener receives an
     * Vardius\Bundle\UserBundle\Event\RegisterEvent instance.
     *
     * @var string
     */
    const REGISTER_PRE_PERSIST = 'vardius_user.register.pre_persist';

    /**
     * The vardius_user.register.post_persist event is thrown each time an user is registered
     *
     * The event listener receives an
     * Vardius\Bundle\UserBundle\Event\RegisterEvent instance.
     *
     * @var string
     */
    const REGISTER_POST_PERSIST = 'vardius_user.register.post_persist';
}


text:
title: Global Programme for Safer Schools
short_title: GPSS
summary: 'Mapping hazards to increase resilience'
description: 'A prototype visualisation of the resilience of schools to natural hazards, working with the World Bank'
fb_title: 'GPSS | Vizzuality'
fb_description: 'See where schools are most resilient to natural hazards'
link: http://gpss.vizzuality.com
link_short: gpss.vizzuality.com
client: World Bank
client_logo: worldbank.png
svg_logo:
image: GPSS_high1.png
cover: gpss_01.jpg
author: Jamie Gibson
date: 2015-06-03
release_date: October 2014
order:
highlighted: true
logoWidth: 180
grid:   1

modules:
    - text_above:
        title: "Dealing with heterogeneous data"
        description: "The datasets to be visualised are all very different, in terms of type and quality, and come from a number of different national and international sources. We built a flexible back end that was able to deal with this variety and serve accurate geospatial data to the front end. In the future we hope to add layers with other hazards at the global and local level and analysis capabilities; the flexibility built into the back end makes this task much easier."
        image: GPSS_high1.png

---

Natural hazards can cause serious damage to buildings and infrastructure. If a hazard hits a school there can be major implications for safety and educational opportunities, hampering long-term performance and achievement of affected children. The World Bank's Global Programme for Safer Schools asked us to develop a prototype open source mapping platform to monitor the resilience of all schools in the world to a variety of hazards. Using a beautiful, engaging design, users can navigate to look at data held related to schools in specific areas or aided by different project types.


text:
package equipe.projetoes.activities;

import android.graphics.PorterDuff;
import android.media.Image;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

import equipe.projetoes.R;
import equipe.projetoes.adapters.BibliotecaRecyclerAdapter;
import equipe.projetoes.models.Livro;
import equipe.projetoes.utilis.LivroDAO;

public class BibliotecaActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {

    private RecyclerView mRecyclerView;
    private BibliotecaRecyclerAdapter adapter;
    private RecyclerView mRecyclerView2;
    private BibliotecaRecyclerAdapter adapter2;
    private LivroDAO dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_biblioteca);
        this.init();

        dao = new LivroDAO(this);

        if (!this.hasNavBar(getResources()))
            findViewById(R.id.navspace).setVisibility(View.GONE);

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);

        // use a linear layout manager
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(mLayoutManager);

        ArrayList<Livro> livros = new ArrayList<Livro>();
        livros.add(new Livro(R.drawable.livro, "Game of Thrones", "George R.R", "Leya", 500, 200, true, true, "0"));
        livros.add(new Livro(R.drawable.livro1, "Harry Potter e a pedra filosofal", "J.K. Rowling", "Racco", 372, 200, true, true, "1"));
        livros.add(new Livro(R.drawable.livro2, "The Hunger Games", "Suzanne Collins", "Casa da Palavra",429, 200, true, true, "2"));
        livros.add(new Livro(R.drawable.livro3, "The Martian", "Matt Damon", "Escreva LTDA", 160, 200, true, true, "3"));

        if (dao.listaTodos().size() < 4) {
            for (Livro livro : livros
                    ) {
                dao.adiciona(livro);
            }
        }

        // specify an adapter (see also next example)
        adapter = new BibliotecaRecyclerAdapter(dao.listaTradables(), BibliotecaRecyclerAdapter.NOINFO, this);
        mRecyclerView.setAdapter(adapter);

        mRecyclerView2 = (RecyclerView) findViewById(R.id.recycler2);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView2.setHasFixedSize(true);
        mRecyclerView2.setNestedScrollingEnabled(false);

        // use a linear layout manager
        int rows = 1;
        switch (getResources().getDisplayMetrics().densityDpi) {
            case DisplayMetrics.DENSITY_LOW:
                rows = 1;
                break;
            case DisplayMetrics.DENSITY_MEDIUM:
                rows = 1;
                break;
            case DisplayMetrics.DENSITY_HIGH:
                rows = 2;
                break;
            case DisplayMetrics.DENSITY_XHIGH:
                rows = 2;
                break;
            case DisplayMetrics.DENSITY_XXHIGH:
                rows = 3;
                break;
            case DisplayMetrics.DENSITY_XXXHIGH:
                rows = 3;
                break;
        }
        GridLayoutManager mGridLayoutManager = new GridLayoutManager(this, rows);
        mGridLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
        mRecyclerView2.setLayoutManager(mGridLayoutManager);

//        ArrayList<Livro> livros2 = new ArrayList<Livro>();
//        livros2.add(new Livro(R.drawable.livro, "Game of Thrones", "George R.R", "Leya", 500));
//        livros2.add(new Livro(R.drawable.livro1, "Game of Thrones", "George R.R", "Leya", 500));
//        livros2.add(new Livro(R.drawable.livro2, "Game of Thrones", "George R.R", "Leya", 500));
//        livros2.add(new Livro(R.drawable.livro3, "Game of Thrones", "George R.R", "Leya", 500));
//        livros2.add(new Livro(R.drawable.livro, "Game of Thrones", "George R.R", "Leya", 500));
//        livros2.add(new Livro(R.drawable.livro1, "Game of Thrones", "George R.R", "Leya", 500));
//        livros2.add(new Livro(R.drawable.livro2, "Game of Thrones", "George R.R", "Leya", 500));
//        livros2.add(new Livro(R.drawable.livro3, "Game of Thrones", "George R.R", "Leya", 500));
//        livros2.add(new Livro(R.drawable.livro, "Game of Thrones", "George R.R", "Leya", 500));
//        livros2.add(new Livro(R.drawable.livro1, "Game of Thrones", "George R.R", "Leya", 500));
//        livros2.add(new Livro(R.drawable.livro2, "Game of Thrones", "George R.R", "Leya", 500));
//        livros2.add(new Livro(R.drawable.livro3, "Game of Thrones", "George R.R", "Leya", 500));

        // specify an adapter (see also next example)
        adapter2 = new BibliotecaRecyclerAdapter(dao.listaTodos(), BibliotecaRecyclerAdapter.FULL, this);
        mRecyclerView2.setAdapter(adapter2);

    }

    public void notifyRecyclers() {
        mRecyclerView.getAdapter().notifyDataSetChanged();
        mRecyclerView2.getAdapter().notifyDataSetChanged();
    }

    public void removeFromTrade(Livro livro) {
        mRecyclerView.setAdapter(new BibliotecaRecyclerAdapter(dao.listaTradables(), BibliotecaRecyclerAdapter.NOINFO, this));
    }

}


text:
DEBUG = True

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'UTC'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'moonbizgame.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'moonbizgame.wsgi.application'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'django.contrib.humanize',

    'south',
    'django_browserid',

    'enterprise',
    'launch',

)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.request',
    'django_browserid.context_processors.browserid',
)

AUTHENTICATION_BACKENDS = (
   'django.contrib.auth.backends.ModelBackend',
   'django_browserid.auth.BrowserIDBackend',
)

LOGIN_REDIRECT_URL = '/'
LOGIN_REDIRECT_URL_FAILURE = '/'
LOGOUT_REDIRECT_URL = '/'

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

try:
    from moonbizgame.localsettings import *
except ImportError:
    raise ValueError('localsettings.py not found, copy from the localsettings.py.in and edit as needed')

TEMPLATE_DEBUG = DEBUG
MANAGERS = ADMINS


text:
Invoking Pants Build
====================

This page discusses some advanced features of invoking the Pants build
tool on the command line. We assume you already know the
[[basic command-line structure|pants('src/docs:first_tutorial')]],
something like:

    :::bash
    $ ./pants goal test.junit --fail-fast bundle path/to/target path/to/another/target

For a full description of specifying target addresses, see
[[Target Addresses|pants('src/docs:target_addresses')]].
For a list of Pants' goals and their options, see the
Goals Reference.

Order of Arguments
------------------

A simple Pants command line looks like <tt>./pants goal <var>goal</var> <var>target</var></tt>.
A less-simple Pants command looks like:

    :::bash
    ./pants goal <global options> <goal1> <options for goal1> <goal2> <options for goal2> \
            <target1> <target2> [-- pass-through options for last goal]

You can specify one or more goals. You can specify options for any goal right after that goal's
name:

    :::bash
    $ ./pants goal list --sep='|' examples/src/python/example:
    examples/src/python/example:readme|examples/src/python/example:pex_design|examples/sr...

Some goals are made up of tasks; to specify an option for that task, use the dotted
_goal.task_ notation:

    :::bash
    ./pants goal compile.java --no-delete-scratch src:: # compile src, keeping Java compile's "scratch files"

You can specify one or more targets to operate upon. Target specifications come after goals
and goal options on the command line.

Global options are the options that `./pants -h` lists, options that affect the whole
Pants run, e.g., `-ldebug`. Specify global options after "goal".

Some goals and tasks take "passthrough" args. That is, you can specify command-line args that are
passed through to some tool that Pants invoke in turn. These are specified last on the command
line after a double-hyphen like `-- foo bar` and are passed to the last goal specified. E.g., to
pass `-k list` to `pytest` (to say "only run tests whose names contain `list`") you could invoke:

    ./pants goal test.pytest tests/python/pants_test/tasks -- -k list

You could use `goal test` instead of `goal test.pytest` above; Pants then applies the
passthrough args to tools called by all of `test`, not just `test.pytest`.
This gets tricky. We happen to know we can pass `-k list` here, that `pytest` accepts passthrough
args, and that this `test` invocation upon `tests/python/...` won't invoke any other tools
(assuming nobody hid a `junit` test in the `python` directory).

rc files
--------

(As of November 2014, rc file support was changing. Expect this
info to be obsolete soon:)

If there's a command line flag that you always (or nearly always) use,
you might set up a configuration file to ease this. A typical Pants
installation looks for machine-specific settings in `/etc/pantsrc` and
personal settings in `~/.pants.rc`, with personal settings overriding
machine-specific settings.

For example, suppose that every time you invoke Pants to compile Java
code, you pass flags
`--compile-javac-args=-source --compile-javac-args=7 --compile-javac-args=-target --compile-javac-args=7`.
Instead of passing them on the command line each time, you could set up
a `~/.pants.rc` file:

    :::ini
    [javac]
    options:
      --compile-javac-args=-source --compile-javac-args=7
      --compile-javac-args=-target --compile-javac-args=7

With this configuration, Pants will have these flags on by default.

`--compile-javac-*` flags go in the `[javac]` section; generally,
`--compile`-*foo*-\* flags go in the `[foo]` section. `--test-junit-*`
flags go in the `[junit]` section; generally, `--test`-*bar*-\* flags go
in the `[bar]` section. `--idea-*` flags go in the `[idea]` section.

If you know the Pants internals well enough to know the name of a `Task`
class, you can use that class' name as a category to set command-line
options affecting it:

    :::ini
    [pants.tasks.nailgun_task.NailgunTask]
    # Don't spawn compilation daemons on this shared build server
    options: --no-ng-daemons

Although `/etc/pantsrc` and `~/.pants.rc` are the typical places for
this configuration, you can check pants.ini \<setup-pants-ini\> to find
out what your source tree uses.

    :::ini
    # excerpt from pants.ini
    [DEFAULT]
    # Look for these rcfiles - they need not exist on the system
    rcfiles: ['/etc/pantsrc', '~/.pants.CUSTOM.rc'] # different .rc name!

In this list, later files override earlier ones.

These files are formatted as [Python config
files](http://docs.python.org/install/index.html#inst-config-syntax),
parsed by
[ConfigParser](http://docs.python.org/library/configparser.html).


text:
require 'bootstrap_form/form_builder'
require 'bootstrap_form/helper'
require 'bootstrap_form/engine'

module BootstrapForm

end

ActionView::Base.send :include, BootstrapForm::Helper


text:
// Copyright(c) 2015, Rodolfo Lam
// All rights reserved.

#include "stdafx.h"
#include "Sprite.h"

#include <array>

std::array<std::string, 8> sections = { "", "IDLE", "MOVE", "ATTACK0", "ATTACK1", "HARMED", "SPECIAL0", "SPECIAL1" };
std::array<std::string, 6> entries = { "resPath", "frameWidth", "frameHeight", "frameDelay", "startRow", "sides" };

std::ostream& operator << (std::ostream& os, const AnimState& obj)
{
    int type = static_cast<std::underlying_type<AnimState>::type>(obj);
    if (type >= 1 && type < 8)
    {
        os << sections[type];
        return os;
    } else
    {
        os << "Corrupt";
        return os;
    }
}

Sprite::Sprite(std::string resLocation)
{
    if (parseADF(resLocation) == false)
    {
        std::cerr << "Warning: Loading of " << resLocation << " failed. Error Image generated." << std::endl;
        return;
    }
    sourceImage = al_load_bitmap(sourceImgPath.c_str());
    if (sourceImage == nullptr)
    {
        animList.clear();
        fallbackToDefaultADF(sourceImgPath);
    }
    rows = al_get_bitmap_height(sourceImage) / frameHeight;
    columns = al_get_bitmap_width(sourceImage) / frameWidth;
    frames = rows * columns;
    frameCount = 0;
    SendNewState(AnimState::IDLE, AnimDir::DOWN);

    // Quick additional sanity check
    for (auto &anim : animList)
    {
        if (anim.second.startRow < 0 || anim.second.startRow > rows - 1)
        {
            std::cerr << "Warning: Animation out of bounds, will default to start at origin. " << resLocation << std::endl
                << "         rows = " << rows << ", and animation wants to start at " << anim.second.startRow << std::endl;
            anim.second.startRow = 0;
        }
    }

    printData();
}

Sprite::Sprite()
{
	sourceImage = nullptr;
    frameCount = 0;
    SendNewState(AnimState::IDLE, AnimDir::DOWN);
    fallbackToDefaultADF("INTENTIONAL ERROR TRIGGER, DISREGARD THIS ERROR");
}

Sprite::~Sprite()
{
	al_destroy_bitmap(sourceImage);
    animList.clear();
}

void Sprite::Update()
{
    frameCount++;
    if (frameCount >= frameDelay)
    {
        curFrame++;
        if (curFrame >= columns)
        {
            curFrame = 0;
        }

        frameCount = 0;
    }
}

void Sprite::Render(float scX, float scY)
{
    // , imagePtr, sourceX, sourceY, SourceW, sourceH, destX, destY

    int drawRow = animList[curState].startRow;
    if (Bitfield::test(animList[curState].sides, animDirToBits(curDir)) == true)
    {
        drawRow += curDir;
    }

    al_draw_bitmap_region(sourceImage, curFrame * frameWidth, drawRow * frameHeight, frameWidth, frameHeight, scX, scY, 0);
}

void Sprite::SendNewState(AnimState state, AnimDir direction)
{
    curDir = direction;

    try
    {
        animList.at(state); //if this fails an exception is thrown, catched below
        curState = state;
    }

    catch (std::out_of_range& e)
    {
        curState = AnimState::IDLE;
        std::cerr << "Warning: Spritesheet at " << sourceImgPath << " has no " << state << " animation defined!" << std::endl
            << "         Defaulting to IDLE animation." << std::endl
            << "         Details: " << e.what() << std::endl;
    }

    curFrame = 0;
    frameCount = 0;
}

const Vec2D Sprite::GetSize(){
	return Vec2D(frameWidth, frameHeight);
}

void Sprite::printData()
{
    std::cout << "****************SPRITE DATA DUMP****************" << std::endl
        << "resPath=" << sourceImgPath << ", loaded at 0x" << sourceImage << std::endl
        << "frames: Width=" << frameWidth << " | Height=" << frameHeight << " | Delay=" << frameDelay << std::endl
        << "total frames=" << frames << " rows=" << rows << " columns=" << columns << std::endl
        << "Animations: " << std::endl;

    for (const auto &anim : animList)
    {
        std::cout << std::endl << " Type=" << anim.first << std::endl
            << "  Starting Row=" << anim.second.startRow << std::endl
            << "  Active sides(BITFIELD)=" << (int)anim.second.sides << std::endl;
    }
}

int Sprite::animDirToBits(int animDir)
{
    int val;
    switch (animDir)
    {
        case DOWN:
            val = bDOWN;
            break;
        case UP:
            val = bUP;
            break;
        case LEFT:
            val = bLEFT;
            break;
        case RIGHT:
            val = bRIGHT;
            break;
        default:
            val = 0;
            break;
    }

    return val;
}

/*
    This makes a blue square with a yellow triangle inside that
    has an exclamation mark. This image is used anytime an image
    file on disk fails to load.

    ---------------
    |      ^      |
    |     / \     |
    |    / ! \    |  <- Kinda like this...
    |   /     \   |
    |   -------   |
    ---------------
*/
bool Sprite::GenErrorImage()
{
	sourceImage = al_create_bitmap(frameWidth, frameHeight);

	if (sourceImage == nullptr)
		return false;

	ALLEGRO_COLOR background = al_color_html("#3f51b5");
	ALLEGRO_COLOR shadow = al_color_html("#1a237e");
	ALLEGRO_COLOR sign = al_color_html("#ffeb3b");

	float w = frameWidth;
	float h = frameHeight;

	al_set_target_bitmap(sourceImage);
	al_clear_to_color(background);

	// Shadow (3 triangles)
	al_draw_filled_triangle(w / 2.0, h / 4.0, w, (h * 3.0) / 4.0, w / 2.0, h, shadow);
	al_draw_filled_triangle(w, (h * 3.0) / 4.0, w, h, w / 2.0, h, shadow);
	al_draw_filled_triangle(w / 2.0, h / 4.0, w / 2.0, h, w / 4.0, (h * 3.0) / 4.0, shadow);

	// Alert sign triangle
	al_draw_filled_triangle(w / 2.0, h / 4.0, ((w * 3.0) / 4), ((h * 3.0) / 4.0), w / 4.0, ((h * 3.0) / 4.0), sign);

	// Exclamation point
	al_draw_filled_rectangle((w * 15.0) / 32.0, ((h * 14.0) / 32.0), ((w * 17.0) / 32.0), ((h * 19.0) / 32.0), background);
	al_draw_filled_rectangle((w * 15.0) / 32.0, (h * 5.0) / 8, (w * 17.0) / 32.0, (h * 11.0) / 16.0, background);

	al_set_target_backbuffer(al_get_current_display());

	return true;
}

void Sprite::fallbackToDefaultADF(std::string resLoc)
{
    std::cerr << "Error: Resource " << resLoc << " not found!, fallback to errorImage" << std::endl;
    frameWidth = 30; frameHeight = 30;
    frameDelay = 1;
    sourceImgPath = "";
    GenErrorImage();

    rows = 30 / frameHeight;
    columns = 30 / frameWidth;
    frames = rows * columns;

    /*animList.emplace_front(AnimState::IDLE, 0, 1);*/
    animList.emplace(AnimState::IDLE, _animations{ 0, 1 });
    return;
}

/*
Load the file
Read first section
while we have a valid section:
    If the first section is the blank section ("") then enter the section
        read the first entry
        while we have a valid entry
            map the entry to its internal container value
            read next entry
    If the section is any other section, map the name to its animation state.
        read the first entry
        while we have a valid entry
            map the entry to its internal container value
            read next entry
    read next section
*/
bool Sprite::parseADF(std::string resLoc)
{
    ALLEGRO_CONFIG *file = al_load_config_file(resLoc.c_str());
    if (file == nullptr)
    {
        fallbackToDefaultADF(resLoc);
        return false;
    }

    ALLEGRO_CONFIG_SECTION *section = nullptr;
    ALLEGRO_CONFIG_ENTRY   *entry   = nullptr;
    const char *sectionName = nullptr;
    const char *entryName   = nullptr;

    sectionName = al_get_first_config_section(file, &section);

    while (section != nullptr)
    {
        if (sectionName == sections[0]) // Global section
        {
            entryName = al_get_first_config_entry(file, sectionName, &entry);
            while (entry != nullptr)
            {
                if (entryName == entries[0])
                {
                    sourceImgPath = al_get_config_value(file, sectionName, entryName);
                } else if (entryName == entries[1])
                {
                    frameWidth = std::atoi(al_get_config_value(file, sectionName, entryName));
                } else if (entryName == entries[2])
                {
                    frameHeight = std::atoi(al_get_config_value(file, sectionName, entryName));
                } else if (entryName == entries[3])
                {
                    frameDelay = std::atoi(al_get_config_value(file, sectionName, entryName));
                } else
                {
                    std::cerr << "Warning: Unknown key-pair for value at " << sectionName << "." << entryName << std::endl;
                }

                entryName = al_get_next_config_entry(&entry);
            }
        } else // All other sections
        {
            AnimState state;
            int start = 0;
            unsigned char sides = 0;

            if (sectionName == sections[1])
            {
                state = AnimState::IDLE;
            } else if (sectionName == sections[2])
            {
                state = AnimState::MOVE;
            } else if (sectionName == sections[3])
            {
                state = AnimState::ATTACK0;
            } else if (sectionName == sections[4])
            {
                state = AnimState::ATTACK1;
            } else if (sectionName == sections[5])
            {
                state = AnimState::HARMED;
            } else if (sectionName == sections[6])
            {
                state = AnimState::SPECIAL0;
            } else if (sectionName == sections[7])
            {
                state = AnimState::SPECIAL1;
            } else
            {
                std::cerr << "Warning: Unknown section name: " << sectionName << " default to IDLE" << std::endl;
                state = AnimState::IDLE;
            }

            entryName = al_get_first_config_entry(file, sectionName, &entry);
            while (entry != nullptr)
            {
                if (entryName == entries[4]) // Start Row
                {
                    start = std::atoi(al_get_config_value(file, sectionName, entryName));
                } else if (entryName == entries[5]) // Sides bitfield
                {
                    sides = std::atoi(al_get_config_value(file, sectionName, entryName));
                } else
                {
                    std::cerr << "Warning: Unknown key-pair for value at " << sectionName << "." << entryName << std::endl;
                }

                entryName = al_get_next_config_entry(&entry);
            }

            /*animList.emplace_front(state, start, sides);*/
            animList.emplace(state, _animations{ start, sides });
        }

        sectionName = al_get_next_config_section(&section);
    }

    al_destroy_config(file);
    return true;
}


text:
@function can-stache.helpers.with {{#with(expression)}}
@parent can-stache/deprecated

@deprecated {4.15.0} Use [can-stache.helpers.let] instead.

Changes the context within a block.

@signature `{{#with(EXPRESSION)}}BLOCK{{/with}}`

Renders `BLOCK` with the result of `EXPRESSION` added to the top of the [can-view-scope].

```html
{{#with(person.address)}}
	Street: {{street}}
	City: {{city}}
{{/with}}
```

@param {can-stache/expressions/key-lookup|can-stache/expressions/call} EXPRESSION A lookup expression that will provide a value.

@param {can-stache.sectionRenderer} BLOCK A template that is rendered
with the context of the `EXPRESSION`'s value.

@signature `{{#with(HASHES)}}BLOCK{{/with}}`

Renders `BLOCK` with the key-value pairs from a [can-stache/expressions/hash] added to the top of the [can-view-scope].

```html
{{#with(innerStreet=person.address.street innerCity=person.address.city)}}
    Street: {{innerStreet}}
    City: {{innerCity}}
{{/with}}
```

@param {can-stache/expressions/hash} HASHES Any number of hash keys and values

@param {can-stache.sectionRenderer} BLOCK A template that is rendered
with the hashes added to the context.

@body

## Use

`{{#with()}}` renders a subsection with a new context added to the [can-view-scope].
For example:

```html
<!-- Template -->
{{#with(person.address)}}
	Street: {{street}}
	City: {{city}}
{{/with}}
```

```js
{ person: { address: { street: "123 Evergreen", city: "Springfield" } } }
```

```html
<!-- Result -->
Street: 123 Evergreen
City: Springfield
```

The new context can be a lookup expression, or a set of hashes which are taken together to be a new context.

```html
<!-- Template -->
{{#with(innerStreet=person.address.street innerCity=person.address.city)}}
	Street: {{innerStreet}}
	City: {{innerCity}}
{{/with}}
```

```js
{ person: { address: { street: "123 Evergreen", city: "Springfield" } } }
```

```html
<!-- Result -->
Street: 123 Evergreen
City: Springfield
```

The difference between `{{#with()}}` and the default [can-stache.tags.section]
is that the subsection `BLOCK` is rendered no matter what:

```html
<!-- Template -->
{{#with(person.address)}}
	Street: {{street}}
	City: {{city}}
{{/with}}
```

```js
{ person: {} }
```

```html
<!-- Result -->
Street:
City:
```


text:
frappe.ui.form.States = Class.extend({
	init: function(opts) {
		$.extend(this, opts);
		this.state_fieldname = frappe.workflow.get_state_fieldname(this.frm.doctype);

		// no workflow?
		if(!this.state_fieldname)
			return;

		this.update_fields = frappe.workflow.get_update_fields(this.frm.doctype);

		var me = this;
		$(this.frm.wrapper).bind("render_complete", function() {
			me.refresh();
		});
	},

	setup_help: function() {
		var me = this;
		this.frm.page.add_action_item(__("Help"), function() {
			frappe.workflow.setup(me.frm.doctype);
			var state = me.get_state();
			var d = new frappe.ui.Dialog({
				title: "Workflow: "
					+ frappe.workflow.workflows[me.frm.doctype].name
			})
			var next_html = $.map(frappe.workflow.get_transitions(me.frm.doctype, state),
				function(d) {
					return d.action.bold() + __(" by Role ") + d.allowed;
				}).join(", ") || __("None: End of Workflow").bold();

			$(d.body).html("
"+__("Current status")+": " + state.bold() + "
"
				+ "
"+__("Document is only editable by users of role")+": "
					+ frappe.workflow.get_document_state(me.frm.doctype,
						state).allow_edit.bold() + "
"
				+ "
"+__("Next actions")+": "+ next_html +"
"
				+ (me.frm.doc.__islocal ? ("
"
					+__("Workflow will start after saving.")+"
") : "")
				+ "
"+__("Note: Other permission rules may also apply")+"
"
				).css({padding: '15px'});
			d.show();
		}, true);
	},

	refresh: function() {
		// hide if its not yet saved
		if(this.frm.doc.__islocal) {
			this.set_default_state();
			return;
		}

		// state text
		var state = this.get_state();

		if(state) {
			// show actions from that state
			this.show_actions(state);
		}
	},

	show_actions: function(state) {
		var added = false,
			me = this;

		this.frm.page.clear_actions_menu();

		// if the loaded doc is dirty, don't show workflow buttons
		if (this.frm.doc.__unsaved===1) {
			return;
		}

		$.each(frappe.workflow.get_transitions(this.frm.doctype, state), function(i, d) {
			if(in_list(roles, d.allowed)) {
				added = true;
				me.frm.page.add_action_item(__(d.action), function() {
					var action = d.action;
					// capture current state
					var doc_before_action = copy_dict(me.frm.doc);

					// set new state
					var next_state = frappe.workflow.get_next_state(me.frm.doctype,
							me.frm.doc[me.state_fieldname], action);
					me.frm.doc[me.state_fieldname] = next_state;
					var new_state = frappe.workflow.get_document_state(me.frm.doctype, next_state);
					var new_docstatus = cint(new_state.doc_status);

					if(new_state.update_field) {
						me.frm.set_value(new_state.update_field, new_state.update_value);
					}

					// revert state on error
					var on_error = function() {
						// reset in locals
						frappe.model.add_to_locals(doc_before_action);
						me.frm.refresh();
					}

					// success - add a comment
					var success = function() {
						me.frm.timeline.insert_comment("Workflow", next_state);
					}
					if(new_docstatus==1 && me.frm.doc.docstatus==0) {
						me.frm.savesubmit(null, success, on_error);
					} else if(new_docstatus==0 && me.frm.doc.docstatus==0) {
						me.frm.save("Save", success, null, on_error);
					} else if(new_docstatus==1 && me.frm.doc.docstatus==1) {
						me.frm.save("Update", success, null, on_error);
					} else if(new_docstatus==2 && me.frm.doc.docstatus==1) {
						me.frm.savecancel(null, success, on_error);
					} else {
						msgprint(__("Document Status transition from ") + me.frm.doc.docstatus + " "
							+ __("to") +
							new_docstatus + " " + __("is not allowed."));
						msgprint(__("Document Status transition from {0} to {1} is not allowed", [me.frm.doc.docstatus, new_docstatus]));
						return false;
					}

					return false;

				});
			}
		});

		if(added) {
			this.frm.page.btn_primary.addClass("hide");
			this.frm.toolbar.current_status = "";
			this.setup_help();
		}
	},

	set_default_state: function() {
		var default_state = frappe.workflow.get_default_state(this.frm.doctype, this.frm.doc.docstatus);
		if(default_state) {
			this.frm.set_value(this.state_fieldname, default_state);
		}
	},

	get_state: function() {
		if(!this.frm.doc[this.state_fieldname]) {
			this.set_default_state();
		}
		return this.frm.doc[this.state_fieldname];
	},

	bind_action: function() {
		var me = this;
		this.dropdown.on("click", "[data-action]", function() {
		})
	}
});


text:
using System;
using System.Threading.Tasks;
using Elasticsearch.Net;

namespace Nest
{
	public partial interface IElasticClient
	{
		///
		/// The count API allows to easily execute a query and get the number of matches for that query.
		/// It can be executed across one or more indices and across one or more types.
		/// <para> </para>http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-count.html
		///
		/// <typeparam name="T">The type used to infer the default index and typename as well as describe the strongly
		///  typed parts of the query</typeparam>
		/// <param name="selector">An optional descriptor to further describe the count operation</param>
		ICountResponse Count<T>(Func<CountDescriptor<T>, ICountRequest> selector = null)
			where T : class;

		/// <inheritdoc/>
		ICountResponse Count<T>(ICountRequest request)
			where T : class;

		/// <inheritdoc/>
		Task<ICountResponse> CountAsync<T>(Func<CountDescriptor<T>, ICountRequest> selector = null)
			where T : class;

		/// <inheritdoc/>
		Task<ICountResponse> CountAsync<T>(ICountRequest request)
			where T : class;
	}

	public partial class ElasticClient
	{
		/// <inheritdoc/>
		public ICountResponse Count<T>(Func<CountDescriptor<T>, ICountRequest> selector = null)
			where T : class =>
			this.Count<T>(selector.InvokeOrDefault(new CountDescriptor<T>()));

		/// <inheritdoc/>
		public ICountResponse Count<T>(ICountRequest request)
			where T : class =>
			this.Dispatcher.Dispatch<ICountRequest, CountRequestParameters, CountResponse>(
				request,
				this.LowLevelDispatch.CountDispatch<CountResponse>
			);

		/// <inheritdoc/>
		public Task<ICountResponse> CountAsync<T>(Func<CountDescriptor<T>, ICountRequest> selector = null)
			where T : class =>
			this.CountAsync<T>(selector.InvokeOrDefault(new CountDescriptor<T>()));

		/// <inheritdoc/>
		public Task<ICountResponse> CountAsync<T>(ICountRequest request)
			where T : class =>
			this.Dispatcher.DispatchAsync<ICountRequest, CountRequestParameters, CountResponse, ICountResponse>(
				request,
				this.LowLevelDispatch.CountDispatchAsync<CountResponse>
			);
	}
}


text:
package com.oculusinfo.binning.properties;

import com.oculusinfo.binning.TileIndex;
import com.oculusinfo.factory.ConfigurationException;
import com.oculusinfo.factory.ConfigurationProperty;
import com.oculusinfo.factory.JSONNode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.UUID;

public class TileIndexProperty implements ConfigurationProperty<TileIndex> {

    private String _name;
	private String _description;
	private TileIndex _defaultValue;
	private String _uuid;

	public TileIndexProperty (String name, String description, TileIndex defaultValue) {
		_name = name;
		_description = description;
		_defaultValue = defaultValue;
		_uuid = UUID.randomUUID().toString();
	}

	@Override
	public String getName () {
		return _name;
	}

	@Override
	public String getDescription () {
		return _description;
	}

	@Override
	public Class<TileIndex> getType () {
		return TileIndex.class;
	}

	@Override
	public TileIndex[] getPossibleValues () {
		return null;
	}

	@Override
	public TileIndex getDefaultValue () {
		return _defaultValue;
	}

	@Override
	public String encode (TileIndex value) {
		if (null == value) return "null";
		return value.toString();
	}

	@Override
	public TileIndex unencode (String value) throws ConfigurationException {
		return TileIndex.fromString(value);
	}

	@Override
	public void encodeJSON (JSONNode propertyNode, TileIndex value) throws JSONException {
		JSONObject result = new JSONObject();
		result.put("level", value.getLevel());
		result.put("xIndex", value.getX());
		result.put("yIndex", value.getY());
		result.put("xBinCount", value.getXBins());
		result.put("yBinCount", value.getYBins());
		propertyNode.setAsJSONObject(result);
	}

	@Override
	public TileIndex unencodeJSON (JSONNode propertyNode) throws JSONException, ConfigurationException {
		JSONObject propertyObj = propertyNode.getAsJSONObject();
		int level = propertyObj.getInt("level");
		int xIndex = propertyObj.getInt("xIndex");
		int yIndex = propertyObj.getInt("yIndex");
		int numXBins = propertyObj.getInt("xBinCount");
		int numYBins= propertyObj.getInt("yBinCount");

		return new TileIndex(level, xIndex, yIndex, numXBins, numYBins);
	}

	@Override
	public int hashCode () {
		return _uuid.hashCode();
	}

	@Override
	public boolean equals (Object that) {
		if (this == that) return true;
		if (null == that) return false;
		if (!(that instanceof TileIndexProperty)) return false;

		TileIndexProperty thatP = (TileIndexProperty) that;
		return thatP._uuid.toLowerCase().equals(this._uuid.toLowerCase());
	}

	@Override
	public String toString () {
		return String.format("<property name=\"%s\" type=\"tile index\"/>");
	}
}


text:
# Policies

## What is a Policy

### Introduction
A Policy is function, that executed before accessing Controllers.
With Policies you can setup access controll, autorization or any processing that can be done before accessing controller function.

You can use Policies for whatever you want, there is no convention.

### Examples

#### Authorization Example

For a policy that named isAdmin, we could write a function that allow access if user is admin and return a 403 if user is not an admin.

#### Auth & Processing Example

An other example can be a processing before access the controller, like refreshTokens, that automaticaly refresh authentication tokens for a user, if the user has not disconect from app, have same ip and has an outdated token that is valid, the result can be let accessing controllers or return a 403 if the user has disconected.

## How to use it in Trails

### Fastest Way : Use Yeoman

```Bash
  yo trails:policy ExamplePolicy
```

With Yeoman you don't need to create the file and include it in index.js

### First Step : Write your policy

The convention is that policies has to be written in api/policies.

#### 1 - Using Hapi

```JavaScript
  'use strict'
  const Policy = require('trails-policy')

  /**
   * @module ExamplePolicy
   * @description This is the example policy
   */
  module.exports = class ExamplePolicy extends Policy {
    test(request, reply) {
      const secret = request.params.secret
      // Your own logic
      /**
      * The following code is an example:
      * It stop when the secret parametter is passed and continue to the Controller when there is no secret parametter.
      */
      if (secret != '') {
        // Stop and return with a custom message
        return reply('Your secret is' + secret)
      }
      // Continue to Example Controller
      reply()
    }
  }
```

#### 2 - Using Express

```JavaScript
'use strict'
 const Policy = require('trails-policy')

 /**
  * @module ExamplePolicy
  * @description This is the example policy
  */
 module.exports = class ExamplePolicy extends Policy {
   test(req, res, next) {
     const secret = req.body.secret
     // Your own logic
     /**
     * The following code is an example:
     * It stop when the secret parametter is passed and continue to the Controller when there is no secret parametter.
     */
     if (secret != '') {
       // Stop and return with a custom message
       return res.send('Your secret is' + secret)
     }
     // Continue to Example Controller
     next()
   }
 }
```
### Second Step : Load your policy

```JavaScript
/**
 * FILE: api/policies/index.js
 */

 'use strict'

 module.exports = {}
 exports.Example = require('./Example')

```

### Third Step : Declare your policy in config the file

```JavaScript
/**
 * FILE: config/policies.js
 * The following Policies are example of what you can do with Trails Policies
 */

 module.exports = {

   // Apply on every controllers
   '*': ['ExamplePolicy.test'],

   ExampleController: {
     // Unique policy for one controller function
     test: [ 'ExamplePolicy.test' ],
     // Before accessing multiple function in ExampleController, processing multiple policies example:
     multiple: ['ExamplePolicy.test', 'ExamplePolicy.testfoo', 'ExamplePolicy.testbar'],
   },
   /**
    * Controller Policies that applies on each function under a specific controller
    */

   DefaultController: ['AccessPolicy.logger'],
   /**
    * Boolean & wilcard policies
    * true -> Unrestricted access
    * False -> Restrict Every Time
    */

    CatsController: {
      // Always access to controller function
      miaou: true,
      // Restrict access to controller function
      purr: false,
      // Apply every policies processing before accessing function
      test: '*'
    }
 }
```


text:
from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, EqualTo, Length

class RegisterForm(Form):
    username = TextField('Username', validators=[DataRequired(), Length(min=3, max=25)])
    email = TextField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)])
    password = PasswordField('Password',
                                validators=[DataRequired(), Length(min=6, max=40)])
    confirm = PasswordField(
                'Verify password',
                [DataRequired(), EqualTo('password', message='Passwords must match')])

class LoginForm(Form):
    username = TextField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])


text:
pyboleto Package
================

:mod:`pyboleto` Package
-----------------------

.. automodule:: pyboleto.__init__
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`data` Module
------------------

.. automodule:: pyboleto.data
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`pdf` Module
-----------------

.. automodule:: pyboleto.pdf
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`html` Module
------------------

.. automodule:: pyboleto.html
    :members:
    :undoc-members:
    :show-inheritance:

Subpackages
-----------

.. toctree::

    pyboleto.bank
    pyboleto.django


text:
package colang.ast.raw

import colang.Strategy.Result
import colang.Strategy.Result.Success
import colang.ast.raw.ParserImpl.SingleTokenStrategy
import colang.issues.{Issues, Term, Terms}
import colang.tokens.{Keyword, NativeKeyword}
import colang.{SourceCode, StrategyUnion, TokenStream}

/**
  * Represents a list of specifiers that may preceed certain symbol definitions (like 'native', etc.)
  * @param specifiers specifiers list
  */
case class SpecifiersList(specifiers: Seq[Keyword], source: SourceCode) extends Node {

  def has[K <: Keyword](keyword: Class[K]) = specifiers exists { _.getClass == keyword }
  def get[K <: Keyword](keyword: Class[K]) = getOption(keyword).get
  def getOption[K <: Keyword](keyword: Class[K]) = specifiers find { _.getClass == keyword }
}

object SpecifiersList {

  /**
    * A strategy template for parsing specifier lists.
    * @param contextDescription a term that describes the node containing this specifier list.
    * @param allowedSpecifiers specifier types that are allowed in this context
    */
  class Strategy(contextDescription: Term,
                 allowedSpecifiers: Class[_ <: Keyword]*) extends ParserImpl.Strategy[SpecifiersList] {

    private val allSpecifiers = Seq(
      classOf[NativeKeyword])

    private val anySpecifierStrategy = StrategyUnion(allSpecifiers map { SingleTokenStrategy(_) } :_*)

    def apply(stream: TokenStream): Result[TokenStream, SpecifiersList] = {
      ParserImpl.parseSequence(
        stream = stream,
        elementStrategy = anySpecifierStrategy,
        elementDescription = Terms.Specifier
      ) match {
        case (specifiers, parseIssues, streamAfterSpecifiers) =>
          val specifiersByType = specifiers groupBy { _.getClass }

          val issues = specifiersByType flatMap { case (specifierType, specs) =>
            if (!(allowedSpecifiers contains specifierType)) {
              specs map { spec => Issues.MisplacedSpecifier(spec.source, (spec.text, contextDescription)) }
            } else {
              specs.tail map { spec => Issues.RepeatedSpecifier(spec.source, (spec.text, specs.head.source)) }
            }
          }

          val validSpecifiers = (specifiersByType filter { allowedSpecifiers contains _._1 }).values map { _.head } toSeq
          val source = if (validSpecifiers.nonEmpty) {
            validSpecifiers.head.source + validSpecifiers.last.source
          } else {
            streamAfterSpecifiers.beforeNextNonWhitespace
          }

          Success(SpecifiersList(validSpecifiers, source), parseIssues ++ issues, streamAfterSpecifiers)
      }
    }
  }
}


text:
/**
 * Created at Sep 9, 2010, 4:35:08 PM
 */
package com.dmurph.mvc.gui.combo;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;

import javax.swing.AbstractListModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.MutableComboBoxModel;

/**
 * Copied from {@link DefaultComboBoxModel}, with methods added for more control
 * over the model data.
 * @author Daniel Murphy
 *
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class MVCJComboBoxModel<E> extends AbstractListModel implements MutableComboBoxModel, Serializable{
	private static final long serialVersionUID = 1L;

	private final Vector<E> objects;
    private E selectedObject;

    /**
     * Constructs an empty DefaultComboBoxModel.
     */
    public MVCJComboBoxModel() {
        objects = new Vector();
    }

    /**
     * Constructs a DefaultComboBoxModel object initialized with
     * an array of objects.
     *
     * @param items  an array of Object objects
     */
	public MVCJComboBoxModel(final E items[]) {
        objects = new Vector();
        objects.ensureCapacity( items.length );

        int i,c;
        for ( i=0,c=items.length;i<c;i++ )
            objects.addElement(items[i]);

        if ( getSize() > 0 ) {
            selectedObject = getElementAt( 0 );
        }
    }

    /**
     * Constructs a DefaultComboBoxModel object initialized with
     * a vector.
     *
     * @param v  a Vector object ...
     */
    public MVCJComboBoxModel(Vector<E> v) {
        objects = v;

        if ( getSize() > 0 ) {
            selectedObject = getElementAt( 0 );
        }
    }

    // implements javax.swing.ComboBoxModel
    /**
     * Set the value of the selected item. The selected item may be null.
     * <p>
     * @param anObject The combo box value or null for no selection.
     */
    public void setSelectedItem(Object anObject) {
        if ((selectedObject != null && !selectedObject.equals( anObject )) ||
	    selectedObject == null && anObject != null) {
	    selectedObject = (E) anObject;
	    fireContentsChanged(this, -1, -1);
        }
    }

    // implements javax.swing.ComboBoxModel
    public E getSelectedItem() {
        return selectedObject;
    }

    // implements javax.swing.ListModel
    public int getSize() {
        return objects.size();
    }

    // implements javax.swing.ListModel
    public E getElementAt(int index) {
        if ( index >= 0 && index < objects.size() )
            return objects.elementAt(index);
        else
            return null;
    }

    /**
     * Returns the index-position of the specified object in the list.
     *
     * @param anObject
     * @return an int representing the index position, where 0 is
     *         the first position
     */
    public int getIndexOf(Object anObject) {
        return objects.indexOf(anObject);
    }

    // implements javax.swing.MutableComboBoxModel
    public void addElement(Object anObject) {
        objects.addElement((E)anObject);
        fireIntervalAdded(this,objects.size()-1, objects.size()-1);
        if ( objects.size() == 1 && selectedObject == null && anObject != null ) {
            setSelectedItem( anObject );
        }
    }

    public void addElements(int argIndex, Collection<E> argElements){
    	if(argElements == null){
    		return;
    	}

    	objects.addAll(argIndex, argElements);
        fireIntervalAdded(this, argIndex, argIndex + argElements.size() - 1);

        if ( objects.size() == 1 && selectedObject == null) {
        	setSelectedItem(objects.get(0));
        }
    }

    public void addElements(Collection<E> argElements){
    	if(argElements == null){
    		return;
    	}

    	int oldSize = argElements.size();
    	objects.addAll(argElements);
        fireIntervalAdded(this,oldSize, objects.size()-1);

        if ( objects.size() == 1 && selectedObject == null) {
        	setSelectedItem(objects.get(0));
        }
    }

    // implements javax.swing.MutableComboBoxModel
    public void insertElementAt(Object anObject,int index) {
        objects.insertElementAt((E)anObject,index);
        fireIntervalAdded(this, index, index);
    }

    public void setElementAt(E anObject, int index){
    	objects.setElementAt(anObject, index);
    	fireContentsChanged(this, index, index);
    }

    // implements javax.swing.MutableComboBoxModel
    public void removeElementAt(int index) {
        if ( getElementAt( index ) == selectedObject ) {
            if ( index == 0 ) {
                setSelectedItem( getSize() == 1 ? null : getElementAt( index + 1 ) );
            }
            else {
                setSelectedItem( getElementAt( index - 1 ) );
            }
        }

        objects.removeElementAt(index);

        fireIntervalRemoved(this, index, index);
    }

    public void sort(Comparator<E> argComparator){
    	Collections.sort(objects, argComparator);
    }

    // implements javax.swing.MutableComboBoxModel
    public void removeElement(Object anObject) {
        int index = objects.indexOf(anObject);
        if ( index != -1 ) {
            removeElementAt(index);
        }
    }

    /**
     * Empties the list.
     */
    public void removeAllElements() {
	    if ( objects.size() > 0 ) {
	            int firstIndex = 0;
	            int lastIndex = objects.size() - 1;
	            objects.removeAllElements();
		    selectedObject = null;
	            fireIntervalRemoved(this, firstIndex, lastIndex);
	        } else {
		    selectedObject = null;
		}
    }
}


text:
class CXFA_MsgId final : public CXFA_Node {
 public:
  CXFA_MsgId(CXFA_Document* doc, XFA_PacketType packet);
  ~CXFA_MsgId() override;
};

#endif  // XFA_FXFA_PARSER_CXFA_MSGID_H_


text:
package io.spine.server.entity;

import com.google.protobuf.Message;
import io.spine.test.entity.ProjectId;
import io.spine.test.entity.Task;
import io.spine.test.entity.event.EntProjectCreated;
import io.spine.test.entity.event.EntTaskAdded;
import io.spine.testdata.Sample;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Optional;

import static com.google.protobuf.util.FieldMaskUtil.fromFieldNumbers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

@DisplayName("`EventFieldFilter` should")
class EventFieldFilterTest {

    @Test
    @DisplayName("pass event if not specified otherwise")
    void allowByDefault() {
        var filter = EventFieldFilter.newBuilder().build();
        var event = EntProjectCreated.getDefaultInstance();
        Optional<? extends Message> filtered = filter.filter(event);
        assertTrue(filtered.isPresent());
        assertEquals(event, filtered.get());
    }

    @Test
    @DisplayName("apply mask and pass")
    void applyFieldMask() {
        var mask = fromFieldNumbers(EntTaskAdded.class, EntTaskAdded.PROJECT_ID_FIELD_NUMBER);
        var filter = EventFieldFilter.newBuilder()
                .putMask(EntTaskAdded.class, mask)
                .build();
        var event = EntTaskAdded.newBuilder()
                .setProjectId(Sample.messageOfType(ProjectId.class))
                .setTask(Sample.messageOfType(Task.class))
                .build();
        Optional<? extends Message> filtered = filter.filter(event);
        assertTrue(filtered.isPresent());
        var maskedEventMessage = (EntTaskAdded) filtered.get();
        assertTrue(maskedEventMessage.hasProjectId());
        assertEquals(event.getProjectId(), maskedEventMessage.getProjectId());
        assertFalse(maskedEventMessage.hasTask());
    }
}


text:
require 'spec_helper'

describe PixiClient::Requests::GetOrderNrExternalByBoxNr do
  include Savon::SpecHelper

  let(:box_nr) { '12345' }
  subject { PixiClient::Requests::GetOrderNrExternalByBoxNr.new(box_nr: box_nr) }

  before(:all) do
    set_default_config
    savon.mock!
  end

  after(:all) { savon.unmock! }

  before do
    set_default_config
  end

  it { is_expected.to be_a_kind_of(PixiClient::Requests::Base) }

  describe '#api_method' do
    it 'should return :pixi_get_order_nr_external_by_box_nr' do
      expect(subject.api_method).to eq :pixi_get_order_nr_external_by_box_nr
    end
  end

  describe '#message' do
    it 'should return a hash in the form {\'BoxNr\' => <box_nr>}' do
      expect(subject.message).to eq('BoxNr' => box_nr)
    end
  end

  describe 'call behaviour' do
    before do
      savon.
        expects(:pixi_get_order_nr_external_by_box_nr).
        with(message: { 'BoxNr' => box_nr }).
        returns(File.read('spec/fixtures/get_order_nr_external_by_box_nr.xml')) # See file for data details
    end

    context 'when the box_nr exists', skip: true do
      it 'returns one row with the box_nr and the external order number' do
        result = subject.call
        expect(result.rows.size).to eq 1
        expect(result.rows.first.order_nr).to eq 10000
        expect(result.rows.first.order_nr_external).to eq '193498' # expected external number
      end
    end
  end
end


text:
using Augustus.CRM.AttributeExtensions;
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Augustus.CRM
{
    [DataContract()]
    public class BaseEntity : Entity
    {
        public BaseEntity(string entityLogicalName) : base(entityLogicalName) { }

        public void SetBaseIdValue(Guid id)
        {
            base.Id = id;
        }

        public void SetBaseAttributeValue(string attributeLogicalName, object value)
        {
            base.SetAttributeValue(attributeLogicalName, value);
        }

        [AttributeLogicalName("createdon")]
        public DateTime? Created
        {
            get { return this.GetAttributeDateTime(); }
        }
    }
}


text:
'use strict';

module.exports = function ucwords(str) {
  //  discuss at: http://locutus.io/php/ucwords/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Waldo Malqui Silva (http://waldo.malqui.info)
  // improved by: Robin
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  //    input by: James (http://www.james-bell.co.uk/)
  //   example 1: ucwords('kevin van  zonneveld')
  //   returns 1: 'Kevin Van  Zonneveld'
  //   example 2: ucwords('HELLO WORLD')
  //   returns 2: 'HELLO WORLD'

  return (str + '').replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function ($1) {
    return $1.toUpperCase();
  });
};
//# sourceMappingURL=ucwords.js.map


text:
package unit.com.bitdubai.fermat_dmp_plugin.layer.transaction.incoming_extra_user.developer.bitdubai.version_1.structure.IncomingExtraUserRelayAgent;

import com.bitdubai.fermat_api.layer.all_definition.enums.Addons;
import com.bitdubai.fermat_api.layer.all_definition.enums.PlatformComponents;
import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins;
import com.bitdubai.fermat_api.layer.all_definition.enums.UISource;
import com.bitdubai.fermat_api.layer.all_definition.events.interfaces.FermatEvent;
import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.enums.Wallets;
import com.bitdubai.fermat_api.layer.dmp_engine.sub_app_runtime.enums.SubApps;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.ErrorManager;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedAddonsExceptionSeverity;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedPlatformExceptionSeverity;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedPluginExceptionSeverity;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedSubAppExceptionSeverity;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedUIExceptionSeverity;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.UnexpectedWalletExceptionSeverity;

/**
 * Created by jorgegonzalez on 2015.07.02..
 */
public class MockErrorManager implements ErrorManager {

    private String reportedException;

    public String getReportedException(){
        return reportedException;
    }

    @Override
    public void reportUnexpectedPlatformException(PlatformComponents exceptionSource, UnexpectedPlatformExceptionSeverity unexpectedPlatformExceptionSeverity, Exception exception) {
        this.reportedException = exception.toString();
    }

    @Override
    public void reportUnexpectedPluginException(Plugins exceptionSource, UnexpectedPluginExceptionSeverity unexpectedPluginExceptionSeverity, Exception exception) {
        this.reportedException = exception.toString();
    }

    @Override
    public void reportUnexpectedWalletException(Wallets exceptionSource, UnexpectedWalletExceptionSeverity unexpectedWalletExceptionSeverity, Exception exception) {
        this.reportedException = exception.toString();
    }

    @Override
    public void reportUnexpectedAddonsException(Addons exceptionSource, UnexpectedAddonsExceptionSeverity unexpectedAddonsExceptionSeverity, Exception exception) {
        this.reportedException = exception.toString();
    }

    @Override
    public void reportUnexpectedSubAppException(SubApps exceptionSource, UnexpectedSubAppExceptionSeverity unexpectedAddonsExceptionSeverity, Exception exception) {
        this.reportedException = exception.toString();
    }

    @Override
    public void reportUnexpectedUIException(UISource exceptionSource, UnexpectedUIExceptionSeverity unexpectedAddonsExceptionSeverity, Exception exception) {

    }

    @Override
    public void reportUnexpectedEventException(FermatEvent exceptionSource, Exception exception) {

    }
}