text:
import gzip
import os
import cPickle as pickle
import logging
import os
import json

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
from requests_toolbelt.downloadutils import stream
import msgpack
from requests.auth import HTTPBasicAuth

import config as cfg

logger = logging.getLogger(__name__)

auth = HTTPBasicAuth('worker', cfg.SECRET_KEY)

class StopWorkOnTask(Exception):
    pass

def add_task(config):
    data = dict(config=config)
    logger.info("Adding task %s" % config['name'])
    r = requests.post(cfg.SERVER_URL + "add_task/", data=msgpack.packb(data), auth=auth, timeout=60)
    r.raise_for_status()

def add_tasks(configs):
    data = dict(configs=configs)
    for config in configs:
        logger.info("Adding tasks %s" % config['name'])
    r = requests.post(cfg.SERVER_URL + "add_tasks/", data=msgpack.packb(data), auth=auth, timeout=60)
    r.raise_for_status()

def get_tasks(get_all):
    data = dict(get_all=get_all)
    r = requests.get(cfg.SERVER_URL + 'get_tasks/', data=pickle.dumps(data, protocol=-1), auth=auth, timeout=60)
    r.raise_for_status()
    return pickle.loads(r.content)

def get_results(config):
    data = dict(config=config)
    r = requests.get(cfg.SERVER_URL + 'get_results/', data=pickle.dumps(data, protocol=-1), auth=auth)
    r.raise_for_status()
    return pickle.loads(r.content)

def get_result(resultid):
    r = requests.get(cfg.SERVER_URL + 'result/%d/' % resultid, auth=auth, timeout=60)
    r.raise_for_status()
    return pickle.loads(r.content)

def get_workers():
    r = requests.get(cfg.SERVER_URL + 'get_workers/', auth=auth, timeout=60)
    r.raise_for_status()
    return pickle.loads(r.content)

def reset_task(taskid):
    data = dict(taskid=taskid)
    r = requests.post(cfg.SERVER_URL + 'reset_task/', data=pickle.dumps(data, protocol=-1), auth=auth, timeout=60)
    r.raise_for_status()

def get_plot_data(config, axes):
    data = dict(config=config, axes=axes)
    logger.info("Requesting plot data for %s", axes)
    r = requests.get(cfg.SERVER_URL + 'plot_data/', data=pickle.dumps(data, protocol=-1), auth=auth, timeout=60)
    r.raise_for_status()
    return pickle.loads(r.content)

def get_task_for_completion(workername, version):
    data = dict(workername=workername, version=version)
    r = requests.post(cfg.SERVER_URL + 'get_task_for_completion/', data=msgpack.packb(data), auth=auth, timeout=60)
    r.raise_for_status()
    return msgpack.unpackb(r.content)

def cleanup():
    r = requests.post(cfg.SERVER_URL + 'cleanup/', auth=auth, timeout=60)
    r.raise_for_status()

def post_status(workername, taskid, percent_completed):
    data = dict(
        workername=workername,
        taskid=taskid,
        percent_completed=percent_completed
        )

    r = requests.post(cfg.SERVER_URL + "task_status/", data=pickle.dumps(data, protocol=-1), auth=auth, timeout=60)
    if r.status_code == 404:
        raise StopWorkOnTask()
    r.raise_for_status()

def post_result(workername, taskid, config, results):
    data = dict(
        workername=workername,
        taskid=taskid,
        config=config,
        results=results
        )
    r = requests.post(cfg.SERVER_URL + 'task_completed/', data=pickle.dumps(data, protocol=-1), auth=auth, timeout=60)
    r.raise_for_status()

def post_replay(taskid, replayname, workername):
    logger.info("Gziping the replay")
    f_in = open(replayname, 'rb')
    f_out = gzip.open(replayname + '.gz', 'wb')
    f_out.writelines(f_in)
    f_out.close()
    f_in.close()

    logger.info("Uploading replay to server")

    with open(replayname + '.gz', 'rb') as f:
        m = MultipartEncoder(
        fields={'taskid': str(taskid),
                'workername': workername,
                'replay': ('replay.bin', f, 'application/gzip')
                }
        )

        #from ipdb import set_trace; set_trace()
        r = requests.post(cfg.SERVER_URL + 'upload_replay/', data=m, auth=auth, timeout=120,
                      headers={'Content-Type': m.content_type})
        r.raise_for_status()

        logger.info("Got response: %s" % r.content)

def download_replay(resultid, filename):
    r = requests.get(cfg.SERVER_URL + 'get_replay/%d/' % resultid, stream=True, auth=auth)
    r.raise_for_status()

    gz_filename = stream.stream_response_to_file(r, path=filename + '.gz')

    logger.info("GUnzipping the replay")
    f_in = gzip.open(gz_filename, 'rb')
    f_out = open(filename, 'wb')
    f_out.writelines(f_in)
    f_out.close()
    f_in.close()
    os.remove(gz_filename)

def download_worker():
    logger.info("Downloading updated worker")
    r = requests.get(cfg.SERVER_URL + 'worker.zip', stream=True, auth=auth, timeout=60)
    r.raise_for_status()
    logger.info("Getting the data")
    filename = stream.stream_response_to_file(r, path='worker.zip')
    logger.info("Download complete")
    return filename


text: bundle exec jekyll serve --baseurl

redpajama_set_name: RedPajamaGithub


text:
class RandomServer
{
public:
	RandomServer();
	virtual ~RandomServer();
	virtual unsigned int generate_uint(unsigned int min, unsigned int max);
	virtual unsigned int generate_uint(unsigned int max);

	virtual unsigned int operator()(unsigned int max);
private:
	class Impl;
	std::unique_ptr<Impl> pimpl;
};


text:
package blackboard.plugin.hayabusa.provider;

import java.util.List;
import java.util.Set;

import blackboard.data.navigation.NavigationItemControl;
import blackboard.persist.PersistenceException;
import blackboard.persist.PersistenceRuntimeException;
import blackboard.persist.navigation.NavigationItemDbLoader;
import blackboard.plugin.hayabusa.command.Category;
import blackboard.plugin.hayabusa.command.Command;
import blackboard.plugin.hayabusa.command.SimpleCommand;
import blackboard.portal.data.Module;
import blackboard.portal.persist.ModuleDbLoader;
import blackboard.portal.view.FramesetUtil;

import com.google.common.collect.Sets;

/**
 * A {@link Provider} for ADMIN EMAIL COMMANDS.
 *
 * @author ZHAOXIA YANG
 * @since 1.0
 */
public class SendEmailProvider implements Provider
{

  private static final String INTERNAL_HANDLER = "inst_email";

  @Override
  public Iterable<Command> getCommands()
  {
    try
    {
      // TODO wire these dependencies as fields/constructor inject
      NavigationItemDbLoader niLoader = NavigationItemDbLoader.Default.getInstance();
      // For admin
      List<NavigationItemControl> nics_admin = NavigationItemControl.createList( niLoader
          .loadByFamily( INTERNAL_HANDLER ) );
      ModuleDbLoader moduleLoader = ModuleDbLoader.Default.getInstance();
      Module module = moduleLoader.loadByExtRef( "platform/admin-tools" );

      NavigationItemControl family = NavigationItemControl.createInstance( niLoader
          .loadByInternalHandle( INTERNAL_HANDLER ) );

      Set<Command> commands = Sets.newTreeSet();

      for ( NavigationItemControl nic : nics_admin )
      {
        if ( !nic.userHasAccess() )
        {
          continue;
        }
        String title = String.format( "%s - %s: %s", module.getTitle(), family.getLabel(), nic.getLabel() );
        String url = FramesetUtil.getTabGroupUrl(blackboard.data.navigation.Tab.TabType.admin, nic.getUrl());
        commands.add( new SimpleCommand( title, url, Category.SYSTEM_ADMIN ) );
      }
      return commands;
    }
    catch ( PersistenceException e )
    {
      throw new PersistenceRuntimeException( e );
    }
  }
}


text:
template<class T>
class Bag : public Collection<T>
{
protected:

  int tally;       // total number of elements

  //////////////////////////////////////////////////////////////////////
  //  Import types
  //////////////////////////////////////////////////////////////////////

public:
  typedef Collection<T>  Super;
  typedef Super::Element Element;

  //////////////////////////////////////////////////////////////////////
  // Constructors and destructor
  //////////////////////////////////////////////////////////////////////

  Bag(int count = 0) : tally(count)
  {}        // make an empty bag
  ~Bag()
  {}                                    // destroy a bag

  //////////////////////////////////////////////////////////////////////
  // Assignment
  //////////////////////////////////////////////////////////////////////
  // virtual void operator = (const Collection<T>& b); // inherited

  //////////////////////////////////////////////////////////////////////
  // Selectors:
  //    size()       return the number of elements within the bag.
  //    capacity()   return the current capacity.
  //    is_empty()   is the bag empty?
  //    contains()   does the bag contains the said element
  //    count()      returns the number of occurance of an element.
  //////////////////////////////////////////////////////////////////////

  inline virtual int  size()     const
  {
    return tally;
  }
  inline virtual Bool is_empty()  const
  {
    return tally == 0;
  }
  inline virtual Bool is_full()   const
  {
    return tally == capacity();
  }
  // virtual int capacity() const;  // inherited
  // virtual Bool contains(const T& e) const; // inherited
  virtual int count(const T& e) const = 0;

  //////////////////////////////////////////////////////////////////////
  // In place multiset operations
  //////////////////////////////////////////////////////////////////////
  // virtual void clear();            // inherited

  inline virtual Ix   insert(const T& e)
  {
    return insert(e,1);
  }
  inline virtual Bool remove
    (const T& e)
  {
    return remove
             (e,1);
  }
  virtual Ix   insert(const T& e, int count) = 0;
  virtual Bool remove
    (const T& e, int count) = 0;
  Bag& Union      (const Bag&);
  Bag& Difference (const Bag&);

  //////////////////////////////////////////////////////////////////////
  //  Iteration
  //////////////////////////////////////////////////////////////////////
  // virtual Ix  first();              // inherited
  // virtual Ix  next(Ix i);           // inherited
  // virtual T&  operator () (Ix i);   // inherited
  // virtual const T&  operator () (Ix i) const;   // inherited

  virtual int occurrence(Ix i) const = 0;
};

//////////////////////////////////////////////////////////////////////
// In place bag union
//////////////////////////////////////////////////////////////////////

template <class T>
Bag<T>& Bag<T>::Union (const Bag<T>& b)
{
  for (Ix i = b.first(); i; i = b.next(i))
    insert(b(i), b.occurrence(i));
  return *this;
}

//////////////////////////////////////////////////////////////////////
// In place bag difference
//////////////////////////////////////////////////////////////////////

template <class T>
Bag<T>& Bag<T>::Difference (const Bag<T>& b)
{
  for (Ix i = b.first(); i; i = b.next(i))
    remove
      (b(i), b.occurrence(i));
  return *this;
}

#endif


text:
Cancer Cell Line Data
=====================

Getting Started
---------------
In this section we will use cancer cell line data. The data has been sub-setted to a 20MB region of chrX to speed up all analyses discussed hereafter.
If you haven't done so yet start the Delly tutorial docker container and then follow the commands.

```shell
cd /data/cldata
```

Alignment Quality Control
-------------------------

Paired-end methods can be affected by a skewed insert size distribution, read-depth methods by non-uniform coverage and split-read methods suffer from high sequencing error rates that cause mis-mappings. Prior to any structural variant discovery you should therefore evaluate the quality of the data such as the percentage of mapped reads, singletons, duplicates, properly paired reads and the insert size & coverage distributions. [Picard](http://broadinstitute.github.io/picard/), [SAMtools](http://www.htslib.org), [FastQC](http://www.bioinformatics.babraham.ac.uk/projects/fastqc/) and also [Delly](https://github.com/tobiasrausch/delly) compute some of these alignment statistics as shown below.

```shell
samtools flagstat tu.bam
stats -o tu.stats -i tu.ins tu.bam
Rscript /opt/delly/R/isize.R tu.ins
feh tu.ins.png
cat tu.stats
samtools flagstat wt.bam
stats -o wt.stats -i wt.ins wt.bam
Rscript /opt/delly/R/isize.R wt.ins
feh wt.ins.png
cat wt.stats
```

There are some general things to watch out for such as mapping percentages below 70%, >20% duplicates or multiple peaks in the insert size distribution. However, these statistics vary largely by protocol and hence, it's usually best to compare multiple different sequencing runs using the same protocol (DNA-seq, RNA-seq, ChIP-seq, paired-end, single-end or mate-pair) against each other, which then highlights the outliers.

Complex Somatic Structural Variant Discovery
--------------------------------------------

The simulated data contained only simple inversions, tandem duplications and deletions. This cancer data set harbors many complex rearrangements instead. As a first step we will again compute somatic structural variants using [Delly](https://github.com/tobiasrausch/delly).

```shell
delly call -t DEL -g chrX.fa -x hg19.ex -o del.bcf tu.bam wt.bam
delly call -t DUP -g chrX.fa -x hg19.ex -o dup.bcf tu.bam wt.bam
delly call -t INV -g chrX.fa -x hg19.ex -o inv.bcf tu.bam wt.bam
delly filter -pt DEL -f somatic -o sdel.bcf -a 0.1 -s spl.tsv -g chrX.fa del.bcf
delly filter -pt DUP -f somatic -o sdup.bcf -a 0.1 -s spl.tsv -g chrX.fa dup.bcf
delly filter -pt INV -f somatic -o sinv.bcf -a 0.1 -s spl.tsv -g chrX.fa inv.bcf
bcftools concat -a -O b -o somatic.bcf sdel.bcf sdup.bcf sinv.bcf
```

As with the simulated data we can, of course, view this BCF file and create summary statistics.

```shell
bcftools view somatic.bcf | grep "^#" -A 1
sampleprops somatic.bcf
```

Visualizing Structural Variant Breakpoints
------------------------------------------

IGV is excellent for inspecting small variants but for these long-range complex re-arrangements its less powerful. You cannot view the entire event in IGV but you can still visualize the breakpoint regions separately, denoted as left breakpoint (L) and right breakpoint (R) below.

```shell
svprops somatic.bcf | tail -n +2 | awk '{print $1"\t"($2-500)"\t"($2+500)"\t"$5"L";}' > somatic.bp.bed
svprops somatic.bcf | tail -n +2 | awk '{print $3"\t"($4-500)"\t"($4+500)"\t"$5"R";}' >> somatic.bp.bed
./igv.sh -g chrX.fa
```

As previously, once IGV has started use 'File' and 'Load from File' to load the tumor and normal bam alignment file. Then import 'somatic.bp.bed' from your working directory using 'Regions' and 'Import Regions'. The somatic structural variants can then be browsed easily using 'Regions' and 'Region Navigator' and you probably want to switch on 'View as pairs' and 'Color alignments by pair orientation'. You may also want to play around with the split screen view, where you can right click a read and select 'View mate region in split screen'.

Visualizing Complex Rearrangements
----------------------------------

To reveal any complex re-arrangement patterns it's worthwhile to create a so-called read-depth ratio plot using [R statistics](https://www.r-project.org) and overlay
the somatic structural variants. We therefore first calculate read counts per 10kbp bin, create a BED file with all somatic structural variants and then start R.

```shell
svprops somatic.bcf > somatic.sv.bed
cov -f tn.cov.gz tu.bam wt.bam
R
```

In R we first load and plot the coverage data.

```R
library(DNAcopy)
library(ggplot2)
library(reshape2)
library(scales)
cov = read.table("tn.cov.gz", comment.char="$", header=T)
cov = cov[cov$wt!=0,]
covNorm = median(cov$wt) / median(cov$tu)
cov$lg2 = log2(covNorm*cov$tu/cov$wt)
p=ggplot(data=cov, aes(x=cov$start, y=cov$lg2)) + geom_point(alpha=3/4, size=2)
p=p + xlab("chrX") + ylab("Log2 read-depth ratio")
p=p + scale_x_continuous(labels = comma)
p
```

Next we can overlay the somatic structural variants.

```R
sv = read.table("somatic.sv.bed", header=T)
sv$type = factor(paste0(sv$svtype, "-", sv$ct))
sv = sv[,c("chr","start","end","type","id")]
sv$middle = as.integer( (sv$start + sv$end) / 2 )
sv$yv = 1
sv = melt(sv, id.vars=c("chr", "type", "id", "yv"))
sv[sv$variable=="middle",]$yv = sv[sv$variable=="middle",]$yv + 0.5
p=p + geom_line(data=sv, aes(x=value, y=yv, group=id, colour=type))
p=p + labs(colour="SV type")
p
```

You might also want to segment the read-depth ratios.

```R
seg=segments.summary(segment(smooth.CNA(CNA(cov$lg2, cov$X.chr, cov$start, data.type="logratio", sampleid="tu"))))
p=p + geom_segment(data=seg, aes(x=loc.start, y=seg.median, xend=loc.end, yend=seg.median), colour="lightblue")
p=p + theme(legend.position="bottom")
p
```

For later retrival save the workspace when you now quit R.

```R
quit()
```

Allelic Depth for SNPs
----------------------

We can also augment the plots with SNP variant allele frequencies. The file 'snps.pos' contains 1000 Genomes SNP locations in our selected region on chrX where the control sample is heterozygous.

```shell
head snps.pos
```

Using [SAMtools](http://www.htslib.org) and [BCFtools](http://www.htslib.org) we can annotate the allelic depth for every SNP.

```shell
samtools mpileup -go mp.bcf -f chrX.fa -t AD -l snps.pos tu.bam wt.bam
bcftools call -vmAO z -o mp.vcf.gz mp.bcf
zcat mp.vcf.gz | grep -v "^##" | cut -f 1,2,4,5,10,11  | sed 's/[^\t]*://g' > ad.tsv
```

Let's look at the allelic counts using R.

```shell
tail -n +2 ad.tsv | cut -f 2,5,6 | tr ',' '\t' | awk 'NF==5' > ad.counts
R
```

```R
library(ggplot2)
library(reshape2)
library(scales)
co = read.table("ad.counts", header=F)
colnames(co) = c("POS", "tREF", "tALT", "wREF", "wALT")
co$tCOV=co$tREF+co$tALT
co$wCOV=co$wREF+co$wALT
co$tVAF=co$tALT/co$tCOV
co$wVAF=co$wALT/co$wCOV
hist(co$wVAF)
hist(co$tVAF)
q=ggplot(data=co, aes(x=co$POS, y=co$tVAF))
q=q + geom_point(alpha=1/4, size=1)
q=q + geom_point(aes(x=co$POS, y=1-co$tVAF), alpha=1/4, size=1)
q=q + xlab("chrX") + ylab("Variant Allele Frequency")
q=q + scale_x_continuous(labels = comma)
q
```

Of course, this plot is more informative if we can also see the read-depth.

```R
library(grid)
library(DNAcopy)
grid.newpage()
pushViewport(viewport(layout=grid.layout(6,1)))
print(q, vp = viewport(layout.pos.row=1:2, layout.pos.col=1))
print(p, vp = viewport(layout.pos.row=3:6, layout.pos.col=1))
```

Interactive Browsing of Structural Variants
-------------------------------------------

[Delly](https://github.com/tobiasrausch/delly) provides a browsable read-depth plot with structural variant connections using JavaScript, SVG and D3. It uses hdf5 coverage tracks that can be created using python.

```python
python /opt/delly/vis/suave/suave_bam_to_h5.py -s tu -o tu.hdf5 tu.bam
python /opt/delly/vis/suave/suave_bam_to_h5.py -s wt -o wt.hdf5 wt.bam
```

Then we start a local webserver with python using the hdf5 files and the somatic structural variant calls and open firefox to display the viewer.

```shell
bcftools view somatic.bcf | bgzip > somatic.sv.vcf.gz
tabix somatic.sv.vcf.gz
python /opt/delly/vis/suave/suave_server.py -f tu.hdf5 -f wt.hdf5 -v somatic.sv.vcf.gz > server.out 2>&1 &
firefox --new-instance http://127.0.0.1:5000/
```

In the browser, go to setup and load the tumor and normal bam file, select chrX, and click "Visualize". If you move the mouse into the read-depth window, you can
zoom, pan and select subregions in the lower overview panel. You can also click on the SV arcs to center the view on the selected structural variant. To go back to the full chromosome view just double-click in the overview panel at the bottom. Once you are done you can close the server with CTRL-C in the terminal.


text:
@interface GiveViewController : UIViewController

@end


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="Pramod site.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <title>
      {% block title %}
        Pramod Lakshmanan
      {% endblock %}
    </title>

    <link rel="icon" type="image/png" href="/static/icons/pythonic-trans.png">

    <link rel="stylesheet" href="/static/material.css">
    <link rel="stylesheet" href="/static/styles.css">

      Projects
      Blog
      About
      Contact

    {% block content %}

    {% endblock %}

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css">


text:
<?php

namespace ZDiet;

use Dietcube\Application as DCApplication;
use Dietcube\Controller as DCController;
use Pimple\Container;
use ZDiet\Service\OauthService;

/**
 * Created by IntelliJ IDEA.
 * User: yui_tang
 * Date: 1/12/16
 * Time: 19:02
 */
class Application extends DCApplication
{
    public function init(Container $container)
    {
        parent::init($container); // TODO: Change the autogenerated stub
    }

    public function config(Container $container)
    {
        $container['service.Oauth'] = function () use ($container) {
            return new OauthService(
                $container,
                $this->getTmpDir()
            );
        };
    }
}


text:
package skinny.micro.contrib

import java.util.Locale

import skinny.micro.base.BeforeAfterDsl
import skinny.micro.context.SkinnyContext
import skinny.micro.contrib.i18n.Messages
import skinny.micro.{ SkinnyMicroBase, SkinnyMicroException }

/**
 * i18n support.
 */
trait I18nSupport { this: SkinnyMicroBase with BeforeAfterDsl =>

  import I18nSupport._

  before() {
    request(context)(LocaleKey) = resolveLocale(context)
    request(context)(MessagesKey) = provideMessages(locale(context))(context)
  }

  def locale(implicit ctx: SkinnyContext): Locale = {
    if (request(ctx) == null) {
      throw new SkinnyMicroException("There needs to be a request in scope to call locale")
    } else {
      request(ctx).get(LocaleKey).map(_.asInstanceOf[Locale]).orNull
    }
  }

  def userLocales(implicit ctx: SkinnyContext): Array[Locale] = {
    if (request(ctx) == null) {
      throw new SkinnyMicroException("There needs to be a request in scope to call userLocales")
    } else {
      request(ctx).get(UserLocalesKey).map(_.asInstanceOf[Array[Locale]]).orNull
    }
  }

  def messages(key: String)(implicit ctx: SkinnyContext): String = messages(ctx)(key)

  def messages(implicit ctx: SkinnyContext): Messages = {
    if (request(ctx) == null) {
      throw new SkinnyMicroException("There needs to be a request in scope to call messages")
    } else {
      request(ctx).get(MessagesKey).map(_.asInstanceOf[Messages]).orNull
    }
  }

  /**
   * Provides a default Message resolver
   *
   * @param locale Locale used to create instance
   * @return a new instance of Messages, override to provide own implementation
   */
  def provideMessages(locale: Locale)(implicit ctx: SkinnyContext): Messages = Messages(locale)

  /*
  * Resolve Locale based on HTTP request parameter or Cookie
  */
  private def resolveLocale(implicit ctx: SkinnyContext): Locale = resolveHttpLocale(ctx) getOrElse defaultLocale

  /*
   * Get locale either from HTTP param, Cookie or Accept-Language header.
   *
   * If locale string is found in HTTP param, it will be set
   * in cookie. Later requests will read locale string directly from this
   *
   * If it's not found, then look at Accept-Language header.
   * Locale strings are transformed to [[java.util.Locale]]
   */
  private def resolveHttpLocale(implicit ctx: SkinnyContext): Option[Locale] = {
    (params(ctx).get(LocaleKey) match {
      case Some(localeValue) =>
        cookies(ctx).set(LocaleKey, localeValue)
        Some(localeValue)
      case _ => cookies(ctx).get(LocaleKey)
    }).map(localeFromString(_)(ctx)) orElse resolveHttpLocaleFromUserAgent(ctx)
  }

  /**
   * Accept-Language header looks like "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4"
   * Specification see [[http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html]]
   *
   * @return first preferred found locale or None
   */
  private def resolveHttpLocaleFromUserAgent(implicit ctx: SkinnyContext): Option[Locale] = {
    request(ctx).headers.get("Accept-Language") map { s =>
      val locales = s.split(",").map(s => {
        def splitLanguageCountry(s: String): Locale = {
          val langCountry = s.split("-")
          if (langCountry.length > 1) {
            new Locale(langCountry.head, langCountry.last)
          } else {
            new Locale(langCountry.head)
          }
        }
        // If this language has a quality index:
        if (s.indexOf(";") > 0) {
          val qualityLocale = s.split(";")
          splitLanguageCountry(qualityLocale.head)
        } else {
          splitLanguageCountry(s)
        }
      })
      // save all found locales for later user
      request(ctx).setAttribute(UserLocalesKey, locales)
      // We assume that all accept-languages are stored in order of quality
      // (so first language is preferred)
      locales.head
    }
  }

  /**
   * Reads a locale from a String
   * @param in a string like en_GB or de_DE
   */
  private def localeFromString(in: String)(implicit ctx: SkinnyContext): Locale = {
    val token = in.split("_")
    new Locale(token.head, token.last)
  }

  private def defaultLocale: Locale = Locale.getDefault

}

object I18nSupport {

  val LocaleKey: String = "skinny.micro.i18n.locale"

  val UserLocalesKey: String = "skinny.micro.i18n.userLocales"

  val MessagesKey: String = "messages"

}


text:
<template name="userProfile">

Info

Activity

{{> userProfileInfo}}

{{> userProfileActivity}}

</template>


text:
package com.vsked.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vsked.dao.SysPermissionDao;

@Service
@Transactional
public class SysPermissionSer extends BaseService{

	public Logger log = Logger.getLogger(this.getClass());

	@Resource
	SysPermissionDao sysPermissionDao;

	public int getSysPermissionCount(Map<String, Object> m){
		int count=0;
		try{
			count=sysPermissionDao.getSysPermissionCount(m);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return count;
	}

	public Map<String, Object> getSysPermissionBySpId(String spId) {
		Map<String, Object> m=new HashMap<String, Object>();
		try{
			m=sysPermissionDao.getSysPermissionBySpId(spId);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return m;
	}

	public String sysPermissionEditPage(String spId){
		try{
			Map<String, Object> sysPermission=getSysPermissionBySpId(spId);
			Session session=getSession();
			session.setAttribute("sysPermission", sysPermission);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return "system/sysPermissionEdit";
	}

}


text:
import suds
from cache import ExtendedObjectCache

from suds.transport.http import HttpTransport as SudsHttpTransport

from .exceptions import *

class MMSoapClient(object):
    """
    Message Media SOAP Client.

    This class is a wrapper for the Suds SOAP client and implements the operations
    found in the following wsdl: http://soap.m4u.com.au/?wsdl'.
    """
    WSDL_URL = "https://soap.m4u.com.au/?wsdl"

    def __init__(self, userId=None, password=None, **kwargs):
        """
        Initialise the SOAP client.

        :param userId: User ID for authenticating requests. Defaults to None.
        :param password: Password for authenticating requests. Defaults to None.
        :param kwargs: Additional arguments to set on the client. Currently only 'cache_location' is supported.
        """
        object_cache = ExtendedObjectCache()
        object_cache.setduration(days=10)
        if 'cache_location' in kwargs:
            object_cache.setlocation(kwargs["cache_location"])

        self.client = suds.client.Client(self.WSDL_URL,
                                         cache=object_cache,
                                         transport=WellBehavedHttpTransport())

        self.authentication = self.create('AuthenticationType')
        if userId and password:
            self.authentication.userId = userId
            self.authentication.password = password

    def create(self, object_name):
        """Short-hand for creating WSDL objects."""
        return self.client.factory.create(object_name)

    def set_userId(self, userId):
        """ Set user id on the authentication element. """
        self.authentication.userId = userId

    def set_password(self, password):
        """ Set password on the authentication element. """
        self.authentication.password = password

    def check_user(self):
        """
        Check user account details.

        :return: The account details including used and remaining credit limits.
        """
        return self.client.service.checkUser(self.authentication).accountDetails

    def send_messages(self, recipients, content, send_mode='normal', scheduled=None, report=None, seq=None):
        """
        Send a single message to `recipients`.

        :param recipients: Iterable of recipient numbers
        :param content: Message content
        :param send_mode: Used for testing. Should be one of:
                            * normal (default) -- send as normal.
                            * dropAll -- drop (not send) the requested messages, return a mix of errors and successes.
                            * dropAllWithErrors -- drop the requested messages, return all as errors.
                            * dropAllWithSuccess -- drop the requested messages, return all as success.
        :param scheduled: Scheduled date/time of the message in UTC format.
        :param report: Request a delivery report for this message.

        :return: Response containing count of sent, scheduled, failed and any associated error code types.
        """
        recipients_type = self.create('RecipientsType')

        for recipient in recipients:
            this_recipient = self.create('RecipientType')
            this_recipient.value = recipient
            # add uid here
            recipients_type.recipient.append(this_recipient)

        message = self.create('MessageType')
        message.recipients = recipients_type
        message.content = content

        if seq:
            message._sequenceNumber = seq

        if scheduled:
            message.scheduled = scheduled

        if report:
            message.deliveryReport = report

        message_list = self.create('MessageListType')
        message_list.message = message
        message_list._sendMode = send_mode

        request_body = self.create('SendMessagesBodyType')
        request_body.messages = message_list

        response = self.client.service.sendMessages(self.authentication, request_body)

        self.raise_for_response(response)

        return response

    def raise_for_response(self, response):
        """
        Raise an exception for a given error code in a SOAP response.

        :param response: SOAP Response containing the error code.
        :raises An exception matching the error code.
        """
        try:
            code = response.errors[0][0]._code

            if code == 'invalidRecipient':
                raise InvalidRecipientException()
            elif code == 'recipientBlocked':
                raise RecipientBlockedException()
            elif code == 'emptyMessageContent':
                raise EmptyMessageContentException()
            elif code == 'other':
                raise OtherMMSOAPException()
            else:
                pass

        except AttributeError:
            pass

    def check_replies(self, maximum_replies=None):
        """
        Check replies to any sent messages.

        :param maximum_replies: Limits the number of replies returned in the response.
                                Default is to return all if this value isn't supplied.

        :return: Iterable containing the replies, never null.
        """
        request_body = self.create('CheckRepliesBodyType')

        if maximum_replies is int and maximum_replies >= 0:
            request_body.maximumReplies = maximum_replies

        response = self.client.service.checkReplies(self.authentication, request_body)
        return response.reply if 'reply' in response else []

    def confirm_replies(self, message_receipt_ids):
        """
        Confirm replies which were previously retrieved with the check_replies function.

        :param message_receipt_ids: Iterable containing the receipt id's of the replies to confirm.
                                    These must correspond to id's previously retrieved using the
                                    check_replies function.

        :return: Response containing the number of replies confirmed.
        """
        confirm_reply_list = self.create('ConfirmReplyListType')
        for receipt_id in message_receipt_ids:
            this_confirm_item = self.create('ConfirmItemType')
            this_confirm_item._receiptId = receipt_id
            confirm_reply_list.reply.append(this_confirm_item)
        request_body = self.create('ConfirmRepliesBodyType')
        request_body.replies = confirm_reply_list

        return self.client.service.confirmReplies(self.authentication, request_body)

    def check_reports(self, maximum_reports=None):
        """
        Check delivery reports to any sent messages.

        :param maximum_reports: Limits the number of reports returned in the response.
                                Default is to return all if this value isn't supplied.

        :return: Iterable containing the reports, never null.
        """
        request_body = self.create('CheckReportsBodyType')

        if maximum_reports is int and maximum_reports >= 0:
            request_body.maximumReports = maximum_reports

        response = self.client.service.checkReports(self.authentication, request_body)
        return response.report if 'report' in response else []

    def confirm_reports(self, delivery_report_ids):
        """
        Confirm reports which were previously retrieved with the check_reports function.

        :param delivery_report_ids: Iterable containing the id's of the reports to confirm.
                                    These must correspond to id's previously retrieved using the
                                    check_reports function.

        :return: Response containing the number of reports confirmed.
        """
        confirm_report_list = self.create('ConfirmReportListType')

        for report_id in delivery_report_ids:
            this_confirm_item = self.create('ConfirmItemType')
            this_confirm_item._deliveryReportd = report_id
            confirm_report_list.report.append(this_confirm_item)

        request_body = self.create('ConfirmReportsBodyType')
        request_body.reports = confirm_report_list

        return self.client.service.confirmReports(self.authentication, request_body)

    def delete_scheduled_messages(self, message_ids):
        """
        Delete scheduled messages.

        :param message_ids: Iterable of message ids to be deleted. These must correspond to message id's previously
                            used in the send_messages function where a scheduled date was set.

        :return: Response containing the count of unscheduled messages.
        """
        messages = self.create('MessageIdListType')

        for msg_id in message_ids:
            item = self.create('MessageIdType')
            item._messageId = msg_id
            messages.message.append(item)

        request_body = self.create('DeleteScheduledMessagesBodyType')
        request_body.messages = messages

        return self.client.service.deleteScheduledMessages(self.authentication, request_body)

    def block_numbers(self, numbers):
        """
        Blocks a list of numbers.

        :param numbers: Iterable of numbers to be blocked.

        :return: Count of blocked and failed.
                 If there are failures the response will contain an associate error code type
                 containing the recipient that was in error.
        """
        request = self.create_recipients_request_body('BlockNumbersBodyType', numbers)
        return self.client.service.blockNumbers(self.authentication, request)

    def get_blocked_numbers(self, maximum_numbers=None):
        """
        Retrieves currently blocked numbers.

        :param maximum_numbers: Max number of recipients to return in the response.
                                Defaults to ll items returned if this value is not supplied.

        :return: Response containing the blocked numbers, never null.
        """
        request_body = self.create('GetBlockedNumbersBodyType')

        if maximum_numbers is int and maximum_numbers >= 0:
            request_body.maximumRecipients = maximum_numbers

        response = self.client.service.getBlockedNumbers(self.authentication, request_body)
        return response.recipients.recipient if 'recipient' in response.recipients else []

    def unblock_numbers(self, numbers):
        """
        Unblocks a list of numbers.

        :param numbers: Iterable of numbers to be unblocked. The provided values must correspond
                        to those previously used in the block_numbers request.

        :return: Count of unblocked and failed. If there are failures the response will contain
                 an associate error code type containing the recipient that was in error.
        """
        request = self.create_recipients_request_body('UnblockNumbersBodyType', numbers)
        return self.client.service.unblockNumbers(self.authentication, request)

    def create_recipients(self, recipients):
        recipients_type = self.create('RecipientsType')

        for r in recipients:
            recipient_type = self.create('RecipientType')
            recipient_type.value = r
            recipients_type.recipient.append(recipient_type)

        return recipients_type

    def create_recipients_request_body(self, tag, recipients):
        """
        Create an xml element for recipients.

        :param tag: Name of the tag which will wrap the recipients.
        :param recipients: Iterable of recipients to wrap.

        :return: Created tag with the name specified in tag containing the recipients.
        """
        request_body = self.create(tag)
        request_body.recipients = self.create_recipients(recipients)
        return request_body

class WellBehavedHttpTransport(SudsHttpTransport):
    """
    HttpTransport which properly obeys the ``*_proxy`` environment
    variables.
    """

    def u2handlers(self):
        """
        Return a list of specific handlers to add.

        The urllib2 logic regarding ``build_opener(*handlers)`` is:

        - It has a list of default handlers to use

        - If a subclass or an instance of one of those default handlers is
        given in ``*handlers``, it overrides the default one.

        Suds uses a custom {'protocol': 'proxy'} mapping in self.proxy, and
        adds a ProxyHandler(self.proxy) to that list of handlers.  This
        overrides the default behaviour of urllib2, which would otherwise use
        the system configuration (environment variables on Linux, System
        Configuration on Mac OS, ...) to determine which proxies to use for the
        current protocol, and when not to use a proxy (no_proxy).

        Thus, passing an empty list will use the default ProxyHandler which
        behaves correctly.
        """
        return []


text:
package main

import (
    "bufio"
    "fmt"
    "net"
    "os"
    "strconv"
    "strings"
    "time"
)

type ThreadRequest struct {
    client_socket net.Conn
    receipt_timestamp int64
}

const (
    SERVER_PORT = 7000
    QUEUE_TIMEOUT_SECS = 4
    LISTEN_BACKLOG = 500

    SERVER_NAME = "http-server.go"
    HTTP_STATUS_OK = "200 OK"
    HTTP_STATUS_TIMEOUT = "408 TIMEOUT"
    HTTP_STATUS_BAD_REQUEST = "400 BAD REQUEST"
)

func current_time_millis() int64 {
    return time.Now().UnixNano() / int64(time.Millisecond)
}

func simulated_file_read(disk_read_time_ms int64) {
    time.Sleep(time.Millisecond * time.Duration(disk_read_time_ms))
}

func handle_socket_request(thread_request *ThreadRequest) {
    // read request from client
    request_line, errs :=
        bufio.NewReader(thread_request.client_socket).ReadString('\n')
    var rc = HTTP_STATUS_BAD_REQUEST
    var tot_request_time_ms = int64(0)
    var file_path = ""

    // read from socket succeeded?
    if errs == nil {
        len_req_payload := len(request_line)
        // did we get anything from client?
        if len_req_payload > 0 {
            // determine how long the request has waited in queue
            var start_processing_timestamp = current_time_millis()
            var server_queue_time_ms =
                start_processing_timestamp - thread_request.receipt_timestamp
            var server_queue_time_secs = server_queue_time_ms / 1000

            var disk_read_time_ms = int64(0)

            // has this request already timed out?
            if server_queue_time_secs >= QUEUE_TIMEOUT_SECS {
                fmt.Println("timeout (queue)")
                rc = HTTP_STATUS_TIMEOUT
            } else {
                var line_tokens = strings.Split(request_line, " ")
                if len(line_tokens) > 1 {
                    //request_method := line_tokens[0]
                    args_text := line_tokens[1]
                    var fields = strings.Split(args_text, ",")
                    if len(fields) == 3 {
                        //rc_input, errs := strconv.Atoi(fields[0])
                        //if errs == nil {
                        req_response_time_ms, errs :=
                            strconv.ParseInt(fields[1], 10, 64)
                        if errs == nil {
                            //rc = rc_input
                            disk_read_time_ms = req_response_time_ms
                            file_path = fields[2]
                            simulated_file_read(disk_read_time_ms)
                            rc = HTTP_STATUS_OK
                        }
                        //}
                    }
                }
            }

            // total request time is sum of time spent in queue and the
            // simulated disk read time
            tot_request_time_ms =
                server_queue_time_ms + disk_read_time_ms
        }
    }

    // create response
    var response_body = fmt.Sprintf("%d,%s",
       tot_request_time_ms,
       file_path)

    var response_headers = fmt.Sprintf("HTTP/1.1 %s\n" +
                                       "Server: %s\n" +
                                       "Content-Length: %d\n" +
                                       "Connection: close\n" +
                                       "\n",
                                       rc,
                                       SERVER_NAME,
                                       len(response_body))
    // return response to client
    thread_request.client_socket.Write([]byte(response_headers))
    thread_request.client_socket.Write([]byte(response_body))

    // close client socket connection
    thread_request.client_socket.Close()
}

func main() {
    //TODO: set listen backlog
    //TODO: set reuse addr
    server_socket, err := net.Listen("tcp",
                                     fmt.Sprintf(":%d", SERVER_PORT))

    if err != nil {
        fmt.Println("error: unable to create server socket on port %s",
                    SERVER_PORT)
        fmt.Println(fmt.Sprintf("%v", err))
        os.Exit(1)
    } else {
        //defer server_socket.Body.Close()
        fmt.Println(fmt.Sprintf("server (%s) listening on port %d",
                                SERVER_NAME,
                                SERVER_PORT))

        for {
            // wait for next socket connection from a client
            client_socket, err := server_socket.Accept()
            if err == nil {
                var thread_request = new(ThreadRequest)
                thread_request.receipt_timestamp = current_time_millis()
                thread_request.client_socket = client_socket
                go handle_socket_request(thread_request)
            }
        }
        os.Exit(0)
    }
}


text:
package cass.pure.aop;

import java.lang.reflect.Method;

public interface AOPHandler {
	boolean canHandle(Method method);

	Object[] before(Object target, Method method, Object[] args,
			AOPBeforeChain chain) throws Throwable;

	Object after(Object target, Method method, Object[] args,
			Object returnValue, AOPAfterChain chain) throws Throwable;

	double layer();
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/batch/v1/job.proto

namespace Google\Cloud\Batch\V1\LogsPolicy;

use UnexpectedValueException;

/**
 * The destination (if any) for logs.
 *
 * Protobuf type google.cloud.batch.v1.LogsPolicy.Destination
 */
class Destination
{
    /**
     * Logs are not preserved.
     *
     * Generated from protobuf enum DESTINATION_UNSPECIFIED = 0;
     */
    const DESTINATION_UNSPECIFIED = 0;
    /**
     * Logs are streamed to Cloud Logging.
     *
     * Generated from protobuf enum CLOUD_LOGGING = 1;
     */
    const CLOUD_LOGGING = 1;
    /**
     * Logs are saved to a file path.
     *
     * Generated from protobuf enum PATH = 2;
     */
    const PATH = 2;

    private static $valueToName = [
        self::DESTINATION_UNSPECIFIED => 'DESTINATION_UNSPECIFIED',
        self::CLOUD_LOGGING => 'CLOUD_LOGGING',
        self::PATH => 'PATH',
    ];

    public static function name($value)
    {
        if (!isset(self::$valueToName[$value])) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no name defined for value %s', __CLASS__, $value));
        }
        return self::$valueToName[$value];
    }

    public static function value($name)
    {
        $const = __CLASS__ . '::' . strtoupper($name);
        if (!defined($const)) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no value defined for name %s', __CLASS__, $name));
        }
        return constant($const);
    }
}


text:
#include <elf_file_t.h>
#include <free_ext_elf_files.h>
#include <platform.h>
#include <types.h>

/**
 * <!-- description -->
 *   @brief Releases a previously allocated elf_file_t that was allocated
 *     using the alloc_and_copy_ext_elf_files function.
 *
 * <!-- inputs/outputs -->
 *   @param pmut_ext_elf_files the elf_file_t to free.
 */
void
free_ext_elf_files(struct elf_file_t *const pmut_ext_elf_files) NOEXCEPT
{
    uint64_t mut_i;
    platform_expects(NULLPTR != pmut_ext_elf_files);

    for (mut_i = ((uint64_t)0); mut_i < HYPERVISOR_MAX_EXTENSIONS; ++mut_i) {
        struct elf_file_t *const pmut_file = &pmut_ext_elf_files[mut_i];
        platform_free(pmut_file->addr, pmut_file->size);
        platform_memset(pmut_file, ((uint8_t)0), sizeof(struct elf_file_t));
    }
}


text:
module.exports = {

  // loading external library before test, example:
  // external: ['http://code.jquery.com/jquery-2.0.3.js'], // i.e. jQuery

  // the test to run
  test: function (sandbox, window, document) {

    // try to set first argument as false to see the result
    sandbox.assert(true, 'this is just fine');

    // simulate a user search
    sandbox.write('input[name=q]', 'hello world').then(
      function(sandbox, window, document){
        // prepare for the next page on submit
        sandbox.onload = function(sandbox, window, document) {
          var href = sandbox.query(
            // Kindle Fire HD Silk browser has very outdated version of Google
            sandbox.navigator.kind === 'Silk' ?
              'div > a:first-child' : 'h3.r > a'
          ).href;
          // clean up the link if it's a query
          if (/\?q=/.test(href)) {
            href = href.slice(href.indexOf('?q=') + 3).split('&')[0];
          }
          // inject from external domain
          sandbox.loadFromDifferentDomain(href).then(sandbox.done);
        };

        // find the submit and trigger it
        var node = sandbox.query('form button[type=submit]');
        // Mobile uses this
        if (node) {
          sandbox.dispatch(node, 'click');

          // iPad will not change href, no onload will be fired
          if (sandbox.navigator.kind === 'iPad') {
            setTimeout(
              sandbox.onload, 2000,
              sandbox, window, document
            );
          }
        }
        // Desktop / Kindle Fire uses this
        else {
          sandbox.query('form').submit();
        }
      }
    );
  }
};


text:
docker kill zookeeper; docker rm zookeeper
docker kill nimbus; docker rm nimbus
docker kill supervisor; docker rm supervisor
docker kill ui; docker rm ui


text:
/*
 * Created:  Sep 7, 2011
 *      By:  kmurdoff
 */
/**
 *
 */
package com.livescribe.aws.tokensvc.config;

/**
 *

 *
 * @author Kevin F. Murdoff
 * @version 1.0
 */
public class AppProperties extends com.livescribe.framework.lsconfiguration.AppProperties implements AppConstants {

	/**
	 *

	 *
	 */
	public AppProperties() {
		super();
	}
}


text:
import '../amp-social-share';
import {toggleExperiment} from '../../../../src/experiments';
import {waitForChildPromise} from '../../../../src/dom';
import {whenCalled} from '../../../../testing/test-helper.js';

const BUTTON_SELECTOR = 'div[role="button"]';
const WINDOW_FEATURES = 'resizable,scrollbars,width=640,height=480';

describes.realWin(
  'amp-social-share-v1.0',
  {
    amp: {
      runtimeOn: true,
      extensions: ['amp-social-share:1.0'],
      canonicalUrl: 'https://canonicalexample.com/',
    },
  },
  (env) => {
    let win, doc;
    let element;

    const waitForRender = async () => {
      await whenCalled(env.sandbox.spy(element, 'attachShadow'));
      const shadow = element.shadowRoot;
      await waitForChildPromise(shadow, (shadow) => {
        return shadow.querySelector(BUTTON_SELECTOR);
      });
    };

    beforeEach(() => {
      win = env.win;
      doc = win.document;
      doc.title = 'Test Title';
      toggleExperiment(win, 'amp-social-share-bento', true);
    });

    it('renders custom endpoint when not using a pre-configured type', async () => {
      element = win.document.createElement('amp-social-share');
      element.setAttribute('type', 'unknown-provider');
      element.setAttribute('data-share-endpoint', 'cats.com');
      win.document.body.appendChild(element);
      await waitForRender();

      // when using a type that is not pre-configured, verify that the custom
      // endpoint is used (in this case cats.com)
      const openWindowDialogStub = env.sandbox.stub(window, 'open');
      element.shadowRoot.querySelector(BUTTON_SELECTOR).click();
      expect(openWindowDialogStub).to.be.calledWithExactly(
        'cats.com',
        '_blank',
        WINDOW_FEATURES
      );
    });

    it('allows configuration of the target attribute', async () => {
      element = win.document.createElement('amp-social-share');
      element.setAttribute('type', 'unknown-provider');
      element.setAttribute('data-share-endpoint', 'cats.com');
      element.setAttribute('data-target', 'target value');
      win.document.body.appendChild(element);
      await waitForRender();

      const openWindowDialogStub = env.sandbox.stub(window, 'open');
      element.shadowRoot.querySelector(BUTTON_SELECTOR).click();

      // verify that the target value can be set via data-target
      expect(openWindowDialogStub).to.be.calledWithExactly(
        'cats.com',
        'target value',
        WINDOW_FEATURES
      );
    });

    it('updates target when using an iOS device for email or sms', async () => {
      env.sandbox.stub(window.navigator, 'userAgent').value('ipad');

      element = win.document.createElement('amp-social-share');
      element.setAttribute('type', 'unknown-provider');
      element.setAttribute('data-share-endpoint', 'mailto:cats.com');
      win.document.body.appendChild(element);
      await waitForRender();

      const openWindowDialogStub = env.sandbox.stub(window, 'open');
      element.shadowRoot.querySelector(BUTTON_SELECTOR).click();

      // when window.navigator.userAgent indicates an iOS device
      // the target is updated to _top for email and sms
      expect(openWindowDialogStub).to.be.calledWithExactly(
        'mailto:cats.com',
        '_top',
        WINDOW_FEATURES
      );
    });

    it('accepts additional user-specified search parameters', async () => {
      element = win.document.createElement('amp-social-share');
      element.setAttribute('type', 'unknown-provider');
      element.setAttribute('data-share-endpoint', 'cats.com');
      element.setAttribute('data-param-test', 'test-value');
      element.setAttribute('data-param-test2', 'test-value2');
      win.document.body.appendChild(element);
      await waitForRender();

      const openWindowDialogStub = env.sandbox.stub(window, 'open');
      element.shadowRoot.querySelector(BUTTON_SELECTOR).click();

      // additional params, test-value and test-value2 are included in the url
      expect(openWindowDialogStub).to.be.calledWithExactly(
        'cats.com?test=test-value&test2=test-value2',
        '_blank',
        WINDOW_FEATURES
      );
    });

    it('receives the recipient from the data attribute when using "email" type', async () => {
      element = win.document.createElement('amp-social-share');
      element.setAttribute('type', 'email');
      element.setAttribute('data-param-recipient', 'recipient-name');
      win.document.body.appendChild(element);
      await waitForRender();

      const openWindowDialogStub = env.sandbox.stub(window, 'open');
      element.shadowRoot.querySelector(BUTTON_SELECTOR).click();

      // the data-param-recipient attribute is included in the url after
      // "mailto:"
      expect(openWindowDialogStub).to.be.calledWithExactly(
        'mailto:recipient-name?subject=Test%20Title&body=https%3A%2F%2F' +
          'canonicalexample.com%2F&recipient=recipient-name',
        '_blank',
        WINDOW_FEATURES
      );
    });

    it('uses special query symbol for "sms" type', async () => {
      element = win.document.createElement('amp-social-share');
      element.setAttribute('type', 'sms');
      win.document.body.appendChild(element);
      await waitForRender();

      const openWindowDialogStub = env.sandbox.stub(window, 'open');
      element.shadowRoot.querySelector(BUTTON_SELECTOR).click();

      // the query symbol for sms should be '?&' instead of '?'
      expect(openWindowDialogStub).to.be.calledWithExactly(
        'sms:?&body=Test%20Title%20-%20https%3A%2F%2Fcanonicalexample.com%2F',
        '_blank',
        WINDOW_FEATURES
      );
    });

    it('properly resolves bindings from amp environment', async () => {
      element = win.document.createElement('amp-social-share');
      element.setAttribute('type', 'twitter');
      win.document.body.appendChild(element);
      await waitForRender();

      const openWindowDialogStub = env.sandbox.stub(window, 'open');
      element.shadowRoot.querySelector(BUTTON_SELECTOR).click();

      // verify that TITLE and CANONICAL_URL (default parameters from Twitter
      // config are properly resolved).  These are set in doc.title and
      // canonicalUrl of the ampdoc info respectively
      expect(openWindowDialogStub).to.be.calledWithExactly(
        'https://twitter.com/intent/tweet?text=Test%20Title&' +
          'url=https%3A%2F%2Fcanonicalexample.com%2F',
        '_blank',
        WINDOW_FEATURES
      );
    });

    it('renders children and hides default icon when children are provided', async () => {
      element = win.document.createElement('amp-social-share');
      element.setAttribute('type', 'sms');
      const child = win.document.createElement('div');
      child.textContent = 'child';
      element.appendChild(child);
      win.document.body.appendChild(element);
      await waitForRender();

      // verify that the unnamed slot is in the shadowroot and the svg is not
      // when a child is included in the amp-social-share element
      expect(
        element.shadowRoot.querySelector(BUTTON_SELECTOR).querySelector('slot')
      ).to.not.be.null;
      expect(element.shadowRoot.querySelector('svg')).to.be.null;
    });

    it('allows color and background to be inherited from parent', async () => {
      element = win.document.createElement('amp-social-share');
      element.setAttribute('type', 'email');
      win.document.body.appendChild(element);
      await waitForRender();

      // verify that color and background color are inherited
      expect(element.shadowRoot.querySelector('svg').style.color).to.be.equal(
        'currentcolor'
      );
      expect(
        element.shadowRoot.querySelector('svg').style.backgroundColor
      ).to.be.equal('inherit');
    });
  }
);


text:
package org.finra.datagenerator.scaffolding.transformer.graph.nodes

import java.util.UUID

import gremlin.scala.Element
import org.finra.datagenerator.scaffolding.transformer.graph.reader.GraphReader
import org.finra.datagenerator.scaffolding.transformer.graph.rules.RuleConditionOptions

import scala.collection.JavaConverters._
/**
  * Created by dkopel on 11/2/16.
  */
trait ElementContainer[T] {
    val uuid: UUID
    implicit val ruleConditionOptions: RuleConditionOptions
    def id: Any
    val element: Element
    def properties: Map[String, AnyVal] = element.keys().asScala
        .map(k => k -> element.property(k).value()).toMap
    def clazz: Class[T] = Class.forName(properties(GraphReader.clazz).toString).asInstanceOf[Class[T]]
    def overrides: Map[String, AnyVal] = properties.filterKeys(k => !ElementContainer.IGNORE.contains(k))
}
object ElementContainer {
    val IGNORE = Seq(GraphReader.clazz, "_id", "id", "_uuid", "_label")
}


text:
import re
import os
import sys
from subprocess import call
from html.parser import HTMLParser
import requests
from termcolor import cprint

# Root page parser class
class AnimeSiteParser(HTMLParser):
    episodes = []
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            for attr in attrs:
                if 'href' in attr[0]:
                    link = attr[1]
                    if link.find('https://anime-odcinki.pl/anime/' + animeName) != -1 and re.search(r'\d+$', link):
                        self.episodes.append(link)

# Children's pages parser class
class AnimeEpisodeSiteParser(HTMLParser):
    encryptedVideoLinks = []
    def handle_starttag(self, tag, attrs):
        if tag == "div":
            for attr in attrs:
                if attr[0] == "data-hash":
                    self.encryptedVideoLinks.append(attr[1])

# $1 is name of anime to downloadd
animeName = "-".join(sys.argv[1].lower().split())
url = "https://anime-odcinki.pl/anime/" + animeName
header = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
}

session = requests.Session()

# get root page
req = session.get(url, headers=header)
# parse root page
animeSiteParser = AnimeSiteParser()
animeSiteParser.feed(req.text)
# search for a links to episodes
for episode in animeSiteParser.episodes:
    cprint(episode, 'green')
animeSiteParser.episodes.reverse()
for episode in animeSiteParser.episodes:
    req = session.get(episode, headers=header)
    animeEpisodeSiteParser = AnimeEpisodeSiteParser()
    animeEpisodeSiteParser.feed(req.text)
    with open('./communicationFile', 'w+') as communicationFile:
        communicationFile.write(animeEpisodeSiteParser.encryptedVideoLinks[0])
    call(['node', './decryptVideoLink.js'])
    os.system('node ./decryptVideoLink.js')
    with open('./communicationFile', 'w+') as communicationFile:
        videoLink = communicationFile.read()
    cprint(videoLink, 'blue')
    os.system('youtube-dl \"%s\"' % animeEpisodeSiteParser.videos[0])


text:
#include <fatal/container/static_array.h>

#include <fatal/type/list.h>

#include <fatal/test/driver.h>

#include <type_traits>

namespace fatal {

struct abc { int x; int y; int z; };

template <typename T>
void check_empty() {
  using factory = typename static_array<>::type<T>;

  using empty_list_array = typename factory::template from_list<type_list<>>;
  FATAL_EXPECT_SAME<T, typename decltype(empty_list_array::get)::value_type>();
  FATAL_EXPECT_EQ(0, empty_list_array::get.size());

  using empty_args_array = typename factory::template from_args<>;
  FATAL_EXPECT_SAME<T, typename decltype(empty_args_array::get)::value_type>();
  FATAL_EXPECT_EQ(0, empty_args_array::get.size());
}

FATAL_TEST(static_array, empty) {
  check_empty<int>();
  check_empty<abc>();
}

struct check_array_visitor {
  template <typename TTag, typename U>
  void operator ()(TTag, U const &array) {
    FATAL_ASSERT_LT(TTag::index, array.size());
    FATAL_EXPECT_EQ(TTag::type::value, array[TTag::index]);
  }
};

template <typename TExpectedList, typename TArray>
void check_array() {
  FATAL_EXPECT_EQ(TExpectedList::size, TArray::get.size());
  TExpectedList::foreach(check_array_visitor(), TArray::get);
}

template <int... Values>
void check_int() {
  using list = type_list<std::integral_constant<int, Values>...>;

  check_array<list, static_array<>::from_list<list>>();
  check_array<list, static_array<>::type<int>::from_list<list>>();

  check_array<
    list,
    static_array<>::from_args<std::integral_constant<int, Values>...>
  >();
  check_array<
    list,
    static_array<>::type<int>::from_args<std::integral_constant<int, Values>...>
  >();
}

FATAL_TEST(static_array, int) {
  check_int<0>();
  check_int<1>();
  check_int<2>();
  check_int<100>();
  check_int<0, 1, 2>();
  check_int<1, 2, 3>();
  check_int<2, 3, 4>();
  check_int<25, 26, 27>();
  check_int<178, 849, 9, 11, 0>();
}

struct check_abc_visitor {
  template <typename T, std::size_t Index, typename U>
  void operator ()(indexed_type_tag<T, Index>, U const &array) const {
    FATAL_ASSERT_LT(Index, array.size());
    FATAL_EXPECT_EQ(T::first::first::value, array[Index].x);
    FATAL_EXPECT_EQ(T::first::second::value, array[Index].y);
    FATAL_EXPECT_EQ(T::second::value, array[Index].z);
  }
};

template <typename TList, typename TArrayFactory>
void check_abc_array() {
  using array = typename TArrayFactory::template from_list<TList>;
  static_assert(TList::size == array::get.size(), "size mismatch");
  TList::foreach(check_abc_visitor(), array::get);
}

struct abc_factory {
  template <typename T>
  static constexpr abc create() {
    return abc{
      T::type::first::first::value,
      T::type::first::second::value,
      T::type::second::value
    };
  }
};

template <int... Values>
void check_abc() {
  using values = type_list<std::integral_constant<int, Values>...>;
  using x = typename values::template unzip<3, 0>;
  using y = typename values::template unzip<3, 1>;
  using z = typename values::template unzip<3, 2>;
  using list = typename x::template combine<>::template list<y>
    ::template combine<>::template list<z>;
  using factory = static_array<abc_factory>;

  check_abc_array<list, factory>();
  check_abc_array<list, typename factory::template type<abc>>();
}

FATAL_TEST(static_array, struct) {
  check_abc<0, 0, 0>();
  check_abc<0, 1, 2>();
  check_abc<99, 56, 43>();

  check_abc<0, 0, 0, 0, 1, 2>();

  check_abc<0, 0, 0, 0, 1, 2, 99, 56, 43>();
  check_abc<0, 1, 2, 3, 4, 5, 6, 7, 8>();

  check_abc<0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11>();
  check_abc<99, 15, 62, 3, 8, 12, 0, 46, 85, 5, 1, 7>();
}

} // namespace fatal {


text:
use strict;
use warnings;
use File::Copy;
use File::Basename;

my $force_cygwin = 0;

BEGIN {
	my $dir = dirname($0);
	push @INC, $dir;
}

#foreach (@INC) { print "INC: $_\n"; }

use TestGlue;

my $iswindows = TestGlue::is_windows();
my $iscygwin  = TestGlue::is_cygwin_perl();

#if($iswindows == 1) {
#	if($iscygwin == 1) {
#		out("Entering remote_task using cygwin perl");
#	} else {
#		out("Entering remote_task using active state perl");
#	}
#}

TestGlue::setup_test_environment();

push @INC, "$ENV{BASE_DIR}/condor_tests";

require CondorTest;
require CondorPersonal;
require CondorUtils;

if( ! defined $ENV{_NMI_TASKNAME} ) {
    die "_NMI_TASKNAME not in environment, can't test anything!\n";
}
my $fulltestname = $ENV{_NMI_TASKNAME};

if( $fulltestname =~ /remote_task/) {
    die "_NMI_TASKNAME set to remote_task meaning 0 tests seen!\n";
}

if( ! $fulltestname ) {
    # if we have no task, just return success immediately
    out("No tasks specified, returning SUCCESS");
    exit 0;
}

my $BaseDir  = $ENV{BASE_DIR} || c_die("BASE_DIR is not in environment!\n");
my $test_dir = File::Spec->catdir($BaseDir, "condor_tests");

# iterations have numbers placed at the end of the name
# for unique db tracking in nmi for now.
if($fulltestname =~ /([\w\-\.\+]+)-\d+/) {
    my $matchingtest = $fulltestname . ".run";
    if(!(-f $matchingtest)) {
        # if we don't have a test called this, strip iterator off
        $fulltestname = $1;
    }
}

######################################################################
# get the testname and group
######################################################################

my @testinfo = split(/\./, $fulltestname);
my $testname = $testinfo[0];
my $compiler = $testinfo[1];

if( ! $testname ) {
    c_die("Invalid input for testname\n");
}

out("REMOTE_TASK.$$ Testname: '$testname'");
if( not TestGlue::is_windows() ) {
    if( $compiler ) {
        out("compiler is $compiler");
    }
    else {
        $compiler = ".";
    }
}
else {
    $compiler = ".";
}

######################################################################
# run the test using batch_test.pl
######################################################################

if (1) {
    my @knobs;
    foreach my $key (keys %ENV) {
        if ( $key =~ m/^_CONDOR_/i ) {
            push @knobs, $key;
            delete($ENV{$key});
        }
    }
    if (scalar @knobs > 0) {
        out("Removing environment config overides : " . join(' ',@knobs));
    }
}

# Some of the tests fail because the schedd fsync can take 30 seconds
# or more on busy nmi filesystems, which causes the tools to timeout.
# Up the tool timeout multipler to try to deal with this.
out("Setting _condor_TOOL_TIMEOUT_MULTIPLIER=4");
$ENV{_condor_TOOL_TIMEOUT_MULTIPLIER}="4";

chdir($test_dir) || c_die("Can't chdir($test_dir): $!\n");

############################################################
##
## Here we examine some requirements which we know about
## now and in the future we already have a list for personals
## but we could expand those into our new more general way.
##
## The new list Test_Requirements file
## has the base test name separated by a colon to a commma
## separated list of requirements
##
## claasad_cache-basic : cygwin
##
## So we look for our test to have requirements by reading the file
## and if we find it we split the requirements into an array
## and then process the array of requirements.
##
############################################################

my $requirements = ProcessTestRequirements();

if( exists( $requirements->{ IPv4 } ) ) {
	my $ENABLE_IPV4 = `condor_config_val ENABLE_IPv4`;
	if( $ENABLE_IPV4 =~ m/FALSE/i || $ENABLE_IPV4 =~ m/0/i ) {
	    out( "'${testname}' requires IPv4, but IPv4 is not enabled.  Returning SUCCESS." );
    	exit( 0 );
	}
}

if( exists( $requirements->{ personal } ) ) {
	out("'$testname' requires a personal HTCondor, starting one now.");
	StartTestPersonal($testname);
}

# Now that we stash all debug messages, we'll only dump them all
# when the test fails. This will be debugs at all levels.

# must use cygwin perl on Windows for batch_test.pl
my $perl_exe = "perl";
if ($ENV{NMI_PLATFORM} =~ /_win/i) {
    my $perlver = `$perl_exe -version`;
    if ($perlver =~ /This is (perl .*)$/m) { $perlver = $1; }
    out("First perl is $perlver.");
    if ( !(exists $requirements->{cygwin})) {
        out("attempting to run tests using current perl");
		if ($ENV{PATH} =~ /[a-z]:\\condor\\bin;/i) {
            out("removing base condor from the path");
            my $tmppath = $ENV{PATH};
            $tmppath =~ s/[a-z]:\\condor\\bin;//i;
            if ($^O =~ /MSWin32/) {
	       		if ($tmppath =~ /[a-z]:\\cygwin\\bin;/i) {
                    out("removing cygwin from the path");
					#out("Before removal:$tmppath\n");
                    $tmppath =~ s/[a-z]:\\cygwin\\bin;//ig;
				}
	    	}
            #out("new PATH=$tmppath");
            $ENV{PATH} = $tmppath;
        }
    } elsif (!($perlver =~ /cygwin/i)) {
        out("Adding cygwin to the front of the path to force the use of cygwin perl.");
        $ENV{PATH} = "c:\\cygwin\\bin;$ENV{PATH}";
		out("new PATH=$ENV{PATH}");

        $perlver = `$perl_exe -version`;
		if ($perlver =~ /This is (perl .*)$/m) { $perlver = $1; }
        out("First perl is now $perlver.");
        if (!($perlver =~ /cygwin/i)) {
            die "cygwin perl not found!\n";
        }
    }
    #my $newpath = join("\n", split(';',$ENV{PATH}));
    #out("PATH is now\n$newpath");
}

# alternative arguments for batch test...
#system("$perl_exe batch_test.pl -d $compiler -t $testname -b --isolated -v");
#system("$perl_exe batch_test.pl -d $compiler -t $testname -b --isolated");

out("RUNNING batch_test.pl -t '$testname'\n---------");
my $batchteststatus = system("$perl_exe batch_test.pl -d $compiler -t $testname");
print "---------\n"; # we print here rather than using out() in order to bracket the batch test output with ----- above and below.
my @returns = TestGlue::ProcessReturn($batchteststatus);

$batchteststatus = $returns[0];
my $signal = $returns[1];
my $signalmsg = $signal ? " and signal $signal" : "";
out("batch_test returned $batchteststatus" . $signalmsg);

# if we started a personal HTCondor, stop it now, if we can't, then fail the test.
#
my $teststatus = $batchteststatus;
if(exists $requirements->{personal}) {
	out("Stopping personal HTCondor for '$testname'");
	my $personalstatus = StopTestPersonal($testname);
	if($personalstatus != 0 && $teststatus == 0) {
		print "\tTest succeeded, but condor failed to shut down or there were\n";
		print "\tcore files or error messages in the logs. see CondorTest::EndTest\n";
		$teststatus = $personalstatus;
	}
}

# report here figure if the test passed or failed.
my $run_success = $batchteststatus ? 0 : 1; # 0 is success for batch test, but 1 is success for RegisterResult
CondorTest::RegisterResult($run_success,test_name=>$testname, check_name=>"run_test");

######################################################################
# print output from .run script to stdout of this task, and final exit
######################################################################

my $compiler_path = File::Spec->catpath($test_dir, $compiler);
chdir($compiler_path) || c_die("Can't chdir($compiler_path): $!\n");
my $run_out       = "$testname.run.out";
my $run_out_path  = File::Spec->catfile($compiler_path, $run_out);
my $test_out      = "$testname.out";
my $test_out_path = File::Spec->catfile($compiler_path, $test_out);
my $test_err      = "$testname.err";
my $test_err_path = File::Spec->catfile($compiler_path, $test_err);

out("Looking for run.out file");
print "\tcompiler_path: $compiler_path\n\trun_out: $run_out\n\trun_out_path: $run_out_path\n\tcompiler_path: $compiler_path\n";
print "\ttest_out: $test_out\n\ttest_out_path: $test_out_path\n\ttest_err: $test_err\n\ttest_err_path: $test_err_path\n";
#print "Here now:\n";
#system("pwd;ls -lh $run_out_path");

if( ! -f $run_out_path ) {
    if( $teststatus == 0 ) {
        # if the test passed but we don't have a run.out file, we
        # should consider that some kind of weird error
        c_die("WTF ERROR: test passed but $run_out does not exist!");
    }
    else {
        # if the test failed, this isn't suprising.  we can print it,
        # but we should just treat it as if the test failed, not an
        # internal error.
        out("No test output... Test failed and $run_out does not exist");
    }
}
else {
    # spit out the contents of the run.out file to the stdout of the task
    if( open(RES, '<', $run_out_path) ) {
        out("Printing test output...\n\n----- Start of $run_out -----");
        while(<RES>) {
            print "$_";
        }
        close RES;
        print "\n----- End of $run_out -----\n";
    }
    else {
        out("Printing test output...  ERROR: failed to open $run_out_path: $!");
    }
}

print "\n********************** EXIT REMOTE_TASK.$$: Status:$teststatus ******************\n";
exit $teststatus;

######################################################################
# helper methods
######################################################################

sub ProcessTestRequirements
{
	my $requirements;

	my $requirementslist = "Test_Requirements";
	open( TR, "< ${requirementslist}" ) or c_die( "Failed to open '${requirementslist}': $!\n" );
	while( my $line = <TR> ) {
		TestGlue::fullchomp( $line );
		if( $line =~ /\s*$testname\s*:\s*(.*)/ ) {
			my @requirementList = split( /,/, $1 );
			foreach my $requirement (@requirementList) {
				$requirement =~ s/^\s+//;
				$requirement =~ s/\s+$//;
				out( "${testname} needs '${requirement}'" );
				$requirements->{ $requirement } = 1;
			}
		}
	}

	return $requirements;
}

sub c_die {
    my($msg) = @_;
    out($msg);
    exit 3;
}

sub StartTestPersonal {
	my $test = shift;

	my $firstappend_condor_config = '
		DAEMON_LIST = MASTER, SCHEDD, COLLECTOR, NEGOTIATOR, STARTD
		NEGOTIATOR_INTERVAL = 5
		JOB_MAX_VACATE_TIME = 15
	';

	my $configfile = CondorTest::CreateLocalConfig($firstappend_condor_config,"remotetask$test");

	CondorTest::StartCondorWithParams(
    	condor_name => "remotetask$test",
    	fresh_local => "TRUE",
    	condorlocalsrc => "$configfile",
		test_glue => "TRUE",
	);
}

sub showEnv {
	foreach my $env (sort keys %ENV) {
		print "$env: $ENV{$env}\n";
	}
}

sub StopTestPersonal {
	my $exit_status = 0;
	$exit_status = CondorTest::EndTest("no_exit");
	return($exit_status);
}


text:
package edu.ur.tag.repository;

import edu.ur.ir.user.IrUser;
import edu.ur.ir.user.IrUserGroup;

/**
 * Functions for dealing with groups
 *
 * @author Nathan Sarr
 *
 */
public class GroupWebUtilFunctions {

	/**
	 * Returns true if the user is part of the specified group.
	 *
	 * @param user - user to check
	 * @param userGroup - user group to check.
	 *
	 * @return true if the user is found within the group.
	 */
	public static boolean isInGroup(IrUser user, IrUserGroup userGroup)
	{
		return userGroup.getUsers().contains(user);
	}

	/**
	 * Returns true if the user is an admin of the specified group.
	 *
	 * @param user  - user to check to see if they are and administrator
	 * @param userGroup - user group to check
	 * @return - true if the user is an admin of the group.
	 */
	public static boolean isAdminOfGroup(IrUser user, IrUserGroup userGroup)
	{
		return userGroup.getAdministrators().contains(user);
	}

}


text:
<!DOCTYPE html>

Welcome to MindTrails!

Past studies have shown that changing the way we think can affect our mood, improve our relationships,
                    and make it easier to achieve our goals.  For instance, many studies have shown that practice
                    thinking about things in new ways can reduce anxiety symptoms. In the studies below,
                    you can complete a computer program that will describe different situations and encourage you to
                    think about them in particular ways.

We have people trying different versions of the computer program for these studies to see which
                    version works best – we think some of these computer programs can improve mental health by changing
                    the way people interpret situations.

We are currently running two different studies: one to reduce anxiety for people who frequently
                    become anxious or scared, and one to encourage healthier thinking about the future for people
                    who tend to expect things will not turn out well. Select the study that seems the most beneficial
                    to you.

                        <button>Managing Anxiety</button>

                        <button>Future Thinking</button>


text:
Creating Extensions - Tutorial - Say Hello
==========================================

In this extension we learn how to create a C function that get a name as string then say hello.

This extension is an update to the (sumtwonumbers) extension in : ring/extensions/tutorial/sumtwonumbers folder

In mylib.c we update the file to add

	RING_FUNC(ring_sayhello)
	{
		// Check Parameters Count
			if (RING_API_PARACOUNT != 1) {
				RING_API_ERROR(RING_API_MISS1PARA);
				return;
			}
		// Check Parameters Type
			if ( ! RING_API_ISSTRING(1) ) {
				RING_API_ERROR(RING_API_BADPARATYPE);
				return;
			}
		printf("Hello %s\n",RING_API_GETSTRING(1));
	}

Then we register the new function

	ring_vm_funcregister("sayhello",ring_sayhello);

The file test.ring contains

	? "Loading Library"
	load "mylib.ring"

	? "Calling a C Function"
	myfunction()

	? "Sum Two Numbers (3,5)"
	? SumTwoNumbers(3,5)

	? "Say Hello"
	SayHello("Mahmoud")

Then we test the function using

	ring test.ring

Output

	Loading Library
	Calling a C Function
	Hello, World!
	Sum Two Numbers (3,5)
	8
	Say Hello
	Hello Mahmoud


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/topLayout"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">

  <com.cordovaplugincamerapreview
      android:id="@+id/preview"
      android:layout_width="match_parent"
      android:layout_height="match_parent">

    <com.cordovaplugincamerapreview
        android:id="@+id/faceOverlay"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

  </com.cordovaplugincamerapreview>

</LinearLayout>


text:
'use strict';

var assert = require('assert');

var async = require('async');
var uuid = require('uuid');

var common = require('../common');
var stormpath = common.Stormpath;
var helpers = require('./helpers');

var Organization = require('../../lib/resource/Organization');

describe('Client', function() {
  var organization;
  describe('creation', function() {
    var createClientFn;

    before(function(done) {
      helpers.loadApiKey(function(apiKey) {
        createClientFn = function createClientFn() {
          new stormpath.Client({ apiKey:apiKey });
        };
        done();
      });
    });

    //it('should not expose an apiKey property', function(done) {
    //  helpers.getClient(function(client) {
    //    assert.equal(client.config.apiKey, undefined);
    //    done();
    //  });
    //});

    //it('should automatically load client.config.apiKey', function(done) {
    //  helpers.getClient(function(client) {
    //    assert(client.config.client.apiKey);
    //    done();
    //  });
    //});

    it('shoud propertly load socialProviders onto the configuration object', function(done) {
      helpers.getClient(function(client) {
        var applicationData = { name: uuid.v4() };
        var application, directory;

        async.series([
          // First, we'll create a new Stormpath Application.
          function(cb) {
            client.createApplication(applicationData, { createDirectory: true }, function(err, app) {
              if (err) {
                return cb(err);
              }

              // Update the Client config, so that when we move onto the mapping
              // step we'll be able to merge in the config!
              client.config.application = {
                href: app.href
              };

              application = app;
              cb();
            });
          },

          // Next, we'll create a Facebook Directory.
          function(cb) {
            var directoryData = {
              name: uuid.v4(),
              provider: {
                clientId: 'xxx',
                clientSecret: 'yyy',
                providerId: 'facebook'
              }
            };

            client.createDirectory(directoryData, function(err, dir) {
              if (err) {
                return cb(err);
              }

              directory = dir;
              cb();
            });
          },

          // Finally, we'll map our newly created Directory to our Application.
          function(cb) {
            var mappingData = {
              application: {
                href: application.href
              },
              accountStore: {
                href: directory.href
              },
              isDefaultAccountStore: false,
              isDefaultGroupStore: false
            };

            application.createAccountStoreMapping(mappingData, function(err) {
              if (err) {
                return cb(err);
              }

              cb();
            });
          }
        ], function(err) {
          if (err) {
            return done(err);
          }

          // Now, we'll run our actual Client.mergeRemoteConfig method to
          // attempt to grab all social providers.
          client.mergeRemoteConfig(function(err) {
            if (err) {
              return done(err);
            }

            assert.equal(client.config.socialProviders.facebook.providerId, 'facebook');
            assert.equal(client.config.socialProviders.facebook.clientId, 'xxx');
            assert.equal(client.config.socialProviders.facebook.clientSecret, 'yyy');
            done();
          });
        });
      });
    });

    it('should not throw', function() {
      assert.doesNotThrow(createClientFn);
    });
  });

  describe('getCurrentTenant', function() {
    var Tenant = require('../../lib/resource/Tenant');

    it('should not err', function(done) {
      helpers.getClient(function(client) {
        client.getCurrentTenant(function(err) {
          assert.ifError(err);
          done();
        });
      });
    });

    it('should return a tenant instance', function(done) {
      helpers.getClient(function(client) {
        client.getCurrentTenant(function(err, tenant) {
          assert.ifError(err);
          assert(tenant instanceof Tenant);
          done();
        });
      });
    });
  });

  describe('createOrganization',function(){
    var client;
    before(function(done){
      helpers.getClient(function(_client){
        client = _client;
        done();
      });
    });
    it('should create an organization',function(done){
      client.createOrganization({
        name: uuid(),
        nameKey: uuid()
      },function(err,_organization){
        assert(_organization instanceof Organization);
        organization = _organization;
        done();
      });
    });
    it('should handle errors',function(done){
      client.createOrganization({
        name: uuid()
      },function(err){
        assert(err.userMessage.match(/Organization nameKey cannot be null/));
        done();
      });
    });
  });

  describe('getOrganization',function(){
    var client;
    before(function(done){
      helpers.getClient(function(_client){
        client = _client;
        done();
      });
    });
    it('should get an organization',function(done){
      client.getOrganization(organization.href,function(err,organization){
        assert(organization instanceof Organization);
        done();
      });
    });
    it('should handle errors',function(done){
      client.getOrganization('bad href',function(err){
        assert(err.status === 404);
        done();
      });
    });
  });

  describe('getOrganizations',function(){
    var client;
    before(function(done){
      helpers.getClient(function(_client){
        client = _client;
        done();
      });
    });
    it('should get an organization',function(done){
      client.getOrganizations(function(err,collection){
        assert(collection.items[0] instanceof Organization);
        done();
      });
    });
  });
});


text:
'use strict'
const glob = require('glob')
exports.register = function(server, options, next) {
  glob(`${__dirname}/**/*.js`, {ignore: `${__dirname}/**/index.js`}, (err, files) => {
    files.forEach(file => require(file)(server))
    next()
  })
}

exports.register.attributes = {
  name: 'api'
}


text:
package smartcache;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

import com.caucho.junit.HttpClient;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class SmartCacheTest
{

  @Before
  public void setup() throws SQLException
  {
    try {
      Connection conn
        = DriverManager.getConnection("jdbc:hsqldb:file:db/sample");

      conn.createStatement().executeUpdate(
        "insert into DATAITEM (id, value) values(12, 'Hello World!')");

      conn.commit();
    } catch (SQLIntegrityConstraintViolationException e) {

    }
  }

  @Test
  public void testSpringData() throws IOException, SQLException
  {
    CacheServer cache = new CacheServer();

    cache.start("--conf", "src/test/resources/conf-spring-data.yml");

    HttpClient client = new HttpClient(8080);

    String response = client.get("/CachedItem/12").go().body();

    Assert.assertEquals("{\"id\":12,\"value\":\"Hello World!\"}", response);

    System.err.println("SmartCacheTest.test " + response);

    cache.stop();
  }

  @Test
  public void testJdbc() throws IOException, SQLException
  {
    CacheServer cache = new CacheServer();

    cache.start("--conf", "src/test/resources/conf-jdbc.yml");

    HttpClient client = new HttpClient(8080);

    String response = client.get("/CachedItem/12").go().body();

    Assert.assertEquals("{\"id\":12,\"value\":\"Hello World!\"}", response);

    System.err.println("SmartCacheTest.test " + response);

    cache.stop();
  }

  @Test
  public void testJpa() throws IOException, SQLException
  {
    CacheServer cache = new CacheServer();

    cache.start("--conf", "src/test/resources/conf-jpa.yml");

    HttpClient client = new HttpClient(8080);

    String response = client.get("/CachedItem/12").go().body();

    Assert.assertEquals("{\"id\":12,\"value\":\"Hello World!\"}", response);

    System.err.println("SmartCacheTest.test " + response);

    cache.stop();
  }

}


text:
import FileSaver from 'file-saver';
import FileConsts from './Consts/FileConsts';

export default class FileService {

  static saveFile(entityData, name, datatype, success) {
    let contentType = 'application/json';
    let data = entityData;

    if (datatype === FileConsts.JSON) {
      contentType = 'text/csv';
      data = JSON.stringify(entityData);
    }

    const blob = new Blob([data], {
      type: contentType
    });

    FileSaver.saveAs(blob, name.concat(
      (datatype === FileConsts.JSON) ? '.json' : '.csv'
    ));
    if (success && success !== undefined) {
      success(datatype);
    }
  }
}


text:
<?php

namespace Vest\ResponsaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Vest\ResponsaBundle\Entity\AddrPersonen;     // Zeigt dem Controller, wo er die Entität findet (verwendet in Zeilte 17)
use Symfony\Component\HttpFoundation\Request;   // Zeigt dem Controller wo er die Funktionen für Requests findet.

class AddrPersonController extends Controller
{
    public function indexAction($id='')
    {
      /*
       *  Check ob eine ID uebergeben wurde und damit ob es sich um einen neuen Eintrag handelt oder nicht.
       */
      if($id== ''){   // wurde keine ID uebergeben, handelt es sich um einen neuen Eintrag, für den ein neues Objekt erzeugt werden muss.
        $person = new AddrPersonen(); // legt eine neue Person an

      }else{  //lädt den vorhandenen Eintrag zu der ID
        $repository = $this->getDoctrine()->getRepository('VestResponsaBundle:AddrPersonen');// Baut Doctrine auf
        $person = $repository->findOneBy(array('personId' => $id));  //hohlt das passende Objekt aus der Doctrine. Wichtig, damit man danach updaten kann.

      }

        /*
         *  Anlegend es Formulars
         */
        $form = $this->createFormBuilder($person) // Formular wird auf Basis der Person erstellt
            ->setAction($this->generateUrl('AddrPerson-save'))     //nimmt die URL aus der routing.yml
            ->add('personId', 'hidden')
            ->add('kontakt_id', 'integer')
            ->add('person_anrede', 'choice', array('choices'=> array('herr' => 'Herr', 'frau' => 'Frau'))) // Gibt an welche Auswahlmöglichkeiten es gibt.
            ->add('person_titel', 'text', array('required'  => false))  // deaktiviert das HTML5 Tag "required". Dies wird standardmäßig gesetzt.
            ->add('person_vorname', 'text')
            ->add('person_name', 'text')
            ->add('person_briefanrede', 'text', array('required'  => false))
            ->add('person_zhanrede', 'text', array('required'  => false))
            ->add('person_telefon', 'text')
            ->add('person_email', 'text')
            ->add('person_mobil', 'text', array('required'  => false))
            ->add('person_pass', 'password')
            ->add('save', 'submit')
            ->getForm();

          return $this->renderTemplate('VestResponsaBundle:Default:AddrPerson.html.twig', array(
              'form' => $form->createView(),   // stellt das Formular da.
          ));
    }

    public function saveAction(Request $request)
    {
        $request_array= $request->request->all() ;       // hohlt alle Felder aus dem Request
        $id = $request_array['form']['personId'];        // hohlt die verwendete ID aus dem request

        if($id >0){   // checkt, ob die ID gesetzt ist. Ist sie gesetzt, wird bearbeitet
          $repository = $this->getDoctrine()->getRepository('VestResponsaBundle:AddrPersonen');      // lädt das repository und sagt ihm um welche Entity es sich kümmern soll.
          $person = $repository->findOneBy(array('Id' => $id));   //Versucht eine Person mit der personId zu finden
        }else{              // ist keine ID gesetzt, handelt es sich um eine neue Person.
          $person = new AddrPersonen();      // wurde keine Person geladen, wird eine neue erzeugt
          $person->setRecordStatus(1);       // setzt de recordstatus bei neuen Personen auf 1

          /*
           *  Die Übergabe eines durch date() erzeugten Strings funktioniert nicht richtig und er wirft dabei einen Fehler.
           *  Bisher habe ich noch keinen Weg gefunden dei Zeit passend ein zu lesen und dann auch speichern zu können.
           */
          //$timestamp = time();
          //$date = date("Y-m-d H:i:s", $timestamp);
          //$person->setPersonAktualisiert($date);
        }

        /*
         *  Anlegend es exakt gleichen Formulars
         */
        $form = $this->createFormBuilder($person)
            ->setAction($this->generateUrl('AddrPerson-save'))
            ->add('personId', 'hidden')
            ->add('kontakt_id', 'integer')
            ->add('person_anrede', 'choice', array('choices'=> array('herr' => 'Herr', 'frau' => 'Frau')))
            ->add('person_titel', 'text', array('required'  => false))
            ->add('person_vorname', 'text')
            ->add('person_name', 'text')
            ->add('person_briefanrede', 'text', array('required'  => false))
            ->add('person_zhanrede', 'text', array('required'  => false))
            ->add('person_telefon', 'text')
            ->add('person_email', 'text')
            ->add('person_mobil', 'text', array('required'  => false))
            ->add('person_pass', 'password')
            ->add('save', 'submit')
            ->getForm();

        $form->handleRequest($request);    // hohlt die Datem aus dem Request in das Formular
        if(!($id>0)){
          $id = 0;    // sollte keine ID vorhanden sein, wird sie auf 0 gesetzt, da sie etwas enthalten muss um beim rendern übergeben zu werden.
        }

        if ($form->isValid()) {    // checkt ob die Daten im Formular valide sind.
          $em = $this->getDoctrine()->getManager();       // lädt den Entity Manager
          $em->persist($person);                          // sagen dem Entity Manager welche Entität er verwalten soll (ist bei neu angelegten Nutzern notwendig)
          $em->flush();                                   // speichert die Daten in die Datenbank

            $ergebnis = 1;    // boolean der ergebnis speichert und beim Rendern übergeben wird
            $error ='';
        }else{
            $ergebnis = 0;

            $error = (string) $form->getErrors(true, false);   //liest die Fehlermeldungen und speichert sie in einen String
        }

        /*
         * Rendert die Erfolgs-Seite
         * Dabei werden in einem Array Werte übergeben, die dann in der
         */
        return $this->renderTemplate('VestResponsaBundle:Default:erfolg.html.twig', array('ergebnis' => $ergebnis, 'id' => $id, 'error' => $error));

    }

}


text:
<!DOCTYPE html>

<meta charset=utf-8>
<title>WebRTC Test: the RTCPeerConnection Ice functionality</title>
<link rel="author" title="Intel" href="http://www.intel.com">
<link rel=help href="http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcpeerconnection-interface">


text:
'use strict'
var extend = require('extend')

var types = {
  ArrayNode: require('./node/ArrayNode'),
  AssignmentNode: require('./node/AssignmentNode'),
  ConditionalNode: require('./node/ConditionalNode'),
  ConstantNode: require('./node/ConstantNode'),
  FunctionNode: require('./node/FunctionNode'),
  OperatorNode: require('./node/OperatorNode'),
  SymbolNode: require('./node/SymbolNode'),
  UnaryNode: require('./node/UnaryNode')
}

var Interpreter = function (owner, options) {
  this.owner = owner
  this.options = extend({
    factory: 'ns.factory',
    raw: false,
    rawArrayExpressionElements: true,
    rawCallExpressionElements: false
  }, options)
}

extend(Interpreter.prototype, types)

// main method which decides which expression to call
Interpreter.prototype.next = function (node) {
  if (!(node.type in this)) {
    throw new TypeError('the node type ' + node.type + ' is not implemented')
  }
  return this[node.type](node)
}

Interpreter.prototype.rawify = function (test, fn) {
  var oldRaw = this.options.raw
  if (test) {
    this.options.raw = true
  }
  fn()
  if (test) {
    this.options.raw = oldRaw
  }
}

module.exports = Interpreter


text:
package gui.init.button;

import javafx.event.EventHandler;
import javafx.scene.control.Button;

public interface ButtonInterface {
	public void retrieveText();
	public Button setText();
	public Button setAction(EventHandler<?> event);
}