text:
import createClass from './functions/createClass';
import View from './View';
import Cursor from './Cursor';

var ModelView = createClass({
	extend: View
},
{
	constructor: function(options)
	{
		View.call(this, options);
		this.scope['*'] = new Cursor({});
	}
});

export default ModelView;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="SPASSmeter" default="all" basedir="." xmlns:jacoco="antlib:org.jacoco.ant">
	<property file="${user.home}/global-build.properties"/>
	<taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml">
        <classpath path="${jacoco.path}/jacocoant.jar"/>
    </taskdef>

	<target name="init">
		<!-- Delete generated folders -->
		<delete dir="junitResults"/>
		<delete dir="${coverage.base.dir}"/>
		<delete dir="${doc.dir}"/>

		<!-- Create folders -->
		<mkdir dir="junitResults"/>
		<mkdir dir="${coverage.base.dir}"/>
		<mkdir dir="${coverage.instr.dir}"/>
		<mkdir dir="${coverage.results.dir}"/>
		<mkdir dir="${doc.dir}"/>
	</target>

	<target name="compile">

        <echo>#####################################</echo>
        <echo>###     Processing SPASS-meter    ###</echo>
        <echo>#####################################</echo>
        <ant dir="Instrumentation.ex" antfile="${build.script.name}" />

	</target>

	<target name="copy.to.eclipse">
	</target>

	<target name="coreTest" depends="copy.to.eclipse">
    </target>

	<target name="report">
	</target>

	<target name="test" depends="coreTest, report">
	</target>

	<target name="storeJars">
	</target>

	<target name="all" depends="init, compile, test, storeJars"/>
	<target name="only.compile" depends="init, compile"/>
</project>

redpajama_set_name: RedPajamaGithub


text:
package thwack.and.bash.game.animation.types;

public enum PlayerAnimationType {
    UP(0), LEFT(1), DOWN(2), RIGHT(3), ;

    private PlayerAnimationType(int id){
	this.ID = id;
    }

    public final int ID;
}


text:
title: Startup Equity Primer
tags: [startups]
published: True
layout: post
---

This is a analysis of SF AngelList job postings and a short explanation of early employee stock options.

I was researching job offers for startups in San Francisco, and wanted to get some real data.

Hopefully this can be a resource for anyone looking for work at startups in SF right now.

## SF Startup Job Data

I found [this analysis](https://www.codingvc.com/analyzing-angellist-job-postings-part-2-salary-and-equity-benchmarks) from 2014 which is pretty good, but is a bit old.

Unfortunately AngelList has since deprecated their API so instead I manually scrolled through ~370 job postings and copied over the company name, job title, company size, and salary and equity ranges. I restricted companies to those strictly in SF with a min salary of at least 40k.

Quick note - this is just raw job posting data, and may not be reflective on actual offers.

#### Salary and Equity for Different Roles

Firstly, I wanted to see the salary and equity breakdown by role.

Basically EM's get paid bank, but this kind of makes sense - the only startups that are trying to hire engineering managers should be quite large/unicorns.

Data Engineers and Devops Engineers see to have the highest salary but this may just be some noise. I was a bit generous with applying the devops engineer label - I catagorized stuff like platform engineer into devops engineer which may have inflated the salaries and also the equity numbers.

The equity numbers have a lot more noise, but it looks pretty consistent across roles outside of CTO / devops. Most of the difference is probably from sample size.

I also broke down these numbers for senior roles. This kind of explains why the average data engineering salary is so high - most data engineering roles are senior roles on average.

It looks like on average Senior roles pay ~20k more. It's hard to spot a trend amongst senior roles in equity data.

Here is the full table of the min, max and avg salary and equity of all job offers, broken down by job title / whether that position is senior or not. You can also check out the notebook I used to make these graphs [here](https://github.com/jcaip/startup).

      Job Title (Normalized)
      Senior
      Min Salary
      Max Salary
      Avg Salary
      Min Equity
      Max Equity
      Avg Equity
      Count

      Backend Engineer
      False
      104.0
      151.0
      127.0
      0.10
      0.44
      0.27
      24

      True
      131.0
      167.0
      149.0
      0.11
      0.68
      0.39
      12

      Data Engineer
      False
      115.0
      144.0
      130.0
      0.08
      0.23
      0.15
      7

      True
      122.0
      178.0
      150.0
      0.11
      0.75
      0.43
      10

      Devops Engineer
      False
      123.0
      161.0
      142.0
      1.96
      2.23
      2.09
      21

      True
      127.0
      174.0
      150.0
      0.06
      0.20
      0.13
      7

      Embedded Engineer
      False
      77.0
      123.0
      100.0
      0.02
      0.40
      0.21
      3

      True
      131.0
      178.0
      154.0
      0.02
      0.20
      0.11
      4

      Engineering Manager
      True
      150.0
      177.0
      164.0
      0.18
      0.55
      0.36
      12

      Frontend Engineer
      False
      96.0
      146.0
      121.0
      0.14
      0.59
      0.37
      19

      True
      125.0
      166.0
      146.0
      0.17
      1.06
      0.62
      18

      Fullstack Engineer
      False
      101.0
      141.0
      121.0
      0.18
      0.81
      0.49
      33

      True
      115.0
      160.0
      137.0
      0.19
      0.83
      0.51
      22

      Head of Engineering / CTO
      True
      118.0
      163.0
      140.0
      2.16
      5.06
      3.61
      24

      Machine Learning Engineer
      False
      109.0
      157.0
      133.0
      0.16
      0.84
      0.50
      22

      True
      121.0
      166.0
      144.0
      0.19
      0.56
      0.38
      11

      Mobile Engineer
      False
      101.0
      152.0
      127.0
      0.08
      0.48
      0.28
      19

      True
      125.0
      168.0
      146.0
      0.18
      0.64
      0.41
      16

      Software Engineer
      False
      102.0
      149.0
      125.0
      0.11
      0.49
      0.30
      36

      True
      125.0
      166.0
      145.0
      0.30
      1.17
      0.74
      34

#### Salary and Equity for Different Sizes

Additionally I looked on the effect size has on salary/equity.

No surprise here - the smaller the company, the less money the offer on average and the more equity they offer on average.

It seems your employee number has a large affect on the equity that you receive, much more than your job title.

#### Salary vs. Equity

Lastly I tried to see if there was a correlation between salary offered and equity offered. Equity and salary are usually presented as two sides of the coin - you give up salary to get equity and vice versa.

It's quite hard to see a precise inverse correlation between the two.

![correlation](/images/startup/salary_vs_equity.png){: .center}

So it looks like if you want a lot of equity you need to be one of the first few hires for startups.
Salary increases and equity decreases with size, and being a senior engineer adds about 20k on average.

There seems to be more job postings for senior engineers than I would have expected, but senior talent is something that's hard to find.

## Startup Equity Primer

This is an explanation of some basic ideas so you can try and evaluate how much your equity is worth.

### Options and Vesting

There are two many different types of stock options, the two most common are: ISOs and RSUs.

Usually if you get RSUs it means your startup is late stage (think Uber, Airbnb), most early-stage employees receive ISOs.

These options allow you to buy a share of stock at your **strike price**, which is usually much lower than the actual share price. It's basically a contract allowing you to purchase stock at a reduced price.

The equity in offers is always structured as "$n$ shares", versus % of the company. So one of the first things you when evaluating an offer is try to figure out what % they are granting you.

Companies do not give you all your options at once, they **vest** over a period of time. The most common scheme is vesting over 4 years with a one year cliff.

This means that you get no options until you hit one-year from your starting date, upon which you get $\frac{12}{48}$ of your promised options. After that you get $\frac{1}{48}$ of your options every month until you've received all your options.

### Dilution and Preferred vs. Common Stock

Companies raise money by issuing stock, which VCs then buy.  Dilution occurs when new stock is issued as part of financing, which increase the overall total number of shares and reduces your relative %.

However, ideally each subsequent round also raises the company valuation, so you still stand to make money.

From what I can tell you can expect 10-15% dilution from each round to the next.

Companies usually differentiate between sweat equity and cash equity -
Employees get **common stock** and investors get **preferred stock**.

Preferred stockholders get the option to either have their investment equity or their investment back, before the common stockholders in the event of an exit. I'll go over an example later demonstrating this.

Some VC funding will also come with a multiple, which allows a sort of guaranteed ROI for the VC.

### Exiting and Taxes
One thing to keep in mind: A share, like any stock is only worth what other people are willing to pay for it.

There are some markets for early startup stock but by and large, these are a very illiquid asset - you usually can only cash out if the startup is acquired or IPOs.

If you ever leave the company, your options usually expire after 90 days. This means that you'll need to either exercise them or give them up.

If you buy your options and then sell them within one year, you'll be charged short term capital gains tax on any return, which is currently 37%.

Otherwise if it's longer than a year before when you buy and sell you'll be charged long term capital gains tax, which is much lower - the highest bracket is 20%.

The American tax code is so complicated that there's something else called the Alternative Minimum Tax. Basically you need to pay at least $n\% $ in taxes, so if you make a bunch of money when you sell your stock then you may be taxed under the AMT rather than by the normal tax brackets.

## Real World Example
Let's consider a concrete example: Say Sally Startup offers you 10000 shares out of a total of 1M shares.

For simplicity we'll say the strike price is $1 and is equal to the current share price, making the current valuation of Sally Startup 1M.

This means you have 1% of Sally Startup or nominally $10000.

Sally Startup then releases a new blockchain based iced tea and this peaks the interest of HardBank, a VC firm who decides to invest.

Sally Startup finances this investment (Series A) by issuing an additional 1M shares of preferred stock, which HardBank buys at $5 a share and a 1x multiple.

HardBank has essential invested 5M at a 5M pre/10M post valuation for 50% of Sally Startup.

When Sally Startup financed that HardBank investment, your 1% was diluted to 0.5%, as you own 10000 shares out of a new total of 2M.

However, as the valuation of the company has went from 1M to 10M your options have increased in value from \\$10000 to \\$50000.

#### Scenario A

Say later on in a year your company struggles a bit because blockchain is no longer hype and is acquired for 7M.

You pull out your calculator and compute (0.005) 7M = $35000, which is the amount of money you expect to receive.

However, when Sally Startup sells for 7M this represent a "down round" or a decrease in valuation.

So in this scenario HardBank has the option to either get his investment back (5M) or his share value which is 50% of 7M or 3.5M. This is because HardBank has preferred stock.

So after HardBank's team of quants does the math and takes the 5M, there's only 2M left, which is split among the plebs who have common stock.

This is also where the multiple comes in - if the multiple was say 7/5x, then HardBank could take the entire 7M and leave nothing.

So after the preferred investors recover their investment, you get (0.01) (2M) = 20000.

But you need to exercise your options to for a dollar a piece, so your net profit is $10000.

This is a bit of a contrived example, but hopefully it shows why down rounds are so bad. The only time when you get the full (acquisition value) * (equity percentage) is if all the perferred investors choose to get their shares instead of their investment back.

#### Scenario B
Suppose Sally Startup does really well and get's acquired for 40M.

In this case, the perferred stockholders have the option to either get their investment back (5M) or their equity value which is 50% of 40M or 20M.

So after consulting taking the 20M, there's still 20M left for the common shareholders, of which you get 1% of.

You still need to exercise your options for a dollar so you're looking at a (20-1)(10000) = 190000 net profit.

It's interesting to note that in Scenario B the company sold for 6x than in Company A, yet you recieve 19x the profit in Scenario B, largely due to the existing financing/cap structure. Long term vs short term capital gains tax could make this difference more pronounced.

Hope you found this helpful.


text:
namespace gin_helper {

// Like Dictionary, but stores object in persistent handle so you can keep it
// safely on heap.
//
// TODO(zcbenz): The only user of this class is ElectronTouchBar, we should
// migrate away from this class.
class PersistentDictionary {
 public:
  PersistentDictionary();
  PersistentDictionary(v8::Isolate* isolate, v8::Local<v8::Object> object);
  PersistentDictionary(const PersistentDictionary& other);
  ~PersistentDictionary();

  PersistentDictionary& operator=(const PersistentDictionary& other);

  v8::Local<v8::Object> GetHandle() const;

  template <typename K, typename V>
  bool Get(const K& key, V* out) const {
    v8::Local<v8::Context> context = isolate_->GetCurrentContext();
    v8::Local<v8::Value> v8_key = gin::ConvertToV8(isolate_, key);
    v8::Local<v8::Value> value;
    v8::Maybe<bool> result = GetHandle()->Has(context, v8_key);
    if (result.IsJust() && result.FromJust() &&
        GetHandle()->Get(context, v8_key).ToLocal(&value))
      return gin::ConvertFromV8(isolate_, value, out);
    return false;
  }

 private:
  v8::Isolate* isolate_ = nullptr;
  v8::Global<v8::Object> handle_;
};

}  // namespace gin_helper

namespace gin {

template <>
struct Converter<gin_helper::PersistentDictionary> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     gin_helper::PersistentDictionary* out) {
    if (!val->IsObject())
      return false;
    *out = gin_helper::PersistentDictionary(isolate, val.As<v8::Object>());
    return true;
  }
};

}  // namespace gin

#endif  // ELECTRON_SHELL_COMMON_GIN_HELPER_PERSISTENT_DICTIONARY_H_


text:
Pier Lorenzo Paracchini
03. dec. 2016

##Required packages

* `readr` package for reading the file containing the dataset,
* `tm` package, used perform text mining operations on unstructured data,
* `snowballC`, used for stemming,
* `wordcloud`, used for visualization purpose and the creation of wordclouds,
* `ggplot2`, used for basic plotting.

## Introduction

The idea is to play around with the `tm` package and perform some common text mining operations on a set of documents, the __corpus__ under analysis in order to learn the potential of this package and, specifically, to understand how to __use the `tm` package functionality to engineer features from free text__.

## The Data

The data used for this experiment is the [SMS Spam Collection v. 1](http://www.dt.fee.unicamp.br/~tiago/smsspamcollection/), a public set of SMS labeled messages that have been collected for mobile phone spam research.

The original file has been pre-processed in order to create a CSV file

* `\t` separator has been replaced by `,`
* `"` in the free text have been replaced by `'`
* the sms text has been included in `"` (quoted text)

```r
dataUri <- "./data/smsspamcollection/SMSSpamCollection.txt"
rawData <- read_csv(dataUri,col_names = F)
```

### A quick look at the data

The dataset contains 5574 entries/ observations, where each entry is a classified sms. The first column represents the label, while the second column represents the text of the sms, both are `character` type. The features/ columns do not have proper names (just the standard names assigned by R).

```r
str(rawData)
## Classes 'tbl_df', 'tbl' and 'data.frame':	5574 obs. of  2 variables:
##  $ X1: chr  "ham" "ham" "spam" "ham" ...
##  $ X2: chr  "Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat..." "Ok lar... Joking wif u oni..." "Free entry in 2 a wkly comp to win FA Cup final tkts 21st May 2005. Text FA to 87121 to receive entry question(std txt rate)T&C"| __truncated__ "U dun say so early hor... U c already then say..." ...
##  - attr(*, "spec")=List of 2
##   ..$ cols   :List of 2
##   .. ..$ X1: list()
##   .. .. ..- attr(*, "class")= chr  "collector_character" "collector"
##   .. ..$ X2: list()
##   .. .. ..- attr(*, "class")= chr  "collector_character" "collector"
##   ..$ default: list()
##   .. ..- attr(*, "class")= chr  "collector_guess" "collector"
##   ..- attr(*, "class")= chr "col_spec"
```

Proper names are given to the columns - `label` and `text` respectively. The `label`, being a categorical variable with two only possible valiues `ham, spam`, is transformed into a factor; the `text` is kept as `character`.

```r
#Adding the column names
colnames(rawData) <- c("label", "text")
#Setting the label as a factor
rawData$label <- as.factor(rawData$label)
```

How many sms have been tagged as `spam` and `ham`?

```r
x <- table(rawData$label)
x
##
##  ham spam
## 4827  747

prop.table(x) * 100
##
##      ham     spam
## 86.59849 13.40151
```

## Importing the __corpus__

The `tm` package offers different options for importing a __corpus__. The creation of a __corpus__ is done using `tm::Corpus` class providing two different arguments

* a __source__ object, containing the documents
* a set of parameters for reading the content from teh source object
    * a __reader__, a function capable of reading in and processing the format delivered by the source object

The list of available __source__ options can be seen using `tm::getSources()`. Text documents can be imported using a dataframe, a vector, a URI, a directory, etc.

```r
getSources()
## [1] "DataframeSource" "DirSource"       "URISource"       "VectorSource"
## [5] "XMLSource"       "ZipSource"
```

The list of available __readers__ can be found using `tm::getReaders()` with the supported text file formats. Each __source__ has a __default reader__ that can be overriden.

```r
getReaders()
##  [1] "readDOC"                 "readPDF"
##  [3] "readPlain"               "readRCV1"
##  [5] "readRCV1asPlain"         "readReut21578XML"
##  [7] "readReut21578XMLasPlain" "readTabular"
##  [9] "readTagged"              "readXML"
```

We have a dataframe containing all of the documents that should be part of our corpus. The __corpus__  is created using `vectorSource` and the sms text `text`, using the default __reader__.

```r
theCorpus <- Corpus(VectorSource(x = rawData$text))
print(theCorpus)
## <<VCorpus>>
## Metadata:  corpus specific: 0, document level (indexed): 0
## Content:  documents: 5574
```

### Inspecting the __corpus__

In order to display detailed information on a corpus, the `tm::inspect` function can be used.

```r
inspect(head(theCorpus,2))
## <<VCorpus>>
## Metadata:  corpus specific: 0, document level (indexed): 0
## Content:  documents: 2
##
## [[1]]
## <<PlainTextDocument>>
## Metadata:  7
## Content:  chars: 111
##
## [[2]]
## <<PlainTextDocument>>
## Metadata:  7
## Content:  chars: 29
```

In order to access the individual documents the `[[` can be used either via position or document identifier using the relevant attribute.

```r
#Using the [[]] format and the position
#first document
theCorpus[[1]]$meta
##   author       : character(0)
##   datetimestamp: 2016-12-03 23:58:35
##   description  : character(0)
##   heading      : character(0)
##   id           : 1
##   language     : en
##   origin       : character(0)
theCorpus[[1]]$content
## [1] "Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat..."

#second document
theCorpus[[2]]$content
## [1] "Ok lar... Joking wif u oni..."

#Getting the document identifier
doc_id <- meta(theCorpus[[2]], "id")
identical(theCorpus[[2]], theCorpus[[doc_id]])
## [1] TRUE
```

## Transforming the corpus

Once we have a corpus, tipically we want to transform its content in order to make it easy to extract information/ insights from it. The `tm` package offfers a variety of __predefined transformations__ that can be applied on the __corpus__. To get a list of the transformation supported use the `tm::getTransformations()` function.

```r
getTransformations()
## [1] "removeNumbers"     "removePunctuation" "removeWords"
## [4] "stemDocument"      "stripWhitespace"
```

* `removeNumbers`, remove numbers from a text document
* `removePunctuation`, remove punctuation `[:punct:]` from a text document
* `removeWords`, remove words specified in the provided list of words from a text document
* `stemDocument`, stem words in a text document using Porter's stemming algorithm
* `stripWhitespace`, strip extra whitespace from a text document, normalized to a single whitespace

Custom transformation can be created and used on the corpus using the `tm::content_transformer` function as a wrapper e.g. `tm::content_tansform(customTransformation)`.

Usually one of the first steps is to remove the most frequently used words from the  corpus, called __stopwords__.  __Stopwords__ are the most common, short function terms, whit no important meaning. The `tm` package offers a list of such words `tm::stopwords` function.

```r
stopwords()
##   [1] "i"          "me"         "my"         "myself"     "we"
##   [6] "our"        "ours"       "ourselves"  "you"        "your"
##  [11] "yours"      "yourself"   "yourselves" "he"         "him"
##  [16] "his"        "himself"    "she"        "her"        "hers"
##  [21] "herself"    "it"         "its"        "itself"     "they"
##  [26] "them"       "their"      "theirs"     "themselves" "what"
##  [31] "which"      "who"        "whom"       "this"       "that"
##  [36] "these"      "those"      "am"         "is"         "are"
##  [41] "was"        "were"       "be"         "been"       "being"
##  [46] "have"       "has"        "had"        "having"     "do"
##  [51] "does"       "did"        "doing"      "would"      "should"
##  [56] "could"      "ought"      "i'm"        "you're"     "he's"
##  [61] "she's"      "it's"       "we're"      "they're"    "i've"
##  [66] "you've"     "we've"      "they've"    "i'd"        "you'd"
##  [71] "he'd"       "she'd"      "we'd"       "they'd"     "i'll"
##  [76] "you'll"     "he'll"      "she'll"     "we'll"      "they'll"
##  [81] "isn't"      "aren't"     "wasn't"     "weren't"    "hasn't"
##  [86] "haven't"    "hadn't"     "doesn't"    "don't"      "didn't"
##  [91] "won't"      "wouldn't"   "shan't"     "shouldn't"  "can't"
##  [96] "cannot"     "couldn't"   "mustn't"    "let's"      "that's"
## [101] "who's"      "what's"     "here's"     "there's"    "when's"
## [106] "where's"    "why's"      "how's"      "a"          "an"
## [111] "the"        "and"        "but"        "if"         "or"
## [116] "because"    "as"         "until"      "while"      "of"
## [121] "at"         "by"         "for"        "with"       "about"
## [126] "against"    "between"    "into"       "through"    "during"
## [131] "before"     "after"      "above"      "below"      "to"
## [136] "from"       "up"         "down"       "in"         "out"
## [141] "on"         "off"        "over"       "under"      "again"
## [146] "further"    "then"       "once"       "here"       "there"
## [151] "when"       "where"      "why"        "how"        "all"
## [156] "any"        "both"       "each"       "few"        "more"
## [161] "most"       "other"      "some"       "such"       "no"
## [166] "nor"        "not"        "only"       "own"        "same"
## [171] "so"         "than"       "too"        "very"
```

Stopwords are unimportant words that will not actually change the meaning of the documents (the sms text). Running a simple example of removing stopwords, it is possible to see that the "and" word is replaced with an empty space, but "AND" is not removed cause of the uppercase letter (case sensitive).

```r
removeWords("going and running", stopwords())
## [1] "going  running"

removeWords("going AND running", stopwords())
## [1] "going AND running"
```

In order to remove the possible challenges connected with uppercase letters, meaningless words, punctuation, numbers, common practices are to simply apply the following transformations to the corpus

* transform the uppercase to lowercase
* remove the stopwords
* remove punctuation symbols
* remove numbers
* normalize the white spaces (a words removed is transformed into a white space)

To iteratively apply transformations to the corpus the `tm::tm_map` function is used.

```r
theCorpus <- tm_map(theCorpus, content_transformer(tolower))
#we had to wrap the tolower function in the content_transformer function, so that our transformation really complies with the tm package's object structure.This is usually required when using a transformation function outside of the tm package (custom transformation).
theCorpus <- tm_map(theCorpus, removeWords, stopwords())
theCorpus <- tm_map(theCorpus, removePunctuation)
theCorpus <- tm_map(theCorpus, removeNumbers)
theCorpus <- tm_map(theCorpus, stripWhitespace)

##see the content of 3 documents
theCorpus[[1]]$content
## [1] "go jurong point crazy available bugis n great world la e buffet cine got amore wat"
theCorpus[[50]]$content
## [1] "u know stubborn even want go hospital kept telling mark weak sucker hospitals weak suckers"
theCorpus[[100]]$content
## [1] " see cup coffee animation"
```

##  Creating the Term Document Matrix (TDM)

In order to find the most common words in the corpus we need to create a sparse matrix from the corpus using `tm::TermDocumentMatrix`.

A `tm::TermDocumentMatrix` is basically a matrix (__sparse matrix__) which includes the all of the possible words in the rows and the documents in the columns. Each cell represents tne number of occurences of that specific word in that specific document.

```r
tdm <- TermDocumentMatrix(theCorpus)
inspect(tdm[1:5, 1:20])
## <<TermDocumentMatrix (terms: 5, documents: 20)>>
## Non-/sparse entries: 0/100
## Sparsity           : 100%
## Maximal term length: 8
## Weighting          : term frequency (tf)
##
##           Docs
## Terms      1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
##   abbey    0 0 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0
##   abdomen  0 0 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0
##   abeg     0 0 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0
##   abelu    0 0 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0
##   aberdeen 0 0 0 0 0 0 0 0 0  0  0  0  0  0  0  0  0  0  0  0
```

To find the most frequent terms using the sparse matrix, the `tm::findFrequentTerms` function can be used. Example which terms is found at least 80 times in the corpus?

```r
#Note the bigger the number of documents, the bigger the lowfreq numer - use 100 if using all of the documents.
findFreqTerms(tdm, lowfreq = 80)
##  [1] "already"  "amp"      "ask"      "back"     "call"     "can"
##  [7] "cash"     "claim"    "come"     "day"      "dear"     "dont"
## [13] "free"     "get"      "give"     "going"    "good"     "got"
## [19] "great"    "happy"    "hey"      "home"     "hope"     "just"
## [25] "know"     "later"    "life"     "like"     "lor"      "love"
## [31] "ltgt"     "make"     "message"  "mobile"   "msg"      "much"
## [37] "need"     "new"      "night"    "now"      "number"   "one"
## [43] "phone"    "please"   "pls"      "prize"    "really"   "reply"
## [49] "right"    "said"     "say"      "see"      "send"     "sorry"
## [55] "still"    "stop"     "take"     "tell"     "text"     "think"
## [61] "time"     "today"    "tomorrow" "txt"      "want"     "wat"
## [67] "way"      "week"     "well"     "will"     "work"     "yeah"
## [73] "yes"
```

One of the limitation of the `tm::findFrequentTerms` function is that it does just return a character vector of terms. To get the number of times a term has been found in the __corpus__ the `tm::tm_term_score` function is of great help.

```r
tm_term_score(tdm, c("already", "tell", "day"), FUN = slam::row_sums)
## already    tell     day
##      90     137     213
```

The `tm::findFrequentTerms` and `tm::tm_term_score` functions can be used to find how many times each term has been used in the __corpus__ overall.

```r
getTermsFrequency <- function(corpus.tdm){
    all.terms <- findFreqTerms(corpus.tdm)
    freq = tm_term_score(x = corpus.tdm, terms = all.terms, FUN = slam::row_sums)
    terms <- names(freq); names(freq) <- NULL
    corpora.allTermsFrequency <- data.frame(term = terms, freq = freq)
    corpora.allTermsFrequency[order(corpora.allTermsFrequency$freq, decreasing = T), ]
}

frequent_terms_df <- getTermsFrequency(tdm)
head(frequent_terms_df, 10)
##      term freq
## 945  call  582
## 4604  now  483
## 985   can  405
## 2673  get  390
## 7631 will  385
## 3522 just  369
## 2516 free  278
## 3946 ltgt  276
## 3619 know  259
## 3787 like  245
tail(frequent_terms_df, 10)
##             term freq
## 7923       zebra    1
## 7925       zeros    1
## 7926       zhong    1
## 7927      zindgi    1
## 7929   zogtorius    1
## 7930        zoom    1
## 7931        zouk    1
## 7932       zyada    1
## 7934      aaniye    1
## 7935 aaooooright    1
```

## Useful Visualizations

Visualizations allows to inspecting the list of words/ terms that are part of the __corpus__ and understand how good the transformation process is.

Visualization can help to identify

* rules that need to be considered when removing punctuation or numbers,
* other words that can be added to the list of stopwords,
* other meaningful insights.

```r
visualizeBarPlot <- function(ftm.df, colorBars = "grey40", titleBarPlot = ""){
    ggplot(ftm.df[1:50,], aes(x = reorder(term,freq), y = freq/1000)) +
        geom_bar(stat = "identity", fill=colorBars) +
        xlab("Terms") + ylab("Frequency (* 1000)")+
        ggtitle(paste(titleBarPlot, "(Top 50)"))  + coord_flip()

}

visualizeWordcloud <- function(ftm.df){
    mypal <- brewer.pal(8,"Dark2")
    wordcloud(words = ftm.df$term,
          freq = ftm.df$freq,
          colors = mypal,
          scale=c(6,.5),
          random.order = F, max.words = 200)
}
```

Visualizing a boxplot with the top 50 terms in decreasing order

```r
visualizeBarPlot(frequent_terms_df, titleBarPlot = "High Frequency Terms")
```

![](exp_NLP_tm_package_files/figure-html/boxplot-1.png)<!-- -->

Visualizing a wordcloud with the top 200 terms

```r
visualizeWordcloud(frequent_terms_df)
```

![](exp_NLP_tm_package_files/figure-html/wordcloud-1.png)<!-- -->

### Stemming words

[Stemming](https://en.wikipedia.org/wiki/Stemming) is the process of reducing inflected (or sometimes derived) words to their word stem, base or root form—generally a written word form. Stemming in R can be performed using the `SnowballC` package. This package has a `SnowballC::wordStem` function that support several languages based on the __Porter's stemming algorithm__.

```r
#example for word stemming
wordStem(c("cats", "mastering", "using", "modelling", "models", "model"))
## [1] "cat"    "master" "us"     "model"  "model"  "model"

#Note that the Porter's algorithm does not provide real english words in all cases
#Something to consider later when looking at the results.
wordStem(c("are", "analyst", "analyze", "analysis"))
## [1] "ar"      "analyst" "analyz"  "analysi"
```

Once the stem has been defined, it is possible to complete the stemmed words using `tm::stemCompletion` function. Be careful when performing stem completion ....

```r
a <- c("mining", "miners", "mining") #Original words
b <- stemDocument(a) #Stemmed words
d <- stemCompletion(
    b, #stemmed words that we want to complete
    dictionary = a #dictionary to be used to complete stemmed words
    )
#Original words
a
## [1] "mining" "miners" "mining"

#Stemmed words
b
## [1] "mine"  "miner" "mine"

#Completion Stemmed Words
d
##     mine    miner     mine
## "miners" "miners" "miners"

#Do u see anything strange?
```

```r
theCorpus_stem <- theCorpus
theCorpus_stem <- tm_map(theCorpus_stem, stemDocument, language = "english")
tdm_stem <- TermDocumentMatrix(theCorpus_stem)
frequent_terms_df_stem <- getTermsFrequency(tdm_stem)
visualizeBarPlot(frequent_terms_df_stem, titleBarPlot = "High Frequency Terms")
```

![](exp_NLP_tm_package_files/figure-html/stemCorpus-1.png)<!-- -->

```r
visualizeWordcloud(frequent_terms_df_stem)
```

![](exp_NLP_tm_package_files/figure-html/stemCorpus-2.png)<!-- -->

## Analysing the Associations among terms
The `tm::TermDocumentMatrix` can be used to identify the association between the cleaned terms found in the corpus. For this purpose we can use the `tm::findAssocs` function in the `tm` package.

```r
#Lets find the associations between the term and others terms that have a correlation higher than 0.2
findAssocs(tdm, "call", 0.20)
## $call
##      prize      claim        ppm     urgent        won   landline
##       0.27       0.26       0.25       0.25       0.25       0.21
##      shows guaranteed       mins
##       0.21       0.20       0.20
```

```r
#Lets find the associations between the bayesian term and others terms that have a correlation higher than 0.2
findAssocs(tdm, "big", 0.20)
## $big
##   africa     avin maturity   silver
##     0.32     0.32     0.23     0.23
```

## References

["SMS Spam Collection v. 1"](http://dcomp.sor.ufscar.br/talmeida/smspamcollection/), Almeida, T.A., Gómez Hidalgo, J.M.
["Introduction to the tm package"](https://cran.r-project.org/web/packages/tm/vignettes/tm.pdf), `tm` vignette
["Text Mining Infrastructure in R"](https://www.jstatsoft.org/article/view/v025i05), Ingo Feinerer, Kurt Hornik, David Meyer

## Session Information

```r
sessionInfo()
## R version 3.3.1 (2016-06-21)
## Platform: x86_64-apple-darwin13.4.0 (64-bit)
## Running under: OS X 10.12.1 (Sierra)
##
## locale:
## [1] no_NO.UTF-8/no_NO.UTF-8/no_NO.UTF-8/C/no_NO.UTF-8/no_NO.UTF-8
##
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base
##
## other attached packages:
## [1] readr_1.0.0        ggplot2_2.1.0      wordcloud_2.5
## [4] RColorBrewer_1.1-2 SnowballC_0.5.1    tm_0.6-2
## [7] NLP_0.1-9
##
## loaded via a namespace (and not attached):
##  [1] Rcpp_0.12.7      knitr_1.14       magrittr_1.5     munsell_0.4.3
##  [5] colorspace_1.2-6 stringr_1.1.0    plyr_1.8.4       tools_3.3.1
##  [9] parallel_3.3.1   grid_3.3.1       gtable_0.2.0     htmltools_0.3.5
## [13] assertthat_0.1   yaml_2.1.13      digest_0.6.10    tibble_1.2
## [17] formatR_1.4      evaluate_0.9     slam_0.1-40      rmarkdown_1.0
## [21] labeling_0.3     stringi_1.1.2    scales_0.4.0
```


text:
package com.github.dreamhead.moco.bootstrap;

import com.github.dreamhead.moco.bootstrap.arg.StartArgs;
import com.github.dreamhead.moco.bootstrap.parser.HttpArgsParser;
import com.github.dreamhead.moco.bootstrap.parser.SocketArgsParser;
import com.github.dreamhead.moco.bootstrap.parser.StartArgsParser;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class StartArgsTest {

    private StartArgsParser startArgsParser;

    @Before
    public void setUp() throws Exception {
        startArgsParser = new HttpArgsParser();
    }

    @Test
    public void should_parse_start_arguments() {
        StartArgs args = startArgsParser.parse(new String[]{"start", "-p", "12306", "-c", "foo.json"});
        assertThat(args.getPort().get(), is(12306));
        assertThat(args.getConfigurationFile().get(), is("foo.json"));
    }

    @Test
    public void should_parse_settings() {
        StartArgs args = startArgsParser.parse(new String[]{"start", "-p", "12306", "-g", "settings.json"});
        assertThat(args.getSettings().get(), is("settings.json"));
    }

    @Test
    public void should_parse_environment() {
        StartArgs args = startArgsParser.parse(new String[]{"start", "-p", "12306", "-g", "setting.json", "-e", "foo"});
        assertThat(args.getEnv().get(), is("foo"));
    }

    @Test(expected = ParseArgException.class)
    public void should_set_at_least_config_or_settings() {
        startArgsParser.parse(new String[]{"start", "-p", "12306"});
    }

    @Test(expected = ParseArgException.class)
    public void should_not_set_config_and_settings() {
        startArgsParser.parse(new String[]{"start", "-p", "12306", "-c", "foo.json", "-g", "settings.json"});
    }

    @Test(expected = ParseArgException.class)
    public void should_not_set_environment_without_global_settings() {
        startArgsParser.parse(new String[]{"start", "-p", "12306", "-e", "foo"});
    }

    @Test(expected = ParseArgException.class)
    public void should_not_set_environment_with_config() {
        startArgsParser.parse(new String[]{"start", "-p", "12306", "-c", "foo.json", "-e", "foo"});
    }

    @Test
    public void should_parse_without_port() {
        StartArgs args = startArgsParser.parse(new String[]{"start", "-c", "foo.json"});
        assertThat(args.getPort().isPresent(), is(false));
        assertThat(args.getConfigurationFile().get(), is("foo.json"));
    }

    @Test
    public void should_parse_socket() {
        StartArgs args = new SocketArgsParser().parse(new String[]{"start", "-c", "foo.json"});
        assertThat(args.isSocket(), is(true));
    }
}


text:
package com.example.black.pmk.gui;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.example.black.pmk.R;
import com.example.black.pmk.data.Patient;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import ca.uhn.fhir.model.dstu2.valueset.AdministrativeGenderEnum;

public class PatientActivity extends FragmentActivity implements
        DatePickerDialog.OnDateSetListener {

    private String name, vorname;
    private int year, month, day;
    private SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    private boolean isMan, changedBirthday;
    private com.example.black.pmk.data.Patient patient = new com.example.black.pmk.data.Patient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        changedBirthday = false;
        setContentView(R.layout.activity_patient);
        Intent intent = getIntent();
        patient = (com.example.black.pmk.data.Patient) intent.getSerializableExtra("patient");

        if (patient != null) {
            if (patient.getName() != "") {
                ((EditText) findViewById(R.id.nameTextfeld)).setText(patient.getName());
            }
            if (patient.getGivenName() != "") {
                ((EditText) findViewById(R.id.vornameTextfeld)).setText(patient.getGivenName());
            }
            if (patient.getGenderEnum() == AdministrativeGenderEnum.MALE) {
                RadioGroup radioGroup = (RadioGroup) findViewById(R.id.genderRadioGroup);
                radioGroup.check(R.id.geschlechtMaennlichButton);
                //(findViewById(R.id.geschlechtMaennlichButton)).setSelected(true);
            }
            if (patient.getGenderEnum() == AdministrativeGenderEnum.FEMALE) {
                RadioGroup radioGroup = (RadioGroup) findViewById(R.id.genderRadioGroup);
                radioGroup.check(R.id.geschlechtWeiblichButton);
                //(findViewById(R.id.geschlechtWeiblichButton)).setSelected(true);
            }
            if (patient.getBirthday() != null) {
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(patient.getBirthday());
                ((Button) findViewById(R.id.geburtstagButton)).setText(sdf.format(calendar.getTime()));
            }
        }

    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
        //do some stuff for example write on log and update TextField on activity
        ((Button) findViewById(R.id.geburtstagButton)).setText( (day) + "."+ (month +1) + "." + year);
        this.day = day;
        this.month = month;
        this.year = year;
        changedBirthday = true;
    }

    public void savePatientCredentials(View v) {
        EditText nameField = (EditText) findViewById(R.id.nameTextfeld);
        EditText surnameField = (EditText) findViewById(R.id.vornameTextfeld);
        RadioButton manRadioButton = (RadioButton) findViewById(R.id.geschlechtMaennlichButton);

        name = nameField.getText().toString();
        vorname = surnameField.getText().toString();

        if(patient == null) {
            patient = new Patient();
        }
        patient.setName(name);
        patient.setGivenName(vorname);
        if(manRadioButton.isChecked()) {
            isMan = true;
            patient.setGenderEnum(AdministrativeGenderEnum.MALE);
        } else {
            isMan = false;
            patient.setGenderEnum(AdministrativeGenderEnum.FEMALE);
        }

        //ehm... a bit strange...
        if (changedBirthday == true) {
            Calendar cal = new GregorianCalendar();
            cal.set(year, month, day, 0, 0, 0);
            patient.setBirthday(cal.getTime());
            //Calendar calendar = new GregorianCalendar();
            //calendar.setTime(patient.getBirthday());
        }

        Intent intent = new Intent();
        intent.putExtra("patient", patient);
        setResult(RESULT_OK, intent);
        finish();
    }
}


text:
"""
    shortly.settings
    ~~~~~~~~~~~~~~~~

    Shortly config.

    :copyright: (c) 2014 by fsp.
    :license: BSD.
"""

import os

DEBUG = False
# Detect environment by whether debug named file exists or not
if os.path.exists(os.path.join(os.path.dirname(__file__), 'debug')):
    DEBUG = True

if DEBUG:
    REDIS_HOST = 'localhost'
    REDIS_PORT = 6379
    REDIS_DB = 0
else:
    REDIS_HOST = 'localhost'
    REDIS_PORT = 6379
    REDIS_DB = 0


text:
dotlink tmux.conf ~/.tmux.conf
mkdir -p ~/.tmux
dotlink plugins ~/.tmux/plugins


text:
#ifndef __GLESDEBUGDRAW_H
#define __GLESDEBUGDRAW_H

#include "Box2D/Box2D.h"
#include "cocos2d.h"

struct b2AABB;

// This class implements debug drawing callbacks that are invoked
// inside b2World::Step.
class GLESDebugDraw : public b2Draw
{
public:
    GLESDebugDraw();

    GLESDebugDraw( float32 ratio );

    virtual void DrawPolygon(const b2Vec2* vertices, int vertexCount, const b2Color& color);

    virtual void DrawFlatPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);

    virtual void DrawSolidPolygon(const b2Vec2* vertices, int vertexCount, const b2Color& color);

    virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color);

    virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color);

    virtual void DrawParticles(const b2Vec2 *centers, float32 radius, const b2ParticleColor *colors, int32 count);

    virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);

    virtual void DrawTransform(const b2Transform& xf);

    virtual void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color);

    virtual void DrawString(int x, int y, const char* string, ...);

    virtual void DrawAABB(b2AABB* aabb, const b2Color& color);

    void setRatio(float32 ratio) { mRatio = ratio; }

protected:
    float32 mRatio;
    cocos2d::GLProgram* mShaderProgram;
    GLint        mPointSizeLocation;
    GLint        mColorLocation;

    void initShader( void );
};

#endif //__GLESDEBUGDRAW_H


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Alagoas</logradouro><bairro>Vila Zilda</bairro><cidade>Guarujá</cidade><uf>SP</uf><cep>11436340</cep></feed>


text:
/**
 * Created by Umayr on 11/29/2014.
 */
var express = require('express');
var router = express.Router();
var tvShowFactory = require('../factories/tvShow');
var is = require('is');
var errors = require('../helpers/errors');

router.get('/get/:id', function (req, res) {
    var id = parseInt(req.params.id);
    if (is.int(id)) {
        tvShowFactory.getByID(id).then(function (result) {
            res.json(result);
        }).catch(function (error) {
            res.json(error);
        });
    }
    else {
        res.json(errors.invalid);
    }
});

router.get('/search/', function (req, res) {
    var name = req.param("name");
    tvShowFactory.search(name).then(function (result) {
        res.json(result);
    }).catch(function (error) {
        res.json(error);
    });

});

module.exports = router;


text:
<?php

namespace app\modules\onedrive;

class Module extends \yii\base\Module
{
    public function init()
    {
        parent::init();
    }
}


text:
<!DOCTYPE html>

  <title>Proon Basic Usage</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="usage.css">

    Proon/Usage/Proon Basic Usage

      proon.add({ name:'c', content:'ok' });proon.add({ name:'c', path:['a','b'] });proon.delete({ path:['a','b'] });proon.delete({ path:[] });

Loading...

    Rich Plastow 2015


text:
<!DOCTYPE html>

        <title>Asela Darshan</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <link rel="stylesheet" type="text/css" href="asela/css/style.css">

Asela Darshan

120496R


text:
package com.fangxu.dota2helper.util;

import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by dear33 on 2016/8/2.
 */
public class NetUtil {
    public static boolean isConnected(Context context) {
        NetworkInfo info = getNetWorkInfo(context);
        return info != null && info.isConnected();
    }

    public static boolean isWifi(Context context) {
        NetworkInfo info = getNetWorkInfo(context);
        if (info != null && info.isConnected()) {
            String type = info.getTypeName();
            return type.equalsIgnoreCase("WIFI");
        }
        return false;
    }

    private static NetworkInfo getNetWorkInfo(Context context) {
        Context ctx;
        if (context instanceof Application) {
            ctx = context;
        } else {
            ctx = context.getApplicationContext();
        }
        ConnectivityManager manager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        return manager.getActiveNetworkInfo();
    }
}


text:
module ShackKit
  module Data
    class HamQTH
      attr_reader :session_key
      QUERY_URL = 'https://www.hamqth.com/xml.php'

      def initialize(params = {})
        return false unless params[:login] && params[:password] || CONFIG && CONFIG.has_key?('ham_qth')
        login = params[:login] || CONFIG['ham_qth']['login']
        password = params[:password] || CONFIG['ham_qth']['password']
        response = HTTP.get("#{QUERY_URL}?u=#{login}&p=#{password}")
        parsed_response = Oga.parse_xml(response.to_s)
        @session_key = parsed_response.xpath("HamQTH/session/session_id").text
        puts parsed_response.xpath("HamQTH/session/error").text if @session_key.empty?
      end

      def lookup(callsign)
        return { error: "Can't query HamQTH.com without submitting valid login credentials first" } if @session_key.nil? || @session_key.empty?
        response = HTTP.get("#{QUERY_URL}?id=#{@session_key}&callsign=#{callsign}&prg=#{USER_AGENT}")
        parsed_response = Oga.parse_xml(response.to_s)
        return { error: parsed_response.xpath("HamQTH/session/error").text } if
          parsed_response.xpath("HamQTH/search").text.empty?
        attributes = parsed_response.xpath("HamQTH/search").first.children.select{ |c| c.class == Oga::XML::Element }.map(&:name)
        {}.tap do |output|
          attributes.each do |attribute|
            output[attribute.to_sym] = parsed_response.xpath("HamQTH/search/#{attribute}").text
          end
        end
      end
    end
  end
end


text:
package vc.kotori.framework.base.exception;

/**
 *
业务异常

 */
public class BusinessException extends BaseException {

	private static final long serialVersionUID = -4902153677077364421L;

	public BusinessException() {
		super();
	}

	public BusinessException(String message, Throwable cause) {
		super(message, cause);
	}

	public BusinessException(String message) {
		super(message);
	}

	public BusinessException(Throwable cause) {
		super(cause);
	}

}


text:
using System;

namespace NBehave.Spec
{
    public delegate void ThrowingAction();
}


text:
#ifndef COLORMAPEDITOR_H_0874895466
#define COLORMAPEDITOR_H_0874895466

/** \file   ColorMapEditor.h
  * \brief  Defines \ref Carna::qt::ColorMapEditor.
  */

#include <Carna/qt/CarnaQt.h>
#include <Carna/qt/MultiSpanSlider.h>
#include <Carna/base/RotatingColor.h>
#include <deque>

namespace Carna
{

namespace qt
{

// ----------------------------------------------------------------------------------
// ColorMapEditor
// ----------------------------------------------------------------------------------

/** \brief
  * Implements user interface for `presets::DVRStage` color map configuration.
  *
  * \author Leonid Kostrykin
  * \date   16.8.11 - 2.4.15
  */
class CARNAQT_LIB ColorMapEditor : public MultiSpanSlider
{

    Q_OBJECT

public:

    /** \brief
      * Holds width of box drawn around ColorMapTrackerEditor instances.
      */
    static const int trackerEditorBoxWidth;

    /** \brief
      * Holds height of box drawn around ColorMapTrackerEditor instances.
      */
    static const int trackerEditorBoxHeight;

    /** \brief
      * Instantiates.
      */
    explicit ColorMapEditor( QWidget* parent = 0 );

    /** \brief
      * Does nothing.
      */
    virtual ~ColorMapEditor();

    /** \brief
      * References the currently selected span or `nullptr` if no span is selected.
      */
    base::math::Span< int >* getSelectedSpan()
    {
        return selectedSpan;
    }

    /** \brief
      * References the currently selected span or `nullptr` if no span is selected.
      */
    const base::math::Span< int >* getSelectedSpan() const
    {
        return selectedSpan;
    }

    /** \brief
      * References the color assigned to the beginning tracker of given span.
      */
    QColor& getFirstColor( int span_index )
    {
        return colors[ 2 * span_index ];
    }

    /** \brief
      * References the color assigned to the ending tracker of given span.
      */
    QColor& getLastColor( int span_index )
    {
        return colors[ 2 * span_index + 1 ];
    }

    /** \brief
      * References the color assigned to the beginning tracker of given span.
      */
    const QColor& getFirstColor( int span_index ) const
    {
        return const_cast< ColorMapEditor* >( this )->getFirstColor( span_index );
    }

    /** \brief
      * References the color assigned to the ending tracker of given span.
      */
    const QColor& getLastColor( int span_index ) const
    {
        return const_cast< ColorMapEditor* >( this )->getLastColor( span_index );
    }

    /** \brief Emits signals indicating this widget's state has changed.
      *
      * Also posts a repaint event.
      */
    void pretendDataChanged()
    {
        emit spansChanged( *this );
        emit spansChanged();
        this->update();
    }

protected:

    virtual void paintEvent( QPaintEvent* ) override;

    /** \brief
      * Updates the layouting of the \ref ColorMapTrackerEditor instances.
      */
    virtual void resizeEvent( QResizeEvent* ) override;

    /** \brief
      * Updates span selection.
      */
    virtual void processTrackerMousePress( base::math::Span< int >&, int index, MultiSpanSliderTracker::Role ) override;

    /** \brief
      * Updates color map.
      */
    virtual void processNewSpan( base::math::Span< int >&, int index ) override;

    /** \brief
      * Updates color map and span selection.
      */
    virtual void processRemovedSpan( base::math::Span< int >&, int index ) override;

    /** \brief
      * Updates ColorMapTrackerEditor instances for currently selected span.
      */
    virtual void processModifiedSpan( base::math::Span< int >&, int index ) override;

private: // TODO: move to PIMPL

    /** \brief
      * References the currently selected span.
      */
    base::math::Span< int >* selectedSpan;

    /** \brief
      * Holds the color map.
      */
    std::deque< QColor > colors;

    /** \brief
      * Holds the color which will be assigned to the span created next.
      */
    base::RotatingColor nextColor;

    /** \brief
      * References the editor for the currently selected beginning tracker or is
      * \f$0\f$ when no span is selected.
      */
    ColorMapTrackerEditor* beginConfigWidget;

    /** \brief
      * References the editor for the currently selected ending tracker or is
      * \f$0\f$ when no span is selected.
      */
    ColorMapTrackerEditor* endConfigWidget;

private slots:

    /** \brief
      * Updates the layouting of the \ref ColorMapTrackerEditor instances.
      */
    void layoutSpanConfigWidgets();

}; // ColorMapEditor

}  // namespace Carna :: qt

}  // namespace Carna

#endif // COLORMAPEDITOR_H_0874895466


text:
package org.interledger.psk;

import org.interledger.InterledgerRuntimeException;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;

/**
 * Convenience header representing the public Encryption header found in PSK messages.
 */
public class PskNonceHeader extends PskMessage.Header {

  /* the expected length of the nonce, in bytes */
  private static final int NONCE_LEN_BYTES = 16;

  private final byte[] nonce;

  private PskNonceHeader(final byte[] nonce) {
    super(WellKnown.NONCE, Base64.getUrlEncoder()
        .withoutPadding()
        .encodeToString(nonce));
    this.nonce = Arrays.copyOf(nonce, nonce.length);
  }

  /**
   * Constructs an instance of the header with a randomly generated value.
   *
   * @return new nonce header
   */
  public static PskNonceHeader seed() {
    try {
      SecureRandom sr = SecureRandom.getInstanceStrong();
      byte[] nonce = new byte[16];
      sr.nextBytes(nonce);
      return new PskNonceHeader(nonce);
    } catch (NoSuchAlgorithmException nsa) {
      throw new InterledgerRuntimeException("Could not generate secure nonce", nsa);
    }
  }

  /**
   * Constructs an instance of the header with the given nonce value.
   *
   * @param nonce The nonce value.
   * @return a {@link PskNonceHeader} instance.
   */
  public static PskNonceHeader fromNonce(byte[] nonce) {
    Objects.requireNonNull(nonce);

    if (nonce.length != NONCE_LEN_BYTES) {
      throw new RuntimeException("Invalid token. Expected 16 bytes.");
    }

    byte[] nonceCopy = Arrays.copyOf(nonce, nonce.length);
    return new PskNonceHeader(nonceCopy);
  }

  /**
   * Constructs an instance of the header with the given header's value interpreted as a base64url
   * encoded nonce.
   *
   * @param header The header value.
   * @return a {@link PskNonceHeader} instance.
   */
  public static PskNonceHeader fromHeader(PskMessage.Header header) {
    Objects.requireNonNull(header);
    return fromNonce(
        Arrays.copyOf(Base64.getUrlDecoder()
            .decode(header.getValue()), NONCE_LEN_BYTES));
  }

  /**
   * Convenience method to retrieve the nonce value.
   * @return The none in {@link byte[]} format.
   */
  public byte[] getNonce() {
    return Arrays.copyOf(nonce, nonce.length);
  }

}


text:
using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using MbUnit.Framework;
using Moq;
using Subtext.Extensibility;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Framework.Data;
using Subtext.Framework.Routing;
using Subtext.Framework.Services;
using Subtext.Framework.Web.HttpModules;
using Subtext.Framework.XmlRpc;
using Enclosure = Subtext.Framework.XmlRpc.Enclosure;
using FrameworkEnclosure = Subtext.Framework.Components.Enclosure;

namespace UnitTests.Subtext.Framework.XmlRpc
{
    [TestFixture]
    public class MetaBlogApiTests
    {
        [Test]
        public void getCategories_ReturnsCategoriesInRepository()
        {
            //arrange
            var blog = new Blog { AllowServiceAccess = true, Host = "localhost", UserName = "username", Password = "password" };
            var category = new LinkCategory
            {
                BlogId = blog.Id,
                IsActive = true,
                Description = "Test category",
                Title = "CategoryA",
                CategoryType = CategoryType.PostCollection,
                Id = 42
            };

            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(blog);
            subtextContext.Setup(c => c.UrlHelper.CategoryUrl(It.IsAny<LinkCategory>())).Returns("/Category/42.aspx");
            subtextContext.Setup(c => c.UrlHelper.CategoryRssUrl(It.IsAny<LinkCategory>())).Returns("/rss.aspx?catId=42");
            subtextContext.Setup(c => c.Repository.GetCategories(CategoryType.PostCollection, false)).Returns(new[] { category });
            subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IDependencyResolver>().Object);
            var api = new MetaWeblog(subtextContext.Object);

            //act
            CategoryInfo[] categories = api.getCategories(blog.Id.ToString(), "username", "password");

            //assert
            Assert.AreEqual(1, categories.Length);
            Assert.AreEqual("http://localhost/Category/42.aspx", categories[0].htmlUrl);
            Assert.AreEqual("http://localhost/rss.aspx?catId=42", categories[0].rssUrl);
        }

        [Test]
        public void newPost_WithCategory_CreatesEntryWithCategory()
        {
            //arrange
            var repository = new DatabaseObjectProvider();
            var blog = new Blog { Id = 42, UserName = "username", Password = "password", AllowServiceAccess = true, Host = "localhost" };

            var entryPublisher = new Mock<IEntryPublisher>();
            Entry publishedEntry = null;
            entryPublisher.Setup(publisher => publisher.Publish(It.IsAny<Entry>())).Callback<Entry>(e => publishedEntry = e);
            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(blog);
            subtextContext.Setup(c => c.Repository).Returns(repository);
            subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IDependencyResolver>().Object);

            var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object);
            var post = new Post
            {
                categories = new[] { "CategoryA" },
                description = "A unit test",
                title = "A unit testing title",
                dateCreated = DateTime.UtcNow
            };

            //act
            api.newPost("42", "username", "password", post, true);

            //assert
            Assert.IsNotNull(publishedEntry);
            Assert.AreEqual(1, publishedEntry.Categories.Count);
            Assert.AreEqual("CategoryA", publishedEntry.Categories.First());
        }

        [Test]
        public void NewPost_WithNullCategories_DoesNotTHrowException()
        {
            //arrange
            var blog = new Blog { Id = 42, UserName = "username", Password = "password", AllowServiceAccess = true, Host = "localhost" };

            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(blog);
            Entry publishedEntry = null;
            var entryPublisher = new Mock<IEntryPublisher>();
            entryPublisher.Setup(publisher => publisher.Publish(It.IsAny<Entry>())).Returns(42).Callback<Entry>(
                entry => publishedEntry = entry);

            var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object);
            var post = new Post
            {
                categories = null,
                description = "A unit test",
                title = "A unit testing title",
                dateCreated = DateTime.UtcNow
            };

            // act
            string result = api.newPost(blog.Id.ToString(CultureInfo.InvariantCulture), "username", "password", post,
                                        true);

            // assert
            int entryId = int.Parse(result);
            Assert.AreEqual(42, entryId);
            Assert.AreEqual(0, publishedEntry.Categories.Count, "Should not have added categories.");
        }

        [Test]
        public void NewPost_WithFutureDate_SyndicatesInTheFuture()
        {
            //arrange
            var blog = new Blog { Id = 42, UserName = "username", Password = "password", AllowServiceAccess = true, Host = "localhost" };

            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(blog);
            Entry publishedEntry = null;
            var entryPublisher = new Mock<IEntryPublisher>();
            entryPublisher.Setup(publisher => publisher.Publish(It.IsAny<Entry>())).Returns(42).Callback<Entry>(
                entry => publishedEntry = entry);
            var utcNow = DateTime.UtcNow;
            var now = new DateTime(utcNow.Year, utcNow.Month, utcNow.Day, utcNow.Hour, utcNow.Minute, utcNow.Second, DateTimeKind.Unspecified);

            var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object);
            var post = new Post
                       {
                           categories = null,
                           description = "A unit test",
                           title = "A unit testing title",
                           dateCreated = now.AddDays(1)
                       };

            // act
            api.newPost(blog.Id.ToString(CultureInfo.InvariantCulture), "username", "password", post, true);

            // assert
            Assert.IsNotNull(publishedEntry);
            Assert.Greater(publishedEntry.DateSyndicated, now.AddDays(.75));
            Assert.LowerEqualThan(publishedEntry.DateSyndicated, now.AddDays(1));
            Assert.AreEqual(publishedEntry.DatePublishedUtc.Kind, DateTimeKind.Utc);
        }

        [Test]
        public void NewPostWithEnclosureCreatesEntryWithEnclosure()
        {
            //arrange
            var blog = new Blog { Id = 42, UserName = "username", Password = "password", AllowServiceAccess = true, Host = "localhost" };

            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(blog);
            FrameworkEnclosure publishedEnclosure = null;
            subtextContext.Setup(c => c.Repository.Create(It.IsAny<FrameworkEnclosure>())).Callback<FrameworkEnclosure>(
                enclosure => publishedEnclosure = enclosure);
            var entryPublisher = new Mock<IEntryPublisher>();
            entryPublisher.Setup(publisher => publisher.Publish(It.IsAny<Entry>())).Returns(42);
            DateTime now = DateTime.UtcNow;
            DateTime utcNow = now.ToUniversalTime();

            var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object);
            var post = new Post();
            post.categories = null;
            post.description = "A unit test";
            post.title = "A unit testing title";
            post.dateCreated = utcNow.AddDays(1);

            var postEnclosure = new Enclosure();
            postEnclosure.url = "http://codeclimber.net.nz/podcast/mypodcast.mp3";
            postEnclosure.type = "audio/mp3";
            postEnclosure.length = 123456789;
            post.enclosure = postEnclosure;

            // act
            string result = api.newPost(blog.Id.ToString(CultureInfo.InvariantCulture), "username", "password", post,
                                        true);

            // assert
            Assert.IsNotNull(publishedEnclosure);
            Assert.AreEqual("http://codeclimber.net.nz/podcast/mypodcast.mp3", publishedEnclosure.Url);
            Assert.AreEqual("audio/mp3", publishedEnclosure.MimeType);
            Assert.AreEqual(123456789, publishedEnclosure.Size);
        }

        [Test]
        public void NewPostAcceptsNullEnclosure()
        {
            //arrange
            var blog = new Blog { Id = 42, UserName = "username", Password = "password", AllowServiceAccess = true, Host = "localhost" };

            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(blog);
            Entry publishedEntry = null;
            var entryPublisher = new Mock<IEntryPublisher>();
            entryPublisher.Setup(publisher => publisher.Publish(It.IsAny<Entry>())).Returns(42).Callback<Entry>(
                entry => publishedEntry = entry);
            DateTime now = DateTime.UtcNow;
            DateTime utcNow = now.ToUniversalTime();

            var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object);
            var post = new Post();
            post.categories = null;
            post.description = "A unit test";
            post.title = "A unit testing title";
            post.dateCreated = utcNow.AddDays(1);
            post.enclosure = null;

            // act
            string result = api.newPost(blog.Id.ToString(CultureInfo.InvariantCulture), "username", "password", post,
                                        true);

            // assert
            Assert.IsNull(publishedEntry.Enclosure);
        }

        [Test]
        public void editPost_WithEntryHavingEnclosure_UpdatesEntryEnclosureWithNewEnclosure()
        {
            //arrange
            var entry = new Entry(PostType.BlogPost) { Title = "Title 1", Body = "Blah", IsActive = true };
            entry.DateCreatedUtc = entry.DatePublishedUtc = entry.DateModifiedUtc = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture);
            entry.Categories.Add("TestCategory");
            var blog = new Blog { Id = 123, Host = "localhost", AllowServiceAccess = true, UserName = "username", Password = "password" };
            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(blog);
            subtextContext.Setup(c => c.Repository.GetEntry(It.IsAny<Int32>(), false, true)).Returns(entry);
            var entryPublisher = new Mock<IEntryPublisher>();
            Entry publishedEntry = null;
            entryPublisher.Setup(p => p.Publish(It.IsAny<Entry>())).Callback<Entry>(e => publishedEntry = e);
            FrameworkEnclosure enclosure = UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>",
                                              "http://perseus.franklins.net/hanselminutes_0107.mp3", "audio/mp3", 123, 26707573, true, true);
            entry.Enclosure = enclosure;
            var post = new Post { title = "Title 2", description = "Blah", dateCreated = DateTime.UtcNow };

            var postEnclosure = new Enclosure
            {
                url = "http://codeclimber.net.nz/podcast/mypodcastUpdated.mp3",
                type = "audio/mp3",
                length = 123456789
            };
            post.enclosure = postEnclosure;
            var metaWeblog = new MetaWeblog(subtextContext.Object, entryPublisher.Object);

            // act
            bool result = metaWeblog.editPost("123", "username", "password", post, true);

            // assert
            Assert.IsTrue(result);
            Assert.IsNotNull(publishedEntry.Enclosure);
            Assert.AreEqual("http://codeclimber.net.nz/podcast/mypodcastUpdated.mp3", entry.Enclosure.Url);
        }

        [Test]
        public void editPost_WithEnclosure_AddsNewEnclosure()
        {
            //arrange
            FrameworkEnclosure enclosure = UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>",
                                              "http://example.com/foo.mp3", "audio/mp3", 123, 26707573, true, true);
            var entry = new Entry(PostType.BlogPost) { Title = "Title 1", Body = "Blah", IsActive = true, Enclosure = enclosure };
            entry.DateCreatedUtc = entry.DatePublishedUtc = entry.DateModifiedUtc = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture);
            entry.Categories.Add("TestCategory");
            var blog = new Blog { Id = 123, Host = "localhost", AllowServiceAccess = true, UserName = "username", Password = "password" };
            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(blog);
            subtextContext.Setup(c => c.Repository.GetEntry(It.IsAny<Int32>(), false, true)).Returns(entry);
            var entryPublisher = new Mock<IEntryPublisher>();
            Entry publishedEntry = null;
            entryPublisher.Setup(p => p.Publish(It.IsAny<Entry>())).Callback<Entry>(e => publishedEntry = e);
            var post = new Post { title = "Title 2", description = "Blah", dateCreated = DateTime.UtcNow };
            var postEnclosure = new Enclosure
            {
                url = "http://example.com/bar.mp3",
                type = "audio/mp3",
                length = 123456789
            };
            post.enclosure = postEnclosure;
            var metaWeblog = new MetaWeblog(subtextContext.Object, entryPublisher.Object);

            // act
            bool result = metaWeblog.editPost("123", "username", "password", post, true);

            // assert
            Assert.IsNotNull(publishedEntry.Enclosure);
            Assert.AreEqual("http://example.com/bar.mp3", entry.Enclosure.Url);
            Assert.AreEqual("audio/mp3", entry.Enclosure.MimeType);
            Assert.AreEqual(123456789, entry.Enclosure.Size);
            Assert.IsTrue(result);
        }

        [Test]
        public void EditPost_WithoutEnclosure_RemovesEnclosureFromEntry()
        {
            // arrange
            FrameworkEnclosure enclosure = UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>",
                                              "http://example.com/foo.mp3", "audio/mp3", 123, 2650, true, true);
            enclosure.Id = 321;
            var entry = new Entry(PostType.BlogPost) { Title = "Title 1", Body = "Blah", IsActive = true, Enclosure = enclosure };
            entry.DateCreatedUtc = entry.DatePublishedUtc = entry.DateModifiedUtc = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture);
            var subtextContext = new Mock<ISubtextContext>();
            var blog = new Blog { Id = 999, Host = "localhost", AllowServiceAccess = true, UserName = "username", Password = "password" };
            subtextContext.Setup(c => c.Blog).Returns(blog);
            subtextContext.Setup(c => c.Repository.GetEntry(It.IsAny<Int32>(), false, true)).Returns(entry);
            bool enclosureDeleted = false;
            subtextContext.Setup(c => c.Repository.DeleteEnclosure(321)).Callback(() => enclosureDeleted = true);
            var entryPublisher = new Mock<IEntryPublisher>();
            entryPublisher.Setup(p => p.Publish(It.IsAny<Entry>()));
            var post = new Post { title = "Title 2", description = "Blah", dateCreated = DateTime.UtcNow };
            var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object);

            // act
            bool result = api.editPost("999", "username", "password", post, true);

            // assert
            Assert.IsTrue(enclosureDeleted);
            Assert.IsTrue(result);
        }

        [Test]
        [RollBack2]
        public void editPost_WithPostHavingDifferentCategoryThanEntry_UpdatesCategory()
        {
            // arrange
            var entry = new Entry(PostType.BlogPost) { Id = 12345, Title = "Title 1", Body = "Blah", IsActive = true };
            entry.Categories.Add("Category1");
            entry.DateCreatedUtc = entry.DatePublishedUtc = entry.DateModifiedUtc = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture);
            var subtextContext = new Mock<ISubtextContext>();
            var blog = new Blog { Id = 999, Host = "localhost", AllowServiceAccess = true, UserName = "username", Password = "password" };
            subtextContext.Setup(c => c.Blog).Returns(blog);
            subtextContext.Setup(c => c.Repository.GetEntry(It.IsAny<Int32>(), false, true)).Returns(entry);
            var entryPublisher = new Mock<IEntryPublisher>();
            Entry publishedEntry = null;
            entryPublisher.Setup(p => p.Publish(It.IsAny<Entry>())).Callback<Entry>(e => publishedEntry = e);
            var post = new Post { title = "Title 2", description = "Blah", categories = new[] { "Category2" }, dateCreated = DateTime.UtcNow };
            var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object);

            // act
            bool result = api.editPost("12345", "username", "password", post, true);

            // assert
            Assert.AreEqual(1, publishedEntry.Categories.Count);
            Assert.AreEqual("Category2", publishedEntry.Categories.First());
            Assert.IsTrue(result);
        }

        [Test]
        public void editPost_WithNoCategories_RemovesCategoriesFromEntry()
        {
            //arrange
            var entry = new Entry(PostType.BlogPost) { Title = "Title 1", Body = "Blah", IsActive = true };
            entry.DateCreatedUtc = entry.DatePublishedUtc = entry.DateModifiedUtc = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture);
            entry.Categories.Add("TestCategory");
            var blog = new Blog { Id = 123, Host = "localhost", AllowServiceAccess = true, UserName = "username", Password = "password" };
            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(blog);
            subtextContext.Setup(c => c.Repository.GetEntry(It.IsAny<Int32>(), false, true)).Returns(entry);
            var entryPublisher = new Mock<IEntryPublisher>();
            Entry publishedEntry = null;
            entryPublisher.Setup(p => p.Publish(It.IsAny<Entry>())).Callback<Entry>(e => publishedEntry = e);
            var post = new Post { title = "Title 2", description = "Blah", categories = null, dateCreated = DateTime.UtcNow };
            var metaWeblog = new MetaWeblog(subtextContext.Object, entryPublisher.Object);

            // act
            metaWeblog.editPost("123", "username", "password", post, true);

            // assert
            Assert.AreEqual(0, publishedEntry.Categories.Count, "We expected no category.");
        }

        [Test]
        [RollBack2]
        public void GetRecentPosts_ReturnsRecentPosts()
        {
            string hostname = UnitTestHelper.GenerateUniqueString();
            var repository = new DatabaseObjectProvider();
            repository.CreateBlog("", "username", "password", hostname, "");
            UnitTestHelper.SetHttpContextWithBlogRequest(hostname, "");
            Blog blog = repository.GetBlog(hostname, "");
            BlogRequest.Current.Blog = blog;
            blog.AllowServiceAccess = true;

            var urlHelper = new Mock<BlogUrlHelper>();
            urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/entry/whatever");
            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog);
            //TODO: FIX!!!
            subtextContext.Setup(c => c.Repository).Returns(repository);
            subtextContext.SetupBlog(blog);
            subtextContext.Setup(c => c.UrlHelper).Returns(urlHelper.Object);
            subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IDependencyResolver>().Object);

            var api = new MetaWeblog(subtextContext.Object);
            Post[] posts = api.getRecentPosts(Config.CurrentBlog.Id.ToString(), "username", "password", 10);
            Assert.AreEqual(0, posts.Length);

            string category1Name = UnitTestHelper.GenerateUniqueString();
            string category2Name = UnitTestHelper.GenerateUniqueString();
            UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category1Name);
            UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category2Name);

            var entry = new Entry(PostType.BlogPost);
            entry.Title = "Title 1";
            entry.Body = "Blah";
            entry.IsActive = true;
            entry.IncludeInMainSyndication = true;
            entry.DateCreatedUtc =
                entry.DatePublishedUtc =
                entry.DateModifiedUtc = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            entry.Categories.Add(category1Name);
            UnitTestHelper.Create(entry);

            entry = new Entry(PostType.BlogPost);
            entry.IncludeInMainSyndication = true;
            entry.Title = "Title 2";
            entry.Body = "Blah1";
            entry.IsActive = true;
            entry.DateCreatedUtc =
                entry.DatePublishedUtc =
                entry.DateModifiedUtc = DateTime.ParseExact("1976/05/25", "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            entry.Categories.Add(category1Name);
            entry.Categories.Add(category2Name);
            UnitTestHelper.Create(entry);

            entry = new Entry(PostType.BlogPost);
            entry.Title = "Title 3";
            entry.IncludeInMainSyndication = true;
            entry.Body = "Blah2";
            entry.IsActive = true;
            entry.DateCreatedUtc =
                entry.DatePublishedUtc =
                entry.DateModifiedUtc = DateTime.ParseExact("1979/09/16", "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            UnitTestHelper.Create(entry);

            entry = new Entry(PostType.BlogPost);
            entry.Title = "Title 4";
            entry.IncludeInMainSyndication = true;
            entry.Body = "Blah3";
            entry.IsActive = true;
            entry.DateCreatedUtc =
                entry.DatePublishedUtc =
                entry.DateModifiedUtc = DateTime.ParseExact("2006/01/01", "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            entry.Categories.Add(category2Name);
            int entryId = UnitTestHelper.Create(entry);

            string enclosureUrl = "http://perseus.franklins.net/hanselminutes_0107.mp3";
            string enclosureMimeType = "audio/mp3";
            long enclosureSize = 26707573;

            FrameworkEnclosure enc =
                UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>",
                                              enclosureUrl, enclosureMimeType, entryId, enclosureSize, true, true);
            repository.Create(enc);

            posts = api.getRecentPosts(Config.CurrentBlog.Id.ToString(), "username", "password", 10);
            Assert.AreEqual(4, posts.Length, "Expected 4 posts");
            Assert.AreEqual(1, posts[3].categories.Length, "Expected our categories to be there.");
            Assert.AreEqual(2, posts[2].categories.Length, "Expected our categories to be there.");
            Assert.IsNotNull(posts[1].categories, "Expected our categories to be there.");
            Assert.AreEqual(1, posts[0].categories.Length, "Expected our categories to be there.");
            Assert.AreEqual(category1Name, posts[3].categories[0], "The category returned by the MetaBlogApi is wrong.");
            Assert.AreEqual(category2Name, posts[0].categories[0], "The category returned by the MetaBlogApi is wrong.");

            Assert.AreEqual(enclosureUrl, posts[0].enclosure.Value.url, "Not what we expected for the enclosure url.");
            Assert.AreEqual(enclosureMimeType, posts[0].enclosure.Value.type,
                            "Not what we expected for the enclosure mimetype.");
            Assert.AreEqual(enclosureSize, posts[0].enclosure.Value.length,
                            "Not what we expected for the enclosure size.");
        }

        [Test]
        [RollBack2]
        public void GetPages_WithNumberOfPosts_ReturnsPostsInPages()
        {
            //arrange
            var repository = new DatabaseObjectProvider();
            string hostname = UnitTestHelper.GenerateUniqueString();
            repository.CreateBlog("", "username", "password", hostname, "");
            UnitTestHelper.SetHttpContextWithBlogRequest(hostname, "");
            BlogRequest.Current.Blog = repository.GetBlog(hostname, "");
            Config.CurrentBlog.AllowServiceAccess = true;

            var urlHelper = new Mock<BlogUrlHelper>();
            urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/entry/whatever");
            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog);
            //TODO: FIX!!!
            subtextContext.Setup(c => c.Repository).Returns(repository);
            subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IDependencyResolver>().Object);
            subtextContext.Setup(c => c.UrlHelper).Returns(urlHelper.Object);

            var api = new MetaWeblog(subtextContext.Object);
            Post[] posts = api.getRecentPosts(Config.CurrentBlog.Id.ToString(), "username", "password", 10);
            Assert.AreEqual(0, posts.Length);

            string category1Name = UnitTestHelper.GenerateUniqueString();
            string category2Name = UnitTestHelper.GenerateUniqueString();
            UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category1Name);
            UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category2Name);

            var entry = new Entry(PostType.Story);
            entry.Title = "Title 1";
            entry.Body = "Blah";
            entry.IsActive = true;
            entry.IncludeInMainSyndication = true;
            entry.DateCreatedUtc =
                entry.DatePublishedUtc =
                entry.DateModifiedUtc = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            UnitTestHelper.Create(entry);

            entry = new Entry(PostType.Story);
            entry.IncludeInMainSyndication = true;
            entry.Title = "Title 2";
            entry.Body = "Blah1";
            entry.IsActive = true;
            entry.DateCreatedUtc =
                entry.DatePublishedUtc =
                entry.DateModifiedUtc = DateTime.ParseExact("1976/05/25", "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            UnitTestHelper.Create(entry);

            entry = new Entry(PostType.Story);
            entry.Categories.Add(category1Name);
            entry.Categories.Add(category2Name);
            entry.Title = "Title 3";
            entry.IncludeInMainSyndication = true;
            entry.Body = "Blah2";
            entry.IsActive = true;
            entry.DateCreatedUtc =
                entry.DatePublishedUtc =
                entry.DateModifiedUtc = DateTime.ParseExact("1979/09/16", "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            UnitTestHelper.Create(entry);

            entry = new Entry(PostType.Story);
            entry.Title = "Title 4";
            entry.IncludeInMainSyndication = true;
            entry.Body = "Blah3";
            entry.IsActive = true;
            entry.DateCreatedUtc =
                entry.DatePublishedUtc =
                entry.DateModifiedUtc = DateTime.ParseExact("2006/01/01", "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            entry.Categories.Add(category2Name);
            int entryId = UnitTestHelper.Create(entry);

            string enclosureUrl = "http://perseus.franklins.net/hanselminutes_0107.mp3";
            string enclosureMimeType = "audio/mp3";
            long enclosureSize = 26707573;

            FrameworkEnclosure enc =
                UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>",
                                              enclosureUrl, enclosureMimeType, entryId, enclosureSize, true, true);
            repository.Create(enc);

            //act
            posts = api.getPages(Config.CurrentBlog.Id.ToString(), "username", "password", 2);

            //assert
            Assert.AreEqual(2, posts.Length);
            Assert.AreEqual(1, posts[0].categories.Length);
            Assert.AreEqual(2, posts[1].categories.Length);
            Assert.IsNotNull(posts[1].categories, "Expected our categories to be there.");

            Assert.AreEqual(enclosureUrl, posts[0].enclosure.Value.url);
            Assert.AreEqual(enclosureMimeType, posts[0].enclosure.Value.type);
            Assert.AreEqual(enclosureSize, posts[0].enclosure.Value.length);
        }

        [Test]
        [RollBack2]
        public void GetPost_WithEntryId_ReturnsPostWithCorrectEntryUrl()
        {
            //arrange
            var repository = new DatabaseObjectProvider();
            string hostname = UnitTestHelper.GenerateUniqueString();
            repository.CreateBlog("", "username", "password", hostname, "");
            UnitTestHelper.SetHttpContextWithBlogRequest(hostname, "");
            BlogRequest.Current.Blog = repository.GetBlog(hostname, "");
            Config.CurrentBlog.AllowServiceAccess = true;

            var urlHelper = new Mock<BlogUrlHelper>();
            urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/entry/whatever");
            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog);
            //TODO: FIX!!!
            subtextContext.Setup(c => c.Repository).Returns(repository);
            subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IDependencyResolver>().Object);
            subtextContext.Setup(c => c.UrlHelper).Returns(urlHelper.Object);

            var api = new MetaWeblog(subtextContext.Object);
            string category1Name = UnitTestHelper.GenerateUniqueString();
            string category2Name = UnitTestHelper.GenerateUniqueString();
            UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category1Name);
            UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category2Name);

            var entry = new Entry(PostType.BlogPost);
            entry.Title = "Title 1";
            entry.Body = "Blah";
            entry.IsActive = true;
            entry.IncludeInMainSyndication = true;
            entry.DateCreatedUtc =
                entry.DatePublishedUtc =
                entry.DateModifiedUtc = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            entry.Categories.Add(category1Name);
            int entryId = UnitTestHelper.Create(entry);
            string enclosureUrl = "http://perseus.franklins.net/hanselminutes_0107.mp3";
            string enclosureMimeType = "audio/mp3";
            long enclosureSize = 26707573;

            FrameworkEnclosure enc =
                UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>",
                                              enclosureUrl, enclosureMimeType, entryId, enclosureSize, true, true);
            repository.Create(enc);

            //act
            Post post = api.getPost(entryId.ToString(), "username", "password");

            //assert
            Assert.AreEqual(1, post.categories.Length);
            Assert.AreEqual("http://" + hostname + "/entry/whatever", post.link);
            Assert.AreEqual("http://" + hostname + "/entry/whatever", post.permalink);
            Assert.AreEqual(category1Name, post.categories[0]);
            Assert.AreEqual(enclosureUrl, post.enclosure.Value.url);
            Assert.AreEqual(enclosureMimeType, post.enclosure.Value.type);
            Assert.AreEqual(enclosureSize, post.enclosure.Value.length);
        }

        [Test]
        [RollBack2]
        public void GetPage_ReturnsPostWithhCorrectEntrUrl()
        {
            //arrange
            var repository = new DatabaseObjectProvider();
            string hostname = UnitTestHelper.GenerateUniqueString();
            repository.CreateBlog("", "username", "password", hostname, "");
            UnitTestHelper.SetHttpContextWithBlogRequest(hostname, "");
            BlogRequest.Current.Blog = repository.GetBlog(hostname, "");
            Config.CurrentBlog.AllowServiceAccess = true;

            var urlHelper = new Mock<BlogUrlHelper>();
            urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/entry/whatever");
            var subtextContext = new Mock<ISubtextContext>();
            subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog);
            //TODO: FIX!!!
            subtextContext.Setup(c => c.Repository).Returns(repository);
            subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IDependencyResolver>().Object);
            subtextContext.Setup(c => c.UrlHelper).Returns(urlHelper.Object);

            var api = new MetaWeblog(subtextContext.Object);
            string category1Name = UnitTestHelper.GenerateUniqueString();
            string category2Name = UnitTestHelper.GenerateUniqueString();
            UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category1Name);
            UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category2Name);

            var entry = new Entry(PostType.Story);
            entry.Title = "Title 1";
            entry.Body = "Blah";
            entry.IsActive = true;
            entry.IncludeInMainSyndication = true;
            entry.DateCreatedUtc =
                entry.DatePublishedUtc =
                entry.DateModifiedUtc = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();
            entry.Categories.Add(category1Name);
            int entryId = UnitTestHelper.Create(entry);
            string enclosureUrl = "http://perseus.franklins.net/hanselminutes_0107.mp3";
            string enclosureMimeType = "audio/mp3";
            long enclosureSize = 26707573;

            FrameworkEnclosure enc =
                UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>",
                                              enclosureUrl, enclosureMimeType, entryId, enclosureSize, true, true);
            repository.Create(enc);

            //act
            Post post = api.getPage(Config.CurrentBlog.Id.ToString(), entryId.ToString(), "username", "password");

            //assert
            Assert.AreEqual(1, post.categories.Length);
            Assert.AreEqual("http://" + hostname + "/entry/whatever", post.link);
            Assert.AreEqual("http://" + hostname + "/entry/whatever", post.permalink);
            Assert.AreEqual(category1Name, post.categories[0]);
            Assert.AreEqual(enclosureUrl, post.enclosure.Value.url);
            Assert.AreEqual(enclosureMimeType, post.enclosure.Value.type);
            Assert.AreEqual(enclosureSize, post.enclosure.Value.length);
        }
    }
}


text:
// Prexonite
//
// Copyright (c) 2014, Christian Klauser
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//
//     Redistributions of source code must retain the above copyright notice,
//          this list of conditions and the following disclaimer.
//     Redistributions in binary form must reproduce the above copyright notice,
//          this list of conditions and the following disclaimer in the
//          documentation and/or other materials provided with the distribution.
//     The names of the contributors may be used to endorse or
//          promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
//  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using Prexonite.Compiler.Symbolic;
using Prexonite.Modular;

namespace Prexonite.Compiler.Build.Internal
{
    [DebuggerDisplay("Target({Name}) success={IsSuccessful}")]
    internal class DefaultModuleTarget : ITarget
    {
        [NotNull]
        private static readonly IReadOnlyCollection<IResourceDescriptor> _emptyResourceCollection =
            new IResourceDescriptor[0];

        [NotNull]
        private readonly Module _module;
        [NotNull]
        private readonly SymbolStore _symbols;
        [CanBeNull]
        private readonly List<Message> _messages;
        [CanBeNull]
        private readonly Exception _exception;

        private readonly bool _isSuccessful;

        public DefaultModuleTarget(Module module, SymbolStore symbols, IEnumerable<Message> messages = null, Exception exception = null)
        {
            if (module == null)
                throw new ArgumentNullException("module");
            if (symbols == null)
                throw new ArgumentNullException("symbols");
            _module = module;
            _symbols = symbols;
            _exception = exception;
            if(messages != null)
                _messages = new List<Message>(messages);
            _isSuccessful = exception == null && (_messages == null || _messages.All(m => m.Severity != MessageSeverity.Error));
        }

        [CanBeNull]
        private static Exception _createAggregateException(Exception[] aggregateExceptions)
        {
            Exception aggregateException;
            if (aggregateExceptions.Length == 1)
                aggregateException = aggregateExceptions[0];
            else if (aggregateExceptions.Length > 0)
                aggregateException = new AggregateException(aggregateExceptions);
            else
                aggregateException = null;
            return aggregateException;
        }

        internal static ITarget _FromLoader(Loader loader, Exception[] exceptions = null, IEnumerable<Message> additionalMessages = null)
        {
            return _FromLoader(loader,
                exceptions == null ? null : _createAggregateException(exceptions),
                additionalMessages);
        }

        internal static ITarget _FromLoader(Loader loader, Exception exception = null, IEnumerable<Message> additionalMessages = null)
        {
            if (loader == null)
                throw new ArgumentNullException("loader");
            Debug.Assert(loader.TopLevelSymbols!= null,"Loader.TopLevelSymbols must not be null.");
            var exported = SymbolStore.Create();
            foreach (var decl in loader.TopLevelSymbols.LocalDeclarations)
                exported.Declare(decl.Key, decl.Value);
            var messages = loader.Errors.Append(loader.Warnings).Append(loader.Infos);
            if (additionalMessages != null)
                messages = additionalMessages.Append(messages);
            return new DefaultModuleTarget(loader.ParentApplication.Module,exported,messages, exception);
        }

        public Module Module
        {
            get { return _module; }
        }

        public IReadOnlyCollection<IResourceDescriptor> Resources
        {
            get { return _emptyResourceCollection; }
        }

        public SymbolStore Symbols
        {
            get { return _symbols; }
        }

        public ModuleName Name
        {
            get { return _module.Name; }
        }

        internal static readonly Message[] NoMessages = new Message[0];

        [NotNull]
        public IReadOnlyCollection<Message> Messages
        {
            get { return (IReadOnlyCollection<Message>)_messages ?? NoMessages; }
        }

        public Exception Exception
        {
            get { return _exception; }
        }

        public bool IsSuccessful
        {
            get { return _isSuccessful; }
        }
    }
}


text:
package com.ineunet.knife.persist.mongo;

/**
 *
 * @author Hilbert
 *
 * @since 1.1.0
 *
 */
public interface MongoDao {
    String getName();
}