text:
/**
 * \file
 *
 * This file contains the template for the graphlab graph
 * data-structure.
 *
 */

#ifndef GRAPHLAB_BASICGRAPH_HPP
#define GRAPHLAB_BASICGRAPH_HPP

#include <cassert>
#include <cmath>

#include <string>
#include <list>
#include <vector>
#include <set>
#include <map>

#include <queue>
#include <algorithm>
#include <functional>
#include <fstream>

#include <boost/bind.hpp>

#include <graphlab/logger/logger.hpp>

#include <graphlab/serialization/iarchive.hpp>
#include <graphlab/serialization/oarchive.hpp>

#include <graphlab/extern/metis/metis.hpp>

#include <graphlab/macros_def.hpp>
namespace graphlab {

  /**
   * \brief the partitioning methods.
   *
   * The partition method struct contains the partition_method_enum
   * which desribes the partitioning method supported by the graphlab
   * graph partitioning framework.  Graphlab links to the metis graph
   * partitioning library and also provides its own partitioning
   * algorithms.
   */
  struct partition_method {

    /**
     * \brief the partition methods
     *
     * <ul>
     *
     *   <li> PARTITION_RANDOM: Randomly partition the graph. </li>
     *
     *   <li> PARTITION_METIS: Partition the graph using the metis
     *   algorithm </li>
     *
     *   <li> PARTITION_BFS: Use BFS partition method. </li>
     *
     * </ul>
     */
    enum partition_method_enum {
      PARTITION_RANDOM,
      PARTITION_METIS,
      PARTITION_BFS,
      PARTITION_EDGE_NUM,
    };
  };

  /** The type of a vertex is a simple size_t */
  typedef uint32_t vertex_id_t;

  /** The type of an edge id */
  typedef uint32_t edge_id_t;

  /** Type for vertex colors **/
  typedef uint8_t vertex_color_type;

  template<typename VertexData, typename EdgeData> class graph;

  // CLASS GRAPH ==============================================================>
  /**
   * The graph data structure which behaves like a container of edge
   * and vertex data. Intuitively the graph behaves like an
   * std::vector over VertexData with data associated with select
   * pairs of indices corresponding to edge data.
   */
  template<typename VertexData, typename EdgeData>
  class graph {
  public:

    /** The type of the vertex data stored in the graph */
    typedef VertexData vertex_data_type;

    /** The type of the edge data stored in the graph */
    typedef EdgeData   edge_data_type;

  public:

    // CONSTRUCTORS ============================================================>
    /**
     * Build a basic graph
     */
    graph() : finalized(true) {  }

    /**
     * BUG: Should not reserve but instead directly create vertices.
     * Create a graph with space allocated for num_vertices and
     * num_edges.
     */
    graph(size_t nverts) :
      vertices(nverts),
      in_edges(nverts), out_edges(nverts), vcolors(nverts),
      finalized(true) { }

    graph(const graph<VertexData, EdgeData> &g) { (*this) = g; }

    // METHODS =================================================================>

    /**
     * Clear all internal data
     */
    void clear() {
      vertices.clear();
      edges.clear();
      in_edges.clear();
      out_edges.clear();
      vcolors.clear();
      finalized = true;
    }

    /**
     * Finalize a graph by sorting its edges to maximize the
     * efficiency of graphlab.  This is invoked by the engine at
     * start.
     */
    void finalize() {
      // check to see if the graph is already finalized
      if(finalized) return;
      // Assert that the graph is not finalized
      typedef std::vector< edge_id_t > edge_set;

      edge_id_less_functor less_functor(this);

      // Sort all in edges sets
      foreach(edge_set& eset, in_edges) {
        std::sort(eset.begin(),
                  eset.end(),
                  less_functor);
        //                  boost::bind(&graph::edge_id_less, this, _1, _2) );
        // Test for duplicate edges
        if (eset.size() > 1) {
          for(size_t i = 0; i < eset.size()-1; ++i) {
            // Duplicate edge test
            assert(edge_id_less(eset[i], eset[i+1]));
          }
        }
      }
      // Sort all out edges sets
      foreach(edge_set& eset, out_edges) {
        std::sort(eset.begin(),
                  eset.end(),
                  less_functor);
        //                 boost::bind(&graph::edge_id_less, this, _1, _2) );
        // Test for dupliate edges
        if (eset.size() > 1) {
          for(size_t i = 0; i < eset.size()-1; ++i) {
            // Duplicate edge test
            assert(edge_id_less(eset[i], eset[i+1]));
          }
        }
      }
      finalized = true;
    } // End of finalize

    /** Get the number of vetices */
    size_t num_vertices() const {
      return vertices.size();
    } // end of num vertices

    /** Get the number of edges */
    size_t num_edges() const {
      return edges.size();
    } // end of num edges

    /** Get the number of in edges */
    size_t num_in_neighbors(vertex_id_t v) const {
      assert(v < vertices.size());
      return in_edges[v].size();
    } // end of num vertices

    /** get the number of out edges */
    size_t num_out_neighbors(vertex_id_t v) const  {
      assert(v < vertices.size());
      return out_edges[v].size();
    } // end of num vertices

    /** Find an edge */
    std::pair<bool, edge_id_t>
    find(vertex_id_t source, vertex_id_t target) const {
      assert(source < in_edges.size());
      assert(target < out_edges.size());
      // Check the base case that the souce or target have no edges
      if (in_edges[target].size() == 0 ||
          out_edges[source].size() == 0) {
        return std::make_pair(false,-1);
      } else if(finalized) { // O( log degree ) search ========================>
        // if it is finalized then do the search using a binary search
        // If their are fewer in edges into the target search the in
        // edges
        if(in_edges[target].size() < out_edges[source].size()) {
          // search the source vertices for the edge
          size_t index = binary_search(in_edges[target], source, target);
          if(index < in_edges[target].size())
            return std::make_pair(true, in_edges[target][index]);
          else
            return std::make_pair(false,-1);
        } else { // If their are fewer edges out of the source binary
                 // search there
          // search the source vertices for the edge
          size_t index = binary_search(out_edges[source], source, target);
          if(index < out_edges[source].size())
            return std::make_pair(true, out_edges[source][index]);
          else
            return std::make_pair(false,-1);
        }
      } else { // O( degree ) search ==========================================>
        // if there are few in edges at the target search there
        if(in_edges[target].size() < out_edges[source].size()) {
          // linear search the in_edges at the target
          foreach(edge_id_t eid, in_edges[target]) {
            assert(eid < edges.size());
            if(edges[eid].source() == source
               && edges[eid].target() == target) {
              return std::make_pair(true, eid);
            }
          }
          return std::make_pair(false, -1);
        } else { // fewer out edges at the source
          // linear search the out_edges at the source
          foreach(edge_id_t eid, out_edges[source]) {
            assert(eid < edges.size());
            if(edges[eid].source() == source
               && edges[eid].target() == target) {
              return std::make_pair(true, eid);
            }
          }
          return std::make_pair(false, -1);
        }
      } // End of else
    } // end of find

    /** get the edge id for the edge */
    edge_id_t edge_id(vertex_id_t source, vertex_id_t target) const {
      std::pair<bool, edge_id_t> res = find(source, target);
      // The edge must exist
      assert(res.first);
      assert(res.second < edges.size());
      return res.second;
    } // end of edge_id

    /** get the reverser edge id for the edge */
    edge_id_t rev_edge_id(edge_id_t eid) const {
      assert(eid < edges.size());
      vertex_id_t source = edges[eid].source();
      vertex_id_t target = edges[eid].target();
      return edge_id(target, source);
    } // end of rev_edge_id

    /**
     * Creates a vertex containing the vertex data and returns the id
     * of the new vertex id.
     */
    vertex_id_t add_vertex(const VertexData& vdata = VertexData() ) {
      vertices.push_back(vdata);
      // Resize edge maps
      out_edges.resize(vertices.size());
      in_edges.resize(vertices.size());
      vcolors.resize(vertices.size());
      return vertices.size() - 1;
    } // End of add vertex;

    /**
     * Add additional vertices up to provided num_vertices.  This will
     * fail is resizing down.
     */
    void resize(size_t num_vertices ) {
      assert(num_vertices >= vertices.size());
      vertices.resize(num_vertices);
      // Resize edge maps
      out_edges.resize(vertices.size());
      in_edges.resize(vertices.size());
      vcolors.resize(vertices.size());
    } // End of resize

    /**
     * Creates an edge connecting vertex source to vertex target.  Any
     * existing data will be cleared.
     */
    edge_id_t add_edge(vertex_id_t source, vertex_id_t target,
                       const EdgeData& edata = EdgeData()) {
      if ( source >= vertices.size()
           || target >= vertices.size() ) {
        logger(LOG_FATAL,
               "Attempting add_edge (%d -> %d) when there are only %d vertices",
               source, target, vertices.size());
        assert(source < vertices.size());
        assert(target < vertices.size());
      }
      // Add the edge to the set of edge data (this copies the edata)
      edges.push_back( edge( source, target, edata ) );

      // Add the edge id to in and out edge maps
      edge_id_t edge_id = edges.size() - 1;
      in_edges[target].push_back(edge_id);
      out_edges[source].push_back(edge_id);

      // Determine if the graph is still finalized A graph is
      // finalized if it was finalized and the newly added edge_id is
      // in the correct location in the in and out edge lists (which
      // is true if either the lists only contain a single element or
      // the last two elements are in the correct order).
      finalized = finalized &&
        ((in_edges[target].size() < 2) ||
         edge_id_less(*(in_edges[target].end()-2),
                      *(in_edges[target].end()-1))) &&
        ((out_edges[source].size() < 2) ||
         edge_id_less(*(out_edges[source].end()-2),
                      *(out_edges[source].end()-1)));
      return edge_id;
    } // End of add edge

    /** Get the vertex data */
    VertexData& vertex_data(vertex_id_t v) {
      assert(v < vertices.size());
      return vertices[v];
    } // end of data(v)

    /** Get the vertex data */
    const VertexData& vertex_data(vertex_id_t v) const {
      assert(v < vertices.size());
      return vertices[v];
    } // end of data(v)

    /** Get the edge_data */
    EdgeData& edge_data(vertex_id_t source, vertex_id_t target) {
      assert(source < vertices.size());
      assert(target < vertices.size());
      std::pair<bool, edge_id_t> ans = find(source, target);
      // We must find the edge!
      assert(ans.first);
      // the edge id should be valid!
      assert(ans.second < edges.size());
      return edges[ans.second].data();
    } // end of edge_data(u,v)

    /** Get the edge_data */
    const EdgeData& edge_data(vertex_id_t source, vertex_id_t target) const {
      assert(source < vertices.size());
      assert(target < vertices.size());
      std::pair<bool, edge_id_t> ans = find(source, target);
      // We must find the edge!
      assert(ans.first);
      // the edge id should be valid!
      assert(ans.second < edges.size());
      return edges[ans.second].data();
    } // end of edge_data(u,v)

    /** Get the edge_data */
    EdgeData& edge_data(edge_id_t edge_id) {
      assert(edge_id < edges.size());
      return edges[edge_id].data();
    }

    /** Get the edge_data */
    const EdgeData& edge_data(edge_id_t edge_id) const {
      assert(edge_id < edges.size());
      return edges[edge_id].data();
    }

    /** get the source of the edge */
    vertex_id_t source(edge_id_t edge_id) const {
      //      assert(edge_id < edges.size());
      return edges[edge_id].source();
    }

    /** get the dest of the edge */
    vertex_id_t target(edge_id_t edge_id) const {
      //      assert(edge_id < edges.size());
      return edges[edge_id].target();
    }

    /** Set vertex color **/
    const vertex_color_type& color(vertex_id_t vertex) const {
      assert(vertex < vertices.size());
      return vcolors[vertex];
    }

    vertex_color_type& color(vertex_id_t vertex) {
      assert(vertex < vertices.size());
      return vcolors[vertex];
    }

    /** This function constructs a coloring for the graph and returns
        the number of colors */
    size_t compute_coloring() {
      // Reset the colors
      for(vertex_id_t v = 0; v < num_vertices(); ++v) color(v) = 0;
      // construct a permuation of the vertices to use in the greedy
      // coloring. \todo Should probably sort by degree instead when
      // constructing greedy coloring.
      std::vector<vertex_id_t> permutation(num_vertices());
      for(vertex_id_t v = 0; v < num_vertices(); ++v)
        permutation[v] = v;
      std::random_shuffle(permutation.begin(), permutation.end());
      // Recolor
      size_t max_color = 0;
      std::set<vertex_color_type> neighbor_colors;
      for(size_t i = 0; i < permutation.size(); ++i) {
        neighbor_colors.clear();
        const vertex_id_t& vid = permutation[i];
        const std::vector<edge_id_t>& in_edges = in_edge_ids(vid);
        // Get the neighbor colors
        foreach(edge_id_t eid, in_edges){
          const vertex_id_t& neighbor_vid = source(eid);
          const vertex_color_type& neighbor_color = color(neighbor_vid);
          neighbor_colors.insert(neighbor_color);
        }
        // Find the lowest free color
        vertex_color_type& vertex_color = color(vid);
        foreach(vertex_color_type neighbor_color, neighbor_colors) {
          if(vertex_color != neighbor_color) break;
          else vertex_color++;
          // Ensure no wrap around
          assert(vertex_color != 0);
        }
        max_color = std::max(max_color, size_t(vertex_color) );
      }
      // Return the NUMBER of colors
      return max_color + 1;
    } // end of compute coloring

    /**
     * Check that the colors satisfy a valid coloring of the graph.
     * return true is coloring is valid;
     */
    bool valid_coloring() {
      for(vertex_id_t vid = 0; vid < num_vertices(); ++vid) {
        const vertex_color_type& vertex_color = color(vid);
        const std::vector<edge_id_t>& in_edges = in_edge_ids(vid);
        // Get the neighbor colors
        foreach(edge_id_t eid, in_edges){
          const vertex_id_t& neighbor_vid = source(eid);
          const vertex_color_type& neighbor_color = color(neighbor_vid);
          if(vertex_color == neighbor_color) return false;
        }
      }
      return true;
    }

    /** Get the ids of the in edges */
    const std::vector<edge_id_t>& in_edge_ids(vertex_id_t v) const {
      assert(v < in_edges.size());
      return in_edges[v];
    } // end of in edges

    /** Get the ids of the out edges */
    const std::vector<edge_id_t>& out_edge_ids(vertex_id_t v) const {
      assert(v < out_edges.size());
      return out_edges[v];
    } // end of out edges

    /** Load the graph from an archive */
    void load(iarchive& arc) {
      clear();
      // read the vertices and colors
      arc >> vertices
          >> edges
          >> in_edges
          >> out_edges
          >> vcolors
          >> finalized;
    } // end of load

    /** Save the graph to an archive */
    void save(oarchive& arc) const {
      // Write the number of edges and vertices
      arc << vertices
          << edges
          << in_edges
          << out_edges
          << vcolors
          << finalized;
    } // end of save

    /** Load the graph from a file */
    void load(const std::string& filename) {
      std::ifstream fin(filename.c_str());
      iarchive iarc(fin);
      iarc >> *this;
      fin.close();
    } // end of load

    /**
     * \brief save the graph to the file given by the filename
     *
     */
    void save(const std::string& filename) const {
      std::ofstream fout(filename.c_str());
      oarchive oarc(fout);
      oarc << *this;
      fout.close();
    } // end of save

    /**
     * \brief save the adjacency structure to a text file.
     *
     * Save the adjacency structure as a text file in:
     *    src_Id, dest_Id \n
     *    src_Id, dest_Id \n
     * format.
     */
    void save_adjacency(const std::string& filename) const {
      std::ofstream fout(filename.c_str());
      assert(fout.good());
      for(size_t i = 0; i < edges.size(); ++i) {
        fout << edges[i].source() << ", " << edges[i].target() << "\n";
        assert(fout.good());
      }
      fout.close();
    }

    /**
     * partition the graph with roughtly the same number of edges for each part
     */
    void edge_num_partition(size_t nparts, std::vector<uint32_t>& vertex2part){

      vertex2part.resize(num_vertices());
      size_t e = 2 * num_edges();
      size_t edge_per_part = e / nparts;

      size_t curpart = 0;
      std::vector<size_t> parts;
      parts.resize(nparts, 0);

      for (size_t i = 0; i< num_vertices(); i++){
        int ne = out_edge_ids(i).size() + in_edge_ids(i).size();
        vertex2part[i] = curpart;
        parts[curpart]+= ne;

        if (parts[curpart] >= edge_per_part  && curpart < nparts-1){
          curpart++;
        }
      }
    }

    /**
     * Randomly assign vertices to partitions.  This will assign
     * vertices evenly to each partition.
     */
    void random_partition(size_t nparts, std::vector<uint32_t>& vertex2part) {
      vertex2part.resize(num_vertices());
      for (size_t i = 0;i < num_vertices(); ++i) {
        vertex2part[i] = i % nparts;
      }
      std::random_shuffle(vertex2part.begin(), vertex2part.end());
    }

    /**
     * Use a modified version of the METIS library to partition the
     * graph. The methis library is described in:
     *
     *   "A Fast and Highly Quality Multilevel Scheme for Partitioning
     *   Irregular Graphs". George Karypis and Vipin Kumar. SIAM
     *   Journal on Scientific Computing, Vol. 20, No. 1, pp. 359—392,
     *   1999.
     *
     * We have modified an alpha version (5.0) to work with the
     * GraphLab framework.  Therefore users having trouble with this
     * function or the included Metis source should direct concerns to
     * the contact information provided at:
     *
     *   http://www.select.cs.cmu.edu/code
     *
     */
    void metis_partition(size_t numparts , std::vector<uint32_t>& ret_part) {
      if (numparts == 1) {
        ret_part.assign(num_vertices(), 0);
        return;
      }
      // Determine parameters needed to construct the partitioning
      metis::idxtype numverts = static_cast<int>(num_vertices());
      assert(numverts > 0);
      // Compute the number of edges
      int numedges = static_cast<int>(num_edges());

      // allocate metis data structures
      metis::idxtype* vweight = new metis::idxtype[numverts];
      assert(vweight != NULL);
      metis::idxtype* xadj = new metis::idxtype[numverts + 1];
      assert(xadj != NULL);
      metis::idxtype* adjacency = new metis::idxtype[2 * numedges];
      assert(adjacency != NULL);
      metis::idxtype* eweight = NULL;
      //       if(weighted) {
      //         eweight = new idxtype[numedges];
      //         assert(eweigth != NULL);
      //       }
      metis::idxtype* res = new metis::idxtype[numverts];
      assert(res != NULL);

      // Pass through vertices filling in the metis data structures
      size_t offset = 0;
      for(vertex_id_t u = 0; u < num_vertices(); ++u) {
        // Update vertex weight
        // Set weight
        vweight[u] = 1;
        // Update the offset
        xadj[u] = offset;
        // Fill the the adjacency data

        std::set<size_t> neighbors;
        foreach(edge_id_t eid, out_edge_ids(u)) {
          neighbors.insert(target(eid));
        }
        foreach(edge_id_t eid, in_edge_ids(u)) {
          neighbors.insert(source(eid));
        }
        foreach(vertex_id_t vid, neighbors) {
          if (vid == u) continue;
          adjacency[offset] = vid;
          assert(adjacency[offset] >= 0);
          offset++;
          assert(offset >= 0);
        }

      } // end of data structure creation

      // Set the last entry in xadj to the end of the adjacency array
      xadj[numverts] = offset;

      // Set additional metis flags
      /**
       * 0 No weights (vwgts and adjwgt are NULL)
       * 1 Weights on the edges only (vwgts = NULL)
       * 2 Weights on the vertices only (adjwgt = NULL)
       * 3 Weights both on vertices and edges.
       */
      metis::idxtype weightflag = 2;
      // 0 for C-style numbering starting at 0 (1 for fortran style)
      metis::idxtype numflag = 0;
      // the number of parts to cut into
      metis::idxtype nparts = numparts;
      // Options array (only care about first element if first element
      // is zero
      metis::idxtype options[5] = {0};
      // output argument number of edges cut
      metis::idxtype edgecut = 0;

      // Call kmetis
      metis::METIS_PartGraphKway(&(numverts),
                                 xadj,
                                 adjacency,
                                 vweight,
                                 eweight,
                                 &(weightflag),
                                 &(numflag),
                                 &(nparts),
                                 options,
                                 &(edgecut),
                                 res);

      //     // Call pmetis
      //     metis::METIS_PartGraphRecursive(&(numverts),
      //                                     xadj,
      //                                     adjacency,
      //                                     vweight,
      //                                     eweight,
      //                                     &(weightflag),
      //                                     &(numflag),
      //                                     &(nparts),
      //                                     options,
      //                                     &(edgecut),
      //                                     res);

      // destroy all unecessary data structures except res
      if(xadj != NULL) delete [] xadj;
      if(adjacency != NULL) delete [] adjacency;
      if(vweight != NULL) delete [] vweight;
      if(eweight != NULL) delete [] eweight;

      // Resize the partition
      ret_part.resize(num_vertices());
      // process the final results
      assert(res != NULL);
      for(vertex_id_t v = 0; v < num_vertices(); ++v) {
        ret_part[v] = res[v];
      }
      // Delete the result array
      if(res != NULL) delete [] res;
    } // end of metis partition

    /**
     * This function computes a weighted graph partition using METIS.
     * \param numparts The number of parts to partition into
     * \param ret_part A vector providing a vertex_id -> partition_id mapping
     * \param vfunction A function of the type size_t (*)(const VertexData &v)
     *                  This function takes in the data on a vertex, and
     *                  returns the weight of the vertex
     * \param efunction A function of the type size_t (*)(const EdgeData &e)
     *                  This function takes in the data on an edge, and
     *                  returns the weight of the edge
     *
     * Use a modified version of the METIS library to partition the
     * graph using user provided edge and vertex weight functions.
     * The methis library is described in:
     *
     *   "A Fast and Highly Quality Multilevel Scheme for Partitioning
     *   Irregular Graphs". George Karypis and Vipin Kumar. SIAM
     *   Journal on Scientific Computing, Vol. 20, No. 1, pp. 359—392,
     *   1999.
     *
     * We have modified an alpha version (5.0) to work with the
     * GraphLab framework.  Therefore users having trouble with this
     * function or the included Metis source should direct concerns to
     * the contact information provided at:
     *
     *   http://www.select.cs.cmu.edu/code
     *
     */
    template <typename EdgeWeightFunction, typename VertexWeightFunction>
    void metis_weighted_partition(size_t numparts ,
                                  std::vector<uint32_t>& ret_part,
                                  VertexWeightFunction vfunction,
                                  EdgeWeightFunction wfunction) {
      if (numparts == 1) {
        ret_part.assign(num_vertices(), 0);
        return;
      }
      // Determine parameters needed to construct the partitioning
      metis::idxtype numverts = static_cast<int>(num_vertices());
      assert(numverts > 0);
      // Compute the number of edges
      int numedges = static_cast<int>(num_edges());

      // allocate metis data structures
      metis::idxtype* vweight = new metis::idxtype[numverts];
      assert(vweight != NULL);
      metis::idxtype* xadj = new metis::idxtype[numverts + 1];
      assert(xadj != NULL);
      metis::idxtype* adjacency = new metis::idxtype[2 * numedges];
      assert(adjacency != NULL);
      metis::idxtype* eweight = NULL;
      eweight = new metis::idxtype[ 2 * numedges];
      assert(eweight != NULL);

      metis::idxtype* res = new metis::idxtype[numverts];
      assert(res != NULL);

      // Pass through vertices filling in the metis data structures
      size_t offset = 0;
      for(vertex_id_t u = 0; u < num_vertices(); ++u) {
        // Update vertex weight
        // Set weight
        vweight[u] = double(vfunction(vertex_data(u)));
        // Update the offset
        xadj[u] = offset;
        // Fill the the adjacency data

        std::set<size_t> neighbors;
        std::map<size_t, double> nbrtoweight;
        foreach(edge_id_t eid, out_edge_ids(u)) {
          neighbors.insert(target(eid));
          nbrtoweight[target(eid)] = double(wfunction(edge_data(eid)));
        }
        foreach(edge_id_t eid, in_edge_ids(u)) {
          neighbors.insert(source(eid));
          nbrtoweight[source(eid)] = double(wfunction(edge_data(eid)));
        }
        foreach(vertex_id_t vid, neighbors) {
          if (vid == u) continue;
          adjacency[offset] = vid;
          eweight[offset] = nbrtoweight[vid];
          assert(adjacency[offset] >= 0);
          offset++;
          assert(offset >= 0);
        }

      } // end of data structure creation

      // Set the last entry in xadj to the end of the adjacency array
      xadj[numverts] = offset;

      // Set additional metis flags
      /**
       * 0 No weights (vwgts and adjwgt are NULL)
       * 1 Weights on the edges only (vwgts = NULL)
       * 2 Weights on the vertices only (adjwgt = NULL)
       * 3 Weights both on vertices and edges.
       */
      metis::idxtype weightflag = 3;
      // 0 for C-style numbering starting at 0 (1 for fortran style)
      metis::idxtype numflag = 0;
      // the number of parts to cut into
      metis::idxtype nparts = numparts;
      // Options array (only care about first element if first element
      // is zero
      metis::idxtype options[5] = {0};

      options[0] = 1;
      options[1]=3;
      options[2]=1;
      options[3]=2;
      options[4]=0;
      // output argument number of edges cut
      metis::idxtype edgecut = 0;

      // Call kmetis
      metis::METIS_PartGraphKway(&(numverts),
                                 xadj,
                                 adjacency,
                                 vweight,
                                 eweight,
                                 &(weightflag),
                                 &(numflag),
                                 &(nparts),
                                 options,
                                 &(edgecut),
                                 res);

      // Call pmetis
      /*   metis::METIS_PartGraphRecursive(&(numverts),
           xadj,
           adjacency,
           vweight,
           eweight,
           &(weightflag),
           &(numflag),
           &(nparts),
           options,
           &(edgecut),
           res);*/

      // destroy all unecessary data structures except res
      if(xadj != NULL) delete [] xadj;
      if(adjacency != NULL) delete [] adjacency;
      if(vweight != NULL) delete [] vweight;
      if(eweight != NULL) delete [] eweight;

      // Resize the partition
      ret_part.resize(num_vertices());
      // process the final results
      assert(res != NULL);
      for(vertex_id_t v = 0; v < num_vertices(); ++v) {
        ret_part[v] = res[v];
      }
      // Delete the result array
      if(res != NULL) delete [] res;
    } // end of metis partition

    void bfs_partition(size_t nparts, std::vector<uint32_t> &vertex2part) {
      // create a list of all unassigned variables
      std::set<vertex_id_t> unassigned;
      vertex2part.resize(num_vertices());
      // initialize the unassigned vertices
      for(vertex_id_t v = 0; v < num_vertices(); ++v) {
        unassigned.insert(v);
      }
      // Compute the partition size
      size_t maxpartsize = (size_t)(std::ceil(double(unassigned.size()) / nparts));
      size_t partid = 0;
      while(!unassigned.empty()) {
        std::list<vertex_id_t> queue;    // Breadth first queue
        std::set<vertex_id_t>  visited;  // Set of visited vertices
        // While the task is still too small and their remains
        // unassigned vertices
        size_t curpartsize = 0;
        while(curpartsize < maxpartsize
              && !unassigned.empty()) {
          if(queue.empty()) {
            queue.push_front(*unassigned.begin());
            visited.insert(*unassigned.begin());
          }
          assert(!queue.empty());
          // Pop the first element off the queue
          vertex_id_t v = queue.front(); queue.pop_front();
          assert(partid < nparts);
          // Add the element to the task
          vertex2part[v] = partid;
          ++curpartsize;
          // Remove the vertex from the set of unassigned vertices
          unassigned.erase(v);
          // Add all its unassigned and unvisited neighbors to the queue
          foreach(edge_id_t eid, out_edge_ids(v)) {
            vertex_id_t u = target(eid);
            if(unassigned.find(u) != unassigned.end() &&
               visited.find(u) == visited.end()) {
              queue.push_back(u);
              visited.insert(u);
            }
          }
          foreach(edge_id_t eid, in_edge_ids(v)) {
            vertex_id_t u = source(eid);
            if(unassigned.find(u) != unassigned.end() &&
               visited.find(u) == visited.end()) {
              queue.push_back(u);
              visited.insert(u);
            }
          }
        } // End of block build foor loop
        // move to the next part
        partid++;
      }// end of outer while loop
    } // end of bfs partition

    /**
     * Partition the graph using one of the available partitioning
     * methods.
     */
    void partition(partition_method::partition_method_enum partmethod,
                   size_t nparts, std::vector<uint32_t>& vertex2part) {
      switch (partmethod) {
      case partition_method::PARTITION_METIS:
        return metis_partition(nparts, vertex2part);
      case partition_method::PARTITION_BFS:
        return bfs_partition(nparts, vertex2part);
      case partition_method::PARTITION_RANDOM:
        return random_partition(nparts, vertex2part);
      case partition_method::PARTITION_EDGE_NUM:
        return edge_num_partition(nparts, vertex2part);
      default:
        ASSERT_TRUE(false); //shoud never ever happen
      }
    }

    /**
     * builds a topological_sort of the graph. assuming it is top
     * sortable will return false if fails (i.e. cycles)
     */
    bool topological_sort(std::vector<vertex_id_t>& topsort) const {
      topsort.clear();
      topsort.reserve(num_vertices());

      std::vector<size_t> indeg;
      indeg.resize(num_vertices());
      std::queue<vertex_id_t> q;
      for (size_t i = 0;i < num_vertices(); ++i) {
        indeg[i] = in_edge_ids(i).size();
        if (indeg[i] == 0) {
          q.push(i);
        }
      }

      while (!q.empty()) {
        vertex_id_t v = q.front();
        q.pop();
        topsort.push_back(v);
        foreach(edge_id_t eid, out_edge_ids(v)) {
          vertex_id_t destv = target(eid);
          --indeg[destv];
          if (indeg[destv] == 0) {
            q.push(destv);
          }
        }
      }

      if (q.empty() && topsort.size() != num_vertices()) return false;
      return true;
    } // end of topological sort

  private:
    /** Internal edge class  */
    class edge {
      vertex_id_t _source;
      vertex_id_t _target;
      EdgeData _data;
    public:
      edge() : _source(-1), _target(-1) { }
      edge(const edge& other) :
        _source(other.source()), _target(other.target()),
        _data(other.data()) { }
      edge(vertex_id_t source, vertex_id_t target) :
        _source(source), _target(target)  { }
      edge(vertex_id_t source, vertex_id_t target, EdgeData data) :
        _source(source), _target(target), _data(data) {}

      bool operator<(const edge& other) const {
        return (_source < other._source) ||
          (_source == other._source && _target < other._target);
      }

      inline vertex_id_t source() const { return _source; }
      inline vertex_id_t target() const { return _target; }
      inline EdgeData& data() { return _data; }
      inline const EdgeData& data() const { return _data; }

      void load(iarchive& arc) {
        arc >> _source
            >> _target
            >> _data;
      }

      void save(oarchive& arc) const {
        arc << _source
            << _target
            << _data;
      }
    }; // end of edge_data

    struct edge_id_less_functor {
      graph* g_ptr;
      edge_id_less_functor(graph* g_ptr) : g_ptr(g_ptr) { }
      bool operator()(edge_id_t a, edge_id_t b) {
        return g_ptr->edge_id_less(a,b);
      }
    };

    /**
     * Used to order edge ids in the in and out edges vectors based on
     * the lexical ordering of the vertex ids of the corresponding
     * edge
     */
    inline bool edge_id_less(edge_id_t a, edge_id_t b) const {
      assert(a < edges.size());
      assert(b < edges.size());
      return edges[a] < edges[b];
    }

    // PRIVATE DATA MEMBERS ===================================================>
    /** The vertex data is simply a vector of vertex data */
    std::vector<VertexData> vertices;

    /** The edge data is a vector of edges where each edge stores its
        source, destination, and data. */
    std::vector<edge> edges;

    /** A map from src_vertex -> dest_vertex -> edge index */
    std::vector< std::vector<edge_id_t> >  in_edges;

    /** A map from src_vertex -> dest_vertex -> edge index */
    std::vector< std::vector<edge_id_t> >  out_edges;

    /** The vertex colors specified by the user. **/
    std::vector< vertex_color_type > vcolors;

    /** Mark whether the graph is finalized.  Graph finalization is a
        costly procedure but it can also dramatically improve
        performance. */
    bool finalized;

    // PRIVATE HELPERS =========================================================>
    /**
     * This function tries to find the edge in the vector.  If it
     * fails it returns size_t(-1)
     */
    size_t binary_search(const std::vector<edge_id_t>& vec,
                         vertex_id_t source, vertex_id_t target) const {
      // Compare to the middle of the list
      size_t first = 0;
      size_t last = vec.size() - 1;
      while(first <= last) {
        size_t mid = (first+last)/2;
        vertex_id_t mid_source = edges[vec[mid]].source();
        vertex_id_t mid_target = edges[vec[mid]].target();
        // Edge found
        if(mid_source == source && mid_target == target) {
          return mid;
        } else if(std::make_pair(source, target) <
                  std::make_pair(mid_source, mid_target) ) {
          // Search left
          last = mid - 1;
        } else {
          // Search right
          first = mid + 1;
        }
      }
      // We failed to find
      return -1;
    } // end of binary search

  }; // End of graph

  template<typename VertexData, typename EdgeData>
  std::ostream& operator<<(std::ostream& out,
                           const graph<VertexData, EdgeData>& graph) {

    out << "Printing vertex data:\n";
    for(size_t i = 0; i < graph.num_vertices(); ++i) {
      out << "V_" << i << ": D[" << graph.vertex_data(i) << "]\n";
    }
    out << "Printing edge data:\n";
    for(size_t i = 0; i < graph.num_edges(); ++i) {
      out << "(V_" << graph.source(i) << "-> V_" << graph.target(i) << "): "
          << "D[" << graph.edge_data(i) << "]\n";
    }
    return out;
  }

} // end of namespace graphlab
#include <graphlab/macros_undef.hpp>

#endif


text:
#ifndef WINDOWS_SCM_H
#define WINDOWS_SCM_H

#include <memory>
#include <string>
using std::string;

#ifdef UNICODE
#undef UNICODE
#endif

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>

namespace qpid {
namespace windows {

/**
 * @class SCM
 *
 * Access the Windows Service Control Manager.
 */
class SCM
{
public:
    SCM();
    ~SCM();

    /**
     * Install this executable as a service
     *
     * @param serviceName   The name of the service
     * @param serviceDesc   Description of the service's purpose
     * @param args          The argument list to pass into the service
     * @param startType     The start type: SERVICE_DEMAND_START,
     *                      SERVICE_AUTO_START, SERVICE_DISABLED
     * @param account       If not empty, the account name to install this
     *                      service under
     * @param password      If not empty, the account password to install this
     *                      service with
     * @param depends       If not empty, a comma delimited list of services
     *                      that must start before this one
     */
    void install(const string& serviceName,
                 const string& serviceDesc,
                 const string& args,
                 DWORD startType = SERVICE_DEMAND_START,
                 const string& account = "NT AUTHORITY\\LocalSystem",
                 const string& password = "",
                 const string& depends = "");

    /**
     * Uninstall this executable as a service
     *
     * @param serviceName the name of the service
     */
    void uninstall(const string& serviceName);

    /**
     * Start the specified service
     *
     * @param serviceName the name of the service
     */
    void start(const string& serviceName);

    /**
     * Stop the specified service
     *
     * @param serviceName the name of the service
     */
    void stop(const string &serviceName);

private:
    SC_HANDLE  scmHandle;

    void openSvcManager();
    DWORD waitForStateChangeFrom(SC_HANDLE svc, DWORD originalState);
    DWORD getDependentServices(SC_HANDLE svc,
                               std::auto_ptr<ENUM_SERVICE_STATUS>& deps);

};

}}  // namespace qpid::windows

#endif  /* #ifndef WINDOWS_SCM_H */

redpajama_set_name: RedPajamaGithub


text:
static void create_cache_directory(NSString *cacheDirectory) {
    NSError *error;
    // ensure that the cache directory is present
    BOOL isDirectory;
    BOOL itemExists = [[NSFileManager defaultManager]
                       fileExistsAtPath:cacheDirectory isDirectory:&isDirectory];
    if (!(itemExists && isDirectory)) {
        if (itemExists) {
            [[NSFileManager defaultManager] removeItemAtPath:cacheDirectory
                                                       error:&error];
        }
        [[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:&error];
    }
}

int main (int argc, const char *argv[])
{
    @autoreleasepool {
        static NSString *cacheDirectory = CACHEDIRECTORY;
        create_cache_directory(cacheDirectory);

        RadHTTPService *service = [[RadHTTPService alloc] init];

        [service addHandlerWithHTTPMethod:@"PUT" path:@"/put" block:
         ^(RadHTTPRequest *request) {

            NSLog(@"PUT %d bytes", (int) [request.body length]);
             //NSString *string = [[NSString alloc] initWithData:request.body encoding:NSUTF8StringEncoding];
             //NSLog(@"%@", string);
             //NSLog(@"------");

            RadHTTPResponse *response = [[RadHTTPResponse alloc] init];
            response.body = nil;
            return response;

        }];

       [service addHandlerWithHTTPMethod:@"HEAD" path:@"/*path:" block:
         ^(RadHTTPRequest *request) {
             RadHTTPResponse *response = [[RadHTTPResponse alloc] init];
             response.body = nil;
             NSLog(@"hit HEAD");
             return response;
         }];

        [service addHandlerWithHTTPMethod:@"GET" path:@"/" block:
         ^(RadHTTPRequest *request) {
             RadHTTPResponse *response = [[RadHTTPResponse alloc] init];
             response.body = [@"RadHTTP" dataUsingEncoding:NSUTF8StringEncoding];
             NSLog(@"hit");
             //usleep(100000);
             //sleep(3);
             return response;
         }];

        [service addHandlerWithHTTPMethod:@"POST" path:@"/item" block:
         ^(RadHTTPRequest *request) {
             NSString *contentType = [request.headers objectForKey:@"Content-Type"];
             NSString *creatorName = [request.headers objectForKey:@"Creator-Name"];
             NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:
                                   request.body, @"Body",
                                   [NSDate date], @"Creation-Time",
                                   contentType, @"Content-Type",
                                   creatorName, @"Creator-Name",
                                   nil];
             NSError *error;
             NSData *data = [NSPropertyListSerialization dataWithPropertyList:item
                                                                       format:NSPropertyListXMLFormat_v1_0
                                                                      options:0
                                                                        error:&error];

             unsigned char result[CC_MD5_DIGEST_LENGTH];
             CC_MD5([request.body bytes], (CC_LONG) [request.body length], result);
             NSData *hashData = [NSData dataWithBytes:result length:CC_MD5_DIGEST_LENGTH];
             NSString *hashString = [hashData hexEncodedString];
             [data writeToFile:[cacheDirectory stringByAppendingPathComponent:hashString] atomically:NO];
             RadHTTPResponse *response = [[RadHTTPResponse alloc] init];
             response.body = [hashString dataUsingEncoding:NSUTF8StringEncoding];
             return response;
         }];

        [service addHandlerWithHTTPMethod:@"GET" path:@"/item/identifier:" block:
         ^(RadHTTPRequest *request) {
             NSString *identifier = [request.bindings objectForKey:@"identifier"];
             NSData *data = [NSData dataWithContentsOfFile:
                             [cacheDirectory stringByAppendingPathComponent:identifier]];
             if (data) {
                 NSDictionary *info =
                 [NSPropertyListSerialization propertyListFromData:data
                                                  mutabilityOption:NSPropertyListImmutable
                                                            format:nil
                                                  errorDescription:nil];
                 RadHTTPResponse *response = [[RadHTTPResponse alloc] init];
                 [response setValue:[info objectForKey:@"Content-Type"] forHTTPHeader:@"Content-Type"];
                 [response setValue:[info objectForKey:@"Creator-Name"] forHTTPHeader:@"Creator-Name"];
                 [response setValue:[info objectForKey:@"Creation-Time"] forHTTPHeader:@"Creation-Time"];
                 response.body = [info objectForKey:@"Body"];
                 return response;
             } else {
                 return (RadHTTPResponse *) nil;
             }
         }];

        // File handler.
        [service addHandlerWithPath:@"/*path:" directory:@"public"];

        // "Not found" handler. This should always be last.
        [service addHandlerWithHTTPMethod:@"GET" path:@"/*path:" block:
         ^(RadHTTPRequest *request) {
             NSString *path = [request.bindings objectForKey:@"*path"];
             RadHTTPResponse *response = [[RadHTTPResponse alloc] init];
             response.status = 404;
             response.body = [[NSString stringWithFormat:@"404 Not found: %@ %@", path, [request.URL description]]
                              dataUsingEncoding:NSUTF8StringEncoding];
             return response;
         }];

        //RadCocoaHTTPServer *server = [[RadCocoaHTTPServer alloc] initWithService:service];
        //RadLibEventHTTPServer *server = [[RadLibEventHTTPServer alloc] initWithService:service];
        RadLibEVHTPServer *server = [[RadLibEVHTPServer alloc] initWithService:service];
        [server setVerbose:YES];
        [server start];
        [[NSRunLoop mainRunLoop] run];
    }
    return 0;
}


text:
<?php

import('pages.rtadmin.RTAdminHandler');
import('classes.rt.ojs.SharingRT');

class RTSharingHandler extends RTAdminHandler {
	/**
	 * Constructor
	 **/
	function RTSharingHandler() {
		parent::RTAdminHandler();
	}

	function sharingSettings($args, $request) {
		$this->validate();
		$journal = $request->getJournal();
		if ($journal) {
			$this->setupTemplate($request, true);
			$templateMgr = TemplateManager::getManager($request);

			$rtDao = DAORegistry::getDAO('RTDAO');
			$rt = $rtDao->getJournalRTByJournal($journal);

			$templateMgr->assign('sharingEnabled', $rt->getSharingEnabled());
			$templateMgr->assign('sharingUserName', $rt->getSharingUserName());
			$templateMgr->assign('sharingButtonStyle', $rt->getSharingButtonStyle());
			$templateMgr->assign('sharingButtonStyleOptions', array_keys(SharingRT::getBtnStyles()));
			$templateMgr->assign('sharingDropDownMenu', $rt->getSharingDropDownMenu());
			$templateMgr->assign('sharingBrand', $rt->getSharingBrand());
			$templateMgr->assign('sharingDropDown', $rt->getSharingDropDown());
			$templateMgr->assign('sharingLanguage', $rt->getSharingLanguage());
			$templateMgr->assign('sharingLanguageOptions', SharingRT::getLanguages());
			$templateMgr->assign('sharingLogo', $rt->getSharingLogo());
			$templateMgr->assign('sharingLogoBackground', $rt->getSharingLogoBackground());
			$templateMgr->assign('sharingLogoColor', $rt->getSharingLogoColor());

			$templateMgr->display('rtadmin/addthis.tpl');
		} else {
			$request->redirect(null, $request->getRequestedPage());
		}
	}

	function saveSharingSettings($args, $request) {
		$this->validate();

		$journal = $request->getJournal();

		if ($journal) {
			$rtDao = DAORegistry::getDAO('RTDAO');
			$rt = $rtDao->getJournalRTByJournal($journal);

			$rt->setSharingEnabled($request->getUserVar('sharingEnabled'));
			$rt->setSharingUserName($request->getUserVar('sharingUserName'));
			$rt->setSharingButtonStyle($request->getUserVar('sharingButtonStyle'));
			$rt->setSharingDropDownMenu($request->getUserVar('sharingDropDownMenu'));
			$rt->setSharingBrand($request->getUserVar('sharingBrand'));
			$rt->setSharingDropDown($request->getUserVar('sharingDropDown'));
			$rt->setSharingLanguage($request->getUserVar('sharingLanguage'));
			$rt->setSharingLogo($request->getUserVar('sharingLogo'));
			$rt->setSharingLogoBackground($request->getUserVar('sharingLogoBackground'));
			$rt->setSharingLogoColor($request->getUserVar('sharingLogoColor'));

			$rtDao->updateJournalRT($rt);
		}
		$request->redirect(null, $request->getRequestedPage());
	}
}

?>


text:
<?php

/**
 * ECSHOP Flow related to language file
 * ============================================================================
 * All right reserved (C) 2005-2011 Beijing Yi Shang Interactive Technology
 * Development Ltd.
 * Web site: http://www.ecshop.com
 * ----------------------------------------------------------------------------
 * This is a free/open source software;it means that you can modify, use and
 * republish the program code, on the premise of that your behavior is not for
 * commercial purposes.
 * ============================================================================
 * $Author: liubo $
 * $Id: shopping_flow.php 17217 2011-01-19 06:29:08Z liubo $
*/

$_LANG['flow_login_register']['username_not_null'] = 'Please enter username.';
$_LANG['flow_login_register']['username_invalid'] = 'Please enter a valid username.';
$_LANG['flow_login_register']['password_not_null'] = 'Please enter password.';
$_LANG['flow_login_register']['email_not_null'] = 'Please enter email address.';
$_LANG['flow_login_register']['email_invalid'] = 'Please enter a valid email address.';
$_LANG['flow_login_register']['password_not_same'] = 'Re-enter password.';
$_LANG['flow_login_register']['password_lt_six'] = 'Please enter password more than six charactor.';

$_LANG['regist_success'] = "Congratulations! %s register successfully!";
$_LANG['login_success'] = 'Congratulations! Login successfully!';

/* 购物车 */
$_LANG['update_cart'] = 'Update the cart';
$_LANG['back_to_cart'] = 'Back to the cart';
$_LANG['update_cart_notice'] = 'Update successfully, please choose the gift again.';
$_LANG['direct_shopping'] = 'I don\'t plan to login, directly purchase.';
$_LANG['goods_not_exists'] = 'Sorry, the product is nonexistence.';
$_LANG['drop_goods_confirm'] = 'Are you sure remove it from the cart?';
$_LANG['goods_number_not_int'] = 'Please enter a valid number.';
$_LANG['stock_insufficiency'] = 'Sorry, the stocks of products %s only %d, you can buy %d largest.';
$_LANG['package_stock_insufficiency'] = 'Sorry, the stocks of packages is not enough, please reduce the number of the package or inform of the seller.';
$_LANG['shopping_flow'] = 'Shopping flow';
$_LANG['username_exists'] = 'The username already exists, please enter another one and try it again.';
$_LANG['email_exists'] = 'The email address already exists, please enter another one and try it again.';
$_LANG['surplus_not_enough'] = 'Your balance is not enough.';
$_LANG['integral_not_enough'] = 'Your points is not enough.';
$_LANG['integral_too_much'] = "The points of your used can\'t more than %d.";
$_LANG['invalid_bonus'] = "he bonus is nonexistent.";
$_LANG['no_goods_in_cart'] = 'There is blank in your cart!';
$_LANG['not_submit_order'] = 'The order of associates have submitted, please don\'t do it again!';
$_LANG['pay_success'] = 'Paid successfully, it is imperative that we make a quick shipping for you.';
$_LANG['pay_fail'] = 'Paid failed, please contact with us timely.';
$_LANG['pay_disabled'] = 'The payment mode have disconnected.';
$_LANG['pay_invalid'] = 'The payment mode is invalid. Please contact with us timely.';
$_LANG['flow_no_shipping'] = 'Select one shipping method.';
$_LANG['flow_no_payment'] = 'Please select a payment mode!';
$_LANG['pay_not_exist'] = 'The payment mode is nonexistence.';
$_LANG['storage_short'] = 'Out of stock';
$_LANG['subtotal'] = 'Subtotal';
$_LANG['accessories'] = 'Accessories';
$_LANG['largess'] = 'Largess';
$_LANG['shopping_money'] = 'Subtotal %s';
$_LANG['than_market_price'] = 'Market price is %s, you save %s (%s). ';
$_LANG['your_discount'] = 'Your discount is %s';
$_LANG['no'] = 'No';
$_LANG['not_support_virtual_goods'] = 'There is(are) virtual product(s), it is not support purchase without login, please login validly.';
$_LANG['not_support_insure'] = 'No support insure.';
$_LANG['clear_cart'] = 'Clear the cart.';
$_LANG['drop_to_collect'] = 'Drop to collect.';
$_LANG['password_js']['show_div_text'] = 'Please Update Cart';
$_LANG['password_js']['show_div_exit'] = 'Close';
$_LANG['goods_fittings'] = 'Goods Fittings';
$_LANG['parent_name'] = 'Goods Releate:';
$_LANG['remark_package'] = 'Preferential Packeage';

/* 优惠活动 */
$_LANG['favourable_name'] = 'Favourable name:';
$_LANG['favourable_period'] = 'Favourable period:';
$_LANG['favourable_range'] = 'Favourable range:';
$_LANG['far_ext'][FAR_ALL] = 'All products';
$_LANG['far_ext'][FAR_BRAND] = 'Following brand';
$_LANG['far_ext'][FAR_CATEGORY] = 'Following category';
$_LANG['far_ext'][FAR_GOODS] = 'Following goods';
$_LANG['favourable_amount'] = 'Favourable amount:';
$_LANG['favourable_type'] = 'Favourable type:';
$_LANG['fat_ext'][FAT_DISCOUNT] = 'Enjoy %d%% discount';
$_LANG['fat_ext'][FAT_GOODS] = 'Select %d from the following gifts (0 indicates no limitation to quantity)';
$_LANG['fat_ext'][FAT_PRICE] = 'Price reduced by %d';

$_LANG['favourable_not_exist'] = 'Favourable is nonexistence';
$_LANG['favourable_not_available'] = 'Favourable is nonexistence';
$_LANG['favourable_used'] = 'Favourable is used';
$_LANG['pls_select_gift'] = 'Please select gift';
$_LANG['gift_count_exceed'] = 'Gift quantity selected is maximizing';
$_LANG['gift_in_cart'] = 'Gift in the cart: %s';
$_LANG['label_favourable'] = 'Favourable';
$_LANG['label_collection'] = 'Collection';
$_LANG['collect_to_flow'] = 'Buy';

/* 登录注册 */
$_LANG['forthwith_login'] = 'Login';
$_LANG['forthwith_register'] = 'Register';
$_LANG['signin_failed'] = 'Soory, login failure, please check your username and password.';
$_LANG['gift_remainder'] = 'Note: please select gift again after login or registering.';

/* 收货人信息 */
$_LANG['flow_js']['consignee_not_null'] = 'Please enter name of consignee!';
$_LANG['flow_js']['country_not_null'] = 'Please select a country of consignee!';
$_LANG['flow_js']['province_not_null'] = 'Please select a province of consignee!';
$_LANG['flow_js']['city_not_null'] = 'Please select a city of consignee!';
$_LANG['flow_js']['district_not_null'] = 'Please select a district of consignee!';
$_LANG['flow_js']['invalid_email'] = 'Please enter a valid email address.';
$_LANG['flow_js']['address_not_null'] = 'Please enter an address!';
$_LANG['flow_js']['tele_not_null'] = 'Please enter a phone number!';
$_LANG['flow_js']['shipping_not_null'] = 'Please select a shipping method!';
$_LANG['flow_js']['payment_not_null'] = 'Please select a payment mode!';
$_LANG['flow_js']['goodsattr_style'] = 1;
$_LANG['flow_js']['tele_invaild'] = 'Please enter valid phone No.';
$_LANG['flow_js']['zip_not_num'] = 'Zip code should be numbers';
$_LANG['flow_js']['mobile_invaild'] = 'Mobile No. is invalid';

$_LANG['new_consignee_address'] = 'New consignee address';
$_LANG['consignee_address'] = 'Address';
$_LANG['consignee_name'] = 'Name';
$_LANG['country_province'] = 'Country/Province';
$_LANG['please_select'] = 'Please select...';
$_LANG['city_district'] = 'City/District';
$_LANG['email_address'] = 'Email';
$_LANG['detailed_address'] = 'Address';
$_LANG['postalcode'] = 'Postalcode';
$_LANG['phone'] = 'Phone';
$_LANG['mobile'] = 'Mobile';
$_LANG['backup_phone'] = 'Mobile';
$_LANG['sign_building'] = 'Sign building';
$_LANG['deliver_goods_time'] = 'Optimal shipping time';
$_LANG['default'] = 'Default';
$_LANG['default_address'] = 'Default address';
$_LANG['confirm_submit'] = 'Submit';
$_LANG['confirm_edit'] = 'Submit';
$_LANG['country'] = 'Country';
$_LANG['province'] = 'Province';
$_LANG['city'] = 'City';
$_LANG['area'] = 'Area';
$_LANG['consignee_add'] = 'Add a new consignee.';
$_LANG['shipping_address'] = 'Shipping according to this address.';
$_LANG['address_amount'] = 'The place of receipt should be less than three.';
$_LANG['not_fount_consignee'] = 'Sorry, the place of receipt is nonexistence.';

/*------------------------------------------------------ */
//-- 订单提交
/*------------------------------------------------------ */

$_LANG['goods_amount_not_enough'] = 'Goods amount is less than the minimum amount %s required, order cannot be submited.';
$_LANG['balance_not_enough'] = 'Your balance is not enough, please select another paymen mode';
$_LANG['select_shipping'] = 'Your select shipping method is';
$_LANG['select_payment'] = 'Your select payment mode is';
$_LANG['order_amount'] = 'Your order money is';
$_LANG['remember_order_number'] = 'Thanks for your shopping! Your order have submitted, please remember your order numbers.';
$_LANG['back_home'] = 'Back to home';
$_LANG['goto_user_center'] = 'Member center';
$_LANG['order_submit_back'] = 'You can %s or go to %s';

$_LANG['order_placed_sms'] = "You has a new order.Consignee:%s Phone:%s";
$_LANG['sms_paid'] = 'Paid';

$_LANG['notice_gb_order_amount'] = '((Remarks: If associates with insurance, the insurance and corresponding pay need to be paid in first payment.)';

$_LANG['pay_order'] = 'Pay order %s';
$_LANG['validate_bonus'] = 'Vadidate bonus';
$_LANG['input_bonus_no'] = 'Input bonus No.';
$_LANG['select_bonus'] = 'Select existing bonus';
$_LANG['bonus_sn_error'] = 'Please enter valid bonus No.';
$_LANG['bonus_min_amount_error'] = 'Order amount is less than the minimum amount of bonus %s';
$_LANG['bonus_is_ok'] = 'Bonus No. is avaible, can be used as %s';

$_LANG['shopping_myship'] = 'My shipping';
$_LANG['shopping_activity'] = 'Activity list';
$_LANG['shopping_package'] = 'Package list';
?>


text:
// ========================================================================
// Copyright (c) 2006-2011 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.osgi.annotations;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jetty.annotations.ClassNameResolver;
import org.eclipse.jetty.osgi.boot.OSGiWebappConstants;
import org.eclipse.jetty.osgi.boot.utils.internal.PackageAdminServiceTracker;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.DiscoveredAnnotation;
import org.eclipse.jetty.webapp.WebAppContext;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;

/**
 * Extend the AnnotationConfiguration to support OSGi:
 * Look for annotations inside WEB-INF/lib and also in the fragments and required bundles.
 * Discover them using a scanner adapted to OSGi instead of the jarscanner.
 */
public class AnnotationConfiguration extends org.eclipse.jetty.annotations.AnnotationConfiguration
{

    /**
     * This parser scans the bundles using the OSGi APIs instead of assuming a jar.
     */
    @Override
    protected org.eclipse.jetty.annotations.AnnotationParser createAnnotationParser()
    {
        return new AnnotationParser();
    }

    /**
     * Here is the order in which jars and osgi artifacts are scanned for discoverable annotations.
     *

     *
The container jars are scanned.

     *
The WEB-INF/classes are scanned

     *
The osgi fragment to the web bundle are parsed.

     *
The WEB-INF/lib are scanned

     *
The required bundles are parsed

     *

     */
    @Override
    public void parseWebInfLib (WebAppContext context, org.eclipse.jetty.annotations.AnnotationParser parser)
    throws Exception
    {
        AnnotationParser oparser = (AnnotationParser)parser;

        Bundle webbundle = (Bundle) context.getAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE);
        Bundle[] fragAndRequiredBundles = PackageAdminServiceTracker.INSTANCE.getFragmentsAndRequiredBundles(webbundle);
        if (fragAndRequiredBundles != null)
        {
            //index:
            for (Bundle bundle : fragAndRequiredBundles)
            {
                Resource bundleRes = oparser.indexBundle(bundle);
                if (!context.getMetaData().getWebInfJars().contains(bundleRes))
                {
                    context.getMetaData().addWebInfJar(bundleRes);
                }
            }

            //scan the fragments
            for (Bundle fragmentBundle : fragAndRequiredBundles)
            {
                if (fragmentBundle.getHeaders().get(Constants.FRAGMENT_HOST) != null)
                {
                    //a fragment indeed:
                    parseFragmentBundle(context,oparser,webbundle,fragmentBundle);
                }
            }
        }
        //scan ourselves
        parseWebBundle(context,oparser,webbundle);

        //scan the WEB-INF/lib
        super.parseWebInfLib(context,parser);
        if (fragAndRequiredBundles != null)
        {
            //scan the required bundles
            for (Bundle requiredBundle : fragAndRequiredBundles)
            {
                if (requiredBundle.getHeaders().get(Constants.FRAGMENT_HOST) == null)
                {
                    //a bundle indeed:
                    parseRequiredBundle(context,oparser,webbundle,requiredBundle);
                }
            }
        }
    }

    /**
     * Scan a fragment bundle for servlet annotations
     * @param context The webapp context
     * @param parser The parser
     * @param webbundle The current webbundle
     * @param fragmentBundle The OSGi fragment bundle to scan
     * @throws Exception
     */
    protected void parseFragmentBundle(WebAppContext context, AnnotationParser parser,
            Bundle webbundle, Bundle fragmentBundle) throws Exception
    {
        parseBundle(context,parser,webbundle,fragmentBundle);
    }

    /**
     * Scan a bundle required by the webbundle for servlet annotations
     * @param context The webapp context
     * @param parser The parser
     * @param webbundle The current webbundle
     * @param fragmentBundle The OSGi required bundle to scan
     * @throws Exception
     */
    protected void parseWebBundle(WebAppContext context, AnnotationParser parser, Bundle webbundle)
    throws Exception
    {
        parseBundle(context,parser,webbundle,webbundle);
    }

    /**
     * Scan a bundle required by the webbundle for servlet annotations
     * @param context The webapp context
     * @param parser The parser
     * @param webbundle The current webbundle
     * @param fragmentBundle The OSGi required bundle to scan
     * @throws Exception
     */
    protected void parseRequiredBundle(WebAppContext context, AnnotationParser parser,
            Bundle webbundle, Bundle requiredBundle) throws Exception
    {
        parseBundle(context,parser,webbundle,requiredBundle);
    }

    protected void parseBundle(WebAppContext context, AnnotationParser parser,
            Bundle webbundle, Bundle bundle) throws Exception
    {
        Resource bundleRes = parser.getResource(bundle);
        parser.parse(bundle,createClassNameResolver(context));
        List<DiscoveredAnnotation> annotations = new ArrayList<DiscoveredAnnotation>();
        gatherAnnotations(annotations, parser.getAnnotationHandlers());
        if (webbundle == bundle)
        {
            //just like the super with its question about annotations in WEB-INF/classes:
            //"TODO - where to set the annotations discovered from WEB-INF/classes?"
            context.getMetaData().addDiscoveredAnnotations(annotations);
        }
        else
        {
            context.getMetaData().addDiscoveredAnnotations(bundleRes, annotations);
        }
    }

    /**
     * Returns the same classname resolver than for the webInfjar scanner
     * @param context
     * @return
     */
    protected ClassNameResolver createClassNameResolver(final WebAppContext context)
    {
        return createClassNameResolver(context,true,false,false,false);
    }

    protected ClassNameResolver createClassNameResolver(final WebAppContext context,
            final boolean excludeSysClass, final boolean excludeServerClass, final boolean excludeEverythingElse,
            final boolean overrideIsParenLoaderIsPriority)
    {
        return new ClassNameResolver ()
        {
            public boolean isExcluded (String name)
            {
                if (context.isSystemClass(name)) return excludeSysClass;
                if (context.isServerClass(name)) return excludeServerClass;
                return excludeEverythingElse;
            }

            public boolean shouldOverride (String name)
            {
                //looking at system classpath
                if (context.isParentLoaderPriority())
                    return overrideIsParenLoaderIsPriority;
                return !overrideIsParenLoaderIsPriority;
            }
        };
    }

}


text:
static Window *s_main_window;
static TextLayer *s_time_layer;

static int s_interval = 0;
static int s_step = 1;

static bool is_countdown_started = false;
static int s_timer = 0;

static void update_time(int value) {
  static char buffer[] = "00:00";

  int minutes = value / 60;
  int seconds = value - 60 * minutes;

  snprintf(buffer, sizeof(buffer), "%02d:%02d", minutes, seconds);

  text_layer_set_text(s_time_layer, buffer);
}

int calculate_step(uint8_t x) {
  if (x > 15) return 15;
  if (x > 10) return 10;
  if (x > 5) return 5;

  return 1;
}

int calculate_interval(int interval, int step) {
  if (step == 1) {
    return interval;
  }

  return interval / step * step;
}

void change_time_click_handler(ClickRecognizerRef recognizer, int flag) {
  s_step = calculate_step(click_number_of_clicks_counted(recognizer));
  s_interval = calculate_interval(s_interval, s_step) + flag * s_step;

  if (s_interval > 59*60 + 59) {
    s_interval = 0;
  } else if (s_interval < 0) {
    s_interval = 59*60 + 59;
  }

  update_time(s_interval);
}

void down_single_click_handler(ClickRecognizerRef recognizer, void *c) {
  change_time_click_handler(recognizer, -1);
}

void up_single_click_handler(ClickRecognizerRef recognizer, void *c) {
  change_time_click_handler(recognizer, 1);
}

void vibe_end() {
  static const uint32_t const segments[] = { 500, 300, 500, 300, 500 };
    VibePattern pattern = {
      .durations = segments,
      .num_segments = ARRAY_LENGTH(segments),
    };
    vibes_enqueue_custom_pattern(pattern);
}

void stop_timer() {
  is_countdown_started = false;
  tick_timer_service_unsubscribe();
  update_time(s_interval);
}

void tick_handler(struct tm *tick_time, TimeUnits units_changed) {
  s_timer -= 1;

  if (s_timer) {
    update_time(s_timer);
  } else {
    vibe_end();
    stop_timer();
  }
}

void start_timer() {
  is_countdown_started = true;
  s_timer = s_interval;
  tick_timer_service_subscribe(SECOND_UNIT, tick_handler);
}

void select_single_click_handler(ClickRecognizerRef recognizer, void *c) {
  if (is_countdown_started) {
    vibes_short_pulse();
    stop_timer();
  } else {
    if (s_interval != 0) start_timer();
  }
}

void config_provider(Window *window) {
  window_single_repeating_click_subscribe(
    BUTTON_ID_DOWN,
    300,
    down_single_click_handler
  );

  window_single_repeating_click_subscribe(
    BUTTON_ID_UP,
    300,
    up_single_click_handler
  );

  window_single_click_subscribe(
    BUTTON_ID_SELECT,
    select_single_click_handler
  );
}

static void main_window_load(Window *window) {
  s_time_layer = text_layer_create(GRect(0, 46, 144, 50));

  text_layer_set_background_color(s_time_layer, GColorClear);
  text_layer_set_text_color(s_time_layer, GColorBlack);

  text_layer_set_font(
    s_time_layer,
    fonts_get_system_font(FONT_KEY_BITHAM_42_MEDIUM_NUMBERS)
  );

  text_layer_set_text_alignment(s_time_layer, GTextAlignmentCenter);

  layer_add_child(
    window_get_root_layer(window),
    text_layer_get_layer(s_time_layer)
  );

  update_time(s_interval);
}

static void main_window_unload(Window *window) {
  text_layer_destroy(s_time_layer);
}

static void init() {
  s_main_window = window_create();

  window_set_window_handlers(s_main_window, (WindowHandlers) {
    .load = main_window_load,
    .unload = main_window_unload
  });

  window_set_click_config_provider(
    s_main_window,
    (ClickConfigProvider) config_provider
  );

  window_stack_push(s_main_window, true);
}

static void destroy() {
  window_destroy(s_main_window);
}

int main(void) {
  init();
  app_event_loop();
  destroy();
}


text:
<!DOCTYPE html>

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

<title>Standardize theme & color scheme for VPBank — theme_vpbank • VPBank</title>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">

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

<meta property="og:title" content="Standardize theme & color scheme for VPBank — theme_vpbank" />

<meta property="og:description" content="Quickly change theme, color &amp; fill scheme,
adding caption to ggplot2 chart. This function is to help
Analytics team to standardize all charts for Analytics projects" />
<meta name="twitter:card" content="summary" />

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">

      </button>

        VPBank
        1.1

  Reference

    Articles

      Automate DEA analysis with `compare_group` & `map`

  Changelog

Standardize theme & color scheme for VPBank

theme_vpbank.Rd

Quickly change theme, color & fill scheme,
adding caption to ggplot2 chart. This function is to help
Analytics team to standardize all charts for Analytics projects

theme_vpbank(discrete = T, facet = F,
  caption = "Source: BICC - Advanced Analytics team", legend_row = 1)

Arguments

    <colgroup><col class="name" /><col class="desc" /></colgroup>

      discrete

- T or F with default is TRUE. If TRUE, color scheme will be
discrete, otherwise will be continuos

      facet

- F or T with default is F. If T, set border of plot as in
theme_bw

      caption

- Caption of the plot.
Default is "Source: BICC - Advanced Analytics team". Set *caption = NULL* to
remove caption

      legend_row

- default is 1. Set row number of legend

Value

Return a plot with standardized theme and color

Examples

#Example 1: For scatter plot
iris %>%
 ggplot(aes(Sepal.Length, Sepal.Width)) +
 geom_point(aes(col = Species)) +
 theme_vpbank(facet = T, discrete = T) +
 facet_wrap(~Species)

#Example 2: For bar plot
mtcars %>%
 ggplot(aes(factor(carb), hp)) +
 geom_col(aes(fill = factor(carb))) +
 theme_vpbank(facet = T) +
 facet_wrap(~am)

mtcars %>%
 ggplot(aes(factor(carb), hp)) +
 geom_col(aes(fill = factor(carb))) +
 theme_vpbank(legend_row = 2) +
 coord_flip()

iris %>%
 ggplot(aes(Species, Sepal.Length)) +
 geom_bar(aes(fill = Species), stat = "identity") +
 labs(title="Sepal Length by Species") +
 theme_vpbank()

#Example 3: For line plot
data.frame(id = 1:100,
          group1 = rnorm(100,2,0.5),
          group2 = rnorm(100,3.5,2)) %>%
 reshape2::melt(id.vars = "id") %>%
 ggplot(aes(id, value)) +
 geom_line(aes(col = variable)) +
 geom_point(aes(col = variable)) +
 theme_vpbank()

#Example 4: For boxplot
iris %>%
 ggplot(aes(Species, Sepal.Length)) +
 geom_boxplot(aes(fill = Species)) +
 theme_vpbank()

#Example 5: For continuous color
faithfuld %>%
 mutate(group = ifelse(eruptions > 3, "high", "low")) %>%
 ggplot(aes(waiting, eruptions)) +
 geom_raster(aes(fill = density)) +
 theme_vpbank(discrete = F, caption = NULL)

Contents

Arguments

Value

Examples

Author

Anh Hoang Duc (anhhd3@vpbank.com.vn)

Developed by Anh Hoang Duc.

Site built with pkgdown.


text:
module.exports = {
		Thematic: require('./thematic'),
		modules: {
			'IModule': require('imodule'),
			'Dasymetric': require('thematic-dot-choropleth'),
			'Choropleth': require('thematic-choropleth'),
			'Dot': require('thematic-dot'),
			'Heatmap': require('thematic-heatmap'),
			'Isarithmic': require('thematic-dot-choropleth')
		},
		converters: require('converters'),
		aggregators: {
			average: require('average-aggregator'),
			separateValues: require('separate-values-aggregator')
		},
		utils: {
			PromisePure: require('promise-sync')
		}
	};


text:
/* medea.js - Open Source, High-Performance 3D Engine based on WebGL.
 *
 * (c) 2011-2013, Alexander C. Gessler
 *  https://github.com/acgessler/medea.js
 *
 * Made available under the terms and conditions of a 3-clause BSD license.
 *
 */

medealib.define('simpleanim',['entity'],function(medealib, undefined) {
	"use strict";
	var medea = this;

	var FromToAnimator = medea.Entity.extend(
	{

		finished_clb : null,

		init : function(from, to, duration, auto_unadd) {
			this.from = from;
			this.to = to;
			this.duration = duration;
			this.auto_unadd = auto_unadd;
		},

		Render : function(viewport,entity,node,rqmanager) {
			// nothing to be done
		},

		Update : function(dtime,node) {
			if (this.finished) {
				if(this.auto_unadd) {
					node.RemoveEntity(this);
					return medea.ENTITY_UPDATE_WAS_REMOVED;
				}
				return;
			}

			if(this.time === undefined) {
				this.time = 0.0;
			}

			this.time += dtime;
			if(this.time > this.duration) {
				// ensure proper end position
				node.LocalPos(this.to);
				this.Finished(true);
				return;
			}

			var fraction = this.time / this.duration;
			var position = [this.from[0],this.from[1],this.from[2]];

			position[0] += (this.to[0] - this.from[0]) * fraction;
			position[1] += (this.to[1] - this.from[1]) * fraction;
			position[2] += (this.to[2] - this.from[2]) * fraction;

			node.LocalPos(position);
		},

		Finished : function(h) {
			if (h === undefined) {
				return this.finished;
			}
			this.finished = h;
			if(h && this.finished_clb != null) {
				this.finished_clb(this);
			}
		},

		FinishingCallback : function(c) {
			if (c === undefined) {
				return this.finished_clb;
			}
			this.finished_clb = c;
		}
	});

	medea.CreateFromToAnimator = function(from, to, duration, auto_unadd) {
		return new FromToAnimator (from, to, duration, auto_unadd);
	};
});


text:
from oslo_utils import importutils

from heat.engine.clients import client_plugin

mistral_base = importutils.try_import('mistralclient.api.base')
mistral_client = importutils.try_import('mistralclient.api.client')

class MistralClientPlugin(client_plugin.ClientPlugin):

    service_types = [WORKFLOW_V2] = ['workflowv2']

    @staticmethod
    def is_available():
        return mistral_base is not None

    def _create(self):
        endpoint_type = self._get_client_option('mistral', 'endpoint_type')
        endpoint = self.url_for(service_type=self.WORKFLOW_V2,
                                endpoint_type=endpoint_type)

        args = {
            'mistral_url': endpoint,
            'auth_token': self.auth_token
        }

        client = mistral_client.client(**args)
        return client

    def is_not_found(self, ex):
        return (isinstance(ex, mistral_base.APIException) and
                ex.error_code == 404)

    def is_over_limit(self, ex):
        return (isinstance(ex, mistral_base.APIException) and
                ex.error_code == 413)

    def is_conflict(self, ex):
        return (isinstance(ex, mistral_base.APIException) and
                ex.error_code == 409)


text:
#include "loengine.h"
#include "rsurface.h"

#include "LETypes.h"
#include "LEFontInstance.h"
#include "RenderingSurface.h"

U_CDECL_BEGIN

void rs_drawGlyphs(rs_surface *surface, const le_font *font, const LEGlyphID *glyphs, le_int32 count,
                   const float *positions, le_int32 x, le_int32 y, le_int32 width, le_int32 height)
{
    RenderingSurface *rs = (RenderingSurface *) surface;

    rs->drawGlyphs((const LEFontInstance *) font, glyphs, count, positions, x, y, width, height);
}

U_CDECL_END


text: jira in docker container with best practice


text:
require 'rails_helper'
require 'csv'

RSpec.describe ConferenceImporter, type: :service do
  describe "#call" do
    # 6 sample conferences in test.csv, 4 valid
    # valid: 2017001, 2017002, *2018*005 and 2017006 .
    # invalid: 2017003: no name, 2017004: start date later than end date

    let!(:file) { "spec/fixtures/files/test.csv" }

    subject { described_class.call(file, content_type: content_type) }

    context 'with valid file' do
      let(:content_type) { 'text/csv' }

      it 'imports the valid conferences' do
        expect { subject }.to change { Conference.count }.from(0).to(4)
      end

      it 'updates an existing conference' do
        create(:conference, gid: 2017001, city: "Bangalore", country: "Belgium")

        expect { subject }.to change { Conference.find_by(gid: 2017001).city }.from("Bangalore").to("Gent")
        expect { subject }.not_to change { Conference.find_by(gid: 2017001).country }
      end

      it 'neglects a conference without a name' do
        # gid 2017003
        expect { subject }.not_to change { Conference.find_by(gid: 2017003) }
      end

      it 'does not add a conference with invalid dates' do
        # gid 2017004 has an start_date later than end_date
        expect { subject }.not_to change { Conference.find_by(gid: 2017004) }
      end

      it "will not destroy conferences" do
        # gid 2017010 is not in the .csv file
        create(:conference, gid: 2017010)
        expect { subject }.not_to change { Conference.find_by(gid: 2017010) }
      end

      it 'assign the season_id' do
        create(:conference, gid: 2017001, season_id: nil)
        create(:conference, gid: 2018005, season_id: nil)
        s_2017 = create(:season, name: "2017")
        s_2018 = create(:season, name: "2018")

        expect { subject }.to change { Conference.find_by(gid: 2017001).season_id }.to(s_2017.id)
        expect(Conference.find_by(gid: 2018005).season_id).to eq s_2018.id
      end
    end

    context 'with non-csv file' do
      let(:content_type) { 'application/json' }

      it 'raises an error with other mime_type' do
        expect { subject }.to raise_error ArgumentError
      end
    end
  end
end


text:
#nullable enable

using Snittlistan.Queue.Messages;
using Snittlistan.Web.Areas.V2.Domain;
using Snittlistan.Web.Areas.V2.Queries;
using Snittlistan.Web.Infrastructure;
using Snittlistan.Web.Models;

namespace Snittlistan.Web.Commands;

public class RegisterMatchesCommandHandler : CommandHandler<RegisterMatchesCommandHandler.Command>
{
    public override Task Handle(HandlerContext<Command> context)
    {
        WebsiteConfig websiteConfig = CompositionRoot.DocumentSession.Load<WebsiteConfig>(WebsiteConfig.GlobalId);
        Roster[] pendingMatches = ExecuteQuery(new GetPendingMatchesQuery(websiteConfig.SeasonId));
        foreach (Roster pendingMatch in pendingMatches.Where(x => x.SkipRegistration == false))
        {
            context.PublishMessage(new RegisterPendingMatchTask(pendingMatch.Id!, pendingMatch.BitsMatchId));
        }

        return Task.CompletedTask;
    }

    public record Command();
}


text:
package com.intellij.java.codeInsight.daemon.quickFix;

import com.intellij.codeInsight.daemon.quickFix.LightQuickFixTestCase;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull;

/**
 * @author ven
 */
public class CreateFieldFromUsageTest extends LightQuickFixTestCase {

  public void testAnonymousClass() throws Exception { doSingleTest(); }
  public void testExpectedTypes() throws Exception { doSingleTest(); }
  public void testInterface() throws Exception { doSingleTest(); }
  public void testMultipleTypes() throws Exception { doSingleTest(); }
  public void testMultipleTypes2() throws Exception { doSingleTest(); }
  public void testParametericMethod() throws Exception { doSingleTest(); }
  public void testQualifyInner() throws Exception { doSingleTest(); }
  public void testTypeArgsFormatted() throws Exception { doSingleTest(); }
  public void testInsideStaticInnerClass() throws Exception { doSingleTest(); }
  public void testCreateFromEquals() throws Exception { doSingleTest(); }
  public void testCreateFromEqualsToPrimitiveType() throws Exception { doSingleTest(); }
  public void testInsideInterface() throws Exception { doSingleTest(); }
  public void testWithAlignment() throws Exception {
    final CommonCodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject()).getCommonSettings(JavaLanguage.INSTANCE);
    boolean old = settings.ALIGN_GROUP_FIELD_DECLARATIONS;
    try {
      settings.ALIGN_GROUP_FIELD_DECLARATIONS = true;
      doSingleTest();
    }
    finally {
      settings.ALIGN_GROUP_FIELD_DECLARATIONS = old;
    }
  }

  public void testSortByRelevance() throws Exception {
    new WriteCommandAction(getProject()) {
      @Override
      protected void run(@NotNull Result result) throws Exception {
        VirtualFile foo = getSourceRoot().createChildDirectory(this, "foo").createChildData(this, "Foo.java");
        VfsUtil.saveText(foo, "package foo; public class Foo { public void put(Object key, Object value) {} }");
        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
      }
    }.execute();
    PsiClass aClass = JavaPsiFacade.getInstance(getProject()).findClass("foo.Foo", GlobalSearchScope.allScope(getProject()));
    assertNotNull(aClass);
    doSingleTest();
  }

  public void testDependantConstant() throws Exception {
    doSingleTest();
  }

  public void testArrayBraces() throws Exception {
    doSingleTest();
  }

  protected void doSingleTest() {
    doSingleTest(getTestName(false) + ".java");
  }

  @Override
  protected String getBasePath() {
    return "/codeInsight/daemonCodeAnalyzer/quickFix/createFieldFromUsage";
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
EntityControlledVocabularyType.Type.Enum (MIM API 1.0)
</TITLE>

<META NAME="date" CONTENT="2011-08-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

gov.nih.nci.lmp.mim.mimVisLevel1

Class EntityControlledVocabularyType.Type.Enum

java.lang.Object
  org.apache.xmlbeans.StringEnumAbstractBase
      gov.nih.nci.lmp.mim.mimVisLevel1.EntityControlledVocabularyType.Type.Enum

All Implemented Interfaces:
java.io.Serializable

Enclosing interface:
EntityControlledVocabularyType.Type

public static final class EntityControlledVocabularyType.Type.Enum
extends org.apache.xmlbeans.StringEnumAbstractBase

Enumeration value class for gov.nih.nci.lmp.mim.mimVisLevel1.EntityControlledVocabularyType$Type.
 These enum values can be used as follows:

 enum.toString(); // returns the string value of the enum
 enum.intValue(); // returns an int value, useful for switches
 // e.g., case Enum.INT_COMPLEX
 Enum.forString(s); // returns the enum value for a string
 Enum.forInt(i); // returns the enum value for an int

 Enumeration objects are immutable singleton objects that
 can be compared using == object equality. They have no
 public constructor. See the constants defined within this
 class for all the valid values.

See Also:
Serialized Form

Nested Class Summary

Nested classes/interfaces inherited from class org.apache.xmlbeans.StringEnumAbstractBase

org.apache.xmlbeans.StringEnumAbstractBase.Table

Field Summary

static org.apache.xmlbeans.StringEnumAbstractBase.Table
table

Method Summary

static EntityControlledVocabularyType.Type.Enum
forInt(int i)

          Returns the enum value corresponding to an int, or null if none.

static EntityControlledVocabularyType.Type.Enum
forString(java.lang.String s)

          Returns the enum value for a string, or null if none.

Methods inherited from class org.apache.xmlbeans.StringEnumAbstractBase

hashCode, intValue, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

table

public static final org.apache.xmlbeans.StringEnumAbstractBase.Table table

Method Detail

forString

public static EntityControlledVocabularyType.Type.Enum forString(java.lang.String s)

Returns the enum value for a string, or null if none.

forInt

public static EntityControlledVocabularyType.Type.Enum forInt(int i)

Returns the enum value corresponding to an int, or null if none.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
'use strict';

angular
    .module('YouWantFood', [
        'ngRoute',
        'ngSanitize',
        'ngResource',
        'ui.bootstrap'
    ])
    .config(['$sceDelegateProvider', '$routeProvider', '$locationProvider', function($sceDelegateProvider, $routeProvider, $locationProvider) {
        $sceDelegateProvider.resourceUrlWhitelist(['https://projects.zacharyseguin.ca/**']);
        $routeProvider
            .when('/', {
                templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/Home.html',
                controller: 'Home'
            })
            .when('/outlet/:outletId', {
                templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/OutletDetails.html',
                controller: 'OutletDetails'
            })
            .when('/email/subscribe', {
                templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/EmailSubscribe.html',
                controller: 'EmailSubscribe'
            })
            .when('/email/unsubscribe', {
                templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/EmailUnsubscribe.html',
                controller: 'EmailUnsubscribe'
            })
            .when('/email/confirmed', {
                templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/EmailConfirmed.html'
            })
            .when('/email/confirmation-error', {
                templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/EmailConfirmationError.html'
            })
            .when('/error', {
                templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/Error.html'
            })
            .otherwise({
                templateUrl: 'https://projects.zacharyseguin.ca/you-want-food/views/NotFound.html'
            });
         $locationProvider.html5Mode(true);
    }]);