text:
package org.waveprotocol.box.server.robots.passive;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.google.common.collect.Maps;
import com.google.wave.api.InvalidRequestException;
import com.google.wave.api.OperationRequest;
import com.google.wave.api.OperationType;
import com.google.wave.api.ProtocolVersion;
import com.google.wave.api.data.converter.EventDataConverter;
import com.google.wave.api.data.converter.EventDataConverterManager;
import com.google.wave.api.event.EventType;
import com.google.wave.api.robot.Capability;

import junit.framework.TestCase;

import org.waveprotocol.box.server.account.RobotAccountData;
import org.waveprotocol.box.server.account.RobotAccountDataImpl;
import org.waveprotocol.box.server.robots.OperationContext;
import org.waveprotocol.box.server.robots.OperationServiceRegistry;
import org.waveprotocol.box.server.robots.RobotCapabilities;
import org.waveprotocol.box.server.robots.operations.OperationService;
import org.waveprotocol.box.server.robots.util.ConversationUtil;
import org.waveprotocol.box.server.util.WaveletDataUtil;
import org.waveprotocol.box.server.waveserver.WaveletProvider;
import org.waveprotocol.wave.federation.Proto.ProtocolWaveletDelta;
import org.waveprotocol.wave.model.id.IdURIEncoderDecoder;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.version.HashedVersion;
import org.waveprotocol.wave.model.version.HashedVersionFactory;
import org.waveprotocol.wave.model.version.HashedVersionZeroFactoryImpl;
import org.waveprotocol.wave.model.wave.ParticipantId;
import org.waveprotocol.wave.model.wave.data.ObservableWaveletData;
import org.waveprotocol.wave.util.escapers.jvm.JavaUrlCodec;

import java.util.Collections;
import java.util.List;

/**
 * Unit tests for {@link RobotOperationApplicator}.
 *
 * @author ljvderijk@google.com (Lennard de Rijk)
 */
public class RobotOperationApplicatorTest extends TestCase {

  private static final IdURIEncoderDecoder URI_CODEC =
      new IdURIEncoderDecoder(new JavaUrlCodec());
  private static final HashedVersionFactory HASH_FACTORY =
      new HashedVersionZeroFactoryImpl(URI_CODEC);
  private static final WaveId WAVE_ID = WaveId.of("example.com", "waveid");
  private static final WaveletId WAVELET_ID = WaveletId.of("example", "conv+root");
  private static final WaveletName WAVELET_NAME = WaveletName.of(WAVE_ID, WAVELET_ID);
  private static final ParticipantId ALEX = ParticipantId.ofUnsafe("alex@example.com");
  private static final ParticipantId ROBOT_PARTICIPANT =
      ParticipantId.ofUnsafe("robot@example.com");
  private static final RobotAccountData ACCOUNT =
      new RobotAccountDataImpl(ROBOT_PARTICIPANT, "www.example.com", "secret",
          new RobotCapabilities(
              Maps.<EventType, Capability> newHashMap(), "fake", ProtocolVersion.DEFAULT), true);

  private EventDataConverterManager converterManager;
  private WaveletProvider waveletProvider;
  private OperationServiceRegistry operationRegistry;
  private RobotOperationApplicator applicator;
  private ObservableWaveletData waveletData;
  private HashedVersion hashedVersionZero;

  @Override
  protected void setUp() {
    converterManager = mock(EventDataConverterManager.class);
    waveletProvider = mock(WaveletProvider.class);
    operationRegistry = mock(OperationServiceRegistry.class);
    EventDataConverter converter = mock(EventDataConverter.class);

    ConversationUtil conversationUtil = mock(ConversationUtil.class);
    applicator = new RobotOperationApplicator(
        converterManager, waveletProvider, operationRegistry, conversationUtil);

    waveletData = WaveletDataUtil.createEmptyWavelet(WAVELET_NAME, ROBOT_PARTICIPANT,
        HASH_FACTORY.createVersionZero(WAVELET_NAME), 0L);
    hashedVersionZero = HASH_FACTORY.createVersionZero(WAVELET_NAME);
  }

  public void testapplyOperationsExecutesAndSubmitsDelta() throws Exception {
    // Use a special operation service that generates a simple delta;
    OperationService service = new OperationService() {
      @Override
      public void execute(
          OperationRequest operation, OperationContext context, ParticipantId participant)
          throws InvalidRequestException {
        context.openWavelet(WAVE_ID, WAVELET_ID, ROBOT_PARTICIPANT).addParticipant(ALEX);
      }
    };
    when(operationRegistry.getServiceFor(any(OperationType.class))).thenReturn(service);

    OperationRequest operation = new OperationRequest("wavelet.create", "op1");
    List<OperationRequest> operations = Collections.singletonList(operation);

    applicator.applyOperations(operations, waveletData, hashedVersionZero, ACCOUNT);

    verify(operationRegistry).getServiceFor(any(OperationType.class));
    verify(waveletProvider).submitRequest(eq(WAVELET_NAME), any(ProtocolWaveletDelta.class),
        any(WaveletProvider.SubmitRequestListener.class));
  }
}


text:
{-# LANGUAGE CPP #-}
module GHCJS.DOM.History (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
  module GHCJS.DOM.JSFFI.Generated.History
#else
  module Graphics.UI.Gtk.WebKit.DOM.History
#endif
  ) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.History
#else
import Graphics.UI.Gtk.WebKit.DOM.History
#endif

redpajama_set_name: RedPajamaGithub


text:
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.spell.DirectSpellChecker;
import org.apache.lucene.search.spell.SuggestWord;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class Example11 {

    public static final String INDEX_DIRECTORY = "index";

    public static final String FIELD_IDENTIFIER = "identifier";
    public static final String FIELD_ASIN = "asin";
    public static final String FIELD_TITLE = "title";

    public static final String IndexFieldVariationSeparator = ":";

    public static final String IndexFieldVariation_Dictionary = "dictionary";

    public static void main(String args[])
            throws Exception {
        Directory directory = FSDirectory.open(Paths.get(INDEX_DIRECTORY));
        Analyzer analyzer = new BasicAnalyzer();

        writeIndex(directory, analyzer);
        getSuggestions(directory, analyzer, "pixals pexals");
        getSuggestions(directory, analyzer, "alohe aleha alehe");
        getSuggestions(directory, analyzer, "chipter chaptor choptor");
        getSuggestions(directory, analyzer, "blue");
    }

    public static void writeIndex(Directory directory, Analyzer analyzer)
            throws IOException {
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);

        // Alternative is IndexWriterConfig.OpenMode.APPEND.
        indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

        try (IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig)) {
            addDocument(indexWriter, "1", "B011KME78M", "Tremors 5: Bloodlines (Blu-ray + DVD + DIGITAL HD)");
            addDocument(indexWriter, "2", "B00YHR5UW0", "Aloha [Blu-ray]");
            addDocument(indexWriter, "3", "B012DWS874", "Pixels (3D Blu-ray + Blu-ray + UltraViolet)");
            addDocument(indexWriter, "4", "B00YT8SCSG", "Insidious: Chapter 3 (Blu-ray + Ultraviolet)");
            addDocument(indexWriter, "5", "B00VGQKBQ0", "The Walking Dead: Season 5 [Blu-ray]");
        }
    }

    private static void addDocument(IndexWriter indexWriter, String identifier, String asin, String title)
            throws IOException {
        Document document = new Document();

        document.add(new Field(FIELD_IDENTIFIER, identifier, FieldTypes.STORED_NOT_TOKENIZED));
        document.add(new Field(FIELD_ASIN, asin, FieldTypes.NOT_STORED_TOKENIZED));
        document.add(new Field(FIELD_TITLE, title, FieldTypes.NOT_STORED_TOKENIZED));
        document.add(new Field(FIELD_TITLE + IndexFieldVariationSeparator + IndexFieldVariation_Dictionary, title, FieldTypes.NOT_STORED_TOKENIZED));

        indexWriter.addDocument(document);
    }

    public static void getSuggestions(Directory directory, Analyzer analyzer, String q)
            throws ParseException, IOException {
        System.out.println("suggestions for: " + q);

        List<String> tokens = getTokens(q);
        DirectSpellChecker directSpellChecker = new DirectSpellChecker();

        IndexReader indexReader = DirectoryReader.open(directory);

        for(String word : tokens) {
            System.out.println("  word: " + word);

            Term term = new Term(FIELD_TITLE + IndexFieldVariationSeparator + IndexFieldVariation_Dictionary, word);
            SuggestWord[] suggestWords = directSpellChecker.suggestSimilar(term, 5, indexReader);

            if(suggestWords.length == 0) {
                System.out.println("    no suggestions.");
            } else {
                for(SuggestWord suggestWord : suggestWords) {
                    System.out.println("    " + suggestWord.string + ", " + suggestWord.freq + ", " + suggestWord.score);
                }
            }
        }

        System.out.println();
    }

    public static List<String> getTokens(String input)
            throws IOException {
        Analyzer analyzer = new BasicAnalyzer();
        TokenStream ts = analyzer.tokenStream(FIELD_TITLE + IndexFieldVariationSeparator + IndexFieldVariation_Dictionary, input);

        CharTermAttribute charTermAttribute = ts.getAttribute(CharTermAttribute.class);

        List<String> tokens = new ArrayList<>();
        ts.reset();

        while (ts.incrementToken()) {
            tokens.add(charTermAttribute.toString());
        }
        ts.end();

        return tokens;
    }

}


text:
package u

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"path/filepath"

	"github.com/kjk/atomicfile"
	"github.com/minio/minio-go/v6"
)

// MinioClient represents s3/spaces etc. client
type MinioClient struct {
	StorageKey    string
	StorageSecret string
	Bucket        string
	Endpoint      string // e.g. "nyc3.digitaloceanspaces.com"
	Secure        bool
	client        *minio.Client
}

// EnsureCondfigured will panic if client not configured
func (c *MinioClient) EnsureConfigured() {
	PanicIf(c.StorageKey == "", "minio storage key not set")
	PanicIf(c.StorageSecret == "", "minio storage secret not set")
	PanicIf(c.Bucket == "", "minio bucket not set")
	PanicIf(c.Endpoint == "", "minio endpoint not set")
}

// URLBase returns base of url under which files are accesible
// (if public it's a publicly available file)
func (c *MinioClient) URLBase() string {
	return fmt.Sprintf("https://%s.%s/", c.Bucket, c.Endpoint)
}

// GetClient returns a (cached) minio client
func (c *MinioClient) GetClient() (*minio.Client, error) {
	if c.client != nil {
		return c.client, nil
	}

	var err error
	c.client, err = minio.New(c.Endpoint, c.StorageKey, c.StorageSecret, c.Secure)
	return c.client, err
}

// ListRemoveFiles returns a list of files under a given prefix
func (c *MinioClient) ListRemoteFiles(prefix string) ([]*minio.ObjectInfo, error) {
	var res []*minio.ObjectInfo
	client, err := c.GetClient()
	if err != nil {
		return nil, err
	}
	doneCh := make(chan struct{})
	defer close(doneCh)

	files := client.ListObjectsV2(c.Bucket, prefix, true, doneCh)
	for oi := range files {
		oic := oi
		res = append(res, &oic)
	}
	return res, nil
}

// IsMinioNotExistsError returns true if an error indicates that a key
// doesn't exist in storage
func IsMinioNotExistsError(err error) bool {
	if err == nil {
		return false
	}
	return err.Error() == "The specified key does not exist."
}

// SetPublicObjectMetadata sets options that mark object as public
// for doing put operation
func SetPublicObjectMetadata(opts *minio.PutObjectOptions) {
	if opts.UserMetadata == nil {
		opts.UserMetadata = map[string]string{}
	}
	opts.UserMetadata["x-amz-acl"] = "public-read"
}

func (c *MinioClient) UploadReaderPublic(remotePath string, r io.Reader, size int64, contentType string) error {
	return c.UploadReader(remotePath, r, size, true, contentType)
}

func (c *MinioClient) UploadReaderPrivate(remotePath string, r io.Reader, size int64, contentType string) error {
	return c.UploadReader(remotePath, r, size, false, contentType)
}

func (c *MinioClient) UploadData(remotePath string, d []byte, opts minio.PutObjectOptions) error {
	client, err := c.GetClient()
	if err != nil {
		return err
	}
	r := bytes.NewReader(d)
	size := int64(len(d))
	_, err = client.PutObject(c.Bucket, remotePath, r, size, opts)
	return err
}

func (c *MinioClient) UploadReader(remotePath string, r io.Reader, size int64, public bool, contentType string) error {
	PanicIf(remotePath[0] == '/', "name '%s' shouldn't start with '/'", remotePath)

	if contentType == "" {
		contentType = MimeTypeFromFileName(remotePath)
	}
	//timeStart := time.Now()
	//sizeStr := humanize.Bytes(uint64(size))
	//fmt.Printf("Uploading '%s' of size %s and type %s as public.", remotePath, sizeStr, contentType)
	client, err := c.GetClient()
	if err != nil {
		return err
	}
	opts := minio.PutObjectOptions{
		ContentType: contentType,
	}
	if public {
		SetPublicObjectMetadata(&opts)
	}
	opts.ContentType = contentType
	_, err = client.PutObject(c.Bucket, remotePath, r, size, opts)
	if err != nil {
		return err
	}
	//fmt.Printf(" Took %s.\n", time.Since(timeStart))
	return nil
}

func (c *MinioClient) DownloadFileAsData(remotePath string) ([]byte, error) {
	client, err := c.GetClient()
	if err != nil {
		return nil, err
	}
	opts := minio.GetObjectOptions{}
	obj, err := client.GetObject(c.Bucket, remotePath, opts)
	if err != nil {
		return nil, err
	}
	defer obj.Close()
	var buf bytes.Buffer
	_, err = io.Copy(&buf, obj)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

func (c *MinioClient) DownloadFileAtomically(dstPath string, remotePath string) error {
	client, err := c.GetClient()
	if err != nil {
		return err
	}
	opts := minio.GetObjectOptions{}
	obj, err := client.GetObject(c.Bucket, remotePath, opts)
	if err != nil {
		return err
	}
	defer obj.Close()

	// ensure there's a dir for destination file
	dir := filepath.Dir(dstPath)
	err = os.MkdirAll(dir, 0755)
	if err != nil {
		return err
	}

	f, err := atomicfile.New(dstPath)
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = io.Copy(f, obj)
	if err != nil {
		return err
	}
	return f.Close()
}

func (c *MinioClient) UploadFilePublic(remotePath string, filePath string) error {
	return c.UploadFile(remotePath, filePath, true)
}

func (c *MinioClient) UploadFilePrivate(remotePath string, filePath string) error {
	return c.UploadFile(remotePath, filePath, false)
}

func (c *MinioClient) UploadFile(remotePath string, filePath string, public bool) error {
	stat, err := os.Stat(filePath)
	if err != nil {
		return err
	}
	size := stat.Size()
	f, err := os.Open(filePath)
	if err != nil {
		return err
	}
	defer func() {
		f.Close()
	}()
	return c.UploadReaderPublic(remotePath, f, size, "")
}

func (c *MinioClient) UploadDataPublic(remotePath string, d []byte) error {
	r := bytes.NewBuffer(d)
	return c.UploadReaderPublic(remotePath, r, int64(len(d)), "")
}

func (c *MinioClient) UploadStringPublic(remotePath string, s string) error {
	r := bytes.NewBufferString(s)
	return c.UploadReaderPublic(remotePath, r, int64(len(s)), "")
}

func (c *MinioClient) UploadStringPrivate(remotePath string, s string) error {
	r := bytes.NewBufferString(s)
	return c.UploadReaderPrivate(remotePath, r, int64(len(s)), "")
}

func (c *MinioClient) StatObject(remotePath string) (minio.ObjectInfo, error) {
	client, err := c.GetClient()
	if err != nil {
		return minio.ObjectInfo{}, err
	}
	var opts minio.StatObjectOptions
	return client.StatObject(c.Bucket, remotePath, opts)
}

func (c *MinioClient) Delete(remotePath string) error {
	client, err := c.GetClient()
	if err != nil {
		return err
	}
	err = client.RemoveObject(c.Bucket, remotePath)
	if IsMinioNotExistsError(err) {
		return nil
	}
	return nil
}


text:
namespace java {
  namespace lang {
    class String;
    class Class;
  }
  namespace io {
    class IOException;
    class PrintStream;
  }
}
template<class T> class JArray;

namespace org {
  namespace apache {
    namespace lucene {
      namespace util {

        class PrintStreamInfoStream : public ::org::apache::lucene::util::InfoStream {
        public:
          enum {
            mid_init$_1b7c898b,
            mid_init$_be16aeab,
            mid_close_54c6a166,
            mid_isEnabled_5fdc3f44,
            mid_isSystemStream_54c6a16a,
            mid_message_4a264742,
            max_mid
          };

          static ::java::lang::Class *class$;
          static jmethodID *mids$;
          static bool live$;
          static jclass initializeClass(bool);

          explicit PrintStreamInfoStream(jobject obj) : ::org::apache::lucene::util::InfoStream(obj) {
            if (obj != NULL)
              env->getClass(initializeClass);
          }
          PrintStreamInfoStream(const PrintStreamInfoStream& obj) : ::org::apache::lucene::util::InfoStream(obj) {}

          PrintStreamInfoStream(const ::java::io::PrintStream &);
          PrintStreamInfoStream(const ::java::io::PrintStream &, jint);

          void close() const;
          jboolean isEnabled(const ::java::lang::String &) const;
          jboolean isSystemStream() const;
          void message(const ::java::lang::String &, const ::java::lang::String &) const;
        };
      }
    }
  }
}

#include <Python.h>

namespace org {
  namespace apache {
    namespace lucene {
      namespace util {
        extern PyTypeObject PY_TYPE(PrintStreamInfoStream);

        class t_PrintStreamInfoStream {
        public:
          PyObject_HEAD
          PrintStreamInfoStream object;
          static PyObject *wrap_Object(const PrintStreamInfoStream&);
          static PyObject *wrap_jobject(const jobject&);
          static void install(PyObject *module);
          static void initialize(PyObject *module);
        };
      }
    }
  }
}

#endif


text:
<?php

namespace PHPHub\Jobs;

use Illuminate\Contracts\Bus\SelfHandling;
use PHPHub\Topic;
use Purifier;

/**
 * 保存帖子,同时生成摘要,解析 markdown etc..
 */
class SaveTopic extends Job implements SelfHandling
{
    /**
     * @var Topic
     */
    private $topic;

    /**
     * Create a new job instance.
     *
     * @param Topic $topic
     */
    public function __construct(Topic $topic)
    {
        $this->topic = $topic;
    }

    /**
     * Execute the job.
     */
    public function handle()
    {
        $this->topic->title = Purifier::clean($this->topic->title, 'title');
        $this->topic->body_original = Purifier::clean(trim($this->topic->body), 'body');
        $this->topic->body = app('markdown')->text($this->topic->body_original);
        $this->topic->excerpt = $this->excerpt($this->topic->body_original);

        $this->topic->save();

        return $this->topic;
    }

    /**
     * 生成正文摘要.
     *
     * @param $body
     *
     * @return string
     */
    protected function excerpt($body)
    {
        $excerpt = trim(preg_replace('/\s+/', ' ', strip_tags($body)));

        return str_limit($excerpt, 200);
    }
}


text:
<!DOCTYPE HTML>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Frequently Asked Questions | Eurex Clearing PME</title>
    <link rel="shortcut icon" href="../../../../../_static/opengamma-favicon.ico"/>
    <link rel="stylesheet" href="../../../../../_static/css/main.css">
    <link rel="stylesheet" href="../../../../../_static/css/syntax.css">
    <link rel="stylesheet" href="../../../../../_static/css/alerts.css">
    <link rel="stylesheet" href="../../../../../_static/font-awesome-4.4.0/css/font-awesome.min.css">

      Eurex Clearing PME

<button type="button" id="toggle-menu" class="button--teal">Menu</button>

Quick Start

Setting up a Development Environment

System requirements

Installation

Running the Examples

Calculation of Initial Margin for OTC Trades

Calculation of Initial Margin for ETD Trades

Calculation of Cash Flows

Basic API Integration Example

Running from the Command Line

Basic Library Integration

Margin Environment Lifecycle

Data Lifecycle

Third-Party Libraries

Advanced Library Integration

Overview

Features

Margin Methodologies

Product Scope

Outputs

System Requirements

Software

Hardware

Release Notes

Known Limitations

General

ETD

OTC

Frequently Asked Questions

System Requirements

Market Data

Trades and Positions

Margin Calculation

Input Data

Portfolio

Eurex ETD CSV

Eurex OTC CSV

Eurex Sensitivities CSV

FpML

FIXML

Market Data

OTC Requirements

ETD Requirements

Cross-Margining Requirements

Fixings

Format

API

Holidays

Format

API

Standard Directory Structure

Directory Layout

Individual File Conventions

Integration

Library Architecture

Loading Market Data

Automatic file resolution

Explicit usage

Error handling during loading

Loading Portfolios

Error handling during loading

Performing Calculations

Trade Requests

Portfolio Requests

Add-ons

Portfolio IM

Building a request

P&L calculation methodology

Output Model

Error handling during calculation

Calculation Modes

Full Revaluation

Delta Approximation

Margin Results

Portfolio Results

Trade Results

Concurrency

CPU utilization

Custom Executor Service

Concurrent use of the API

Common Tasks

What-If Analysis

Multiple Days of Market Data

Log Configuration

Advanced Topics

Trade Model

Third-Party Dependencies

Frequently Asked Questions

System Requirements

Can I run the Eurex Clearing PME if I do not have a machine which meets the recommended hardware specification?

Yes you can run the solution on a smaller machine. However it is recommended that you only
load the market data that you require, for example just OTC data or only the open interest
theoretical instrument file for ETD. If you do run on a machine with less memory and load
all the available data then you will find that the calculations are slower than expected.

What if my operating system isn’t in the list of supported systems?

This is the list of operating systems that the Eurex Clearing PME has been tested on.
However, as a Java library it is expected to run successfully on other operating systems.

Market Data

Why do I have to provide my own fixings and holiday files?

For licensing reasons CCPs are not able to publish the fixings and holiday data that they
use in their calculations. However, this data should be readily available within your own
firm for your valuations. CSV parsers have been provided with Eurex Clearing PME to make
it easy for you to integrate this data.

Do I need to provide fixings data for all eligible products?

In general you only need to provide the fixings necessary to price your trades. In particular,
if you do not trade zero coupon inflation swaps then you do not need to provide inflation
fixings.

What holiday data do I need to provide?

You will need to provide the holidays required to price your trades correctly. Providing
past holidays is important to make sure that pricing does not fail trying to find fixings
on days when they are not available.

Inflation fixings are for the month. Why do I have to provide a day in the input file?

The fixings file format expects an actual date to be provided. However it does not matter
which day of the month is provided as the solution will automatically sort this out. Some
data providers use the first day of the month whilst others use the last day of the month.
The parser is flexible to allow for this.

Do I have to reload market data every time I want to calculate a margin?

No you only need to load the market data once into a MarginEnvironment, say at the start
of day. You can then run all your calculation requests against that environment.

Trades and Positions

What products are supported?

The Eurex Clearing PME supports all products which use the Eurex PRISMA for ETD or Eurex OTC
methodologies (see Product Scope. There are
some known limitations to the supported OTC trades which are listed in Known Limitations.
Any ETD products in the Eurex Transparency Enabler files are supported.

Are any eligibility checks performed on trades?

There are no specific eligibility checks performed on trades so it is possible that the
Eurex Clearing PME will calculate margin on an ineligible trade. The Eurex Transparency Enabler
files ensure that margin can only be calculated for OTC trades in valid currencies or for
ETD positions on valid securities.  Checks are also performed to exclude matured trades
and trades with a termination date beyond the end of the provided curves.

Does the Eurex Clearing PME perform any netting?

The solution does not perform any netting on ETD trades (see Known Limitations).
To calculate the margin correctly for an ETD portfolio it requires it to be provided as
total positions. Netting will be performed of long and short positions to calculate a net
position if it is provided as a single record in either CSV or FIXML format.

My trades are not available in one of the provided formats. How do I load them into the PME?

The PME supports the file formats supported by Eurex but if you cannot access your trades
in any of these formats then you have two options; you can take the format that you
do have and convert it to one of the supported formats or you can load the trades
by constructing the OpenGamma domain objects programmatically. For further information see
Loading Portfolios.

Margin Calculation

Can I use the Eurex Clearing PME to calculate variation margin?

The Eurex Clearing PME calculates initial margin. Variation margin is not available as
an output. However, it is possible to output PV for all trades, and for premium paid up
front options this is equivalent to the premium margin.

Can I choose the currency that my margin is calculated in?

You can choose to calculate your margin in either EUR or CHF.

How can I use the Eurex Clearing PME to better understand my margin?

The output from the Eurex Clearing PME provides a full breakdown of all the elements of
the Eurex algorithms. It also provides some additional trade level information such as PV
and P&L. Therefore it is possible to understand, for example, which trades are contributing
most to the VaR components of the margin or what is driving the level of the Liquidity Risk.

I am trying to do a what-if analysis. My base portfolio is a sensitivity profile and my new trade is in trade format. What does my calculation request need to be?

If any part of your portfolio is provided as a sensitivity profile then you need to
use the delta approximation calculation mode (see Calculation Modes.
The PME cannot combine full revaluation and delta approximation modes when calculating
OTC margins. Similarly if you are trying to do cross margining and have your OTC
portfolio as a sensitivity profile then you will need to use delta approximation mode.

Version 1.8.3

© 2015 OpenGamma Limited


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of User
 *
 * @author Ajilore Raphael
 */

class Sms extends My_Model{

    public $sms_id;

	public $user_creditbalance;

	public $user_lastcreditadd;

	public $user_lastcreditadddate;

	public $user_id;

	protected $table = 'sms';

    protected $primary = 'sms_id';

	public $columns = array(

		'sms_id'=> array(
			'type' => 'INT',
			'constraint' => 11,
			'unsigned' => TRUE,
			'auto_increment'=> TRUE,
			),

		'user_creditbalance' =>array(

			'type' => 'INT',
			'constraint'=> 20,
			'null' => FALSE,
			),

		'user_lastcreditadd' =>array(
			'type' => 'INT',
            'constraint' => 20,
			'null' => FALSE,
			),

        'user_lastcreditadddate' => array(
            'type' => 'DATETIME',
            'null' => FALSE,
            ),

		'user_id' =>array(

			'type' => 'INT',
			'constraint'=> 11,
			'null' => FALSE,
			)
		);

}


text:
<?php

namespace Fannan\LotteryModule\Test\Unit\Grant;

class GrantTableBuilderTest extends \TestCase
{

}


text:
require 'stdlib/core'
require 'stdlib/area/position'

Chunk = {}
MAX_UINT = 4294967296

--- Calculates the chunk coordinates for the tile position given
--  @param position to calculate the chunk for
--  @return the chunk position as a table
--  @usage
----local chunk_x = Chunk.from_position(pos).x
function Chunk.from_position(position)
    position = Position.to_table(position)
    local x = math.floor(position.x)
    local y = math.floor(position.y)
    local chunk_x = bit32.arshift(x, 5)
    if x < 0 then
        chunk_x = chunk_x - MAX_UINT
    end
    local chunk_y = bit32.arshift(y, 5)
    if y < 0 then
        chunk_y = chunk_y - MAX_UINT
    end
    return {x = chunk_x, y = chunk_y}
end

--- Converts a chunk to the area it contains
-- @param chunk_pos to convert to an area
-- @return area that chunk is valid for
function Chunk.to_area(chunk_pos)
    fail_if_missing(chunk_pos, "missing chunk_pos argument")
    chunk_pos = Position.to_table(chunk_pos)

    local left_top = { x = chunk_pos.x * 32, y = chunk_pos.y * 32 }
    return { left_top = left_top, right_bottom = Position.offset(left_top, 32, 32) }
end

--- Gets user data from the chunk, stored in a mod's global data.
---
 The data will persist between loads

--  @param surface the surface to look up data for
--  @param chunk_pos the chunk coordinates to look up data for
--  @param default_value (optional) to set and return if no data exists
--  @return the data, or nil if no data exists for the chunk
function Chunk.get_data(surface, chunk_pos, default_value)
    fail_if_missing(surface, "missing surface argument")
    fail_if_missing(chunk_pos, "missing chunk_pos argument")
    if not global._chunk_data then
        if not default_value then return nil end
        global._chunk_data = {}
    end

    local idx = Chunk.get_index(surface, chunk_pos)
    local val = global._chunk_data[idx]
    if not val then
        global._chunk_data[idx] = default_value
        val = default_value
    end

    return val, idx
end

--- Sets user data on the chunk, stored in a mod's global data.
---
 The data will persist between loads

--  @param surface the surface to look up data for
--  @param chunk_pos the chunk coordinates to look up data for
--  @param data the data to set (or nil to erase the data for the chunk)
--  @return the previous data associated with the chunk, or nil if the chunk had no previous data
function Chunk.set_data(surface, chunk_pos, data)
    fail_if_missing(surface, "missing surface argument")
    fail_if_missing(chunk_pos, "missing chunk_pos argument")
    if not global._chunk_data then global._chunk_data = {} end

    local idx = Chunk.get_index(surface, chunk_pos)
    local prev = global._chunk_data[idx]
    global._chunk_data[idx] = data

    return prev
end

--- Calculates and returns a stable, deterministic, unique integer id for the given chunk_pos
---
 The id will not change once calculated

--  @param surface the chunk is on
--  @param chunk_pos of the chunk
function Chunk.get_index(surface, chunk_pos)
    fail_if_missing(surface, "missing surface argument")
    fail_if_missing(chunk_pos, "missing chunk_pos argument")
    if not global._next_chunk_index then global._next_chunk_index = 0 end
    if not global._chunk_indexes then global._chunk_indexes = {} end

    if type(surface) == "string" then
        surface = game.surfaces[surface]
    end
    local surface_idx = surface.index
    if not global._chunk_indexes[surface_idx] then global._chunk_indexes[surface_idx] = {} end

    local surface_chunks = global._chunk_indexes[surface_idx]
    if not surface_chunks[chunk_pos.x] then surface_chunks[chunk_pos.x] = {} end
    if not surface_chunks[chunk_pos.x][chunk_pos.y] then
        surface_chunks[chunk_pos.x][chunk_pos.y] = global._next_chunk_index
        global._next_chunk_index = global._next_chunk_index + 1
    end

    return surface_chunks[chunk_pos.x][chunk_pos.y]
end


text:
import os
import sys
import re

mergedFileName = 'treeviewer_merged.js'
resultFileName = '../build/treeviewer.js'

def MergeFiles (inputFileNames, outputFileName):
	for fileName in inputFileNames:
		if (not os.path.exists (fileName)):
			return False

	outputFile = open (outputFileName, 'w')
	for fileName in inputFileNames:
		inputFile = open (fileName, 'r')
		for line in inputFile:
			outputFile.write (line)
		outputFile.write ('\n')
		inputFile.close ()

	outputFile.close ()
	return True

def CompileFile (inputFileName, outputFileName):
	result = os.system ('java -jar compiler/compiler.jar --language_in=ECMASCRIPT5_STRICT --warning_level=VERBOSE --jscomp_off=globalThis --jscomp_off=checkTypes --js ' + inputFileName + ' --js_output_file ' + outputFileName)
	if result != 0:
		return False
	return True

def Main (argv):
	currentPath = os.path.dirname (os.path.abspath (__file__))
	os.chdir (currentPath)

	files = [
		'../src/core.js',
		'../src/treenode.js',
		'../src/treelayout.js',
		'../src/treeviewer.js',
		'../src/drawstyle.js',
		'../src/svgdrawer.js',
		'../src/canvasdrawer.js',
		'../src/createviewer.js'
	]

	MergeFiles (files, mergedFileName)
	CompileFile (mergedFileName, resultFileName)
	os.remove (mergedFileName)
	return 0

sys.exit (Main (sys.argv))


text:
from django.conf.urls import patterns, include, url
from django.contrib.flatpages import urls
from search.views import CustomSearchView
from haystack.views import search_view_factory
from django.conf import settings

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url('', include('lobbyingph.urls')),
    url(r'^api/', include('api.urls')),
    url(r'^search/', search_view_factory(
        view_class=CustomSearchView,
        ), name='haystack_search'),
    url(r'^about/', include(urls.urlpatterns)),
    url(r'^admin/', include(admin.site.urls)),
)

if not settings.DEBUG:
    urlpatterns += patterns('',
        url(r'^static/(.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
    )


text:
..
 This work is licensed under a Creative Commons Attribution 3.0 Unported
 License.

 http://creativecommons.org/licenses/by/3.0/legalcode

==================
Custom Actions API
==================

Launchpad blueprint:

https://blueprints.launchpad.net/mistral/+spec/mistral-custom-actions-api

This specification sets a formal basis for those Mistral users who want to
create their own actions and make them available to use as part of Mistral
workflows. The number one question that the spec addresses is "What is
available in Mistral code base in order to implement custom actions?"

Problem description
===================

Custom actions are now possible to create and it's as simple as just
implementing a class inherited from mistral.actions.base.Action that
has 3 methods:

* run() - executes main action logic, **mandatory** to implement

* test() - execute action in test mode, related to future dry-run
  functionality, optional to implement

* is_sync() - must return **True** if action returns its result right from
  method run() or **False** if method run() only starts action logic and
  result is supposed to be delivered later via public Mistral API

There's also a mechanism based on stevedore library that allows to plug in
new actions via adding new entry points in setup.cfg file.

If a custom action doesn't require any integration neither with Mistral
nor with OpenStack this is enough to know in order to implement it.

However, if this action needs to leverage more advanced capabilities
provided by Mistral and OpenStack then Action class itself doesn't
give any knowledge about means that can be used to achieve that.
A simple example of integration with OpenStack infrastructure is the need
to call endpoints of OpenStack services. In this case, at minimum, action
needs to be able to authenticate with Keystone, i.e., have access to
Mistral security context.

Use Cases
---------

Simple OpenStack actions
^^^^^^^^^^^^^^^^^^^^^^^^
As a user of Mistral I want to create actions that call OpenStack services.
In this case action needs to be able to access Mistral security context
that contains auth token to be able to pass it to a corresponding service.
Note: This use case is generally implemented within Mistral but it needs
to be rethought since OpenStack actions that are implemented now in Mistral
use Mistral Python code that is not assumed to be a public API and hence
stable.

Complex OpenStack actions
^^^^^^^^^^^^^^^^^^^^^^^^^
As a user of Mistral I want to create actions that call multiple OpenStack
services from within one action.

For example, we may want to create action
"create_cinder_volume_and_attach_to_vm" that creates a Cinder volume and
attaches it to a virtual instance. In this case action needs to have access
to Mistral security context that contains auth token so that it can pass
that token to Cinder and Nova.

Reusing existing actions
^^^^^^^^^^^^^^^^^^^^^^^^

As a user of Mistral I want to be able to reuse existing actions while
implementing my new actions so that I don't have to reimplement similar
functionality.

For example, I want to create action that checks if a certain virtual
instance exists in the tenant by calling Nova and if it does the action
runs a number of secure shell commands to configure it. In this scenario,
we need to call Nova and do ssh. Both already exist in Mistral as actions
"nova.servers_get" and "std.ssh". So there should be a mechanism allowing
to reuse those actions while creating a new more complex action.

Proposed change
===============

General idea
------------

We need to have one or more Python packages in Mistral that are designed
and documented as a public Python API for developers that want to create
custom actions. These packages should effectively provide a number of
classes that can be used directly or inherited as needed. They should
cover the following aspects of action development:

* Base class or a number of classes that can be extended in order to build
  new Mistral actions. Currently existing **mistral.actions.base.Action**
  is an example of such class.

* Module that provides access to security context associated with the
  current workflow that this action belongs to. Security context should
  at least include user, project/tenant, auth token.

* Module that provides access to current Mistral execution context. That
  context should include:

  * Current workflow execution id

  * Current task execution id

  * Current action execution id

* Package with most frequently used utils and data types used during
  custom actions development. For example, class
  mistral.workflow.utils.Result that now exists in the code base is
  needed by actions but it's not clear that it's part of Python API.

* Module that allows to get and reuse existing actions

Since these Python entities must be available for both engine and
executor they should be moved to a separate subproject of Mistral, for
example, **mistral-actions-api**.

Existing OpenStack actions should be moved out of mistral project into
a different Mistral subproject. The proposal is to use **mistral-extra**
repo for this purpose because although we use it only for collecting
Mistral examples its initial idea was also to have additional tools
and extensions in it.

Specific entities
-----------------

mistral.actions.api
^^^^^^^^^^^^^^^^^^^
Main Python package that contains all modules and classes which are part
of Custom Actions API.

mistral.actions.api.base
^^^^^^^^^^^^^^^^^^^^^^^^
Python module that contains base classes for custom actions. Currently
module **mistral.actions.base** performs similar function.

Note: Specific content of this module is out of scope of this spec and
must be defined at implementation stage.

mistral.actions.api.security
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Python module that contains required functions to get all required
information related to current OpenStack security context. At minimum:
user, project, auth token.

Note: Specific content of this module is out of scope of this spec and
must be defined at implementation stage.

mistral.actions.api.types
^^^^^^^^^^^^^^^^^^^^^^^^^
Python module that contains all data types that custom actions need to
use. One candidate to go to that module that now exists is
**mistral.workflow.utils.Result**.

Note: Specific content of this module is out of scope of this spec and
defined at implementation stage.

mistral.actions.api.utils
^^^^^^^^^^^^^^^^^^^^^^^^^
Python module that contains additional functions helpful for creating
new Mistral actions. At minimum: functions to get instances of existing
actions so that action developers could re-use functionality of existing
actions. Return type for these actions though must be rather a wrapper
that doesn't just call **Action.run()** method but instead uses Mistral
action execution machinery to actually call action just like as if it
was called as part of workflow (taking care of data transformations,
fulfilling security and execution context etc.)

Note: Specific content of this module is out of scope of this spec and
must be defined at implementation stage.

Alternatives
------------

None.

Data model impact
-----------------

None.

REST API impact
---------------

None.

End user impact
---------------

REST API users
^^^^^^^^^^^^^^
No impact.

Custom actions developers
^^^^^^^^^^^^^^^^^^^^^^^^^
Having to use Custom Actions API described in this spec whereas now they
can only use **mistral.actions.base** safely.

Performance Impact
------------------

No significant impact is expected. Minor is possible.

Deployer impact
---------------

Deployers will need to make sure to install a new library containing
Custom Action API packages, modules and classes. However, this impact
is not supposed to be severe because all dependencies must be handled
smoothly by Pip.

In case if there's an existing Mistral installation with installed
actions, some DB migration might be required. Changes in DB schema are
not expected though. If so, Mistral project should provide convenient
tools to help make this transition to using new actions.

Implementation
==============

Assignee(s)
-----------

To be found based on discussions around the spec.

Work Items
----------

* Create a new repo containing the code of Custom Actions API (e.g.
  **mistral-lib** or **mistral-common**, particular name is to be defined)
* Design and implement modules listed in Specific Entities section
* Provide deprecation mechanism so that during some period of time it
  would be possible to use the old approach for implementing Mistral
  actions (with **mistral.actions.base**) and the new one
* Fix existing action implementations so that they use new API
* Fix Mistral Executor accordingly
* Fix Mistral Engine accordingly
* Revisit and restructure repo **mistral-extra**
* Move existing OpenStack actions into **mistral-extra**

Dependencies
============

No additional dependencies are required.

Testing
=======

Custom Actions API can be tested on devstack based OpenStack CI gates
such as gate-mistral-devstack-dsvm by creating and running custom
actions that use this API.

References
==========

Initial patch for TripleO/Mistral integration:
https://review.openstack.org/#/c/282366/


text:
"""
URL mappings for package index functionality.
"""
from collections import OrderedDict
from functools import wraps
from urlparse import urljoin

from flask import jsonify, make_response, render_template, request

from cheddar.auth import check_authentication
from cheddar.exceptions import BadRequestError, NotFoundError
from cheddar.model.versions import sort_key

def create_routes(app):

    def authenticated(func):
        """
        Basic Auth decorator.
        """
        @wraps(func)
        def wrapper(*args, **kwargs):
            if not check_authentication(app.redis):
                response = make_response("", 401)
                response.headers["WWW-Authenticate"] = 'Basic realm="cheddar"'
                return response
            return func(*args, **kwargs)
        return wrapper

    @app.route("/")
    def index():
        """
        Index page: show recent history.
        """
        app.logger.debug("Showing index page")
        return _render("index.html", history=app.history.all())

    @app.route("/simple/")
    @app.route("/simple")
    def list_project():
        """
        List all hosted projects.
        """
        app.logger.debug("Showing all projects")

        def name_sort_key(name):
            return name.lower()

        projects = sorted([project.name for project in app.index.get_projects()],
                          key=name_sort_key)

        return _render("simple.html", projects=projects)

    @app.route("/simple/<name>/")
    @app.route("/simple/<name>")
    def get_project(name):
        """
        List versions for a hosted project.
        """
        app.logger.info("Showing package index for: {}".format(name))

        versions = app.index.get_versions(name)

        if not versions:
            raise NotFoundError()

        sorted_versions = OrderedDict()
        for version in sorted(versions.keys(), key=sort_key, reverse=True):
            sorted_versions[version] = versions[version]

        return _render("project.html", project=name, versions=sorted_versions)

    @app.route("/simple/<name>/<version>/", methods=["GET", "DELETE"])
    @app.route("/simple/<name>/<version>", methods=["GET", "DELETE"])
    def handle_version(name, version):
        if request.method == "DELETE":
            return remove_version(name, version)
        else:
            return get_version(name, version)

    def get_version(name, version):
        """
        Get metadata for version.
        """
        app.logger.debug("Getting: {} {}".format(name, version))

        metadata = app.index.get_metadata(name, version)

        if metadata is None:
            raise NotFoundError()

        return _render("version.html", project=name, version=version, metadata=metadata)

    @authenticated
    def remove_version(name, version):
        """
        Delete all version data. Requires auth.
        """
        app.logger.debug("Removing: {} {}".format(name, version))
        app.index.remove_version(name, version)
        return ""

    @app.route("/local/<path:location>/")
    @app.route("/local/<path:location>")
    def get_local_distribution(location):
        """
        Local distribution download access.
        """
        app.logger.debug("Getting local distribution: {}".format(location))
        content_data, content_type = app.index.get_distribution(location, local=True)
        response = make_response(content_data)
        response.headers['Content-Type'] = content_type
        return response

    @app.route("/remote/<path:path>/")
    @app.route("/remote/<path:path>")
    def get_remote_distribution(path):
        """
        Remote distribution download access.

        Proxies and caches content.
        """
        # To account for redirects, we need to save the base url in the link URL along
        # with the path to the distribution. It's still a little awkward because the
        # urljoin logic happens here instead of within the remote index.
        location = urljoin(request.args["base"], path)

        app.logger.debug("Getting remote distribution: {}".format(location))
        content_data, content_type = app.index.get_distribution(location, local=False)
        response = make_response(content_data)
        response.headers['Content-Type'] = content_type
        return response

    @app.route("/pypi/", methods=["POST"])
    @app.route("/pypi", methods=["POST"])
    def pypi():
        """
        Register and upload endpoint for pip.
        """
        if request.files:
            return upload()
        else:
            return register()

    @authenticated
    def upload():
        """
        Upload a distribution. Requires auth.
        """
        app.logger.debug("Uploading distribution")

        _, upload_file = next(request.files.iterlists())
        app.index.upload_distribution(upload_file[0])

        return ""

    def register():
        """
        Register a distribution.

        The correct behavior for the `setuptools` register command is somewhat
        vague. The PEP 301 docs (for `distutils`) mostly cover user management,
        whereas `setuptools` CLI help says "register the distribution with the
        Python package index."

        Given this ambiguity and the fact that register does *NOT* send auth
        credentials, this operation simply validates the provided metadata.
        """
        app.logger.debug("Registering distribution")

        metadata = {key: values[0] for key, values in request.form.iterlists()}
        if not app.index.validate_metadata(metadata):
            raise BadRequestError()

        return ""

    def _render(template, **data):
        """
        Render response as either a template or just the raw JSON data.
        """
        if _wants_json():
            return jsonify(data)
        else:
            return render_template(template, **data)

    def _wants_json():
        """
        Should response use JSON?
        """
        for mime_type, _ in request.accept_mimetypes:
            # If we see a mime type that means HTML before JSON, return False
            if mime_type.startswith("text/html"):
                return False
            elif mime_type.startswith("application/xhtml"):
                return False
            # If we see JSON explicitly, return True
            elif mime_type.startswith("application/json"):
                return True
        # Default to False (HTML)
        return False


text:
package com.google.api;

public final class EndpointProto {
  private EndpointProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_api_Endpoint_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_api_Endpoint_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n\031google/api/endpoint.proto\022\ngoogle.api\032" +
      "\034google/api/annotations.proto\"m\n\010Endpoin" +
      "t\022\014\n\004name\030\001 \001(\t\022\017\n\007aliases\030\002 \003(\t\022\014\n\004apis" +
      "\030\003 \003(\t\022\020\n\010features\030\004 \003(\t\022\016\n\006target\030e \001(\t" +
      "\022\022\n\nallow_cors\030\005 \001(\010Bo\n\016com.google.apiB\r" +
      "EndpointProtoP\001ZEgoogle.golang.org/genpr" +
      "oto/googleapis/api/serviceconfig;service" +
      "config\242\002\004GAPIb\006proto3"
    };
    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
        new com.google.protobuf.Descriptors.FileDescriptor.    InternalDescriptorAssigner() {
          public com.google.protobuf.ExtensionRegistry assignDescriptors(
              com.google.protobuf.Descriptors.FileDescriptor root) {
            descriptor = root;
            return null;
          }
        };
    com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
          com.google.api.AnnotationsProto.getDescriptor(),
        }, assigner);
    internal_static_google_api_Endpoint_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_google_api_Endpoint_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_api_Endpoint_descriptor,
        new java.lang.String[] { "Name", "Aliases", "Apis", "Features", "Target", "AllowCors", });
    com.google.api.AnnotationsProto.getDescriptor();
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
```javascript
sdkbox.PluginMisc.init();
```
>  初始化插件

```javascript
sdkbox.PluginMisc.setListener(listener);
```
> 设置 Listener

```javascript
sdkbox.PluginMisc.localNotify(title, content, delaymillisecond);
```
> 发送本地消息
@return 消息id

### Listeners
```javascript
onHandleLocalNotify (payloadJson);
```


text:
let mockPath = "/app/designer/plants";
jest.mock("../../history", () => ({
  history: { push: jest.fn() },
  getPathArray: jest.fn(() => { return mockPath.split("/"); })
}));

jest.mock("../../api/crud", () => ({
  edit: jest.fn()
}));

import { movePlant, closePlantInfo, setDragIcon } from "../actions";
import { MovePlantProps } from "../interfaces";
import { fakePlant } from "../../__test_support__/fake_state/resources";
import { edit } from "../../api/crud";
import { Actions } from "../../constants";
import { DEFAULT_ICON, svgToUrl } from "../../open_farm/icons";
import { history } from "../../history";

describe("movePlant", () => {
  function movePlantTest(
    caseDescription: string,
    attempted: { x: number, y: number },
    expected: { x: number, y: number }) {
    it(`restricts plant to grid area: ${caseDescription}`, () => {
      const payload: MovePlantProps = {
        deltaX: attempted.x,
        deltaY: attempted.y,
        plant: fakePlant(),
        gridSize: { x: 3000, y: 1500 }
      };
      movePlant(payload);
      expect(edit).toHaveBeenCalledWith(
        // Old plant
        expect.objectContaining({
          body: expect.objectContaining({
            x: 100, y: 200
          })
        }),
        // Update
        expect.objectContaining({
          x: expected.x, y: expected.y
        })
      );
    });
  }
  movePlantTest("within bounds", { x: 1, y: 2 }, { x: 101, y: 202 });
  movePlantTest("too high", { x: 10000, y: 10000 }, { x: 3000, y: 1500 });
  movePlantTest("too low", { x: -10000, y: -10000 }, { x: 0, y: 0 });
});

describe("closePlantInfo()", () => {
  it("no plant info open", () => {
    mockPath = "/app/designer/plants";
    const dispatch = jest.fn();
    closePlantInfo(dispatch)();
    expect(history.push).not.toHaveBeenCalled();
    expect(dispatch).not.toHaveBeenCalled();
  });

  it("plant edit open", () => {
    mockPath = "/app/designer/plants/1";
    const dispatch = jest.fn();
    closePlantInfo(dispatch)();
    expect(history.push).toHaveBeenCalledWith("/app/designer/plants");
    expect(dispatch).toHaveBeenCalledWith({
      payload: undefined, type: Actions.SELECT_PLANT
    });
  });

  it("plant info open", () => {
    mockPath = "/app/designer/plants/1";
    const dispatch = jest.fn();
    closePlantInfo(dispatch)();
    expect(history.push).toHaveBeenCalledWith("/app/designer/plants");
    expect(dispatch).toHaveBeenCalledWith({
      payload: undefined, type: Actions.SELECT_PLANT
    });
  });
});

describe("setDragIcon()", () => {
  it("sets the drag icon", () => {
    const setDragImage = jest.fn();
    const e = { currentTarget: new Image(), dataTransfer: { setDragImage } };
    setDragIcon("icon")(e);
    const img = new Image();
    img.src = svgToUrl("icon");
    expect(setDragImage).toHaveBeenCalledWith(img, 0, 0);
  });

  it("sets a default drag icon", () => {
    const setDragImage = jest.fn();
    const e = { currentTarget: new Image(), dataTransfer: { setDragImage } };
    setDragIcon(undefined)(e);
    const img = new Image();
    img.src = DEFAULT_ICON;
    expect(setDragImage).toHaveBeenCalledWith(img, 0, 0);
  });
});


text:
<Alloy>
	<Window class="generalWindow" id="window">
		<View id="toolbar"/>
		<View class="content" id="content">
		</View>
	</Window>
</Alloy>


text:
typedef struct {
    char key[128]; //It is enough to hold POST key names
    char value[256];
} shock_hash_entry_t;

typedef struct {
    size_t length;
    shock_hash_entry_t entries[HASHMAP_SIZE];
} shock_hashmap_t;

shock_hashmap_t shock_hashmap_init();
int shock_hashmap_put(shock_hashmap_t* map, char* key, char* value);
char* shock_hashmap_get(shock_hashmap_t* map, char* key);
size_t shock_hashmap_exists(shock_hashmap_t* map, char* key);

#endif // SHOCK_HASHMAP_H


text:
#include <iostream>
using namespace std;

#include "myclass.h"

int main(int argc, char** argv) {

    myclass mc;

    /*
     * about this sandbox:
     * i was trying to get python code to run inside a cpp app, in order to delegate some routines for smaller python scripts:
     * more precisely, a cpp game engine with entities. each entity's think() method would be coded with python. thats all.
     * as of today, boost.python is very good and complete to make wrappers for cpp stuff to run inside a python script.
     * but the other way around (running python inside cpp - what i was trying to accomplish as aforementioned), is still
     * not complete. the boost.python page says, though, that as of today (21/dez/2013) it makes that job alot easier,
     * but you may need to fill some gaps by using the python C API. by the way, to accomplish this, its necessary to embed
     * a python interpreter inside your cpp app. I figured this would be a much bigger sandbox/case study than just copy-pasting
     * some examples from boost.python's page (i'm guessing i'd have to read some serious python C API stuff), so i'm scrapping
     * it for now. hopefully by the time I get back to this, boost.python will be truly complete.
     * ps. this sandbox currently links with -lboost_python -lpython2.7
     * mv.
     */

    // update: as of mid/2019, the above commentary about embedding boost.python is is true (still not complete, it's still necessary
    // to fill in the gaps with the python C API, but makes it easier)

    cout << "boost python test" << endl;
    return 0;

}


text:
package org.easyrec.model.web;

import org.easyrec.model.core.web.Item;

public class Assoc {
    Item itemFrom;
    Item itemTo;
    String assoc;
    Double value;
    String sourceType;
    String sourceInfo;
    String viewType;

    public Assoc(Item itemFrom, Item itemTo, String assoc, Double value, String sourceType, String viewType, String sourceInfo) {
        this.itemFrom = itemFrom;
        this.itemTo = itemTo;
        this.assoc = assoc;
        this.value = value;
        this.sourceType = sourceType;
        this.viewType = viewType;
        this.sourceInfo = sourceInfo;
    }

    public String getAssoc() {
        return assoc;
    }

    public void setAssoc(String assoc) {
        this.assoc = assoc;
    }

    public Item getItemFrom() {
        return itemFrom;
    }

    public void setItemFrom(Item itemFrom) {
        this.itemFrom = itemFrom;
    }

    public Item getItemTo() {
        return itemTo;
    }

    public void setItemTo(Item itemTo) {
        this.itemTo = itemTo;
    }

    public String getSourceType() {
        return sourceType;
    }

    public void setSourceType(String sourceType) {
        this.sourceType = sourceType;
    }

    public String getSourceInfo() {
        return sourceInfo;
    }

    public void setSourceInfo(String sourceInfo) {
        this.sourceInfo = sourceInfo;
    }

    public Double getValue() {
        return value;
    }

    public void setValue(Double value) {
        this.value = value;
    }

    public String getViewType() {
        return viewType;
    }

    public void setViewType(String viewType) {
        this.viewType = viewType;
    }

}


text:
#ifndef MATERIAL_H
#define MATERIAL_H

#include "vec3.h"

using namespace math;

enum Refl_t
{
    DIFF = 0x01, SPEC = 0x02, REFR = 0x04, GLOS = 0x08
};

/*
inline Refl_t operator|(Refl_t left, Refl_t right)
{
    return static_cast<Refl_t>(static_cast<int>(left) | static_cast<int>(right));
}*/

/*  Material
    refl_t = Surface type
    emittance = Surface emission color
    reflectance = Surface reflection color
    ior = Index of refraction, glass = ~1.52f
    roughness = cook-torrance brdf term
    fresnel = cook-torrance brdf term
    density = cook-torrance brdf term
*/
class Material
{
public:
    Material(Refl_t refl_t = DIFF, vec3 em = vec3(), vec3 re = vec3(), float ior = 1.52f, float roughness = 0.25f, float fresnel = 1.0f, float density = 0.33f):
        m_refl_t(refl_t), m_emittance(em), m_reflectance(re), m_ior(ior), m_roughness(roughness), m_fresnel(fresnel), m_density(density) { }

    Refl_t getReflT() const
    {
        return m_refl_t;
    }

    vec3 getEmittance() const
    {
        return m_emittance;
    }

    vec3 getReflectance() const
    {
        return m_reflectance;
    }

    float getIOR() const
    {
        return m_ior;
    }

    float getRoughness() const
    {
        return m_roughness;
    }

    float getFresnel() const
    {
        return m_fresnel;
    }

    float getDensity() const
    {
        return m_density;
    }

    void setReflT(Refl_t t)
    {
        m_refl_t = t;
    }

    void setEmittance(vec3 emittance)
    {
        m_emittance = emittance;
    }

    void setReflectance(vec3 reflectance)
    {
        m_reflectance = reflectance;
    }

    void setIOR(float ior)
    {
        m_ior = ior;
    }

private:
    Refl_t m_refl_t;
    vec3 m_emittance;
    vec3 m_reflectance;
    float m_ior;
    float m_roughness;
    float m_fresnel;
    float m_density;
};

#endif


text:
package org.wso2.carbon.device.mgt.user.common;

public class Claims {

    private String dialectUrl;
    private String description;
    private String claimUrl;
    private String value;

    public String getDialectUrl() {
        return dialectUrl;
    }

    public void setDialectUrl(String dialectUrl) {
        this.dialectUrl = dialectUrl;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getClaimUrl() {
        return claimUrl;
    }

    public void setClaimUrl(String claimUrl) {
        this.claimUrl = claimUrl;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}


text:
(function() {
  'use strict';

  angular
    .module('projectMateApp')
    .controller('AddOrganizationCtrl',AddOrganizationCtrl);

  AddOrganizationCtrl.$inject = ['Session','Organizations', 'notifications', '$log'];

  function AddOrganizationCtrl(Session, Organizations, notifications, $log) {
    var vm = this;
    vm.loading = false;

    vm.addNewOrg = function(newOrg) {
      vm.loading = true;

      Organizations.addOrg(newOrg)
          .then(function(res){
            $log.debug('AddOrganizationCtrl -> addNewOrg() -> Organizations.addOrg()');
            $log.debug(res);
            var addedOrg = {orgId: res._id, orgName: res.orgName, orgRole: "admin"};
            Session.user.organizations.push(addedOrg);
            vm.resetForm(newOrg);

            notifications.showSuccess({message: 'Your organization posted successfully'});
          },
          function(error){
            $log.debug('AddOrganizationCtrl -> addNewOrg() -> Organizations.addOrg() :: ERROR');
            $log.debug(error);
            notifications.showError({message: "something wrong when adding this organization" + error.data.message});
          })
          .finally(function() {
            vm.loading = false;
          });
    };

    vm.resetForm = function(newOrg) {
      newOrg.orgName = "";
      newOrg.description = "";
    };

  }

})();


text:
namespace Simple.Owin.Static
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;

    internal static class SendFileShim
    {
        public static Func<string, long, long?, CancellationToken, Task> Shim(OwinEnv env)
        {
            var stream = env.ResponseBody;

#if(NET40)
            return (path, offset, count, ct) =>
            {
                var tcs = new TaskCompletionSource<int>();
                try
                {
                    using (var source = File.OpenRead(path))
                    {
                        env.ResponseHeaders["Content-Length"] = new[] { source.Length.ToString(CultureInfo.InvariantCulture) };
                        source.CopyTo(stream);
                        tcs.SetResult(0);
                    }

                }
                catch (Exception exception)
                {
                    tcs.SetException(exception);
                }

                return tcs.Task;
            };
#else
            return async (path, offset, count, ct) =>
            {
                using (var source = File.OpenRead(path))
                {
                    env.ResponseHeaders["Content-Length"] = new[] {source.Length.ToString(CultureInfo.InvariantCulture)};
                    await source.CopyToAsync(stream, 4096, ct);
                }
            };
#endif
        }
    }
}


text:
import { defined } from "@cesium/engine";

import { Animation, AnimationViewModel, ClockViewModel } from "../../index.js";

import pollToPromise from "../../../../Specs/pollToPromise.js";

describe("Widgets/Animation/Animation", function () {
  let container;
  let animation;
  afterEach(function () {
    if (defined(animation)) {
      animation = animation.destroy();
    }
    if (defined(container) && defined(container.parentNode)) {
      container.parentNode.removeChild(container);
    }
  });

  it("Can create and destroy", function () {
    const clockViewModel = new ClockViewModel();
    const animationViewModel = new AnimationViewModel(clockViewModel);
    animation = new Animation(document.body, animationViewModel);
  });

  it("Can create with container not in the DOM", function () {
    container = document.createElement("div");
    const clockViewModel = new ClockViewModel();
    const animationViewModel = new AnimationViewModel(clockViewModel);
    const animation = new Animation(container, animationViewModel);

    //Verify applyThemeChanges is called when we add the container to the DOM.
    spyOn(animation, "applyThemeChanges").and.callThrough();
    document.body.appendChild(container);

    //This is done via polling because we can't control when the DOM decides to
    //fire the Mutation event.
    return pollToPromise(function () {
      return animation.applyThemeChanges.calls.count() === 1;
    });
  });

  it("Can destroy without container ever being in the DOM", function () {
    container = document.createElement("div");
    const clockViewModel = new ClockViewModel();
    const animationViewModel = new AnimationViewModel(clockViewModel);
    animation = new Animation(container, animationViewModel);
  });
});


text:
package org.apache.wicket.markup.html.form;

import java.util.Locale;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.convert.ConversionException;
import org.apache.wicket.util.convert.IConverter;
import org.apache.wicket.util.lang.Objects;
import org.apache.wicket.util.value.IValueMap;
import org.apache.wicket.validation.validator.RangeValidator;

/**
 * A {@link TextField} for HTML5 <input> with type number.
 *
 *

 * Automatically validates the input against the configured {@link #setMinimum(N) min} and
 * {@link #setMaximum(N) max} attributes. If any of them is null then respective
 * MIN_VALUE or MAX_VALUE for the number type is used. If the number type has no minimum and/or
 * maximum value then {@link Double#MIN_VALUE} and {@link Double#MAX_VALUE} are used respectfully.
 *
 * @param <N>
 *            the type of the number
 */
public class NumberTextField<N extends Number & Comparable<N>> extends TextField<N>
{
	private static final long serialVersionUID = 1L;

	/**
	 * Use this as a marker of step attribute value "any"
	 * Because the w3c spec requires step to be a non-negative digit
	 * greater than zero we use zero as delegate for "any" keyword.
	 */
	public static final Double ANY = Double.valueOf(0d);

	private RangeValidator<N> validator;

	private N minimum;

	private N maximum;

	private N step;

	/**
	 * Construct.
	 *
	 * @param id
	 *            The component id
	 */
	public NumberTextField(String id)
	{
		this(id, null, null);
	}

	/**
	 * Construct.
	 *
	 * @param id
	 *            The component id
	 * @param type
	 *            The type to use when updating the model for this text field
	 */
	public NumberTextField(String id, Class<N> type)
	{
		this(id, null, type);
	}

	/**
	 * Construct.
	 *
	 * @param id
	 *            The component id
	 * @param model
	 *            The input value
	 */
	public NumberTextField(String id, IModel<N> model)
	{
		this(id, model, null);
	}

	/**
	 * Construct.
	 *
	 * @param id
	 *            The component id
	 * @param model
	 *            The input value
	 * @param type
	 *            The type to use when updating the model for this text field
	 */
	public NumberTextField(String id, IModel<N> model, Class<N> type)
	{
		super(id, model, type);

		validator = null;
		minimum = null;
		maximum = null;
	}

	/**
	 * Sets the minimum allowed value
	 *
	 * @param minimum
	 *            the minimum allowed value
	 * @return this instance
	 */
	public NumberTextField<N> setMinimum(final N minimum)
	{
		this.minimum = minimum;
		return this;
	}

	/**
	 * Sets the maximum allowed value
	 *
	 * @param maximum
	 *            the maximum allowed value
	 * @return this instance
	 */
	public NumberTextField<N> setMaximum(final N maximum)
	{
		this.maximum = maximum;
		return this;
	}

	/**
	 * Sets the step attribute
	 *
	 * @param step
	 *            the step attribute
	 * @return this instance
	 */
	public NumberTextField<N> setStep(final N step)
	{
		this.step = step;
		return this;
	}

	@Override
	protected void onConfigure()
	{
		super.onConfigure();

		if (validator != null)
		{
			remove(validator);
			validator = null;
		}

		if (minimum != null || maximum != null)
		{
			validator = RangeValidator.range(minimum, maximum);
			add(validator);
		}
	}

	@SuppressWarnings("unchecked")
	private Class<N> getNumberType()
	{
		Class<N> numberType = getType();
		if (numberType == null && getModelObject() != null)
		{
			numberType = (Class<N>)getModelObject().getClass();
		}
		return numberType;
	}

	@Override
	protected void onComponentTag(final ComponentTag tag)
	{
		super.onComponentTag(tag);

		IValueMap attributes = tag.getAttributes();

		if (minimum != null)
		{
			attributes.put("min", Objects.stringValue(minimum));
		}
		else
		{
			attributes.remove("min");
		}

		if (maximum != null)
		{
			attributes.put("max", Objects.stringValue(maximum));
		}
		else
		{
			attributes.remove("max");
		}

		if (step != null)
		{
			if (step.doubleValue() == ANY)
			{
				attributes.put("step", "any");
			}
			else
			{
				attributes.put("step", Objects.stringValue(step));
			}
		}
		else
		{
			attributes.remove("step");
		}
	}

	@Override
	protected String[] getInputTypes()
	{
		return new String[] {"number"};
	}

	/**
	 * The formatting for {@link Locale#ENGLISH} might not be compatible with HTML (e.g. group
	 * digits), thus use {@link Objects#stringValue(Object)} instead.
	 *
	 * @return value
	 */
	@Override
	protected String getModelValue()
	{
		N value = getModelObject();
		if (value == null)
		{
			return "";
		}
		else
		{
			return Objects.stringValue(value);
		}
	}

	/**
	 * Always use {@link Locale#ENGLISH} to parse the input.
	 */
	@Override
	public void convertInput()
	{
		IConverter<N> converter = getConverter(getNumberType());

		try
		{
			setConvertedInput(converter.convertToObject(getInput(), Locale.ENGLISH));
		}
		catch (ConversionException e)
		{
			error(newValidationError(e));
		}
	}
}


text:
"""
The ``list`` module: Lists of traceables
===============================================================================

"""

from docutils import nodes
from docutils.parsers.rst import Directive, directives

from .infrastructure import FormatProcessorBase, TraceablesFilter

# =============================================================================
# Node types

class traceable_list(nodes.General, nodes.Element):
    """Placeholder node to be replaced by a list of traceables.

    Attributes:
        traceable-filter: The filter expression to determine which
            traceables to include in the output.

    """

    pass

# =============================================================================
# Processors

class ListProcessor(FormatProcessorBase):

    def __init__(self, app):
        FormatProcessorBase.__init__(self, app, traceable_list)

    def process_node_with_formatter(self, list_node, formatter,
                                    doctree, docname):
        traceables = sorted(self.storage.traceables_set,
                            key=lambda t: t.tag)

        filter = TraceablesFilter(traceables)
        filter_expression = list_node["traceables-filter"]
        if filter_expression:
            filtered_traceables = filter.filter(filter_expression)
        else:
            filtered_traceables = traceables

        options = {
            "format": list_node.get("traceables-format"),
            "filter": list_node.get("traceables-filter"),
            "attributes": list_node.get("traceables-attributes"),
        }

        new_nodes = formatter.format(self.app, docname, list_node,
                                     filtered_traceables, options)
        list_node.replace_self(new_nodes)

# =============================================================================
# Built-in formatters

class ListFormatterBase(object):

    def format(self, app, docname, node, traceables, options):
        raise NotImplementedError()

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

class TableListFormatter(ListFormatterBase):

    def format(self, app, docname, node, traceables, options):
        additional_attributes = options.get("attributes") or []
        columns = ["tag", "title"] + additional_attributes

        table = nodes.table()
        table["classes"].append("traceables-listtable")
        tgroup = nodes.tgroup(cols=len(columns), colwidths="auto")
        table += tgroup

        # Add column specifications.
        for attribute_name in columns:
            tgroup += nodes.colspec(colwidth=1)

        # Add heading row.
        thead = nodes.thead()
        tgroup += thead
        row = nodes.row()
        thead += row
        for attribute_name in columns:
            entry = nodes.entry()
            row += entry
            container = nodes.container()
            entry += container
            text = attribute_name.capitalize()
            inline = nodes.inline(text, text)
            container += inline

        # Add table body.
        tbody = nodes.tbody()
        tgroup += tbody
        for traceable in traceables:
            row = nodes.row()
            tbody += row

            for attribute_name in columns:
                entry = nodes.entry()
                row += entry
                if attribute_name == "tag":
                    inline = nodes.inline()
                    inline += traceable.make_reference_node(
                        app.builder, docname)
                elif attribute_name == "title":
                    text = traceable.title if traceable.has_title else ""
                    inline = nodes.inline(text, text)
                else:
                    text = traceable.attributes.get(attribute_name, "")
                    inline = nodes.inline(text, text)
                entry += inline

        return table

#        container = traceable_matrix_crosstable()
#        container += table
#        container["traceables-matrix"] = matrix
#        return container

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

class BulletListFormatter(ListFormatterBase):

    def format(self, app, docname, node, traceables, options):
        new_node = nodes.bullet_list()
        for traceable in traceables:
            item_node = nodes.list_item()
            new_node += item_node
            inline = nodes.inline()
            item_node += inline
            inline += traceable.make_reference_node(
                app.builder, docname)
            if traceable.has_title:
                title = u" " + traceable.title
                inline += nodes.inline(title, title)

        return new_node

# =============================================================================
# Directives

def list_of_attributes(argument):
    if not argument:
        return []
    return filter(None, (attribute.strip()
                         for attribute in argument.split(",")))

class TraceableListDirective(Directive):

    required_arguments = 0
    optional_arguments = 0
    option_spec = {
        "format": ListProcessor.directive_format_choice,
        "filter": directives.unchanged,
        "attributes": list_of_attributes,
    }

    def run(self):
        env = self.state.document.settings.env

        node = traceable_list()
        node["source"] = env.docname
        node["line"] = self.lineno
        for option in self.option_spec.keys():
            node["traceables-" + option] = self.options.get(option)

        return [node]

# =============================================================================
# Setup this extension part

ListProcessor.register_formatter("table", TableListFormatter(), default=True)
ListProcessor.register_formatter("bullets", BulletListFormatter())

def setup(app):
    app.add_node(traceable_list)
    app.add_directive("traceable-list", TraceableListDirective)


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

package dp;

import java.util.Arrays;

public class Leetcode1092ShortestCommonSupersequence {
  /*
  return the shortest string that has both str1 and str2 as subsequences.
  If multiple answers exist, you may return any of them.
   */

  // O(M*N)
  static String shortestCommonSupersequence(String str1, String str2) {
    /*
       1 <= str1.length, str2.length <= 1000
       str1 and str2 consist of lowercase English letters.
    */
    int M = str1.length(), N = str2.length();
    String[][] dp = new String[M + 1][N + 1];
    Arrays.fill(dp[0], "");
    for (int i = 0; i <= M; i++) { // note it is <=
      dp[i][0] = "";
    }
    for (int i = 1; i <= M; i++) { // note it is stat from 1 and  <=M
      for (int j = 1; j <= N; j++) { // note it is stat from 1 and  <=M
        if (str1.charAt(i - 1) == str2.charAt(j - 1))
          dp[i][j] = dp[i - 1][j - 1] + str1.charAt(i - 1);
        else {
          dp[i][j] = dp[i - 1][j].length() > dp[i][j - 1].length() ? dp[i - 1][j] : dp[i][j - 1];
        }
      }
    }
    String lcs = dp[M][N];
    int i = 0, j = 0;
    StringBuilder r = new StringBuilder();
    for (char k : lcs.toCharArray()) { // need not k < lcs.length() && (i < M || j < N)
      while (i < M && str1.charAt(i) != k) {
        r.append(str1.charAt(i));
        i++;
      }
      while (j < N && str2.charAt(j) != k) {
        r.append(str2.charAt(j));
        j++;
      }
      r.append(k); // Note here
      i++;
      j++;
    }
    // Note here 2 string left chars
    if (i < M) r.append(str1.substring(i));
    if (j < N) r.append(str2.substring(j));
    return r.toString();
  }
}


text:
module.exports = {
  index: function(req,res){
    res.render('index');
  }
}


text:
package com.nitorcreations.cloudyplugin;

import java.util.Properties;

import org.apache.maven.plugin.MojoExecutionException;

public interface CustomizerResolver {
    public TemplateCustomizer resolveCustomizer(String instanceTag, String provider, Properties developerProperties) throws MojoExecutionException;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.google.code.maven-replacer-plugin</groupId>
	<artifactId>replacer</artifactId>
	<packaging>maven-plugin</packaging>
	<version>1.5.1</version>
	<url>http://code.google.com/p/maven-replacer-plugin</url>
	<name>maven-replacer-plugin Maven Mojo</name>

	<parent>
		<artifactId>oss-parent</artifactId>
		<groupId>org.sonatype.oss</groupId>
		<version>7</version>
	</parent>

	<description>
		Maven plugin to replace tokens in a given file with a value
	</description>
	<scm>
		<url>https://maven-replacer-plugin.googlecode.com/svn/</url>
		<connection>scm:svn:https://maven-replacer-plugin.googlecode.com/svn/</connection>
		<developerConnection>scm:svn:https://maven-replacer-plugin.googlecode.com/svn/</developerConnection>
	</scm>
	<licenses>
		<license>
			<name>MIT License</name>
			<url>http://www.opensource.org/licenses/mit-license.php</url>
			<distribution>repo</distribution>
			<comments>
Copyright (c) 2009-2011. Steven Baker - bakersemail@hotmail.com.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</comments>
		</license>
	</licenses>

	<issueManagement>
		<url>http://code.google.com/p/maven-replacer-plugin</url>
	</issueManagement>
	<developers>
		<developer>
			<id>bakersemail@hotmail.com</id>
			<name>Steven Baker</name>
			<email>bakersemail@hotmail.com</email>
		</developer>
	</developers>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.codehaus.mojo</groupId>
					<artifactId>dashboard-maven-plugin</artifactId>
					<version>1.0.0-beta-1</version>
				</plugin>
			</plugins>
		</pluginManagement>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<version>2.2.1</version>
				<configuration>
					<tagBase>https://maven-replacer-plugin.googlecode.com/svn/tags</tagBase>
					<mavenExecutorId>forked-path</mavenExecutorId>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>dashboard-maven-plugin</artifactId>
				<version>1.0.0-beta-1</version>
			</plugin>
		</plugins>
	</build>

	<reporting>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-pmd-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<targetJdk>1.5</targetJdk>
				</configuration>
			</plugin>
		</plugins>
	</reporting>

	<dependencies>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-plugin-api</artifactId>
			<version>3.0.3</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.ant</groupId>
			<artifactId>ant</artifactId>
			<version>1.8.2</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.8.5</version>
			<type>jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.1</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.8.0</version>
        </dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-all</artifactId>
			<version>1.1</version>
			<type>jar</type>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
class Libxaw3d < Formula
  desc "3D Athena widget set based on the X Toolkit Intrinsics (Xt) library"
  homepage "https://www.x.org"
  url "https://www.x.org/archive/individual/lib/libXaw3d-1.6.3.tar.bz2"
  mirror "https://ftp.x.org/archive/individual/lib/libXaw3d-1.6.3.tar.bz2"
  sha256 "2dba993f04429ec3d7e99341e91bf46be265cc482df25963058c15f1901ec544"

  bottle do
    root_url "https://linuxbrew.bintray.com/bottles-xorg"
    cellar :any_skip_relocation
    sha256 "b16f1cb6c8c7a86c998e3a0b5b8d42827755a755411632dc005d82d2eb612d3f" => :x86_64_linux
  end

  option "without-test", "Skip compile-time tests"
  option "without-multiplane-bitmaps", "Build without multiplane bitmaps"

  depends_on "linuxbrew/xorg/util-macros" => :build
  depends_on "pkg-config" => :build
  depends_on "linuxbrew/xorg/libx11"
  depends_on "linuxbrew/xorg/libxext"
  depends_on "linuxbrew/xorg/libxmu"
  depends_on "linuxbrew/xorg/libxpm" if build.with? "multiplane-bitmaps"
  depends_on "linuxbrew/xorg/libxt"

  def install
    args = %W[
      --prefix=#{prefix}
      --sysconfdir=#{etc}
      --localstatedir=#{var}
      --disable-dependency-tracking
      --disable-silent-rules
      --enable-gray-stipples
      --enable-arrow-scrollbars
    ]
    args << "--enable-multiplane-bitmaps" if build.with? "multiplane-bitmaps"

    system "./configure", *args
    system "make"
    system "make", "check" if build.with? "test"
    system "make", "install"
  end

  test do
    (testpath/"test.c").write <<~EOS
      #include <stdio.h>
      #include <X11/Xaw3d/Label.h>
      int main() { printf("%d", sizeof(LabelWidget)); }
    EOS
    system ENV.cc, "test.c", "-o", "test"
    output = shell_output("./test").chomp
    assert_match "8", output
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
    <title>DebugGhost</title>

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

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

DebugGhost

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

            </button>

            App: {{PROJECT_NAME}}

Database

Shared Preferences

Device Info

Commands

Help

<form id="form" action="" method="post">
    <input id="prefs" type="hidden" name="prefs" value="prefsFile" />
    <input id="field" type="hidden" name="field" value="fieldName" />
    <input id="fieldValue" type="hidden" name="fieldValue" value="fieldValue" />
    <input id="fieldType" type="hidden" name="fieldType" value="fieldType" />
    <input id="returnPath" type="hidden" name="returnPath" value="prefs" />
</form>

Infos on SharedPreferences

            Using numbers (Float, Long, Integer):

            If you type in a wrong, non numerical value or a float value for Long or Integer, saving the value will be ignored. You will only see an error message in the LogCat.

            Using StringSet (HashSet):

            Carriage return means: new entry. Be sure to have no carriage return at the end of the textarea, otherwise you will have an empty String entry in your set.

            Float:

            Float accepts dot (.) or comma (,). 3.3 is the same as 3,3

    {{SHARED_PREFS_LIST}}


text:
package hochschuledarmstadt.photostream_tools.callback;

/**
 * {@link OnCommentCountChangedListener#onCommentCountChanged(int, int)}<br>
 * Wird aufgerufen, wenn sich die Anzahl der Kommentare zu einem Photo geändert hat.
 */
public interface OnCommentCountChangedListener {
    /**
     * Wird aufgerufen, wenn sich die Anzahl der Kommentare zu dem Photo mit der id {@code photoId} geändert hat.
     * @param photoId id des Photos zu der die Kommentare zugeordnet sind
     * @param commentCount Aktuelle Anzahl der Kommentare zu dem Photo
     */
    void onCommentCountChanged(int photoId, int commentCount);
}