text:
/**
 * Created by daniel.joppi on 12/4/14.
 */

module.exports = function(router, db) {
    var mongo = require('mongodb');
    var Grid = require('gridfs-stream');

    var gfs = Grid(db, mongo);

    // upload image
    router.post('/image', function (req, res) {
        var data = req.body;
        try {
            var stream = gfs.createWriteStream({
                filename: data.filename,
                contentType: data.type
            });
            req.pipe(stream);
            res.statusCode = 200;
            res.send(stream);
        } catch(e) {
            res.statusCode = 500;
        }
    });

    // get image to url
    router.get('/image/:id', function (req, res) {
        var stream = gfs.createReadStream({
            _id: req.params.id
        });
        //error handling, e.g. file does not exist
        stream.on('error', function (err) {
            console.log('An error occurred!', err);
            throw err;
        });

        res.header("Content-Type", stream.contentType);
        res.setHeader('Cache-Control', 'no-cache');
        try {
            stream.pipe(res);
        } catch(e) {
            res.statusCode = 500;
        }
    });
};

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import

# The bundled version of PyWordNet has custom fixes.
# - line  365: check if lexnames exist.
# - line  765: check if lexnames exist + use os.path.join().
# - line  674: add HYPONYM and HYPERNYM to the pointer table.
# - line  916: implement "x in Dictionary" instead of Dictionary.has_key(x)
# - line  804: Dictionary.dataFile now stores a list of (file, size)-tuples.
# - line 1134: _dataFilePath() returns a list (i.e., data.noun can be split into data.noun1 + data.noun2).
# - line 1186: _lineAt() seeks in second datafile if offset > EOF first datafile.

# Note that pywordnet has been included in nltk upstream
# TODO ensure these are fixed upstream (so we can use that?

import codecs  # TODO use this exclusively for opening?
import os
import sys
import glob

from math import log

try:
    MODULE = os.path.dirname(os.path.realpath(__file__))
except:
    MODULE = ""

# Path to WordNet /dict folder.
CORPUS = ""
os.environ["WNHOME"] = os.path.join(MODULE, CORPUS)
os.environ["WNSEARCHDIR"] = os.path.join(MODULE, CORPUS, "dict")

# This requires use of ENV variables (set above)
from .pywordnet import wordnet as wn
from .pywordnet import wntools

try:
    basestring
except NameError: # python 3
    basestring = str
    unicode = str

VERSION = ""
s = open(os.path.join(MODULE, CORPUS, "dict", "index.noun")).read(2048)
if "WordNet 2.1" in s:
    VERSION = "2.1"
if "WordNet 3.0" in s:
    VERSION = "3.0"
del s

#-------------------------------------------------------------------------

DIACRITICS = {
    "a": ("á", "ä", "â", "à", "å"),
    "e": ("é", "ë", "ê", "è"),
    "i": ("í", "ï", "î", "ì"),
    "o": ("ó", "ö", "ô", "ò", "ō", "ø"),
    "u": ("ú", "ü", "û", "ù", "ů"),
    "y": ("ý", "ÿ", "ý"),
    "s": ("š",),
    "c": ("ç", "č"),
    "n": ("ñ",),
    "z": ("ž",)
}

def normalize(word):
    """Normalizes the word for synsets() or Sentiwordnet[] by removing
    diacritics (PyWordNet does not take unicode)."""
    if not isinstance(word, basestring):
        word = str(word)
    if not isinstance(word, str):
        try:
            word = word.encode("utf-8", "ignore")
        except:
            pass
    for k, v in DIACRITICS.items():
        for v in v:
            word = word.replace(v, k)
    return word

### SYNSET ###############################################################

NOUNS, VERBS, ADJECTIVES, ADVERBS = \
    wn.N, wn.V, wn.ADJ, wn.ADV

NOUN, VERB, ADJECTIVE, ADVERB = \
    NN, VB, JJ, RB = \
    "NN", "VB", "JJ", "RB"

def synsets(word, pos=NOUN):
    """Returns a list of Synset objects, one for each word sense.

    Each word can be understood in different "senses",
    each of which is part of a set of synonyms (= Synset).

    """
    word, pos = normalize(word), pos.lower()
    try:
        if pos.startswith(NOUN.lower()):  # "NNS" or "nn" will also pass.
            w = wn.N[word]
        elif pos.startswith(VERB.lower()):
            w = wn.V[word]
        elif pos.startswith(ADJECTIVE.lower()):
            w = wn.ADJ[word]
        elif pos.startswith(ADVERB.lower()):
            w = wn.ADV[word]
        else:
            raise TypeError(
                "part of speech must be NOUN, VERB, ADJECTIVE or ADVERB, not %s" % repr(pos))
        return [Synset(s.synset) for i, s in enumerate(w)]
    except KeyError:
        return []
    return []

class Synset(object):

    def __init__(self, synset=None, pos=NOUN):
        """A set of synonyms that share a common meaning."""
        if isinstance(synset, int):
            synset = wn.getSynset(
                {NN: "n", VB: "v", JJ: "adj", RB: "adv"}[pos], synset)
        if isinstance(synset, basestring):
            synset = synsets(synset, pos)[0]._synset
        self._synset = synset

    def __iter__(self):
        for s in self._synset.getSenses():
            yield unicode(s.form)

    def __len__(self):
        return len(self._synset.getSenses())

    def __getitem__(self, i):
        return unicode(self._synset.getSenses()[i].form)

    def __eq__(self, synset):
        return isinstance(synset, Synset) and self.id == synset.id

    def __ne__(self, synset):
        return not self.__eq__(synset)

    def __repr__(self):
        return "Synset(%s)" % repr(self[0])

    @property
    def id(self):
        return self._synset.offset

    @property
    def pos(self):
        """ Yields the part-of-speech tag (NOUN, VERB, ADJECTIVE or ADVERB).
        """
        pos = self._synset.pos
        if pos == "noun":
            return NOUN
        if pos == "verb":
            return VERB
        if pos == "adjective":
            return ADJECTIVE
        if pos == "adverb":
            return ADVERB

    part_of_speech = tag = pos

    @property
    def synonyms(self):
        """ Yields a list of word forms (i.e. synonyms), for example:
            synsets("TV")[0].synonyms => ["television", "telecasting", "TV", "video"]
        """
        return [unicode(s.form) for s in self._synset.getSenses()]

    # Backwards compatibility; senses = list of Synsets for a word.
    senses = synonyms

    @property
    def gloss(self):
        """ Yields a descriptive string, for example:
            synsets("glass")[0].gloss => "a brittle transparent solid with irregular atomic structure".
        """
        return unicode(self._synset.gloss)

    @property
    def lexname(self):
        """Yields a category, e.g., noun.animal."""
        return self._synset.lexname and unicode(self._synset.lexname) or None

    @property
    def antonym(self):
        """ Yields the semantically opposite synset, for example:
            synsets("death")[0].antonym => Synset("birth").
        """
        p = self._synset.getPointers(wn.ANTONYM)
        return len(p) > 0 and Synset(p[0].getTarget()) or None

    def meronyms(self):
        """ Yields a list of synsets that are semantic members/parts of this synset, for example:
            synsets("house")[0].meronyms() =>
            [Synset("library"),
             Synset("loft"),
             Synset("porch")
            ]
        """
        p1 = self._synset.getPointers(wn.MEMBER_HOLONYM)
        p2 = self._synset.getPointers(wn.PART_HOLONYM)
        return ([Synset(p.getTarget()) for p in p1] +
                [Synset(p.getTarget()) for p in p2])

    def holonyms(self):
        """ Yields a list of synsets of which this synset is a member/part, for example:
            synsets("tree")[0].holonyms() => Synset("forest").
        """
        p1 = self._synset.getPointers(wn.MEMBER_MERONYM)
        p2 = self._synset.getPointers(wn.PART_MERONYM)
        return ([Synset(p.getTarget()) for p in p1] +
                [Synset(p.getTarget()) for p in p2])

    def hyponyms(self, recursive=False, depth=None):
        """ Yields a list of semantically more specific synsets, for example:
            synsets("train")[0].hyponyms() =>
            [Synset("boat train"),
             Synset("car train"),
             Synset("freight train"),
             Synset("hospital train"),
             Synset("mail train"),
             Synset("passenger train"),
             Synset("streamliner"),
             Synset("subway train")
            ]
        """
        p = [Synset(p.getTarget())
             for p in self._synset.getPointers(wn.HYPONYM)]
        if depth is None and recursive is False:
            return p
        if depth == 0:
            return []
        if depth is not None:
            depth -= 1
        if depth is None or depth > 0:
            [p.extend(s.hyponyms(True, depth)) for s in list(p)]
        return p

    def hypernyms(self, recursive=False, depth=None):
        """Yields a list of semantically broader synsets."""
        p = [Synset(p.getTarget())
             for p in self._synset.getPointers(wn.HYPERNYM)]
        if depth is None and recursive is False:
            return p
        if depth == 0:
            return []
        if depth is not None:
            depth -= 1
        if depth is None or depth > 0:
            [p.extend(s.hypernyms(True, depth)) for s in list(p)]
        return p

    @property
    def hypernym(self):
        """ Yields the synset that is the semantic parent, for example:
            synsets("train")[0].hypernym => Synset("public transport").
        """
        p = self._synset.getPointers(wn.HYPERNYM)
        try:
            first = p[0] if isinstance(p, tuple) else next(p)
            return Synset(first.getTarget())
        except StopIteration:
            return None

    def similar(self):
        """ Returns a list of similar synsets for adjectives and adverbs, for example:
            synsets("almigthy",JJ)[0].similar() => Synset("powerful").
        """
        # ALSO_SEE returns wn.Sense instead of wn.Synset in some cases:
        s = lambda x: isinstance(x, wn.Sense) and x.synset or x
        p = [Synset(s(p.getTarget()))
             for p in self._synset.getPointers(wn.SIMILAR)]
        p += [Synset(s(p.getTarget()))
              for p in self._synset.getPointers(wn.ALSO_SEE)]
        return p

    def similarity(self, synset):
        """ Returns the semantic similarity of the given synsets (0.0-1.0).
            synsets("cat")[0].similarity(synsets("dog")[0]) => 0.86.
            synsets("cat")[0].similarity(synsets("box")[0]) => 0.17.
        """
        if self == synset:
            return 1.0
        try:  # Lin semantic distance measure.
            lin = 2.0 * log(lcs(self, synset).ic) / \
                (log(self.ic * synset.ic) or 1)
        except OverflowError:
            lin = 0.0
        except ValueError:  # / log(0)
            lin = 0.0
        return abs(lin)

    @property
    def ic(self):
        return information_content(self)

    @property
    def weight(self):
        return sentiwordnet is not None \
            and sentiwordnet.synset(self.id, self.pos)[:2] \
            or None

def similarity(synset1, synset2):
    """Returns the semantic similarity of the given synsets."""
    return synset1.similarity(synset2)

def ancestor(synset1, synset2):
    """Returns the common ancestor of both synsets.

    For example synsets("cat")[0].ancestor(synsets("dog")[0]) => Synset("carnivore")

    """
    h1, h2 = synset1.hypernyms(
        recursive=True), synset2.hypernyms(recursive=True)
    for s in h1:
        if s in h2:
            return s

least_common_subsumer = lcs = ancestor

### INFORMATION CONTENT ##################################################
# Information Content (IC) is used to calculate semantic similarity in Synset.similarity().
# Information Content values for each synset are derived from word frequency in a given corpus.
# The idea is that less frequent words convey more information.
# Semantic similarity depends on the amount of information two concepts (synsets) have in common,
# given by the Most Specific Common Abstraction (MSCA), i.e. the shared ancestor in the taxonomy.
# http://www.d.umn.edu/~tpederse/Pubs/AAAI04PedersenT.pdf
# http://afflatus.ucd.ie/papers/ecai2004b.pdf

IC = {}  # Switch data file according to WordNet version:
IC_CORPUS = os.path.join(MODULE, "resnik-ic" + VERSION[0] + ".txt")
IC_MAX = 0

def information_content(synset):
    """Returns the IC value for the given Synset (trained on the Brown
    corpus)."""
    global IC_MAX
    if not IC:
        IC[NOUN] = {}
        IC[VERB] = {}
        for s in open(IC_CORPUS).readlines()[1:]:  # Skip the header.
            s = s.split()
            id, w, pos = (
                int(s[0][:-1]),
                float(s[1]),
                s[0][-1] == "n" and NOUN or VERB)
            if len(s) == 3 and s[2] == "ROOT":
                IC[pos][0] = IC[pos].get(0, 0) + w
            if w != 0:
                IC[pos][id] = w
            if w > IC_MAX:
                IC_MAX = w
    return IC.get(synset.pos, {}).get(synset.id, 0.0) / IC_MAX

### WORDNET3 TO WORDNET2 #################################################
# Map WordNet3 synset id's to WordNet2 synset id's.

_map32_pos1 = {NN: "n", VB: "v", JJ: "a", RB: "r"}
_map32_pos2 = {"n": NN, "v": VB, "a": JJ, "r": RB}
_map32_cache = None

def map32(id, pos=NOUN):
    """ Returns an (id, pos)-tuple with the WordNet2 synset id for the given WordNet3 synset id.
        Returns None if no id was found.
    """
    global _map32_cache
    if not _map32_cache:
        _map32_cache = codecs.open(os.path.join(MODULE, "dict", "index.32"))\
                             .readlines()
        _map32_cache = (x for x in _map32_cache if x[0] != ";")  # comments
        _map32_cache = (x.strip().split(b" ", 1) for x in _map32_cache)
        _map32_cache = dict(x for x in _map32_cache if len(x) == 2)

    k = pos in _map32_pos2 and pos or _map32_pos1.get(pos, "x")
    k += str(id).lstrip("0")
    k = _map32_cache.get(k.encode("utf-8"), None)

    if k is not None:
        k = k.decode("utf-8")
        return int(k[1:]), _map32_pos2[k[0]]
    return None

#### SENTIWORDNET ########################################################
# http://nmis.isti.cnr.it/sebastiani/Publications/LREC06.pdf
# http://nmis.isti.cnr.it/sebastiani/Publications/LREC10.pdf

sys.path.insert(0, os.path.join(MODULE, "..", ".."))

try:
    from pattern.text import Sentiment
except:
    class Sentiment(object):
        PLACEHOLDER = True

sys.path.pop(0)

class SentiWordNet(Sentiment):

    def __init__(self, path="SentiWordNet*.txt", language="en"):
        """A sentiment lexicon with scores from SentiWordNet.

        The value for each word is a tuple with values for
        polarity (-1.0-1.0), subjectivity (0.0-1.0) and intensity (0.5-2.0).

        """
        Sentiment.__init__(self, path=path, language=language)

    def load(self):
        # Backwards compatibility: look for SentiWordNet*.txt in:
        # given path, pattern/text/en/ or pattern/text/en/wordnet/
        try:
            f = (
                glob.glob(os.path.join(self.path)) +
                glob.glob(os.path.join(MODULE, self.path)) +
                glob.glob(os.path.join(MODULE, "..", self.path)))[0]
        except IndexError:
            raise ImportError("can't find SentiWordnet data file")
        # Map synset id: a-00193480" => (193480, JJ).
        # Map synset id's to WordNet2 if VERSION == 2:
        if int(float(VERSION)) == 3:
            m = lambda id, pos: (int(id.lstrip("0")), _map32_pos2[pos])
        if int(float(VERSION)) == 2:
            m = map32
        for s in open(f):
            if not s.startswith(("#", "\t")):
                pos, id, p, n, senses, gloss = s.split("\t")
                w = senses.split()
                k = m(id, pos)
                v = (float(p) - float(n),
                     float(p) + float(n)
                     )
                # Apply the score to the first synonym in the synset.
                # Several WordNet3 entries may point to the same WordNet2
                # entry.
                if k is not None:
                    k = "%s-%s" % (pos, str(k[0]).zfill(8))  # "a-00193480"
                    if k not in self._synsets or w[0].endswith("#1"):
                        self._synsets[k] = v
                for w in w:
                    if w.endswith("#1"):
                        dict.__setitem__(self, w[:-2].replace("_", " "), v)

    # Words are stored without diacritics,
    # use wordnet.normalize(word).
    def __getitem__(self, k):
        return Sentiment.__getitem__(self, normalize(k))

    def get(self, k, *args, **kwargs):
        return Sentiment.get(self, normalize(k), *args, **kwargs)

    def assessments(self, words=[], negation=True):
        raise NotImplementedError

    def __call__(self, s, negation=True):
        raise NotImplementedError

if not hasattr(Sentiment, "PLACEHOLDER"):
    sentiwordnet = SentiWordNet()
else:
    sentiwordnet = None

# Backwards compatibility.
# Older code may be using pattern.en.wordnet.sentiment[w],
# which yields a (positive, negative, neutral)-tuple.
class sentiment(object):

    def load(self, **kwargs):
        sentiwordnet.load(**kwargs)

    def __getitem__(self, w):
        p, s = sentiwordnet.get(w, (0.0, 0.0))
        return p < 0 and (0.0, -p, 1.0 - s) or (p, 0.0, 1.0 - s)

    def __contains__(self, w):
        return w in sentiwordnet

sentiment = sentiment()

# print sentiwordnet["industry"] # (0.0, 0.0)
# print sentiwordnet["horrible"] # (-0.625, 0.625)
# print sentiwordnet.synset(synsets("horrible", pos="JJ")[0].id, pos="JJ")
# print synsets("horrible", pos="JJ")[0].weight


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20140522164856 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'.");

//        $this->addSql("DROP TABLE lexik_maintenance");
        $this->addSql("ALTER TABLE establecimiento_recurso ADD origen_hora_id INT DEFAULT NULL, DROP origen_horas");
        $this->addSql("ALTER TABLE establecimiento_recurso ADD CONSTRAINT FK_D4968F62EA54AA7B FOREIGN KEY (origen_hora_id) REFERENCES origen_hora (id)");
        $this->addSql("CREATE INDEX IDX_D4968F62EA54AA7B ON establecimiento_recurso (origen_hora_id)");
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql", "Migration can only be executed safely on 'mysql'.");

//        $this->addSql("CREATE TABLE lexik_maintenance (ttl DATETIME DEFAULT NULL) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB");
        $this->addSql("ALTER TABLE establecimiento_recurso DROP FOREIGN KEY FK_D4968F62EA54AA7B");
        $this->addSql("DROP INDEX IDX_D4968F62EA54AA7B ON establecimiento_recurso");
        $this->addSql("ALTER TABLE establecimiento_recurso ADD origen_horas VARCHAR(255) DEFAULT NULL, DROP origen_hora_id");
    }
}


text:
require 'rubygems/format'
require 'rubygems/indexer'
require 'fog'

module Hostess
  class Indexer
    def write_gem(body, spec)
      gem_file = directory.files.create(
        :body   => body.string,
        :key    => "gems/#{spec.original_name}.gem",
        :public => true
      )

      gem_spec = directory.files.create(
        :body   => Gem.deflate(Marshal.dump(spec)),
        :key    => "quick/Marshal.4.8/#{spec.original_name}.gemspec.rz",
        :public => true
      )
    end

    def update_index
      log "Updating the index"
      upload("specs.4.8.gz", specs_index)
      log "Uploaded all specs index"
      upload("latest_specs.4.8.gz", latest_index)
      log "Uploaded latest specs index"
      upload("prerelease_specs.4.8.gz", prerelease_index)
      log "Uploaded prerelease specs index"
      log "Finished updating the index"
    end

    private

    def directory
      fog.directories.get('repo')
    end

    def all_gems
      fog.directories.get('repo/gems').files
    end

    def fog
      $fog || Fog::Storage.new(
        :provider => 'Local',
        :local_root => File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'server'))
      )
    end

    def stringify(value)
      final = StringIO.new
      gzip = Zlib::GzipWriter.new(final)
      gzip.write(Marshal.dump(value))
      gzip.close

      final.string
    end

    def upload(key, value)
      file = directory.files.create(
        :body   => stringify(value),
        :key    => key,
        :public => true
      )
    end

    def minimize_specs(data)
      names     = Hash.new { |h,k| h[k] = k }
      versions  = Hash.new { |h,k| h[k] = Gem::Version.new(k) }
      platforms = Hash.new { |h,k| h[k] = k }

      data.each do |row|
        row[0] = names[row[0]]
        row[1] = versions[row[1].strip]
        row[2] = platforms[row[2]]
      end

      data
    end

    def specs_index
      minimize_specs rows_for_index
    end

    def rows_for_index
      all_gems.collect do |gf|
        spec = Gem::Package.open(StringIO.new(gf.body), "r", nil) {|pkg| pkg.metadata }
        [spec.name, spec.version.to_s, spec.platform]
      end
    end

    def latest_index
      minimize_specs rows_for_latest_index
    end

    def rows_for_latest_index
      latest = { }
      all_gems.collect do |gf|
        spec = Gem::Package.open(StringIO.new(gf.body), "r", nil) {|pkg| pkg.metadata }
        latest[spec.name] ||= [spec.name, spec.version.to_s, spec.platform]
        if Gem::Version.new(latest[spec.name][1]) < spec.version
          latest[spec.name] = [spec.name, spec.version.to_s, spec.platform]
        end
      end

      return latest.values
    end

    def prerelease_index
      return []
      minimize_specs rows_for_prerelease_index
    end

    def log(message)
      puts "#{Time.now} #{message}"
    end
  end
end


text:
package com.recursivity.commons

import java.util.Properties
import collection.mutable.HashMap

/**
 * Created by IntelliJ IDEA.
 * User: wfaler
 * Date: Nov 4, 2010
 * Time: 5:21:44 PM
 * To change this template use File | Settings | File Templates.
 */

object ClasspathPropertiesResolver {

  def getProperties(context: Class[_], locale: List[String] = Nil): Properties = {
    var properties: Properties = null

    if (locale == Nil) {
      properties = loadProperties(context)
    } else {
      try {
        properties = loadProperties(context, Some(locale.head))
      } catch {
        case ex: NullPointerException => {
          val localeList = locale.drop(1)
          properties = getProperties(context, localeList)
        }
      }
    }

    return properties
  }

  private def loadProperties(context: Class[_], locale: Option[String] = None): Properties = {
    var properties = new Properties
    ClasspathResourceResolver.getAbsoluteResource(context, ".properties", locale) {
      is => properties.load(is)
    }

    return properties
  }

}


text:
package org.streamingpool.core.domain;

import static java.util.Objects.requireNonNull;

import org.reactivestreams.Publisher;

import io.reactivex.Flowable;

public abstract class ErrorStreamPair<T> {

    private static final EmptyStream<?> EMPTY_STREAM = new EmptyStream<>();

    public abstract Publisher<T> data();

    public abstract Publisher<Throwable> error();

    public abstract boolean isPresent();

    @SuppressWarnings("unchecked")
    public static final <T> ErrorStreamPair<T> empty() {
        return (ErrorStreamPair<T>) EMPTY_STREAM;
    }

    public static final <T> ErrorStreamPair<T> ofDataError(Publisher<T> dataStream, Publisher<Throwable> errorStream) {
        return new NonEmptyStream<>(dataStream, errorStream);
    }

    public static final <T> ErrorStreamPair<T> ofData(Publisher<T> dataStream) {
        return ofDataError(dataStream, Flowable.never());
    }

    private static class NonEmptyStream<T> extends ErrorStreamPair<T> {

        private final Publisher<T> data;
        private final Publisher<Throwable> error;

        public NonEmptyStream(Publisher<T> data, Publisher<Throwable> error) {
            this.data = requireNonNull(data, "dataStream must not be null");
            this.error = requireNonNull(error, "errorStream must not be null");
        }

        @Override
        public Publisher<T> data() {
            return this.data;
        }

        @Override
        public Publisher<Throwable> error() {
            return this.error;
        }

        @Override
        public boolean isPresent() {
            return true;
        }

    }

    private static class EmptyStream<T> extends ErrorStreamPair<T> {

        @Override
        public Publisher<T> data() {
            throw new UnsupportedOperationException("Empty Stream! This call is not allowed.");
        }

        @Override
        public Publisher<Throwable> error() {
            throw new UnsupportedOperationException("Empty Stream! This call is not allowed.");
        }

        @Override
        public boolean isPresent() {
            return false;
        }

    }

}


text:
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  Distribution.Client.Reporting
-- Copyright   :  (c) David Waern 2008
-- License     :  BSD-like
--
-- Maintainer  :  david.waern@gmail.com
-- Stability   :  experimental
-- Portability :  portable
--
-- Anonymous build report data structure, printing and parsing
--
-----------------------------------------------------------------------------
module Distribution.Server.Features.BuildReports.BuildReport (
    BuildReport(..),
    InstallOutcome(..),
    Outcome(..),

    -- * parsing and pretty printing
    read,
    parse,
    parseList,
    show,
    showList,
  ) where

import Distribution.Package
         ( PackageIdentifier )
import Distribution.PackageDescription
         ( FlagName(..), FlagAssignment )
--import Distribution.Version
--         ( Version )
import Distribution.System
         ( OS, Arch )
import Distribution.Compiler
         ( CompilerId )
import qualified Distribution.Text as Text
         ( Text(disp, parse) )
import Distribution.ParseUtils
         ( FieldDescr(..), ParseResult(..), Field(..)
         , simpleField, listField, readFields
         , syntaxError, locatedErrorMsg, showFields )
import Distribution.Simple.Utils
         ( comparing )
import Distribution.Server.Util.Merge

import qualified Distribution.Compat.ReadP as Parse
         ( ReadP, pfail, munch1, skipSpaces )
import qualified Text.PrettyPrint.HughesPJ as Disp
         ( Doc, char, text )
import Text.PrettyPrint.HughesPJ
         ( (<+>), (<>) )

import Data.List
         ( unfoldr, sortBy )
import Data.Char as Char
         ( isAlpha, isAlphaNum )
import Data.Typeable
         ( Typeable )

import Prelude hiding (show, read)

data BuildReport
   = BuildReport {
    -- | The package this build report is about
    package         :: PackageIdentifier,

    -- | The OS and Arch the package was built on
    os              :: OS,
    arch            :: Arch,

    -- | The Haskell compiler (and hopefully version) used
    compiler        :: CompilerId,

    -- | The uploading client, ie cabal-install-x.y.z
    client          :: PackageIdentifier,

    -- | Which configurations flags we used
    flagAssignment  :: FlagAssignment,

    -- | Which dependent packages we were using exactly
    dependencies    :: [PackageIdentifier],

    -- | Did installing work ok?
    installOutcome  :: InstallOutcome,

    --   Which version of the Cabal library was used to compile the Setup.hs
--    cabalVersion    :: Version,

    --   Which build tools we were using (with versions)
--    tools      :: [PackageIdentifier],

    -- | Configure outcome, did configure work ok?
    docsOutcome     :: Outcome,

    -- | Configure outcome, did configure work ok?
    testsOutcome    :: Outcome
  }
  deriving (Eq, Typeable, Show)

data InstallOutcome
   = DependencyFailed PackageIdentifier
   | DownloadFailed
   | UnpackFailed
   | SetupFailed
   | ConfigureFailed
   | BuildFailed
   | InstallFailed
   | InstallOk
   deriving (Eq, Show)

data Outcome = NotTried | Failed | Ok deriving (Eq, Show)

-- ------------------------------------------------------------
-- * External format
-- ------------------------------------------------------------

initialBuildReport :: BuildReport
initialBuildReport = BuildReport {
    package         = requiredField "package",
    os              = requiredField "os",
    arch            = requiredField "arch",
    compiler        = requiredField "compiler",
    client          = requiredField "client",
    flagAssignment  = [],
    dependencies    = [],
    installOutcome  = requiredField "install-outcome",
--    cabalVersion  = Nothing,
--    tools         = [],
    docsOutcome     = NotTried,
    testsOutcome    = NotTried
  }
  where
    requiredField fname = error ("required field: " ++ fname)

-- -----------------------------------------------------------------------------
-- Parsing

read :: String -> BuildReport
read s = case parse s of
  Left  err -> error $ "error parsing build report: " ++ err
  Right rpt -> rpt

parse :: String -> Either String BuildReport
parse s = case parseFields s of
  ParseFailed perror -> Left  msg where (_, msg) = locatedErrorMsg perror
  ParseOk   _ report -> Right report

--FIXME: this does not allow for optional or repeated fields
parseFields :: String -> ParseResult BuildReport
parseFields input = do
  fields <- mapM extractField =<< readFields input
  let merged = mergeBy (\desc (_,name,_) -> compare (fieldName desc) name)
                       sortedFieldDescrs
                       (sortBy (comparing (\(_,name,_) -> name)) fields)
  checkMerged initialBuildReport merged

  where
    extractField :: Field -> ParseResult (Int, String, String)
    extractField (F line name value)  = return (line, name, value)
    extractField (Section line _ _ _) = syntaxError line "Unrecognized stanza"
    extractField (IfBlock line _ _ _) = syntaxError line "Unrecognized stanza"

    checkMerged report [] = return report
    checkMerged report (merged:remaining) = case merged of
      InBoth fieldDescr (line, _name, value) -> do
        report' <- fieldSet fieldDescr line value report
        checkMerged report' remaining
      OnlyInRight (line, name, _) ->
        syntaxError line ("Unrecognized field " ++ name)
      OnlyInLeft  fieldDescr ->
        fail ("Missing field " ++ fieldName fieldDescr)

parseList :: String -> [BuildReport]
parseList str =
  [ report | Right report <- map parse (split str) ]

  where
    split :: String -> [String]
    split = filter (not . null) . unfoldr chunk . lines
    chunk [] = Nothing
    chunk ls = case break null ls of
                 (r, rs) -> Just (unlines r, dropWhile null rs)

-- -----------------------------------------------------------------------------
-- Pretty-printing

show :: BuildReport -> String
show = showFields fieldDescrs

-- -----------------------------------------------------------------------------
-- Description of the fields, for parsing/printing

fieldDescrs :: [FieldDescr BuildReport]
fieldDescrs =
 [ simpleField "package"         Text.disp      Text.parse
                                 package        (\v r -> r { package = v })
 , simpleField "os"              Text.disp      Text.parse
                                 os             (\v r -> r { os = v })
 , simpleField "arch"            Text.disp      Text.parse
                                 arch           (\v r -> r { arch = v })
 , simpleField "compiler"        Text.disp      Text.parse
                                 compiler       (\v r -> r { compiler = v })
 , simpleField "client"          Text.disp      Text.parse
                                 client         (\v r -> r { client = v })
 , listField   "flags"           dispFlag       parseFlag
                                 flagAssignment (\v r -> r { flagAssignment = v })
 , listField   "dependencies"    Text.disp      Text.parse
                                 dependencies   (\v r -> r { dependencies = v })
 , simpleField "install-outcome" Text.disp      Text.parse
                                 installOutcome (\v r -> r { installOutcome = v })
 , simpleField "docs-outcome"    Text.disp      Text.parse
                                 docsOutcome    (\v r -> r { docsOutcome = v })
 , simpleField "tests-outcome"   Text.disp      Text.parse
                                 testsOutcome   (\v r -> r { testsOutcome = v })
 ]

sortedFieldDescrs :: [FieldDescr BuildReport]
sortedFieldDescrs = sortBy (comparing fieldName) fieldDescrs

dispFlag :: (FlagName, Bool) -> Disp.Doc
dispFlag (FlagName name, True)  =                  Disp.text name
dispFlag (FlagName name, False) = Disp.char '-' <> Disp.text name

parseFlag :: Parse.ReadP r (FlagName, Bool)
parseFlag = do
  name <- Parse.munch1 (\c -> Char.isAlphaNum c || c == '_' || c == '-')
  case name of
    ('-':flag) -> return (FlagName flag, False)
    flag       -> return (FlagName flag, True)

instance Text.Text InstallOutcome where
  disp (DependencyFailed pkgid) = Disp.text "DependencyFailed" <+> Text.disp pkgid
  disp DownloadFailed  = Disp.text "DownloadFailed"
  disp UnpackFailed    = Disp.text "UnpackFailed"
  disp SetupFailed     = Disp.text "SetupFailed"
  disp ConfigureFailed = Disp.text "ConfigureFailed"
  disp BuildFailed     = Disp.text "BuildFailed"
  disp InstallFailed   = Disp.text "InstallFailed"
  disp InstallOk       = Disp.text "InstallOk"

  parse = do
    name <- Parse.munch1 Char.isAlphaNum
    case name of
      "DependencyFailed" -> do Parse.skipSpaces
                               pkgid <- Text.parse
                               return (DependencyFailed pkgid)
      "DownloadFailed"   -> return DownloadFailed
      "UnpackFailed"     -> return UnpackFailed
      "SetupFailed"      -> return SetupFailed
      "ConfigureFailed"  -> return ConfigureFailed
      "BuildFailed"      -> return BuildFailed
      "InstallFailed"    -> return InstallFailed
      "InstallOk"        -> return InstallOk
      _                  -> Parse.pfail

instance Text.Text Outcome where
  disp NotTried = Disp.text "NotTried"
  disp Failed   = Disp.text "Failed"
  disp Ok       = Disp.text "Ok"
  parse = do
    name <- Parse.munch1 Char.isAlpha
    case name of
      "NotTried" -> return NotTried
      "Failed"   -> return Failed
      "Ok"       -> return Ok
      _          -> Parse.pfail


text:
<?php

abstract class AlmanacTransactionType
  extends PhabricatorModularTransactionType {

  protected function getAlmanacPropertyOldValue($object) {
    $property_key = $this->getMetadataValue('almanac.property');
    $exists = $object->hasAlmanacProperty($property_key);
    $value = $object->getAlmanacPropertyValue($property_key);

    return array(
      'existed' => $exists,
      'value' => $value,
    );
  }

  protected function setAlmanacProperty($object, $value) {
    $property_key = $this->getMetadataValue('almanac.property');

    if ($object->hasAlmanacProperty($property_key)) {
      $property = $object->getAlmanacProperty($property_key);
    } else {
      $property = id(new AlmanacProperty())
        ->setObjectPHID($object->getPHID())
        ->setFieldName($property_key);
    }

    $property
      ->setFieldValue($value)
      ->save();
  }

  protected function deleteAlmanacProperty($object) {
    $property_key = $this->getMetadataValue('almanac.property');
    if ($object->hasAlmanacProperty($property_key)) {
      $property = $object->getAlmanacProperty($property_key);
      $property->delete();
    }
  }

  protected function getAlmanacSetPropertyTitle() {
    $property_key = $this->getMetadataValue('almanac.property');

    return pht(
      '%s updated the property %s.',
      $this->renderAuthor(),
      $this->renderValue($property_key));
  }

  protected function getAlmanacDeletePropertyTitle() {
    $property_key = $this->getMetadataValue('almanac.property');

    return pht(
      '%s removed the property %s.',
      $this->renderAuthor(),
      $this->renderValue($property_key));
  }

  protected function validateAlmanacSetPropertyTransactions(
    $object,
    array $xactions) {
    $errors = array();

    foreach ($xactions as $xaction) {
      $property_key = $xaction->getMetadataValue('almanac.property');

      $message = null;
      try {
        AlmanacNames::validateName($property_key);
      } catch (Exception $ex) {
        $message = $ex->getMessage();
      }

      if ($message !== null) {
        $errors[] = $this->newInvalidError($message, $xaction);
        continue;
      }

      $new_value = $xaction->getNewValue();
      try {
        phutil_json_encode($new_value);
      } catch (Exception $ex) {
        $message = pht(
          'Almanac property values must be representable in JSON. %s',
          $ex->getMessage());
      }

      if ($message !== null) {
        $errors[] = $this->newInvalidError($message, $xaction);
        continue;
      }
    }

    return $errors;
  }

}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
    <title>Simple Map</title>
    <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/esri/css/esri.css">

Legend


text:
#ifndef PLCRASH_ASYNC_DWARF_PRIVATE_H
#define PLCRASH_ASYNC_DWARF_PRIVATE_H 1

#include "PLCrashFeatureConfig.h"

#if PLCRASH_FEATURE_UNWIND_DWARF

/**
 * @internal
 * @ingroup plcrash_async_dwarf
 * @defgroup plcrash_async_dwarf_private DWARF Internal Utility Classes
 */

#endif /* PLCRASH_FEATURE_UNWIND_DWARF */
#endif /* PLCRASH_ASYNC_DWARF_PRIVATE_H */


text:
'''
Created on 2014-2-17
@author: CL.lam
'''
import os
import random
import traceback
import transaction
import shutil
import json
from datetime import datetime as dt
from tg import expose, redirect, flash, request, config, session
from tg.decorators import paginate
from repoze.what import authorize
from repoze.what.predicates import has_permission
from sqlalchemy.sql.expression import and_, desc

from rpac.lib.base import BaseController
from rpac.util.common import tabFocus, logError, serveFile, \
    ReportGenerationException, sendEmail
import rpac.model as DBModel
from rpac.model import qry, DBSession, OrderHeader, PrintShop, AddressBook, \
                        Product, Option, CO, Care, DateCode, DotPantone, Category, Fibers
from rpac.widgets.ordering import order_search_form
from rpac.util.excel_helper import FDReport, getExcelVersion, FDOrder
from rpac.model.ordering import ORDER_INPROCESS, ORDER_COMPLETE, ORDER_NEW, \
    OrderDetail, ORDER_CANCEL, ORDER_MANUAL
from rpac.util.layout_pdf import gen_pdf

__all__ = ['OrderingController', ]

DEFAULT_SENDER = 'r-pac-fd-order-system@r-pac.com.hk'

class OrderingController(BaseController):
    allow_only = authorize.not_anonymous()

    @expose('rpac.templates.ordering.index')
    @paginate("result", items_per_page = 20)
    @tabFocus(tab_type = "main")
    def index(self , **kw):
        ws = [OrderHeader.active == 0]
        if kw.get("no", False) : ws.append(OrderHeader.no.op("ilike")("%%%s%%" % kw["no"]))
        if kw.get("customerpo", False) : ws.append(OrderHeader.customerpo.op("ilike")("%%%s%%" % kw["customerpo"]))
        if kw.get("vendorpo", False) : ws.append(OrderHeader.vendorpo.op("ilike")("%%%s%%" % kw["vendorpo"]))
        if kw.get("status", False) : ws.append(OrderHeader.status == kw["status"])
        if kw.get("printShopId", False) : ws.append(OrderHeader.printShopId == kw["printShopId"])
        if not has_permission("MAIN_ORDERING_CHECKING_ALL"): ws.append(OrderHeader.createById == request.identity["user"].user_id)

        result = qry(OrderHeader).filter(and_(*ws)).order_by(desc(OrderHeader.createTime)).all()
        ps = qry(PrintShop).filter(and_(PrintShop.active == 0)).order_by(PrintShop.name)
        return { "result" : result , "values" : kw, "widget" : order_search_form , "printshops" : ps}

    @expose()
    def export(self, **kw):
        ws = [OrderHeader.active == 0]
        if kw.get("no", False) : ws.append(OrderHeader.no.op("ilike")("%%%s%%" % kw["no"]))
        if kw.get("customerpo", False) : ws.append(OrderHeader.customerpo.op("ilike")("%%%s%%" % kw["customerpo"]))
        if kw.get("vendorpo", False) : ws.append(OrderHeader.vendorpo.op("ilike")("%%%s%%" % kw["vendorpo"]))
        if kw.get("status", False) : ws.append(OrderHeader.status == kw["status"])
        if kw.get("printShopId", False) : ws.append(OrderHeader.printShopId == kw["printShopId"])
        if not has_permission("MAIN_ORDERING_CHECKING_ALL"): ws.append(OrderHeader.createById == request.identity["user"].user_id)

        data = []
        for h in  qry(OrderHeader).filter(and_(*ws)).order_by(desc(OrderHeader.createTime)):
            data.append(map(unicode, [ h.no, h.customerpo, h.vendorpo, h.createTime.strftime("%Y/%m/%d %H:%M"),
                                      h.createBy, h.printShop, h.showStatus(),
                                      h.completeDate.strftime("%Y/%m/%d %H:%M") if h.completeDate else '',
                                      h.shipQty or '',
                                     ]))

        try:
            v = getExcelVersion()
            if not v : raise ReportGenerationException()
            if v <= "2003" :  # version below 2003
                templatePath = os.path.join(config.get("public_dir"), "TEMPLATE", "FD_REPORT_TEMPLATE.xls")
            else :  # version above 2003
                templatePath = os.path.join(config.get("public_dir"), "TEMPLATE", "FD_REPORT_TEMPLATE.xlsx")

            tempFileName, realFileName = self._getReportFilePath(templatePath)
            sdexcel = FDReport(templatePath = tempFileName, destinationPath = realFileName)
            sdexcel.inputData(data)
            sdexcel.outputData()
        except:
            traceback.print_exc()
            logError()
            if sdexcel:sdexcel.clearData()
            raise ReportGenerationException()
        else:
            return serveFile(realFileName)

    def _getReportFilePath(self, templatePath):
        current = dt.now()
        dateStr = current.strftime("%Y%m%d")
        fileDir = os.path.join(config.get("public_dir"), "fd", dateStr)
        if not os.path.exists(fileDir): os.makedirs(fileDir)
        v = getExcelVersion()
        if not v : raise ReportGenerationException()
        if v <= "2003" :  # version below 2003
            tempFileName = os.path.join(fileDir, "%s_%s_%d.xls" % (request.identity["user"].user_name,
                                                               current.strftime("%Y%m%d%H%M%S"), random.randint(0, 1000)))
            realFileName = os.path.join(fileDir, "%s_%s.xls" % (request.identity["user"].user_name, current.strftime("%Y%m%d%H%M%S")))
        else:
            tempFileName = os.path.join(fileDir, "%s_%s_%d.xlsx" % (request.identity["user"].user_name,
                                                               current.strftime("%Y%m%d%H%M%S"), random.randint(0, 1000)))
            realFileName = os.path.join(fileDir, "%s_%s.xlsx" % (request.identity["user"].user_name, current.strftime("%Y%m%d%H%M%S")))
        shutil.copy(templatePath, tempFileName)
        return tempFileName, realFileName

    @expose('rpac.templates.ordering.detail')
    @paginate("result", items_per_page = 20)
    @tabFocus(tab_type = "main")
    def detail(self, **kw):
        hid = kw.get('id', None)
        if not hid :
            flash("No ID provides!", "warn")
            return redirect('/ordering/index')

        try:
            obj = qry(OrderHeader).filter(and_(OrderHeader.active == 0 , OrderHeader.id == hid)).one()
        except:
            flash("The record does not exist!", "warn")
            return redirect('/ordering/index')

        return {
                'obj' : obj ,

                }

    @expose('rpac.templates.ordering.placeorder')
    @tabFocus(tab_type = "main")
    def placeorder(self , **kw):
        locations = qry(PrintShop).filter(and_(PrintShop.active == 0)).order_by(PrintShop.name)
        address = qry(AddressBook).filter(and_(AddressBook.active == 0, AddressBook.createById == request.identity['user'].user_id)).order_by(AddressBook.createTime).all()
        values = {}
        if len(address) > 0 :
            for f in ['shipCompany', 'shipAttn', 'shipAddress', 'shipAddress2', 'shipAddress3',
                      'shipCity', 'shipState', 'shipZip', 'shipCountry', 'shipTel', 'shipFax', 'shipEmail', 'shipRemark',
                      'billCompany', 'billAttn', 'billAddress', 'billAddress2', 'billAddress3',
                      'billCity', 'billState', 'billZip', 'billCountry', 'billTel', 'billFax', 'billEmail', 'billRemark'] :
                values[f] = unicode(getattr(address[0], f) or '')

        products = []
        for p in session.get('items', []) :
            p['productobj'] = qry(Product).get(p['id'])
            products.append(p)

        return {'locations' : locations ,
                'products' : products, 'address' : address,
                'values' : values,
                'address' : address,
                }

    @expose()
    def saveorder(self, **kw):
        try:
            addressFields = [
                              'shipCompany', 'shipAttn', 'shipAddress', 'shipAddress2', 'shipAddress3', 'shipCity', 'shipState', 'shipZip', 'shipCountry', 'shipTel', 'shipFax', 'shipEmail', 'shipRemark',
                              'billCompany', 'billAttn', 'billAddress', 'billAddress2', 'billAddress3', 'billCity', 'billState', 'billZip', 'billCountry', 'billTel', 'billFax', 'billEmail', 'billRemark',
                             ]
            fields = [ 'customerpo', 'vendorpo', 'printShopId', 'shipInstructions']
            params = {}
            for f in addressFields: params[f] = kw.get(f, None) or None
            if kw.get('addressID', None) == 'OTHER': DBSession.add(AddressBook(**params))
            for f in fields: params[f] = kw.get(f, None) or None
            if params['printShopId'] : params['printShopCopy'] = unicode(qry(PrintShop).get(params['printShopId']))

            hdr = OrderHeader(**params)
            DBSession.add(hdr)
            qtys = []
            for item in session.get('items' , []):
                params = {
                          'header' : hdr, 'product' : item['productobj'],
                          'itemCode' : item['productobj'].itemCode,
                          'desc' : item['productobj'].desc,
                          'size' : item['productobj'].size,
                          'qty' : item['qty'] or None,
                          }
                if item.get('values', None) or None : params['optionContent'] = json.dumps(item.get('values', []))
                if item.get('optionstext', None) or None : params['optionText'] = json.dumps(item['optionstext'])

                params['layoutValue'] = json.dumps(self._setLayoutValue(item.get('values', [])))
                DBSession.add(OrderDetail(**params))
                qtys.append(item['qty'])
            DBSession.flush()
            hdr.totalQty = sum(map(int, filter(unicode.isdigit , qtys)))
        except:
            transaction.doom()
            traceback.print_exc()
            flash('Error occur on the server side!', "warn")
            return redirect('/ordering/placeorder')
        else:
            try:
                del session['items']
                session.save()
            except:
                pass
            return redirect('/ordering/afterSaveOrder?id=%s' % hdr.id)

    def _genExcel(self, hdr):
        v = getExcelVersion()
        if not v : raise ReportGenerationException()
        if v <= "2003" :  # version below 2003
            templatePath = os.path.join(config.get("public_dir"), "TEMPLATE", "FD_DETAIL_TEMPLATE.xls")
        else :  # version above 2003
            templatePath = os.path.join(config.get("public_dir"), "TEMPLATE", "FD_DETAIL_TEMPLATE.xlsx")

        current = dt.now()
        dateStr = current.strftime("%Y%m%d")
        fileDir = os.path.join(config.get("public_dir"), "excel", dateStr)
        if not os.path.exists(fileDir): os.makedirs(fileDir)

        if v <= "2003" :  # version below 2003
            tempFileName = os.path.join(fileDir, "%s_%s_%d.xls" % (request.identity["user"].user_name,
                                                               current.strftime("%Y%m%d%H%M%S"), random.randint(0, 1000)))
            realFileName = os.path.join(fileDir, "%s_%s.xls" % (request.identity["user"].user_name, current.strftime("%Y%m%d%H%M%S")))
        else:
            tempFileName = os.path.join(fileDir, "%s_%s_%d.xlsx" % (request.identity["user"].user_name,
                                                               current.strftime("%Y%m%d%H%M%S"), random.randint(0, 1000)))
            realFileName = os.path.join(fileDir, "%s_%s.xlsx" % (hdr.no, current.strftime("%Y%m%d%H%M%S")))

        shutil.copy(templatePath, tempFileName)

        data = { 'createTime' : hdr.createTime.strftime("%Y-%m-%d %H:%M") }
        for f in [ 'no', 'shipCompany', 'shipAttn', 'shipAddress', 'shipAddress2', 'shipAddress3',
                   'shipCity', 'shipState', 'shipZip', 'shipCountry', 'shipTel', 'shipFax',
                   'shipEmail', 'shipRemark',
                   'billCompany', 'billAttn', 'billAddress', 'billAddress2', 'billAddress3',
                   'billCity', 'billState', 'billZip', 'billCountry', 'billTel', 'billFax',
                   'billEmail', 'billRemark',
                   'customerpo', 'vendorpo', 'printShopCopy', 'shipInstructions' ]:
            data[f] = unicode(getattr(hdr, f) or '')

        data['details'] = [map(lambda v : unicode(v or ''), [d.itemCode, d.desc, d.size, d.qty,
                                                             '\n'.join(json.loads(d.optionText)) if d.optionText else '',
                                                             ]) for d in hdr.dtls]
        try:
            sdexcel = FDOrder(templatePath = tempFileName, destinationPath = realFileName)
            sdexcel.inputData(data)
            sdexcel.outputData()
            return realFileName
        except Exception, e:
            traceback.print_exc()
            raise e

    @expose()
    def getexcel(self, **kw):
        hid = kw.get('id', None)
        if not hid :
            flash("No ID provided!")
            return redirect('/index')

        hdr = DBSession.query(OrderHeader).get(hid)
        xls = self._genExcel(hdr)
        return serveFile(unicode(xls))

    @expose()
    def afterSaveOrder(self, **kw):
        _id = kw.get('id', None) or None
        if not _id:
            flash("No ID provided !", "warn")
            return redirect('/index')

        try:
            hdr = qry(OrderHeader).get(_id)
            #=======================================================================
            # generate excel
            #=======================================================================
            xls = self._genExcel(hdr)
            #=======================================================================
            # generate PDF
            #=======================================================================
            details = [(d.id, d.itemCode) for d in hdr.dtls]
            pdf = gen_pdf(hdr.no, details)
            files1 = [pdf]
            files2 = [pdf, xls, ]

            #=======================================================================
            # send email to user
            #=======================================================================
            subject = "[FD] Order(%s) is placed" % hdr.no
            content = [
                       "Dear User:",
                       "Order(%s) is placed, please check the below link to check the detail." % hdr.no,
                       "%s/ordering/detail?id=%s" % (config.get('website_url', ''), hdr.id),
                       "Thanks.", "",
                       "*" * 80,
                       "This e-mail is sent by the r-pac Family Dollar ordering system automatically.",
                       "Please don't reply this e-mail directly!",
                       "*" * 80,
                       ]
            self._toVendor(hdr, subject, content, files1)
            #=======================================================================
            # send email to print shop
            #=======================================================================
            self._toPrintshop(hdr, subject, content, files2)
            flash("Save the order successfully!", "ok")
        except:
            traceback.print_exc()
            flash("The service is not available now ,please try again later.", 'warn')
            return redirect('/ordering/index')
        else:
            return redirect('/ordering/detail?id=%s' % hdr.id)

    @expose()
    def cancelOrder(self, **kw):
        _id = kw.get("id", None) or None
        if not _id :
            flash("No ID provided!")
            return redirect('/ordering/index')

        hdr = qry(OrderHeader).get(_id)
        hdr.status = ORDER_CANCEL
        subject = "[FD] Order(%s) is cancelled" % hdr.no
        content = [
                   "Dear User:",
                   "Order(%s) is cancelled." % hdr.no,
                   "Thanks.", "",
                   "*" * 80,
                   "This e-mail is sent by the r-pac Family Dollar ordering system automatically.",
                   "Please don't reply this e-mail directly!",
                   "*" * 80,
                   ]
        #=======================================================================
        # send email to user
        #=======================================================================
        self._toVendor(hdr, subject, content)
        #=======================================================================
        # send email to print shop
        #=======================================================================
        self._toPrintshop(hdr, subject, content)
        flash("Cancel the order successfully!")
        return redirect('/ordering/index')

    @expose("json")
    def ajaxOrderInfo(self, **kw):
        hid = kw.get('id', None)
        if not hid : return {'flag' : 1 , 'msg' : 'No ID provided!'}
        try:
            data = []
            for d in qry(OrderDetail).filter(and_(OrderDetail.active == 0, OrderDetail.headerId == hid)).order_by(OrderDetail.id):
                data.append({'id' : d.id, 'code' : d.itemCode , 'qty' : d.qty})
            return {'flag' : 0, 'data' : data}
        except:
            traceback.print_exc()
            return {'flag' : 1 , 'msg' : 'Error occur on the server side!'}

    @expose('rpac.templates.ordering.manage_address')
    @paginate("result", items_per_page = 20)
    @tabFocus(tab_type = "ship")
    def manageAddress(self, **kw):
        result = DBSession.query(AddressBook).filter(and_(AddressBook.active == 0, AddressBook.createById == request.identity['user'].user_id)).order_by(desc(AddressBook.createTime))
        return {'result' : result}

    @expose('rpac.templates.ordering.edit_address')
    @tabFocus(tab_type = "ship")
    def editAddress(self, **kw):
        _id = kw.get('id', None)
        if not _id :
            flash('No id provided!' , "warn")
            return redirect('/index')

        obj = DBSession.query(AddressBook).get(_id)
        values = {'id' : obj.id}
        for f in ['shipCompany', 'shipAttn', 'shipAddress', 'shipAddress2', 'shipAddress3',
                  'shipCity', 'shipState', 'shipZip', 'shipCountry', 'shipTel', 'shipFax', 'shipEmail', 'shipRemark',
                  'billCompany', 'billAttn', 'billAddress', 'billAddress2', 'billAddress3',
                  'billCity', 'billState', 'billZip', 'billCountry', 'billTel', 'billFax', 'billEmail', 'billRemark'] :
            values[f] = unicode(getattr(obj, f) or '')
        return {'values' : values}

    @expose()
    def saveAddress(self, **kw):
        _id = kw.get('id', None)
        if not _id :
            flash('No id provided!', 'warn')
            return redirect('/ordering/manageAddress')

        fields = ['shipCompany', 'shipAttn', 'shipAddress', 'shipAddress2', 'shipAddress3',
                  'shipCity', 'shipState', 'shipZip', 'shipCountry', 'shipTel', 'shipFax', 'shipEmail', 'shipRemark',
                  'billCompany', 'billAttn', 'billAddress', 'billAddress2', 'billAddress3',
                  'billCity', 'billState', 'billZip', 'billCountry', 'billTel', 'billFax', 'billEmail', 'billRemark']

        try:
            obj = DBSession.query(AddressBook).get(_id)
            for f in fields : setattr(obj, f, kw.get(f, None) or None)
            flash('Save the record successfully!', 'ok')
        except:
            traceback.print_exc()
            flash("The service is not available now ,please try again later.", 'warn')
        return redirect('/ordering/manageAddress')

    @expose()
    def delAddress(self, **kw):
        oid = kw.get('id', None)
        if not oid :
            flash('No id provided!', 'warn')
            return redirect('/ordering/manageAddress')

        obj = DBSession.query(AddressBook).get(oid)
        if not obj :
            flash('The record does not exist!', 'warn')
            return redirect('/ordering/manageAddress')

        obj.active = 1
        flash('Update the record successfully!', 'ok')
        return redirect('/ordering/manageAddress')

    @expose('json')
    def ajaxAddress(self, **kw):
        aid = kw.get('addressID', None)
        if not aid : return {'code' : 1 , 'msg' : 'No ID provided!'}

        obj = qry(AddressBook).get(aid)
        if not obj : return {'code' : 1 , 'msg' : 'The record does not exist!'}

        result = {'code' : 0}
        for f in ["shipCompany", "shipAttn", "shipAddress", "shipAddress2", "shipAddress3", "shipCity", "shipState",
                  "shipZip", "shipCountry", "shipTel", "shipFax", "shipEmail", "shipRemark",
                  "billCompany", "billAttn", "billAddress", "billAddress2", "billAddress3", "billCity", "billState",
                  "billZip", "billCountry", "billTel", "billFax", "billEmail", "billRemark", ] :
            result[f] = unicode(getattr(obj, f) or '')
        return result

    @expose('json')
    def ajaxChangeStatus(self, **kw):
        _id, status = kw.get('id', None) or None , kw.get('status', None) or None
        if not _id or not status:
            return {'flag' : 1 , 'msg' : 'No enough parameter(s) provided!'}

        if status not in map(unicode, [ORDER_INPROCESS, ORDER_COMPLETE, ]):
            return {'flag' : 1 , 'msg' : 'No such operation!'}

        try:
            hdr = qry(OrderHeader).get(_id)

            if status == unicode(ORDER_INPROCESS):
                so = kw.get('so', None) or None
                if not so : return {'flag' : 1 , 'msg' : 'No enough parameter(s) provided!'}
                if hdr.status != ORDER_NEW:
                    return {'flag' : 1 , 'msg' : 'The record is not in NEW status!'}
                hdr.so, hdr.status = so, ORDER_INPROCESS
            elif status == unicode(ORDER_COMPLETE):
                if hdr.status != ORDER_INPROCESS:
                    return {'flag' : 1 , 'msg' : 'The record is not in process status!'}
                hdr.status, hdr.completeDate = ORDER_COMPLETE, dt.now()
                totalqty = 0
                for d in hdr.dtls:
                    key = "ship_%s" % d.id
                    if kw.get(key, None) :
                        d.shipQty = kw[key]
                        try:
                            totalqty += int(d.shipQty)
                        except:
                            pass
                hdr.shipQty = totalqty
                self._sendEmailToVendor(hdr)
                self._sendEmailToPrintshop(hdr)
        except:

            traceback.print_exc()
            return {'flag' : 1, 'msg' : 'Error occur on the sever side !'}
        return {'flag' : 0}

    def _sendEmailToVendor(self, hdr):
        subject = "[FD] Order(%s) is completed" % hdr.no
        content = [
                   "Dear User:",
                   "Order(%s) is completed, please check the below link to check the detail." % hdr.no,
                   "%s/ordering/detail?id=%s" % (config.get('website_url', ''), hdr.id),
                   "Thanks.", "",
                   "*" * 80,
                   "This e-mail is sent by the r-pac Family Dollar ordering system automatically.",
                   "Please don't reply this e-mail directly!",
                   "*" * 80,
                   ]
        self._toVendor(hdr, subject, content)

    def _sendEmailToPrintshop(self, hdr):
        subject = "[FD] Order(%s) is completed" % hdr.no
        content = [
                   "Dear User:",
                   "Order(%s) is completed, please check the below link to check the detail." % hdr.no,
                   "%s/ordering/detail?id=%s" % (config.get('website_url', ''), hdr.id),
                   "Thanks.", "",
                   "*" * 80,
                   "This e-mail is sent by the r-pac Family Dollar ordering system automatically.",
                   "Please don't reply this e-mail directly!",
                   "*" * 80,
                   ]
        self._toPrintshop(hdr, subject, content)

    def _toVendor(self, hdr , subject, content, files = []):
        defaultsendto = config.get("default_email_sendto", "").split(";")
        if hdr.createBy.email_address:  to = hdr.createBy.email_address.split(";")
        else: to = []
        sendto = defaultsendto + to
        cc = config.get("default_email_cc", "").split(";")
        if config.get("sendout_email", None) != 'F': sendEmail(DEFAULT_SENDER, sendto, subject, '\n'.join(content), cc, files)

    def _toPrintshop(self, hdr, subject, content, files = []):
        defaultsendto = config.get("default_email_sendto", "").split(";")
        if hdr.printShopId and hdr.printShop.email: to = hdr.printShop.email
        else: to = []
        sendto = defaultsendto + to
        cc = config.get("default_email_cc", "").split(";")
        if config.get("sendout_email", None) != 'F': sendEmail(DEFAULT_SENDER, sendto, subject, '\n'.join(content), cc, files)

    def _filterAndSorted(self, prefix, kw):
        return sorted(filter(lambda (k, v): k.startswith(prefix), kw.iteritems()), cmp = lambda x, y:cmp(x[0], y[0]))

    #===========================================================================
    # new function  for phase 2
    #===========================================================================
    @expose('rpac.templates.ordering.listItems')
    @tabFocus(tab_type = "main")
    def listItems(self, **kw):
        products = qry(Product).filter(and_(Product.active == 0)).order_by(Product.itemCode)
        return {'products' : products}

    def _getMaster(self, opt):
        if opt.master == 'CO' :
            objs = qry(CO).filter(and_(CO.active == 0)).order_by(CO.english)
        elif opt.master == 'Care' :
            objs = qry(Care).filter(and_(Care.active == 0 , Care.type == opt.conditions)).order_by(Care.english)
        elif opt.master == 'DateCode' :
            objs = qry(DateCode).filter(and_(DateCode.active == 0)).order_by(DateCode.val)
        elif opt.master == 'DotPantone' :
            objs = qry(DotPantone).filter(and_(DotPantone.active == 0)).order_by(DotPantone.val)
        elif opt.master == 'Category':
            objs = qry(Category).filter(and_(Category.active == 0)).order_by(Category.val)
        elif opt.master == 'Fibers':
            objs = qry(Fibers).filter(and_(Fibers.active == 0)).order_by(Fibers.english)
        else:
            objs = []
        return objs

    def _getProductInfo(self, obj):
        options = []
        product = {'id' : obj.id , 'moq' : obj.moq , 'roundup' : obj.roundup }
        for opt in obj.getOptions() :
            tmp = {
                   'name' : opt.name, 'type' : opt.type,
                   'id' : opt.id, 'multiple' : opt.multiple or '',
                   'css' :  json.loads(opt.css) if opt.css else {'SELECT' : [], 'TEXT' : []}
                   }
            if opt.type == 'TEXT':
                pass
            elif opt.type == 'SELECT' :
                tmp['values'] = [{'key' : obj.key, 'val' : obj.value} for obj in self._getMaster(opt)]
            elif opt.type == 'SELECT+TEXT':
                tmp['values'] = [{'key' : obj.key, 'val' : obj.value} for obj in self._getMaster(opt)]
            elif opt.type == 'SELECT+SELECT':
                pass
            options.append(tmp)
        return product, options

    @expose('json')
    def ajaxProductInfo(self, **kw):
        _id = kw.get('id', None) or None
        if not _id: return {'flag' : 1 , 'msg' : 'No ID provided!'}

        try:
            obj = qry(Product).get(_id)
            product, options = self._getProductInfo(obj)
            return {'flag' : 0 , 'product' : product, 'options' : options}
        except:
            traceback.print_exc()
            return {'flag' : 1, 'msg' : 'Error occur on the sever side !'}

    def _formatKW(self, kw):
        values, optionstext = [], []
        for k, v in self._filterAndSorted("option_", kw):
            val, text = v.split("|")
            values.append({ 'key' : k, 'value' : val, 'text' : text })
            if k.startswith('option_a_') :  # SELECT OR TEXT
                oid = k.split("_")[2]
                option = qry(Option).get(oid)
                if option.master in ['CO', 'Care']:
                    clz = getattr(DBModel, option.master)
                    obj = qry(clz).get(val)
                    if obj.english.upper() == 'NONE':
                        optionstext.append("%s : %s" % (option.name, ''))
                    elif option.language and 'S' not in option.language.split("|"):  # this option just need the english
                        optionstext.append("%s : %s" % (option.name, obj.english))
                    else:
                        optionstext.append("%s : [English]%s [Spanish]%s" % (option.name, obj.english, obj.spanish or ''))
                else:
                    optionstext.append("%s : %s" % (option.name, text))
            elif k.startswith('option_as_') :  # SELECT + TEXT
                oid = k.split("_")[2]
                option = qry(Option).get(oid)
                obj = qry(Fibers).get(val)
                e = obj.english if obj.english.upper() != 'NONE' else ''
                s = obj.spanish if obj.english.upper() != 'NONE' else ''

                k2 = k.replace('_as_', '_at_')
                v2 = kw.get(k2, '') or ''
                if option.language and 'S' not in option.language.split("|"):  # this option just need the english
                    optionstext.append("%s : %s - %s" % (option.name, e, v2.split('|')[0]))
                else:
                    optionstext.append("%s : [English]%s [Spanish]%s [Percentage]%s" % (option.name, e, s or '', v2.split('|')[0]))
        return values, optionstext

    @expose('json')
    def ajaxAddtoCart(self, **kw):
        _id = kw.get('id', None) or None
        if not _id : return {'flag' : 1 , 'msg' : 'No ID provided!'}

        try:
            items = session.get('items', [])
            tmp = {
                   '_k' : "%s%s" % (dt.now().strftime("%Y%m%d%H%M%S"), random.randint(100, 10000)) ,
                   'id' : _id,
                   'qty' : kw.get('qty', None),
                   }
            tmp['values'], tmp['optionstext'] = self._formatKW(kw)
            items.append(tmp)
            session['items'] = items
            session.save()
            return {'flag' : 0 , 'total' : len(session['items'])}
        except:
            traceback.print_exc()
            return {'flag' : 1, 'msg':'Error occur on the sever side!'}

    @expose('json')
    def ajaxSavetoCart(self, **kw):
        _k = kw.get("_k", None)
        if not _k : return {'flag' : 1 , 'msg' : 'No ID provided!'}

        try:
            items = session.get('items', [])
            for index, item in enumerate(items):
                if item['_k'] != _k : continue
                item['qty'] = kw.get('qty', None) or None
                item['values'], item['optionstext'] = self._formatKW(kw)
                items[index] = item
                session['items'] = items
                session.save()
                return {'flag' : 0 , 'optionstext' : item['optionstext'], }
        except:
            traceback.print_exc()
            return {'flag' : 1 , 'msg' : 'Error occur on the sever side!'}
        return {'flag' : 1 , 'msg' : 'No such item!'}

    @expose('json')
    def ajaxRemoveItem(self, **kw):
        _k = kw.get("_k", None)
        if not _k : return {'flag' : 1 , 'msg' : 'No ID provided!'}

        try:
            session['items'] = filter(lambda item : item['_k'] != _k, session.get('items', []))
            session.save()
            return {'flag' : 0 }
        except:
            traceback.print_exc()
            return {'flag' : 1, 'msg':'Error occur on the sever side!'}

    @expose('json')
    def ajaxEditItem(self, **kw):
        _k = kw.get('_k', None) or None
        if not _k: return {'flag' : 1 , 'msg' : 'No ID provided!'}
        try:
            for s in session.get('items', []):
                if s['_k'] != _k : continue
                obj = qry(Product).get(s['id'])
                product, options = self._getProductInfo(obj)
                product['qty'] = s.get('qty', '')
                return {'flag' : 0 , 'product' : product, 'options' : options , 'values' : s.get('values', []) }
        except:
            traceback.print_exc()
            return {'flag' : 1, 'msg' : 'Error occur on the sever side !'}
        return {'flag' : 1 , 'msg' : 'No such item!'}

    @expose()
    def removeall(self, **kw):
        try:
            del session['items']
            session.save()
        except:
            pass
        return redirect('/ordering/listItems')

    def _setLayoutValue(self , values):
        layout = {}
        for v in values :
            gs = v['key'].split("_")
            f, oid = gs[1], gs[2]
            if f == 'at' : continue  # it's percentage ,will add in the fibers
            option = qry(Option).get(oid)

            if option.layoutKey in ['TRACKING', 'DESC', 'SKU', 'PRICE', 'NAME', 'SIZE', 'SKU', 'WPL']:
                lv = v['value']
            elif option.layoutKey in ['DOT', ]:
                d = qry(DotPantone).get(v['value'])
                lv = {'value' : v['text'] , 'css' : d.css}
            elif option.layoutKey in ['DATECODE', 'CATEGORY', ]:
                lv = v['text']
            elif option.layoutKey in ['CO', 'WASH', 'BLEACH', 'IRON', 'DRY', 'DRYCLEAN', 'SPECIALCARE']:
                if option.layoutKey == 'CO':
                    k = qry(CO).get(v['value'])
                else:
                    k = qry(Care).get(v['value'])
                if k.english.upper() == 'NONE':
                    lv = {'english' : '', 'spanish' : ''}
                else:
                    lv = {'english' : k.english, 'spanish' : k.spanish}
            elif option.layoutKey in ['FIBERS', ]:
                k = qry(Fibers).get(v['value'])
                if k.english.upper() == 'NONE':
                    lv = {'english' : '', 'spanish' : ''}
                else:
                    lv = {'english' : k.english, 'spanish' : k.spanish}

                pkey = v['key'].replace("_as_", "_at_")
                for tmp in values :
                    if tmp['key'] == pkey :
                        lv['percent'] = tmp['value']
                        break;
            if option.layoutKey not in layout:
                layout[option.layoutKey] = {'values' : [lv]}
            else:
                layout[option.layoutKey]['values'].append(lv)
        return layout

    @expose()
    def manual(self, **kw):
        _f = lambda k : kw.get(k, None) or None
        params = {
                  "customerpo" : _f("m_customerpo"), "vendorpo" : _f('m_po'), 'vendorName' : _f('m_vendorName'),
                  'so' : _f('m_so'), 'printShopId' : _f('m_location'), 'createTime' : _f('m_received'),
                  'completeDate' : _f('m_shipped'), 'status' : ORDER_MANUAL, 'source' : 'MANUAL',
                  }
        try:
            if params['printShopId'] :
                s = qry(PrintShop).get(params['printShopId'])
                params['printShopCopy'] = unicode(s)
            hdr = OrderHeader(**params)
            DBSession.add(hdr)

            itemcodes = self._filterAndSorted("m_itemcode_", kw)
            qtys = self._filterAndSorted("m_qty_", kw)
            shippedQty = []
            for (ck, cv), (qk, qv) in zip(itemcodes, qtys):
                if not cv or not qv : continue
                cv, qv = cv.strip(), qv.strip()
                if not qv.isdigit() : continue
                DBSession.add(OrderDetail(header = hdr, itemCode = cv, qty = qv, shipQty = qv))
                shippedQty.append(int(qv))
            hdr.shipQty = sum(shippedQty)
            hdr.totalQty = sum(shippedQty)
        except:
            traceback.print_exc()
            flash("Error occur on the server side!")
        else:
            flash('Save the manual order successfully!')
        return redirect('/ordering/index')


text:
namespace sdo{
namespace coh{
void CCohResponseMsg::SetStatus(int nCode, const string &strMsg)
{
    m_nStatusCode=nCode;
    m_strStatusMsg=strMsg;
}
void CCohResponseMsg::SetAttribute(const string &strPath, const string &strValue)
{
    m_strParameters.append("<"+strPath+">"+strValue+"</"+strPath+">");
}
void CCohResponseMsg::SetAttribute(const string &strPath, int nValue)
{
    char szBuf[16]={0};
    sprintf(szBuf,"%d",nValue);
    m_strParameters.append("<"+strPath+">"+szBuf+"</"+strPath+">");
}
void CCohResponseMsg::SetXmlAttribute(const string &strPath, const string &strValue)
{

    m_strParameters.append("<"+strPath+"><![CDATA["+strValue+"]]></"+strPath+">");
}

const string & CCohResponseMsg::Encode()
{
    char bufCode[10];
	char bufLength[36];

	sprintf(bufCode,"%d",m_nStatusCode);
	string body=string("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" \
		"<response><result code=\"")+bufCode+"\">"+m_strStatusMsg+"</result>" \
		"<parameters>" +m_strParameters+"</parameters></response>";

	sprintf(bufLength,"Content-Length: %d\r\n",body.length());

	m_strRresponseMsg.append("HTTP/1.0 200 OK\r\n");
	m_strRresponseMsg.append("Content-Type: text/xml;charset=utf-8\r\n");
	m_strRresponseMsg.append(bufLength);
	m_strRresponseMsg.append("Server: COH Server/1.0\r\n\r\n");

	m_strRresponseMsg.append(body);
	return m_strRresponseMsg;
}
int CCohResponseMsg::Decode(const string &strResponse)
{
        double ver;
        int httpCode=0;
        sscanf(strResponse.c_str(),"%*[HTTPhttp]/%lf %d",&ver,&httpCode);
        if(httpCode<200||httpCode>=300)
        {
            CS_XLOG(XLOG_WARNING,"CCohResponseMsg::Decode,httpCode[%d]\n",httpCode);
            return -3;
        }

        size_t end;
        end= strResponse.find("\r\n\r\n");
        if(end==string::npos)
        {
            CS_XLOG(XLOG_WARNING,"CCohResponseMsg::Decode,can't find /r/n/r/n\n");
            return -2;
        }

        sdo::util::TiXmlElement *root,*resultNode;
        m_xmlDoc.Parse(strResponse.substr(end+4).c_str());
        if (m_xmlDoc.Error())
        {
            CS_XLOG(XLOG_WARNING,"CCohResponseMsg::Decode,error:%s\n",m_xmlDoc.ErrorDesc());
            return -1;
        }
        if((root=m_xmlDoc.RootElement())==NULL)
        {
            CS_XLOG(XLOG_WARNING,"CCohResponseMsg::Decode,no root node\n");
            return -1;
        }
        if(strncmp(root->Value(),"response",8)!=0)
        {
            CS_XLOG(XLOG_WARNING,"CCohResponseMsg::Decode,no response node\n");
            return -1;
        }
        if((resultNode=root->FirstChildElement("result"))==NULL)
        {
            CS_XLOG(XLOG_WARNING,"CCohResponseMsg::Decode,no result node\n");
            return -1;
        }

        string strCode=resultNode->Attribute("code");
        if(strCode.length()==0)
        {
            CS_XLOG(XLOG_WARNING,"CCohResponseMsg::Decode,code value NULL\n");
            return -1;
        }
        m_nStatusCode=atoi(strCode.c_str());
        const char *p=NULL;
        p=resultNode->GetText();
        if(p==NULL)
        {
            m_strStatusMsg="";
        }
        else
        {
            m_strStatusMsg.assign(p);
        }
        m_pxmlParameters=root->FirstChildElement("parameters");
        return 0;

}
int CCohResponseMsg::GetStatusCode() const
{
    return m_nStatusCode;
}
const string & CCohResponseMsg::GetStatusMsg() const
{
    return m_strStatusMsg;
}
string CCohResponseMsg::GetAttribute(const string &strPath)
{
    string elemet;
	size_t begin=0,end=0;
	sdo::util::TiXmlElement *before=m_pxmlParameters;
	if(before==NULL)
    {
            return "";
    }
	while((end=strPath.find("/",begin))!=string::npos)
	{
		elemet=strPath.substr(begin,end-begin);
		begin=end+1;
		if(elemet==""||elemet=="/")
			continue;
		if((before=before->FirstChildElement(elemet))==NULL)
		{
			return "";
		}
	}

	elemet=strPath.substr(begin);
	if(elemet!="")
	{
		if((before=before->FirstChildElement(elemet))==NULL)
		{
			return "";
		}
	}
    sdo::util::TiXmlPrinter print;
    before->InnerAccept(&print);
    string result=print.Str();
    result=result.substr(0,result.find_last_not_of("   \n\r\t")+1);
    return result;
}
vector<string> CCohResponseMsg::GetAttributes(const string &strPath)
{
    string elemet;
    vector<string> result;
    size_t begin=0,end=0;
    sdo::util::TiXmlElement *before=m_pxmlParameters;
    if(before==NULL)
    {
        return result;
    }
    while((end=strPath.find("/",begin))!=string::npos)
    {
        elemet=strPath.substr(begin,end-begin);
        begin=end+1;
        if(elemet==""||elemet=="/")
            continue;
        if((before=before->FirstChildElement(elemet))==NULL)
        {
            return result;
        }
    }
    elemet=strPath.substr(begin);

    if(elemet!="")
    {
        if((before=before->FirstChildElement(elemet))==NULL)
        {
            return result;
        }
        else
        {
            sdo::util::TiXmlPrinter print;
            before->InnerAccept(&print);
            string strTmp=print.Str();
            strTmp=strTmp.substr(0,strTmp.find_last_not_of("   \n\r\t")+1);
			result.push_back(strTmp);
        }
        while((before=before->NextSiblingElement(elemet))!=NULL)
        {
            sdo::util::TiXmlPrinter print;
            before->InnerAccept(&print);
            string strTmp=print.Str();
            strTmp=strTmp.substr(0,strTmp.find_last_not_of("   \n\r\t")+1);
			result.push_back(strTmp);
        }
    }
    return result;

}
}
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.examples.bpmn.servicetask;

import java.io.Serializable;

/**
 * @author Christian Stettler
 */
public class ValueBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private final String value;

    public ValueBean(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

}


text:
layout: organization
category: local

title: Thirteen
impact_area: Human Rights
keywords:
location_services:
location_offices:
website: www.thirteen.org

description:
mission: |
  Be a leading provider of educational, informational and cultural products and services, using all media, which: Reflect and respect a diverse and complex world, Serve the underserved, Offer cultural enrichment, Facilitate responsible citizenship, Adhere to the highest standards of artistic and editorial integrity

      * Create opportunities for experimentation

cash_grants:
grants:
service_opp:
services:

learn:
cont_relationship:

salutation:
first_name:
last_name:
title_contact_person:

city: New York
state: NY
address: |
  450 West 33rd Street
  New York NY 10016
lat: 40.753651
lng: -73.99898
phone: 212-560-1313
ext:
fax: 212-560-1314
email:
preferred_contact:
contact_person_intro:
---


text:
from behave import *
from hamcrest import assert_that, contains_string, is_
from features.factories import VisitorFactory, RegisteredUserFactory
from nectr.users.models import User
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from nectr.users.tests.factories import UserFactory

use_step_matcher("parse")

@given("{name} is not registered to nectr")
def step_impl(context, name):
    """
    :type name: str
    :type context: behave.runner.Context
    """
    VisitorFactory(first_name=name)

@given("{name} is registered to nectr")
def step_impl(context, name):
    """
    :param name: str
    :type context: behave.runner.Context
    """
    RegisteredUserFactory(first_name=name)

@given("{name} is on nectr site")
def step_impl(context, name):
    """
    :param name: str ID of User using Name
    :type context: behave.runner.Context
    """
    context.driver.get(context.server_url)

@step("{name} clicks on {element_name} button")
def step_impl(context, name, element_name):
    """
    :type element_name: str
    :type name: str
    :type context: behave.runner.Context
    """
    context.driver.find_element_by_name(element_name).click()

@step('{name} clicks on "{html_element_link}"')
def step_impl(context, name, html_element_link):
    """
    :type name: str
    :type html_element_link: str
    :type context: behave.runner.Context
    """
    context.driver.find_element_by_name(html_element_link).click()

@step("charlie enters correct username and assert Falseword")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

#
# @step("{name} clicks on the {element_type} button")
# def step_impl(context, element_type):
#     """
#     :type type: str
#     :type context: behave.runner.Context
#     """
#     context.driver.find_element_by_xpath("/html/body/div[2]/div/div/form/button").click()

@step("enoc enters incorrect username or assert Falseword")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("enoc clicks the sign in button")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@then('enoc is given message that states "incorrect username or password"')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("login form is reloaded with blank username and assert Falseword fields")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@given("mike does not have a nectr account")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@given("charlie has a nectr student account")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@given("brandon has a nectr student account")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@given("Juan has a nectr student account")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@given("mike is not signed in")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("mike clicks on join the hive")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@then("{name} is redirected to {title} page")
def step_impl(context, name, title):
    """
    :type title: str
    :type name: str
    :type context: behave.runner.Context
    """
    print(title)
    print(context.driver.title)
    WebDriverWait(context.driver, 10).until(
        EC.title_contains(title))
    current_page_title = context.driver.title
    assert_that(current_page_title, contains_string(title),
                "{0} Should be on {1} page".format(name, title))

@given("charlie is signed in")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("charlie clicks on join the hive page")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("presented with join the hive application")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@given("brandon is on join the hive page")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("brandon does not complete application")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@when("brandon clicks on submit button")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@then("application is reloaded with information that has already been filled")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("is incomplete fields are highlighted")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@given("juan is on join the hive page")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("juan completes application")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@when("juan clicks on submit button")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@then("juan is presened with success message")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("charlie enters correct username and password")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@then("{name} is redirected to dashboard")
def step_impl(context, name):
    """
    :type name: str
    :type context: behave.runner.Context
    """
    assert_that(context.driver.title.lower(), contains_string(name.lower()))

@when("{name} enters his correct username")
def step_impl(context, name):
    """
    :type name: str
    :type context: behave.runner.Context
    """
    user = User.objects.get(first_name__exact=name)
    username = user.get_username()
    e = context.driver.find_element_by_name("login")
    e.send_keys(username)

@step("{name} enters his correct password")
def step_impl(context, name):
    """
    :type name: str
    :type context: behave.runner.Context
    """
    user = User.objects.get(first_name__exact=name)
    user.set_password("password")
    e = context.driver.find_element_by_name("password")
    e.send_keys("password")

@step("mike clicks on login button on menu")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    context.driver.find_element_by_id('log-in-link').click()

@step("charlie clicks on login")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    context.driver.find_element_by_id('log-in-link').click()

@step("Charlie clicks on sign in")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    context.driver.find_element_by_name(
        'login_button_form').click()

@step("Brandon is on home page of nectr")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    context.driver.get(context.server_url + "/")

@when('Brandon clicks "Menu"')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    context.driver.find_element_by_name('menu').click()

@step('Brandon clicks "Log In" button')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """

    context.driver.find_element_by_name('nav_Login').click()

@when("Brandon clicks on username text field")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    context.current_element = context.driver.find_element_by_id('id_login').click()

@step('Brandon enters "Cashmeousside"')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    context.current_element.send_keys("Cashmeousside")

@step("Brandon clicks on password text field")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step('Brandon cicks "Sign In" button')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("Brandon is not signed in")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@given('Brandon\'s registered to nectR with username is "Cashmeousside"')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("Brandon's password is Howboudat")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step('title of the page is "Login"')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step('page contains an h1 whos text is "Sign In"')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@then("Brandon is presented with an alert")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("username text field is cleared")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step("password text field is cleared")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step('Brandon enters "Howboudat"')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@step('Brandon enters "Howboudatt"')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    assert False

@when('Brandon enters "Cashmeousside" in username field on Login page')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    element = context.driver.find_element_by_id('id_login')
    element.send_keys('Cashmeousside')

@step('Brandon enters "Howboudat" in password field on Login page')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    element = context.driver.find_element_by_id('id_password')
    element.send_keys('Howboudat')

@step('Brandon clicks "Sign In" button')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    context.driver.find_element_by_name('login_button_form').click()

@then('Brandon goes to his user dashboard page, or his "Dashboard"')
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    print(context.driver.title + '\n')
    print(context.driver.current_url + '\n')
    WebDriverWait(context.driver, 3).until(
        EC.title_contains("cashmeousside"))

@given("Brandon is registered to nectr and wants to login")
def step_impl(context):
    """
    :type context: behave.runner.Context
    """
    user = UserFactory(
        username='Cashmeousside',
        first_name='Brandon',
        last_name='Fox',
        password='Howboudat', )
    assert_that(user.username,is_('Cashmeousside'),
                "The username was not set correctly.")


text:
package org.apache.sis.internal.referencing;

import org.opengis.referencing.cs.AxisDirection;
import org.opengis.referencing.cs.CoordinateSystem;
import org.apache.sis.referencing.cs.CoordinateSystems;
import org.apache.sis.internal.util.Numerics;

import static java.lang.Long.numberOfTrailingZeros;

/**
 * Maps coordinate axes for a "sub-coordinate system" to the axes of a coordinate systems with more dimensions.
 * This enumeration contains the criterion to apply for matching axes, in priority order.
 *
 *
In current implementation, the enumeration values are used only internally.
 * The useful method is {@link #indices(CoordinateSystem, CoordinateSystem)}.

 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 1.2
 * @since   1.2
 * @module
 */
enum AxesMapper {
    /**
     * Match axes having the exact same direction.
     */
    SAME,

    /**
     * Match axes having opposite direction.
     */
    OPPOSITE,

    /**
     * Match axes of the kind "South along 90° East".
     */
    POLAR;

    /**
     * Bitmask for axis direction handled in a special way.
     * They are the substitute for directions like "South along 90° East".
     * We arbitrarily replace the first direction by East and the second direction by North.
     */
    private static final int EAST = 1, NORTH = 2;

    /**
     * Returns the indices in {@code cs} of axes presumed covariant with the {@code subCS} axes.
     * Directions such as "South along 90°E" are arbitrarily handled as if they were covariant with East and North.
     *
     *
Limitations

     * Current implementation considers only the first 64 dimensions.
     * If there is more dimensions, the extra ones are silently ignored.
     *
     * @param  cs     the coordinate system which contains all axes, or {@code null}.
     * @param  subCS  the coordinate system to search into {@code cs}.
     * @return indices in {@code cs} of axes covariant with {@code subCS} axes in the order they appear in {@code subCS},
     *         or {@code null} if at least one {@code subCS} axis cannot be mapped to a {@code cs} axis.
     */
    public static int[] indices(final CoordinateSystem cs, final CoordinateSystem subCS) {
        final int[] indices = new int[subCS.getDimension()];
        long  axesToSearch  = Numerics.bitmask(indices.length) - 1;      // Bit mask of `subCS` axes not yet used.
        long  availableAxes = Numerics.bitmask(cs.getDimension()) - 1;   // Bit mask of `cs` axes not yet used.
        int   directionUsed = 0;
        for (final AxesMapper comparisonMode : values()) {
            /*
             * We will do 3 attempts to match axes, with matching criteria relaxed on each iteration:
             *
             *   1) Matches axes having the same direction.
             *   2) Matches axes having opposite directions.
             *   3) Matches axes of the kind "South along 90° East".
             *
             * On each `comparisonMode` iteration, we iterate over all `subCS` axes which have not be selected in
             * a previous iteration. The `iterSubCS` bitmask has a bit set to 1 for each remaining axes to visit.
             */
            long iterSubCS = axesToSearch, clearSubCS;
            for (int dimSubCS; hasMore(dimSubCS = numberOfTrailingZeros(iterSubCS)); iterSubCS &= clearSubCS) {
                clearSubCS = clearMask(dimSubCS);
                AxisDirection search = subCS.getAxis(dimSubCS).getDirection();
                switch (comparisonMode) {
                    case OPPOSITE: {
                        if (search == (search = AxisDirections.opposite(search)) || search == null) {
                            continue;               // Axis already examined in previous iteration.
                        }
                        break;
                    }
                    case POLAR: {
                        if (CoordinateSystems.isAlongMeridian(search)) {
                            switch (directionUsed) {
                                case 0:     // For first axis, fallback on EAST.
                                case NORTH: search = AxisDirection.EAST;  break;
                                case EAST:  search = AxisDirection.NORTH; break;
                                default:    return null;  // Too many such axes.
                            }
                        }
                    }
                }
                /*
                 * At this point we got the axis direction to search adjusted for the comparison mode.
                 * Now iterate over all `cs` dimensions in search for an axis having a compatible direction.
                 */
                long iterCS = availableAxes, clearCS;
                for (int dimCS; hasMore(dimCS = numberOfTrailingZeros(iterCS)); iterCS &= clearCS) {
                    clearCS = clearMask(dimCS);
                    AxisDirection candidate = cs.getAxis(dimCS).getDirection();
                    if (comparisonMode == POLAR && CoordinateSystems.isAlongMeridian(candidate)) {
                        switch (directionUsed) {
                            case 0:     // For first axis, fallback on EAST.
                            case NORTH: candidate = AxisDirection.EAST;  break;
                            case EAST:  candidate = AxisDirection.NORTH; break;
                            default:    return null;    // Too many such axes.
                        }
                    }
                    if (search.equals(candidate)) {
                        if (search.equals(AxisDirection.EAST))  directionUsed |= EAST;
                        if (search.equals(AxisDirection.NORTH)) directionUsed |= NORTH;
                        indices[dimSubCS] = dimCS;
                        availableAxes &= clearCS;
                        axesToSearch  &= clearSubCS;
                        if (axesToSearch == 0) {
                            return indices;
                        }
                        break;      // Move to next `subCS` axis.
                    }
                }
            }
        }
        return (axesToSearch == 0) ? indices : null;
    }

    /**
     * Returns {@code true} if the given value computed by {@link Long#numberOfTrailingZeros(long)}
     * means that there is at least one more dimension to process. This is used for stopping iterations.
     */
    private static boolean hasMore(final int numBits) {
        return (numBits & ~(Long.SIZE - 1)) == 0;
    }

    /**
     * Returns a mask for clearing the bit associated to the given coordinate system dimension.
     */
    private static long clearMask(final int dim) {
        return ~(1L << dim);
    }
}