text:
template <typename TUrlTraits>
class AbstractUrlTest : public testing::Test {
 protected:
  // Wrappers that help ellide away TUrlTraits.
  //
  // Note that calling the wrappers needs to be prefixed with `this->...` to
  // avoid hitting: explicit qualification required to use member 'IsAboutBlank'
  // from dependent base class.
  using UrlType = typename TUrlTraits::UrlType;
  UrlType CreateUrlFromString(base::StringPiece s) {
    return TUrlTraits::CreateUrlFromString(s);
  }
  bool IsAboutBlank(const UrlType& url) {
    return TUrlTraits::IsAboutBlank(url);
  }
  bool IsAboutSrcdoc(const UrlType& url) {
    return TUrlTraits::IsAboutSrcdoc(url);
  }
};

TYPED_TEST_SUITE_P(AbstractUrlTest);

TYPED_TEST_P(AbstractUrlTest, IsAboutBlankTest) {
  // See https://tools.ietf.org/html/rfc6694 which explicitly allows
  // `about-query` and `about-fragment` parts in about: URLs.
  const std::string kAboutBlankUrls[] = {"about:blank", "about:blank?foo",
                                         "about:blank/#foo",
                                         "about:blank?foo#foo"};
  for (const auto& input : kAboutBlankUrls) {
    SCOPED_TRACE(testing::Message() << "Test input: " << input);
    auto url = this->CreateUrlFromString(input);
    EXPECT_TRUE(this->IsAboutBlank(url));
  }

  const std::string kNotAboutBlankUrls[] = {"",
                                            "about",
                                            "about:",
                                            "about:blanky",
                                            "about:blan",
                                            "about:about:blank:",
                                            "data:blank",
                                            "http:blank",
                                            "about://blank",
                                            "about:blank/foo",
                                            "about://:8000/blank",
                                            "about://foo:foo@/blank",
                                            "foo@about:blank",
                                            "foo:bar@about:blank",
                                            "about:blank:8000",
                                            "about:blANk"};
  for (const auto& input : kNotAboutBlankUrls) {
    SCOPED_TRACE(testing::Message() << "Test input: " << input);
    auto url = this->CreateUrlFromString(input);
    EXPECT_FALSE(this->IsAboutBlank(url));
  }
}

TYPED_TEST_P(AbstractUrlTest, IsAboutSrcdocTest) {
  // See https://tools.ietf.org/html/rfc6694 which explicitly allows
  // `about-query` and `about-fragment` parts in about: URLs.
  //
  // `about:srcdoc` is defined in
  // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#about:srcdoc
  // which refers to rfc6694 for details.
  const std::string kAboutSrcdocUrls[] = {
      "about:srcdoc", "about:srcdoc/", "about:srcdoc?foo", "about:srcdoc/#foo",
      "about:srcdoc?foo#foo"};
  for (const auto& input : kAboutSrcdocUrls) {
    SCOPED_TRACE(testing::Message() << "Test input: " << input);
    auto url = this->CreateUrlFromString(input);
    EXPECT_TRUE(this->IsAboutSrcdoc(url));
  }

  const std::string kNotAboutSrcdocUrls[] = {"",
                                             "about",
                                             "about:",
                                             "about:srcdocx",
                                             "about:srcdo",
                                             "about:about:srcdoc:",
                                             "data:srcdoc",
                                             "http:srcdoc",
                                             "about:srcdo",
                                             "about://srcdoc",
                                             "about://srcdoc\\",
                                             "about:srcdoc/foo",
                                             "about://:8000/srcdoc",
                                             "about://foo:foo@/srcdoc",
                                             "foo@about:srcdoc",
                                             "foo:bar@about:srcdoc",
                                             "about:srcdoc:8000",
                                             "about:srCDOc"};
  for (const auto& input : kNotAboutSrcdocUrls) {
    SCOPED_TRACE(testing::Message() << "Test input: " << input);
    auto url = this->CreateUrlFromString(input);
    EXPECT_FALSE(this->IsAboutSrcdoc(url));
  }
}

REGISTER_TYPED_TEST_SUITE_P(AbstractUrlTest,
                            IsAboutBlankTest,
                            IsAboutSrcdocTest);

#endif  // URL_GURL_ABSTRACT_TESTS_H_


text:
package money

import (
	"bytes"
	"database/sql"
	"database/sql/driver"
	"encoding/json"
	"errors"
	"text/template"
	"unicode"
	"unicode/utf8"

	"github.com/corestoreio/csfw/utils/log"
	"github.com/juju/errgo"
)

var (
	_          json.Unmarshaler = (*Currency)(nil)
	_          json.Marshaler   = (*Currency)(nil)
	_          sql.Scanner      = (*Currency)(nil)
	_          driver.Valuer    = (*Currency)(nil)
	nullString                  = []byte(`null`)
)

// ErrDecodeMissingColon can be returned on malformed JSON value when decoding a currency.
var ErrDecodeMissingColon = errors.New("No colon found in JSON array")

const (
	// JSONNumber encodes/decodes a currency as a number string to directly use
	// in e.g. JavaScript
	JSONNumber JSONType = 1 << iota
	// JSONLocale encodes/decodes a currency according to its locale format.
	// Decoding: Considers the locale if the currency symbol is valid.
	JSONLocale
	// JSONExtended encodes/decodes a currency into a JSON array:
	// [1234.56, "€", "1.234,56 €"].
	// Decoding: Considers the locale if the currency symbol is valid.
	JSONExtended
)

// JSONType defines the type of the marshaller/unmarshaller
type JSONType uint8

type (
	// JSONMarshaller interface for JSON encoding
	JSONMarshaller interface {
		// MarshalJSON encodes the currency
		MarshalJSON(*Currency) ([]byte, error)
	}
	// JSONUnmarshaller interface for JSON decoding
	JSONUnmarshaller interface {
		// UnmarshalJSON reads the bytes and decodes them into the currency
		UnmarshalJSON(*Currency, []byte) error
	}
)

// MarshalJSON generates JSON output depending on the Marshaller.
func (c Currency) MarshalJSON() ([]byte, error) {
	return c.jm.MarshalJSON(&c)
}

// UnmarshalJSON reads JSON and fills the currency struct depending on the Unmarshaller.
func (c *Currency) UnmarshalJSON(src []byte) error {
	c.applyDefaults()
	if src == nil {
		c.m, c.Valid = 0, false
		return nil
	}
	return c.jum.UnmarshalJSON(c, src)
}

// Value implements the SQL driver Valuer interface.
func (c Currency) Value() (driver.Value, error) {
	if !c.Valid {
		return nil, nil
	}
	return c.Getf(), nil
}

// Scan scans a value into the Currency struct. Returns an error on data loss.
// Errors will be logged. Initial default settings are the guard and precision value.
func (c *Currency) Scan(src interface{}) error {
	c.applyDefaults()

	if src == nil {
		c.m, c.Valid = 0, false
		if log.IsDebug() {
			log.Debug("money.Currency.Scan", "case", 89, "c", c, "src", src)
		}
		return nil
	}

	if b, ok := src.([]byte); ok {
		return c.ParseFloat(string(b))
	}
	return log.Error("money.Currency.Scan.Assertion", "err", errgo.Newf("Unsupported Type %T for value. Supported: []byte", src), "src", src)
}

// NewJSONEncoder creates a new encoder depending on the type.
// Accepts either zero or one argument.
// Default encoder is JSONLocale
func NewJSONEncoder(jts ...JSONType) JSONMarshaller {
	if len(jts) != 1 {
		return JSONLocale
	}
	return jts[0]
}

// NewJSONDecoder creates a new decoder depending on the type.
// Accepts either zero or one argument.
// Default decoder is JSONLocale
func NewJSONDecoder(jts ...JSONType) JSONUnmarshaller {
	if len(jts) != 1 {
		return JSONLocale
	}
	return jts[0]
}

var _ JSONMarshaller = new(JSONType)
var _ JSONUnmarshaller = new(JSONType)

// MarshalJSON encodes a currency to JSON bytes according to the defined JSONType
func (t JSONType) MarshalJSON(c *Currency) ([]byte, error) {
	switch t {
	case JSONNumber:
		return jsonNumberMarshal(c)
	case JSONExtended:
		return jsonExtendedMarshal(c)
	default:
		return jsonLocaleMarshal(c)
	}
}

// UnmarshalJSON decodes three different currency representations into a currency
// struct.
func (t JSONType) UnmarshalJSON(c *Currency, b []byte) error {
	if len(b) < 1 || false == utf8.Valid(b) { // we must have a valid string
		if log.IsDebug() {
			log.Debug("money.JSONType.UnmarshalJSON.1", "case", "invalid_bytes", "c", c, "bytes", string(b))
		}
		c.m, c.Valid = 0, false
		return nil
	}

	runes := bytes.Runes(b)
	lenRunes := len(runes)
	var realNumber, isNull, lRunes, posSepComma, posSepDot int
	var isArray bool
	number := make([]rune, 0, lenRunes)
	// atm not needed because currency symbol depends on the formatter
	//symbol := make([]rune, 0, lenRunes)

	// strip quotes
	if lenRunes > 1 && runes[0] == '"' && runes[lenRunes-1] == '"' {
		runes = runes[1 : lenRunes-1]
	}
	lenRunes = len(runes)

	if 0 == lenRunes {
		if log.IsDebug() {
			log.Debug("money.JSONType.UnmarshalJSON.2", "case", "lenRunes=0", "c", c, "bytes", string(b))
		}
		c.m, c.Valid = 0, false
		return nil
	}

OuterLoop:
	for i, r := range runes {

		switch {
		case unicode.IsSpace(r):
			continue
		case r == '[':
			isArray = true // [999.0000,"$","$ 999.00"] only until the first comma will be considered.
		case unicode.IsNumber(r): // 1234.56
			number = append(number, r)
			realNumber++
		case r == '.', r == '-': // -1234.56
			number = append(number, r)
			realNumber++
		case r == ',': // -1,234.56 or -1.234,56 or -1 234,56
			if isArray { // we stop after the first colon, because then the 2nd entry starts in the array
				isArray = false
				break OuterLoop
			}
			number = append(number, r)
			//case unicode.IsLetter(r), unicode.IsSymbol(r):
			//	symbol = append(symbol, r)
		}

		if posSepComma == 0 && r == ',' { // check for first occurrence of the comma
			posSepComma = i
		}
		if posSepDot == 0 && r == '.' {
			posSepDot = i
		}

		switch unicode.ToLower(r) {
		case 'n', 'u', 'l':
			isNull++
		}

		if isNull == 4 {
			if log.IsDebug() {
				log.Debug("money.JSONType.UnmarshalJSON.3", "case", "isNull", "c", c, "bytes", string(b), "runes", string(runes))
			}
			c.m, c.Valid = 0, false
			return nil
		}

		lRunes++
	}

	if isArray { // now it's an error because no colon found
		c.m, c.Valid = 0, false
		return log.Error("money.JSONType.UnmarshalJSON.MissingColon", "err", ErrDecodeMissingColon, "bytes", string(b), "number", string(number))
	}

	switch {
	case realNumber == lRunes: // real number e.g. -1234.56 without any other stuff
		return c.ParseFloat(string(runes))

	case posSepComma == 0 && posSepDot == 0, // no decimals but included any other stripped of character
		posSepComma == 0 && posSepDot > 0: // currency contains only a dot
		return c.ParseFloat(string(number))

	case posSepComma > 0 && posSepDot == 0: // currency contains only a comma
		for i, r := range number {
			if r == ',' {
				number[i] = '.'
			}
		}
		return c.ParseFloat(string(number))

	case posSepComma > 0 && posSepDot > 0:
		replaceChar := ','           // number is 12,211,232.45 or 1,234.56
		if posSepDot < posSepComma { // number is 12.211.232,45 or 1.234,56
			replaceChar = '.'
		}

		var i int
		for i < len(number) {
			switch {
			case replaceChar == '.' && number[i] == ',':
				number[i] = '.' // replace decimal comma with a dot to create fractals
			case number[i] == replaceChar:
				number = append(number[:i], number[i+1:]...) // cut comma
				i = 0                                        // restart loop
			}
			i++
		}
		return c.ParseFloat(string(number))
	}

	c.m, c.Valid = 0, false
	return log.Error("money.JSONType.UnmarshalJSON.Invalid", "err", errors.New("Invalid bytes"), "bytes", string(b), "number", string(number))
}

// jsonNumberMarshal generates a number formatted currency string
func jsonNumberMarshal(c *Currency) ([]byte, error) {
	if c == nil || c.Valid == false {
		return nullString, nil
	}
	return c.Ftoa(), nil
}

// jsonLocaleMarshal encodes into a locale specific quoted string
func jsonLocaleMarshal(c *Currency) ([]byte, error) {
	if c == nil || c.Valid == false {
		return nullString, nil
	}
	var b bytes.Buffer
	b.WriteString(`"`)
	lb, err := c.Localize()
	if err != nil {
		return nil, log.Error("money.jsonLocaleMarshal.Localize", "err", err, "currency", c, "bytes", lb)
	}
	template.JSEscape(&b, lb)
	b.WriteString(`"`)
	return b.Bytes(), err
}

// jsonExtendedMarshal encodes a currency into a JSON array: [1234.56, "€", "1.234,56 €"]
func jsonExtendedMarshal(c *Currency) ([]byte, error) {
	if c == nil || c.Valid == false {
		return nullString, nil
	}
	var b bytes.Buffer
	b.WriteRune('[')
	b.Write(c.Ftoa())
	b.WriteString(`, "`)
	b.WriteString(template.JSEscapeString(string(c.Symbol())))
	b.WriteString(`", "`)
	lb, err := c.Localize()
	if err != nil {
		return nil, log.Error("money.jsonExtendedMarshal.Localize", "err", err, "currency", c, "bytes", lb)
	}
	template.JSEscape(&b, lb)

	b.WriteRune('"')
	b.WriteRune(']')
	return b.Bytes(), err
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Runtime.InteropServices;

#pragma warning disable 0169

namespace OsxIntegration.Framework
{
	public static class AppleEvent
	{
		const string AELib = Carbon.CarbonLib;

		//[DllImport (AELib)]
		//OSErr AECreateDesc (DescType typeCode, IntPtr dataPtr, Size dataSize, out AEDesc result);
	}
}


text:
package org.leguan.versioncontrol.git;

import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.leguan.config.VersionsystemConf;
import org.leguan.versioncontrol.BranchInfo;
import org.leguan.versioncontrol.LastChangeInfo;
import org.leguan.versioncontrol.ModuleInfo;
import org.leguan.versioncontrol.ProjectInfo;
import org.leguan.versioncontrol.VersionControlException;

@Slf4j
public class StashAdapterTester {

  public static void main(String[] args) throws VersionControlException {
    String url = args [0];
    String username = args [1];
    String password = args [2];

    VersionsystemConf versionsystemConf = new VersionsystemConf();
    versionsystemConf.setUrl(url);
    versionsystemConf.setUser(username);
    versionsystemConf.setVersionsystemPassword(password);
    versionsystemConf.setName("Bitbucket");

    log.info("Using url " + url + " with username " + username + " and password " + password);

    StashAdapter stashAdapter = new StashAdapter();
    stashAdapter.login(versionsystemConf);

    List<BranchInfo> allBranches = new ArrayList<>();

    long durationBefore = System.currentTimeMillis();

    List<ProjectInfo> projects = stashAdapter.getProjects(null, null);
    System.out.println ("Found " + projects.size() + " projects");

    for (ProjectInfo project: projects) {

      List<ModuleInfo> modules = project.getModules();
      System.out.println ("Found " + modules.size() + " modules in project " + project.getKey());

      for (ModuleInfo nextModule: modules) {

        List<BranchInfo> branches = nextModule.getBranches();
        System.out.println ("Found " + branches.size() + " branches in module " + nextModule.getProjectInfo().getKey() + "-" + nextModule.getName());

        allBranches.addAll(branches);
      }
    }
    long durationAfter = System.currentTimeMillis();

    /**for (BranchInfo next: allBranches) {
      log.info("Branch " + next.getModuleInfo().getProjectInfo().getName() + " - " + next.getModuleInfo().getName() + " - " + next.getName());
    }**/
    log.info("Found " + allBranches.size() + " branches in " + (durationAfter - durationBefore) + " ms");

    BranchInfo branchInfo = allBranches.get(0);
    LastChangeInfo lastChangeInfo = stashAdapter.getLastChangeInfo(branchInfo);
    log.info(lastChangeInfo.getLatestChangeUser() + "-" + lastChangeInfo.getLatestChangeDate());

  }

}


text:
package menu

//ButtonTypeClick ..
var ButtonTypeClick = "click"

//ButtonTypeView ..
var ButtonTypeView = "view"

//ButtonTypeScanCodePush ...
var ButtonTypeScanCodePush = "scancode_push"

//ButtonTypeScanCodeWaitMsg ...
var ButtonTypeScanCodeWaitMsg = "scancode_waitmsg"

//ButtonTypePicSysPhoto ...
var ButtonTypePicSysPhoto = "pic_sysphoto"

//ButtonTypePicPhotoOrAlbum ...
var ButtonTypePicPhotoOrAlbum = "pic_photo_or_album"

//ButtonTypePicWechat ...
var ButtonTypePicWechat = "pic_weixin"

//ButtonTypeLocationSelect ...
var ButtonTypeLocationSelect = "location_select"

//ButtonTypeMediaID ...
var ButtonTypeMediaID = "media_id"

//ButtonTypeMiniProgaram ...
var ButtonTypeMiniProgaram = "miniprogram"


text:
import datetime
import getpass
import json
import urllib2

REST_API_URL = "http://awx.example.com/api/v1/"
REST_API_USER = "admin"
REST_API_PASS = "password"
JOB_TEMPLATE_ID = 1

# Setup urllib2 for basic password authentication.
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, REST_API_URL, REST_API_USER, REST_API_PASS)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)

# Read the job template.
JOB_TEMPLATE_URL="%sjob_templates/%d/" % (REST_API_URL, JOB_TEMPLATE_ID)
response = urllib2.urlopen(JOB_TEMPLATE_URL)
data = json.loads(response.read())

# Update data if needed for the new job.
data.pop('id')
data.update({
    'name': 'my new job started at %s' % str(datetime.datetime.now()),
    'verbosity': 3,
})

# Create a new job based on the template and data.
JOB_TEMPLATE_JOBS_URL="%sjobs/" % JOB_TEMPLATE_URL
request = urllib2.Request(JOB_TEMPLATE_JOBS_URL, json.dumps(data),
                          {'Content-type': 'application/json'})
response = urllib2.urlopen(request)
data = json.loads(response.read())

# Get the job ID and check for passwords needed to start the job.
JOB_ID = data['id']
JOB_START_URL = '%sjobs/%d/start/' % (REST_API_URL, JOB_ID)
response = urllib2.urlopen(JOB_START_URL)
data = json.loads(response.read())

# Prompt for any passwords needed.
start_data = {}
for password in data.get('passwords_needed_to_start', []):
    value = getpass.getpass('%s: ' % password)
    start_data[password] = value

# Make POST request to start the job.
request = urllib2.Request(JOB_START_URL, json.dumps(start_data),
                          {'Content-type': 'application/json'})
response = urllib2.urlopen(request)


text:
package com.github.leeyazhou.scf.server.util;

import java.util.List;

import com.github.leeyazhou.scf.core.annotation.OperationContract;
import com.github.leeyazhou.scf.core.annotation.ServiceContract;
import com.github.leeyazhou.scf.core.entity.Out;

/**
 * A ServiceContract for news
 *
 *
 */
@ServiceContract // 标记该接口对外提供服务
public interface INewsService {

  /**
   * get news by newsID
   *
   * @param newsID
   * @return news entity
   * @throws Exception
   */
  @OperationContract // 标记该方法对外暴露
  public News getNews(int newsID) throws Exception;

  /**
   * get news list by cateID
   *
   * @param cateID
   * @param totalCount
   * @return news list
   * @throws Exception
   */
  @OperationContract // 标记该方法对外暴露
  public List<News> getNews(int cateID, int userID, Out<Integer> totalCount) throws Exception;

  /**
   *
   * @param cateID
   * @param userID
   * @return
   * @throws Exception
   */
  @OperationContract // 标记该方法对外暴露
  public List<News> getNews(int cateID, int userID) throws Exception;

  /**
   * delete news
   *
   * @param newsID
   * @throws Exception
   */
  @OperationContract // 标记该方法对外暴露
  public void deleteNews(int newsID) throws Exception;

  /**
   *
   * @throws Exception
   */
  @OperationContract // 标记该方法对外暴露
  public void addNews(News news) throws Exception;
}


text:
<?php

namespace luya\web;

use Yii;
use yii\base\Object;
use yii\helpers\Json;
use luya\helpers\Url;
use luya\helpers\ArrayHelper;
use luya\web\jsonld\Person;
use luya\Exception;
use luya\web\jsonld\BaseThing;
use luya\web\jsonld\Event;

/**
 * Registerin Microdata as JsonLD.
 *
 * In order to register a json ld tag just call:
 *
 * ```php
 * JsonLd::sponsor('Jon Doe', 'https://luya.io');
 * ```
 *
 * Or any other tags. This will register the json ld output into the layout file of the view.
 *
 * @see https://schema.org/docs/schemas.html
 * @author Basil Suter <basil@nadar.io>
 * @since 1.0.0
 */
class JsonLd extends Object
{
    /**
     * Register Organization.
     *
     * @param unknown $companyName
     * @param unknown $website
     */
    public static function organization($companyName, $website = null)
    {
        self::addGraph([
            '@context' => 'http://schema.org',
            '@type' => 'Organization',
            'name' => $companyName,
            'url' => Url::home(true),
        ]);
    }

    /**
     * Register new Event.
     *
     * @param array $config
     *
     * @return \luya\web\jsonld\Event
     */
    public static function event(array $config = [])
    {
        return self::addGraph((new Event($config)));
    }

    /**
     * Register new Person.
     *
     * @param array $config Optional config array to provided person data via setter methods.
     *
     * @return \luya\web\jsonld\Person
     */
    public static function person(array $config = [])
    {
        return self::addGraph((new Person($config)));
    }

    /**
     * Register Image Microodata.
     *
     * @param string $url
     * @param string $caption The image caption about what is on the picture.
     * @param array $options An array with optional informations, allowed:
     * - contentLocation: The location where the image was taken.
     * - author: The author who made the picture.
     * - datePublished: A unix timestamp (or string e.g. 2008-01-25) when the image was published.
     * - name: The name of the picture.
     */
    public static function image($url, $caption, array $options = [])
    {
        $date = ArrayHelper::remove($options, 'datePublished', null);

        if ($date !== null && is_numeric($date)) {
            $date = date("Y-d-m", $date);
        }

        self::addGraph([
            "@context" => "http://schema.org",
            "@type" => "ImageObject",
            "author" => ArrayHelper::remove($options, 'author', null),
            "contentLocation" => ArrayHelper::remove($options, 'contentLocation', null),
            "contentUrl" => $url,
            "datePublished" => $date,
            "description" => $caption,
            "name" => ArrayHelper::remove($options, 'name', null),
        ]);
    }

    /**
     * Register graph data.
     *
     * @param \luya\web\jsonld\BaseThing|array $data Can be either an array or an object based on {{luya\web\jsonld\BaseThing}} which contains the Arrayable Inteface.
     * @return
     */
    public static function addGraph($data)
    {
        self::registerView();

        if (is_scalar($data)) {
            throw new Exception("data must be either an array or an object of type luya\web\jsonld\BaseThing.");
        }

        Yii::$app->view->params['@graph'][] = $data;

        return $data;
    }

    /**
     * Reset the JsonLd Data.
     *
     * This method is mainly usefull when working with unit tests for JsonLd.
     */
    public static function reset()
    {
        self::$_view = null;
        Yii::$app->view->params['@graph'] = [];
    }

    private static $_view;

    /**
     * Register the view file an observe the event which then reads the data from @graph params key.
     */
    protected static function registerView()
    {
        if (self::$_view === null) {
            Yii::$app->view->on(View::EVENT_BEGIN_BODY, function ($event) {
                echo '<script type="application/ld+json">' . Json::encode($event->sender->params) . '</script>';
            });

            self::$_view = true;
        }
    }
}


text:
	<!-- Open Graph -->
	<meta property="og:locale" content="{{ site.locale }}">
	<meta property="og:type" content="article">
	<meta property="og:title" content="{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}">
	{% if page.excerpt %}
  <meta property="og:description" content="{{ page.excerpt | strip_html }}">
  {% else %}
  <meta property="og:description" content="Radish Lab's Tips & Techniques for using the NationBuilder platform">
  {% endif %}
	<meta property="og:url" content="{{ page.url | replace:'index.html','' | prepend: site.url }}">
	<meta property="og:site_name" content="{{ site.title }}">
  <meta property="og:image" content="http://radishlab.github.io/nationbuilder-guide/images/nationbuilder-guide-social.png" />

  <!-- Twitter Cards -->
  <meta name="twitter:title" content="{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}">
  {% if page.excerpt %}
  <meta name="twitter:description" content="{{ page.excerpt | strip_html }}">
  {% else %}
  <meta name="twitter:description" content="Radish Lab's Tips & Techniques for using the NationBuilder platform">
  {% endif %}
  {% if site.owner.twitter %}<meta name="twitter:site" content="@RadishLab">{% endif %}
  {% if author.twitter %}<meta name="twitter:creator" content="@RadishLab">{% endif %}
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:image" content="http://radishlab.github.io/nationbuilder-guide/images/nationbuilder-guide-social.png">
  <meta name="twitter:url" content="{{ page.url | replace:'index.html','' | prepend: site.url }}" />


text:
package org.omg.CORBA.portable;

/**
 * An interface with no members whose only purpose is to serve as a marker
 * indicating  that an implementing class is a
 * Java value type from IDL that has a corresponding Helper class.
 * RMI IIOP serialization looks for such a marker to perform
 * marshalling/unmarshalling.
 **/
public interface IDLEntity extends java.io.Serializable {

}


text:
.class public Lcom/baidu/server/dp/SyncTransaction;
.super Ljava/lang/Object;
.source "SyncTransaction.java"

# interfaces
.implements Lcom/baidu/server/dp/Transaction;

# static fields
.field private static final TAG:Ljava/lang/String; = "DynamicPermissionService"

# instance fields
.field private mTransport:Lcom/baidu/server/dp/ISyncTransport;

# direct methods
.method public constructor <init>(Lcom/baidu/server/dp/ISyncTransport;)V
    .locals 0
    .parameter "it"

    .prologue
    .line 11
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 12
    iput-object p1, p0, Lcom/baidu/server/dp/SyncTransaction;->mTransport:Lcom/baidu/server/dp/ISyncTransport;

    .line 13
    return-void
.end method

# virtual methods
.method public trans(ILandroid/content/Context;)V
    .locals 3
    .parameter "grant"
    .parameter "context"

    .prologue
    .line 16
    :try_start_0
    iget-object v1, p0, Lcom/baidu/server/dp/SyncTransaction;->mTransport:Lcom/baidu/server/dp/ISyncTransport;

    invoke-interface {v1, p1}, Lcom/baidu/server/dp/ISyncTransport;->localTrans(I)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 20
    :goto_0
    return-void

    .line 17
    :catch_0
    move-exception v0

    .line 18
    .local v0, e:Landroid/os/RemoteException;
    const-string v1, "DynamicPermissionService"

    const-string v2, "Client may be dead."

    invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0
.end method


text:
require 'simplecov'

$LOAD_PATH << File.dirname(__FILE__) + '/../../lib/'

require 'clarify'

srand RSpec.configuration.seed


text:
<Record>
<Term>Cryoprotective Agents</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Protective Agents</ParentTerm>
<ClassificationPath>Chemical Actions and Uses/Specialty Uses of Chemicals/Protective Agents/Cryoprotective Agents</ClassificationPath>
<ClassificationPath>Chemical Actions and Uses/Pharmacologic Actions/Physiological Effects of Drugs/Protective Agents/Cryoprotective Agents</ClassificationPath>
<BroaderTerm>Pharmacologic Actions</BroaderTerm>
<BroaderTerm>Specialty Uses of Chemicals</BroaderTerm>
<BroaderTerm>Chemical Actions and Uses</BroaderTerm>
<BroaderTerm>Physiological Effects of Drugs</BroaderTerm>
<BroaderTerm>Cryoprotective Agents</BroaderTerm>
<BroaderTerm>Protective Agents</BroaderTerm>
<Synonym>Cryoprotective Agents</Synonym>
<Description>Substances that provide protection against the harmful effects of freezing temperatures.</Description>
<Source>MeSH</Source>
</Record>


text:
var util = require('util');
var levelup = require('levelup');
var memdown = require('memdown');
var PeerRegistry = require('zetta/lib/peer_registry');

var MemPeerRegistry = module.exports = function() {
    var db = levelup({ db: memdown });
      PeerRegistry.call(this, { db: db, collection: 'peers' });
}
util.inherits(MemPeerRegistry, PeerRegistry);


text:
@implementation NSArray (DPAdditions)

- (NSMutableArray *)droPubConfsByStrippingOptionalData {
	NSMutableArray *confs = [NSMutableArray arrayWithCapacity:[self count]];
	NSUInteger i, count = [self count];
	for (i = 0; i < count; i++) {
		NSMutableDictionary *conf = [self objectAtIndex:i];
		if ([conf respondsToSelector:@selector(droPubConfByStrippingOptionalData)])
			conf = [conf droPubConfByStrippingOptionalData];
		[confs insertObject:conf atIndex:i];
	}
	return confs;
}

@end


text:
package com.reactnativenavigation.params.parsers;

import android.os.Bundle;

import com.reactnativenavigation.params.ActivityParams;
import com.reactnativenavigation.params.AppStyle;
import com.reactnativenavigation.params.SideMenuParams;
import com.reactnativenavigation.views.SideMenu;

public class ActivityParamsParser extends Parser {
    public static ActivityParams parse(Bundle params) {
        ActivityParams result = new ActivityParams();

        AppStyle.setAppStyle(params);

        if (hasKey(params, "screen")) {
            result.type = ActivityParams.Type.SingleScreen;
            result.screenParams = ScreenParamsParser.parse(params.getBundle("screen"));
        }

        if (hasKey(params, "tabs")) {
            result.type = ActivityParams.Type.TabBased;
            result.tabParams = new ScreenParamsParser().parseTabs(params.getBundle("tabs"));
            if (result.tabParams.size() == 0) {
                throw new RuntimeException("Tried to start tab based app with zero tabs");
            }
        }

        if (hasKey(params, "sideMenu")) {
            SideMenuParams[] sideMenus = SideMenuParamsParser.parse(params.getBundle("sideMenu"));
            result.leftSideMenuParams = sideMenus[SideMenu.Side.Left.ordinal()];
            result.rightSideMenuParams = sideMenus[SideMenu.Side.Right.ordinal()];
        }

        result.animateShow = params.getBoolean("animateShow", true);

        return result;
    }
}


text:
using BrailleIO.Interface;
using Gestures.Recognition.Interfaces;
using System;
using System.Collections.Generic;

namespace tud.mci.tangram.TangramLector
{
    ///
    /// Interface for proxies forwarding interaction events
    ///
    public interface IInteractionEventProxy
    {
        ///
        /// Occurs when at leased one button was released.
        ///
        event EventHandler<ButtonReleasedEventArgs> ButtonReleased;
        ///
        /// Occurs when a button combination released (contains of at least one button).
        ///
        event EventHandler<ButtonReleasedEventArgs> ButtonCombinationReleased;
        ///
        /// Occurs when at leased one button was pressed.
        ///
        event EventHandler<ButtonPressedEventArgs> ButtonPressed;
        ///
        /// Occurs when a gesture was performed.
        ///
        event EventHandler<GestureEventArgs> GesturePerformed;

        /// Occurs when a specific function should be called after a user interaction.
        event EventHandler<FunctionCallInteractionEventArgs> FunctionCall;
    }

    #region EventArgs
    ///
    /// Cancelable event for BrailleIO interactions
    ///
    public abstract class BrailleIOInteractionEventArgs : System.ComponentModel.CancelEventArgs
    {
        #region Members

        ///
        /// The sending device.
        ///
        /// <value>The device.</value>
        public BrailleIO.BrailleIODevice Device { get; protected set; }

        protected BrailleIO_DeviceButton _pressedGeneralKeys = BrailleIO_DeviceButton.None;
        ///
        /// Gets or sets the pressed general keys.
        ///
        /// <value>The pressed general keys.</value>
        public BrailleIO_DeviceButton PressedGeneralKeys
        {
            get { return _pressedGeneralKeys; }
            set { _pressedGeneralKeys = value; }
        }

        protected BrailleIO_BrailleKeyboardButton _pressedBrailleKeyboardKeys = BrailleIO_BrailleKeyboardButton.None;
        ///
        /// Gets or sets the pressed general Braille-keyboard keys.
        ///
        /// <value>The pressed general Braille-keyboard keys.</value>
        public BrailleIO_BrailleKeyboardButton PressedBrailleKeyboardKeys
        {
            get { return _pressedBrailleKeyboardKeys; }
            set { _pressedBrailleKeyboardKeys = value; }
        }

        protected BrailleIO_AdditionalButton[] _pressedAdditionalKeys = null;
        ///
        /// Gets or sets the pressed additional general keys.
        ///
        /// <value>The pressed additional general keys.</value>
        public BrailleIO_AdditionalButton[] PressedAdditionalKeys
        {
            get { return _pressedAdditionalKeys; }
            set { _pressedAdditionalKeys = value; }
        }

        protected List<String> _pressedGenericKeys = null;
        ///
        /// Gets or sets the pressed generic keys.
        ///
        /// <value>The interpreted pressed generic keys.</value>
        public List<String> PressedGenericKeys
        {
            get { return _pressedGenericKeys; }
            set
            {
                _pressedGenericKeys = value;
                if (_pressedGenericKeys != null && _pressedGenericKeys.Count > 1)
                    _pressedGenericKeys.Sort();
            }
        }

        internal BrailleIO.Structs.KeyCombinationItem KeyCombinationItem = new BrailleIO.Structs.KeyCombinationItem();

        ///
        /// Gets or sets the timestamp the interaction occurs.
        ///
        /// <value>The timestamp.</value>
        public DateTime Timestamp { get; protected set; }

        #endregion

        #region Constructor

        /// Initializes a new instance of the <see cref="T:tud.mci.tangram.TangramLector.BrailleIOInteractionEventArgs"/> class.
        /// <param name="device">The sending device.</param>
        /// <param name="pressedGeneralKeys">The pressed general keys (Flag).</param>
        /// <param name="pressedBrailleKeyboardKeys">The pressed braille keyboard keys (Flag).</param>
        /// <param name="pressedAdditionalKeys">An array of pressed additional keys (Flag).</param>
        /// <param name="pressedGenericKeys">The interpreted pressed generic keys (proprietary).</param>
        public BrailleIOInteractionEventArgs(
            BrailleIO.BrailleIODevice device,
            BrailleIO_DeviceButton pressedGeneralKeys,
            BrailleIO_BrailleKeyboardButton pressedBrailleKeyboardKeys,
            BrailleIO_AdditionalButton[] pressedAdditionalKeys,
            List<String> pressedGenericKeys) :
            this(DateTime.Now, device, pressedGeneralKeys,
                pressedBrailleKeyboardKeys, pressedAdditionalKeys,
                pressedGenericKeys)
        { }
        ///
        /// Initializes a new instance of the <see cref="BrailleIOInteractionEventArgs"/> class.
        ///
        /// <param name="timestamp">The timestamp the interaction occurred.</param>
        /// <param name="pressedGeneralKeys">The pressed general keys (Flag).</param>
        /// <param name="pressedBrailleKeyboardKeys">The pressed braille keyboard keys (Flag).</param>
        /// <param name="pressedAdditionalKeys">An array of pressed additional keys (Flag).</param>
        /// <param name="pressedGenericKeys">The interpreted pressed generic keys (proprietary).</param>
        public BrailleIOInteractionEventArgs(
            DateTime timestamp,
            BrailleIO.BrailleIODevice device,
            BrailleIO_DeviceButton pressedGeneralKeys,
            BrailleIO_BrailleKeyboardButton pressedBrailleKeyboardKeys,
            BrailleIO_AdditionalButton[] pressedAdditionalKeys,
            List<String> pressedGenericKeys)
        {
            Timestamp = timestamp;
            Device = device;
            PressedGeneralKeys = pressedGeneralKeys;
            PressedBrailleKeyboardKeys = pressedBrailleKeyboardKeys;
            PressedAdditionalKeys = pressedAdditionalKeys;
            PressedGenericKeys = pressedGenericKeys;

            KeyCombinationItem = new BrailleIO.Structs.KeyCombinationItem(
                PressedGeneralKeys, BrailleIO_DeviceButton.None,
                PressedBrailleKeyboardKeys, BrailleIO_BrailleKeyboardButton.None,
                PressedAdditionalKeys, null
                );
        }

        #region KeyCombinationItem Function Wrapping

        ///
        /// Determines whether some currently pressed buttons are detected or not.
        ///
        /// <returns><c>true</c> if some pressed buttons are registered; otherwise, <c>false</c>.</returns>
        public bool AreButtonsPressed(){ return this.KeyCombinationItem.AreButtonsPressed(); }

        ///
        /// Determines whether some released buttons are detected or not.
        ///
        /// <returns><c>true</c> if some released buttons are registered; otherwise, <c>false</c>.</returns>
        public bool AreButtonsReleased() { return this.KeyCombinationItem.AreButtonsReleased(); }

        ///
        /// Returns a comma separated list of all currently pressed buttons.
        ///
        /// <returns>String of currently pressed buttons.</returns>
        public string PressedButtonsToString() { return this.KeyCombinationItem.PressedButtonsToString(); }

        ///
        /// Returns a comma separated list of all released buttons.
        ///
        /// <returns>String of released buttons.</returns>
        public string ReleasedButtonsToString() { return this.KeyCombinationItem.ReleasedButtonsToString(); }

        #endregion

        ///
        /// Returns a <see cref="System.String" /> that represents this instance.
        ///
        /// <returns>
        /// A <see cref="System.String" /> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return String.Format("Released:'{2}' \tPressed:'{1}' \tDevice: {0}", Device.Name +"|"+Device.AdapterType, PressedButtonsToString(), ReleasedButtonsToString());
        }

        #endregion
    }

    ///
    /// Extend the <see cref="BrailleIOInteractionEventArgs"/> with member field for released keys
    ///
    public class ButtonReleasedEventArgs : BrailleIOInteractionEventArgs
    {
        protected BrailleIO_DeviceButton _releasedGeneralKeys = BrailleIO_DeviceButton.None;
        ///
        /// Gets or sets the released general keys.
        ///
        /// <value>The released general keys.</value>
        public BrailleIO_DeviceButton ReleasedGeneralKeys
        {
            get { return _releasedGeneralKeys; }
            set { _releasedGeneralKeys = value; }
        }

        protected BrailleIO_BrailleKeyboardButton _releasedBrailleKeyboardKeys = BrailleIO_BrailleKeyboardButton.None;
        ///
        /// Gets or sets the pressed general Braille-keyboard keys.
        ///
        /// <value>The pressed general Braille-keyboard keys.</value>
        public BrailleIO_BrailleKeyboardButton ReleasedBrailleKeyboardKeys
        {
            get { return _releasedBrailleKeyboardKeys; }
            set { _releasedBrailleKeyboardKeys = value; }
        }

        protected BrailleIO_AdditionalButton[] _releasedAdditionalKeys = null;
        ///
        /// Gets or sets the pressed additional general keys.
        ///
        /// <value>The pressed additional general keys.</value>
        public BrailleIO_AdditionalButton[] ReleasedAdditionalKeys
        {
            get { return _releasedAdditionalKeys; }
            set { _releasedAdditionalKeys = value; }
        }

        protected List<String> _releasedGenericKeys = null;
        ///
        /// Gets or sets the released generic keys.
        ///
        /// <value>The interpreted released generic keys.</value>
        public List<String> ReleasedGenericKeys
        {
            get { return _releasedGenericKeys; }
            set
            {
                _releasedGenericKeys = value;
                if (_releasedGenericKeys != null && _releasedGenericKeys.Count > 1)
                    _releasedGenericKeys.Sort();
            }
        }

        /// Initializes a new instance of the <see cref="T:tud.mci.tangram.TangramLector.ButtonReleasedEventArgs"/> class.
        /// <param name="device">The sending device.</param>
        /// <param name="pressedGeneralKeys">The pressed general keys (Flag).</param>
        /// <param name="pressedBrailleKeyboardKeys">The pressed braille keyboard keys (Flag).</param>
        /// <param name="pressedAdditionalKeys">An array of pressed additional keys (Flag).</param>
        /// <param name="pressedGenericKeys">The interpreted pressed generic keys (proprietary).</param>
        /// <param name="releasedGeneralKeys">The released general keys (Flag).</param>
        /// <param name="releasedBrailleKeyboardKeys">The released braille keyboard keys (Flag).</param>
        /// <param name="releasedAdditionalKeys">An array of released additional keys (Flag).</param>
        /// <param name="releasedGenericKeys">The interpreted released generic keys (proprietary).</param>
        public ButtonReleasedEventArgs(
            BrailleIO.BrailleIODevice device,
            BrailleIO_DeviceButton pressedGeneralKeys,
            BrailleIO_BrailleKeyboardButton pressedBrailleKeyboardKeys,
            BrailleIO_AdditionalButton[] pressedAdditionalKeys,
            List<String> pressedGenericKeys,
            BrailleIO_DeviceButton releasedGeneralKeys,
            BrailleIO_BrailleKeyboardButton releasedBrailleKeyboardKeys,
            BrailleIO_AdditionalButton[] releasedAdditionalKeys,
            List<String> releasedGenericKeys)
            : base(device, pressedGeneralKeys, pressedBrailleKeyboardKeys, pressedAdditionalKeys, pressedGenericKeys)
        {
            ReleasedGeneralKeys = releasedGeneralKeys;
            ReleasedBrailleKeyboardKeys = releasedBrailleKeyboardKeys;
            ReleasedAdditionalKeys = releasedAdditionalKeys;
            ReleasedGenericKeys = releasedGenericKeys;

            KeyCombinationItem = new BrailleIO.Structs.KeyCombinationItem(
                PressedGeneralKeys, ReleasedGeneralKeys,
                PressedBrailleKeyboardKeys, ReleasedBrailleKeyboardKeys,
                PressedAdditionalKeys, ReleasedAdditionalKeys
                );
        }

        /// Initializes a new instance of the <see cref="T:tud.mci.tangram.TangramLector.ButtonReleasedEventArgs"/> class.
        /// <param name="device">The sending device.</param>
        /// <param name="keyCombination">The complex key combination item, sent by BrailleIO framework.</param>
        /// <param name="pressedGenericKeys">The interpreted pressed generic keys (proprietary).</param>
        /// <param name="releasedGenericKeys">The interpreted released generic keys (proprietary).</param>
        public ButtonReleasedEventArgs(
            BrailleIO.BrailleIODevice device,
            BrailleIO.Structs.KeyCombinationItem keyCombination,
            List<String> pressedGenericKeys,
            List<String> releasedGenericKeys)
            : base(device, keyCombination.PressedGeneralKeys, keyCombination.PressedKeyboardKeys, keyCombination.PressedAdditionalKeys, pressedGenericKeys)
        {
            ReleasedGeneralKeys = keyCombination.ReleasedGeneralKeys;
            ReleasedBrailleKeyboardKeys = keyCombination.ReleasedKeyboardKeys;
            ReleasedAdditionalKeys = keyCombination.ReleasedAdditionalKeys;
            ReleasedGenericKeys = releasedGenericKeys;
            KeyCombinationItem = keyCombination;
        }
    }

    ///
    /// Event args for pressed buttons <see cref="BrailleIOInteractionEventArgs"/>
    ///
    public class ButtonPressedEventArgs : BrailleIOInteractionEventArgs
    {
        //TODO: maybe extend this
        /// Initializes a new instance of the <see cref="T:tud.mci.tangram.TangramLector.ButtonPressedEventArgs"/> class.
        /// <param name="device">The sending device.</param>
        /// <param name="pressedGeneralKeys">The pressed general keys (Flag).</param>
        /// <param name="pressedBrailleKeyboardKeys">The pressed braille keyboard keys (Flag).</param>
        /// <param name="pressedAdditionalKeys">An array of pressed additional keys (Flag).</param>
        /// <param name="pressedGenericKeys">The interpreted pressed generic keys (proprietary).</param>
        public ButtonPressedEventArgs(
            BrailleIO.BrailleIODevice device,
            BrailleIO_DeviceButton pressedGeneralKeys,
            BrailleIO_BrailleKeyboardButton pressedBrailleKeyboardKeys,
            BrailleIO_AdditionalButton[] pressedAdditionalKeys,
            List<String> pressedGenericKeys)
            : base(device, pressedGeneralKeys, pressedBrailleKeyboardKeys, pressedAdditionalKeys, pressedGenericKeys)
        { }
    }

    ///
    /// extend the <see cref="ButtonReleasedEventArgs"/> event args with members for gestures.
    ///
    public class GestureEventArgs : ButtonReleasedEventArgs
    {
        ///
        /// gesture classification result
        ///
        public IClassificationResult Gesture;

        /// Initializes a new instance of the <see cref="T:tud.mci.tangram.TangramLector.GestureEventArgs"/> class.
        /// <param name="device">The sending device.</param>
        /// <param name="pressedGeneralKeys">The pressed general keys (Flag).</param>
        /// <param name="pressedBrailleKeyboardKeys">The pressed braille keyboard keys (Flag).</param>
        /// <param name="pressedAdditionalKeys">An array of pressed additional keys (Flag).</param>
        /// <param name="pressedGenericKeys">The interpreted pressed generic keys (proprietary).</param>
        /// <param name="releasedGeneralKeys">The released general keys (Flag).</param>
        /// <param name="releasedBrailleKeyboardKeys">The released braille keyboard keys (Flag).</param>
        /// <param name="releasedAdditionalKeys">An array of released additional keys (Flag).</param>
        /// <param name="releasedGenericKeys">The interpreted released generic keys (proprietary).</param>
        /// <param name="gesture">The gesture classification result.</param>
        public GestureEventArgs(
            BrailleIO.BrailleIODevice device,
            BrailleIO_DeviceButton pressedGeneralKeys,
            BrailleIO_BrailleKeyboardButton pressedBrailleKeyboardKeys,
            BrailleIO_AdditionalButton[] pressedAdditionalKeys,
            List<String> pressedGenericKeys,
            BrailleIO_DeviceButton releasedGeneralKeys,
            BrailleIO_BrailleKeyboardButton releasedBrailleKeyboardKeys,
            BrailleIO_AdditionalButton[] releasedAdditionalKeys,
            List<String> releasedGenericKeys,
            IClassificationResult gesture)
            : base(
                  device, pressedGeneralKeys, pressedBrailleKeyboardKeys, pressedAdditionalKeys, pressedGenericKeys,
                  releasedGeneralKeys, releasedBrailleKeyboardKeys, releasedAdditionalKeys, releasedGenericKeys)
        { this.Gesture = gesture; }
    }

    /// Event arguments for an interaction event that should call a specific function.
    /// extends the <see cref="tud.mci.tangram.TangramLector.ButtonReleasedEventArgs"/>
    public class FunctionCallInteractionEventArgs : ButtonReleasedEventArgs
    {
        ///
        /// The name of the function to be called.
        ///
        public string Function { get; private set; }

        ///
        /// Flag determining if this event/function was already handled or not.
        /// Set this flag after handling the requested function.
        ///
        public bool Handled { get; set; }

        /// Initializes a new instance of the <see cref="T:tud.mci.tangram.TangramLector.Interaction_Manager.FunctionCallInteractionEventArgs"/> class.
        /// <param name="functionName">Name of the function to be called.</param>
        /// <param name="device">The sending device.</param>
        /// <param name="pressedGeneralKeys">The pressed general keys (Flag).</param>
        /// <param name="pressedBrailleKeyboardKeys">The pressed braille keyboard keys (Flag).</param>
        /// <param name="pressedAdditionalKeys">An array of pressed additional keys (Flag).</param>
        /// <param name="pressedGenericKeys">The interpreted pressed generic keys (proprietary).</param>
        /// <param name="releasedGeneralKeys">The released general keys (Flag).</param>
        /// <param name="releasedBrailleKeyboardKeys">The released braille keyboard keys (Flag).</param>
        /// <param name="releasedAdditionalKeys">An array of released additional keys (Flag).</param>
        /// <param name="releasedGenericKeys">The interpreted released generic keys (proprietary).</param>
        public FunctionCallInteractionEventArgs(
            string functionName,
            BrailleIO.BrailleIODevice device,
            BrailleIO_DeviceButton pressedGeneralKeys,
            BrailleIO_BrailleKeyboardButton pressedBrailleKeyboardKeys,
            BrailleIO_AdditionalButton[] pressedAdditionalKeys,
            List<String> pressedGenericKeys,
            BrailleIO_DeviceButton releasedGeneralKeys,
            BrailleIO_BrailleKeyboardButton releasedBrailleKeyboardKeys,
            BrailleIO_AdditionalButton[] releasedAdditionalKeys,
            List<String> releasedGenericKeys)
            : base(device,
                  pressedGeneralKeys, pressedBrailleKeyboardKeys, pressedAdditionalKeys, pressedGenericKeys,
                  releasedGeneralKeys, releasedBrailleKeyboardKeys, releasedAdditionalKeys, releasedGenericKeys)
        {
            Function = functionName;
        }

        /// Initializes a new instance of the <see cref="T:tud.mci.tangram.TangramLector.Interaction_Manager.FunctionCallInteractionEventArgs"/> class.
        /// <param name="functionName">Name of the function to be called.</param>
        /// <param name="device">The sending device.</param>
        /// <param name="keyCombination">The complex key combination item, sent by BrailleIO framework.</param>
        /// <param name="pressedGenericKeys">The interpreted pressed generic keys (proprietary).</param>
        /// <param name="releasedGenericKeys">The interpreted released generic keys (proprietary).</param>
        public FunctionCallInteractionEventArgs(
            string functionName,
            BrailleIO.BrailleIODevice device,
            BrailleIO.Structs.KeyCombinationItem keyCombination,
            List<String> pressedGenericKeys,
            List<String> releasedGenericKeys)
            : base(device, keyCombination, pressedGenericKeys, releasedGenericKeys)
        {
            Function = functionName;
        }
    }

    #endregion

}


text:
texture::TextureFormat* texture::TextureLoader::loadImage(std::string filename)
{
	GLint texture_width;
	GLint texture_height;
	GLint channels_no;

	GLubyte* texture_data = SOIL_load_image(filename.c_str(), &texture_width, &texture_height, &channels_no, SOIL_LOAD_RGB);

	if (!texture_data)
		std::cout << "Failed to load Texture" << std::endl;

	texture::TextureFormat* tf = new texture::TextureFormat(texture_width, texture_height, channels_no, filename, texture_data);

	return tf;
}


text:
//
//  CommentTableViewCell.m
//  心愿很忙
//
//  Created by Jackeylove on 2017/5/6.
//  Copyright © 2017年 Jackeylove. All rights reserved.
//

#import "CommentTableViewCell.h"
#import "BBInput.h"
#import "revertModel.h"
#import "WSIPerosonalViewController.h"
#import "WSIMeDetailViewController.h"
#import "STPopupController.h"

@interface CommentTableViewCell ()

@property (weak, nonatomic) IBOutlet UIImageView *comHead;

@property (weak, nonatomic) IBOutlet UILabel *comContent;

@property (weak, nonatomic) IBOutlet UILabel *comTime;

@property(nonatomic,strong)NSMutableArray *revertArr;

@property(nonatomic,strong)NSMutableAttributedString *contentT;

@property (weak, nonatomic) IBOutlet YYLabel *nickName;

@property (weak, nonatomic) IBOutlet YYLabel *revertL3;

@property (weak, nonatomic) IBOutlet YYLabel *revertL4;

@property (weak, nonatomic) IBOutlet YYLabel *allRevert;

@property (weak, nonatomic) IBOutlet YYLabel *revertView;

@property (weak, nonatomic) IBOutlet YYLabel *revertL1;

@property (weak, nonatomic) IBOutlet YYLabel *revertL2;

@property (weak, nonatomic) IBOutlet UILabel *likeCount;

@property (weak, nonatomic) IBOutlet UIButton *starBt;

@property (nonatomic,assign) NSInteger like;

@property(nonatomic,strong)WSIPerosonalViewController *personVc;

@property(nonatomic,strong)STPopupController *popVc;

@end

@implementation CommentTableViewCell

static NSString *notiName = @"pushVc";

#pragma mark - 懒加载和赋值

-(WSIPerosonalViewController *)personVc {

    if (!_personVc) {

        _personVc = [WSIPerosonalViewController new];
    }

    return _personVc;
}

-(NSMutableArray *)revertArr {

    if (!_revertArr) {

        _revertArr = [NSMutableArray array];
    }

    return _revertArr;
}

- (void)awakeFromNib {
    [super awakeFromNib];

    [self setupGesture];

    // 设置button中图片尺寸

    [_starBt setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];

    [_comHead circleHeader:_comHead withBorderWidth:0 andBorderColor:nil];

}

/** 手势 */

-(void)setupGesture {

    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];

    [_comHead setUserInteractionEnabled:YES];

    [_comHead addGestureRecognizer:tapGr];
}

-(void)tap {

    [STPopupNavigationBar appearance].barTintColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1.0];
    [STPopupNavigationBar appearance].tintColor = [UIColor whiteColor];

    [STPopupNavigationBar appearance].titleTextAttributes = @{ NSFontAttributeName: [UIFont fontWithName:nil size:15], NSForegroundColorAttributeName: [UIColor whiteColor] };

    WSIMeDetailViewController *meVc = [WSIMeDetailViewController new];

    [[NSNotificationCenter defaultCenter] postNotificationName:notiName object:@[@(_headerIv.tag),meVc]];

    _popVc = [[STPopupController alloc] initWithRootViewController:meVc];

    _popVc.containerView.layer.cornerRadius = 3.0f;

    [_popVc presentInViewController:[UIApplication sharedApplication].keyWindow.rootViewController];

    [_popVc.backgroundView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundViewDidTap)]];
}

-(void)backgroundViewDidTap {

    [_popVc dismiss];

}

/** 抽取设置富文本的方法 */

-(NSMutableAttributedString*)setupAttributeWithnickName: (NSString*)nickName {

    if (nickName != nil) { //容错处理 防止程序崩溃

        _contentT = [[NSMutableAttributedString alloc]initWithString:nickName];

        [_contentT setYy_font:[UIFont systemFontOfSize:14.0f]];

        [_contentT yy_setTextHighlightRange:NSMakeRange(0,nickName.length) color:HiBlueColor backgroundColor:[UIColor colorWithRed:202/255.0 green:202/255.0 blue:202/255.0 alpha:1.0f] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {

            [[UIViewController getNavi] pushViewController:self.personVc animated:YES];

        }];

    } else {

    }

    return _contentT;
}

-(void)setComModel:(commentModel *)comModel {

    _comModel = comModel;

    if (!comModel) {

        return;
    }

    [_comContent setText:comModel.content]; //设置配图文字

    [_comTime setText:[NSString stringWithFormat:@"%@", comModel.commentTime]]; //设置时间

    // 设置评论人信息

    BmobQuery *q = [BmobQuery queryWithClassName:@"_User"];

    [q getObjectInBackgroundWithId:comModel.user.objectId block:^(BmobObject *object, NSError *error) {

        [_nickName setAttributedText:[self setupAttributeWithnickName:[object objectForKey:@"nickName"]]];
        NSString *str = [object objectForKey:@"userHeader"];

        [_comHead sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:nil];

    }];

    //查询对应状态的总赞数

    BmobQuery *allQuery = [BmobQuery queryWithClassName:@"commentPraise"];

    [allQuery whereKey:@"comment" equalTo:comModel.comObj];

    [allQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {

        _like = number;
        [_likeCount setText:[NSString stringWithFormat:@"%d", number]];

        if ([_likeCount.text integerValue] == -1) {

             [_likeCount setText:[NSString stringWithFormat:@"%d", 0]];
        }

    }];

    //判断当前状态是否被当前用户赞过 如果赞过 则无论何时图标都显示selected状态

    BmobQuery *query1 = [BmobQuery queryWithClassName:@"commentPraise"];

    [query1 whereKey:@"starUser" equalTo:[BmobUser currentUser]];

    BmobQuery *query2 = [BmobQuery queryWithClassName:@"commentPraise"];

    [query2 whereKey:@"comment" equalTo:comModel.comObj];

    BmobQuery *addQuery = [BmobQuery queryWithClassName:@"commentPraise"];

    [addQuery add:query1];

    [addQuery add:query2];

    [addQuery andOperation];

    [addQuery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {

        if (array.count == 0) {

            _starBt.selected = NO;

        }else {

            _starBt.selected = YES;
        }

    }];

}

- (IBAction)likeBt:(UIButton *)sender {

    sender.selected = !sender.selected;

    /**构建查询条件 如已点过赞 将不再增加数据 并将该条数据从后台delete*/

    BmobQuery *query1 = [BmobQuery queryWithClassName:@"commentPraise"];

    [query1 whereKey:@"starUser" equalTo:[BmobUser currentUser]];

    BmobQuery *query2 = [BmobQuery queryWithClassName:@"commentPraise"];

    [query2 whereKey:@"comment" equalTo:_comModel.comObj];

    BmobQuery *query = [BmobQuery queryWithClassName:@"commentPraise"];

    [query add:query1];

    [query add:query2];

    [query andOperation];

    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {

        if (array.count == 0) {

            BmobObject *obj = [BmobObject objectWithClassName:@"commentPraise"];

            [obj setObject:[BmobUser currentUser] forKey:@"starUser"];
            [obj setObject:_comModel.comObj forKey:@"comment"];
            [obj saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {

                if (isSuccessful) {

                    NSLog(@"评论点赞成功");
                    [_likeCount setText:[NSString stringWithFormat:@"%ld", _like + 1]];
                    _like += 1;

                }else {

                    NSLog(@"评论点赞失败---%@", error);

                }

            }];

        }else {

            NSLog(@"已经赞过");
            [array[0] deleteInBackground];
            [_likeCount setText:[NSString stringWithFormat:@"%ld", _like - 1]];
            _like -= 1;
        }

    }];
}

- (IBAction)revert:(id)sender {

    [BBInput setDescTitle:@"回复"];
    [BBInput setMaxContentLength:140];
    [BBInput showInput:^(NSString *inputContent) {

        BmobObject *wishObj = [[BmobObject alloc] initWithClassName:@"Revert"]; //建表
        [wishObj setObject:inputContent forKey:@"content"]; //回复内容
        [wishObj setObject:_comModel.comObj forKey:@"comment"]; //回复的对应的评论
        [wishObj setObject:[BmobUser currentUser] forKey:@"wishUser"]; //回复人

        [wishObj saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {

            if (isSuccessful) {

                NSLog(@"回复成功");

                [BBInput setNormalContent:nil];
                [self resignFirstResponder];

            }else {

                NSLog(@"评论失败");
            }

        }];

    }];

}

@end


text:
TextQuery::TextQuery(std::ifstream &ifs) : file(new StrBlob)
{
	StrBlob::size_type lineNo{ 0 };
	for (string line; std::getline(ifs, line); ++lineNo)
	{
		file->push_back(line);
		std::istringstream stream(line);
		for (string text, word; stream >> text; word.clear())
		{
			std::remove_copy_if(text.begin(), text.end(), std::back_inserter(word), ispunct);
			auto &lines = wordmap[word];
			if (!lines)
				lines.reset(new std::set<StrBlob::size_type>);
			lines->insert(lineNo);
		}
	}
}

QueryResult TextQuery::query(const string &sought) const
{
	static std::shared_ptr<std::set<StrBlob::size_type>> nodata(new std::set < StrBlob::size_type>);
	auto found = wordmap.find(sought);
	if (found != wordmap.end())
		return QueryResult(sought, found->second, file);
	else
	return QueryResult(sought,nodata, file);
}

std::ostream & print(std::ostream & os, QueryResult & query_result)
{
	// TODO: 在此处插入 return 语句
	os << query_result.word << " occurs " << query_result.lines->size() << " "
		<< (query_result.lines->size() > 1 ? "times." : "time.") << std::endl;
	for (const auto &x : *query_result.lines)
	{
		ConstStrBlobPtr p(*query_result.file, x);
		os << "\t(line " << x + 1 << ") " << p.deref() << std::endl;
	}
	return os;
}


text:
require "spec_helper"

describe V1::ProvincesApi do

  def province_cities_path province
    "v1/provinces/#{province.id}/cities"
  end

  context "provice cities" do
    it "get one province cities" do

      cities = create_list :city, 2
      cities1 = create_list :city, 3

      province = create :province, cities: cities
      province1 = create :province, cities: cities1
      res = auth_json_get province_cities_path(province), id: province.id
      expect(res.size).to eq(2)
    end
  end

end


text:
package apple.storekit;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSData;
import apple.foundation.NSDate;
import apple.foundation.NSError;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

@Generated
@Library("StoreKit")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class SKPaymentTransaction extends NSObject {
    static {
        NatJ.register();
    }

    @Generated
    protected SKPaymentTransaction(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native SKPaymentTransaction alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native SKPaymentTransaction allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native SKPaymentTransaction new_objc();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    /**
     * Available downloads (SKDownload) for this transaction
     */
    @Generated
    @Selector("downloads")
    public native NSArray<? extends SKDownload> downloads();

    /**
     * Only set if state is SKPaymentTransactionFailed
     */
    @Generated
    @Selector("error")
    public native NSError error();

    @Generated
    @Selector("init")
    public native SKPaymentTransaction init();

    /**
     * Only valid if state is SKPaymentTransactionStateRestored.
     */
    @Generated
    @Selector("originalTransaction")
    public native SKPaymentTransaction originalTransaction();

    @Generated
    @Selector("payment")
    public native SKPayment payment();

    /**
     * The date when the transaction was added to the server queue. Only valid if state is
     * SKPaymentTransactionStatePurchased or SKPaymentTransactionStateRestored.
     */
    @Generated
    @Selector("transactionDate")
    public native NSDate transactionDate();

    /**
     * The unique server-provided identifier. Only valid if state is SKPaymentTransactionStatePurchased or
     * SKPaymentTransactionStateRestored.
     */
    @Generated
    @Selector("transactionIdentifier")
    public native String transactionIdentifier();

    /**
     * Only valid if state is SKPaymentTransactionStatePurchased.
     */
    @Generated
    @Deprecated
    @Selector("transactionReceipt")
    public native NSData transactionReceipt();

    @Generated
    @Selector("transactionState")
    @NInt
    public native long transactionState();
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>darerun</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

Module darerun

Functions

    main

Variables

    __email__
    parser

[hide private]


text:
<?php

namespace backend\modules\user\models;

use Yii;

/**
 * This is the model class for table "user_profile".
 *
 * @property integer $user_id
 * @property string $first_name
 * @property string $last_name
 * @property string $gender
 * @property string $date_of_birth
 * @property string $phone_number
 * @property string $country
 * @property string $state
 * @property string $city
 * @property string $address
 * @property string $postal_code
 * @property string $security_private_profile
 * @property string $security_request_following
 * @property string $security_account
 * @property string $paypal_id
 * @property string $school
 * @property string $college
 * @property string $degree
 * @property string $work
 * @property string $position
 * @property string $facebook_link
 * @property string $instagram_link
 * @property string $youtube_link
 * @property string $twitter_link
 * @property string $google_link
 * @property string $snapchat_link
 *
 * @property User $user
 */
class UserProfile extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user_profile';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'first_name', 'last_name'], 'required'],
            [['user_id'], 'integer'],
            [['date_of_birth'], 'safe'],
            [['paypal_id'], 'string'],
            [['first_name', 'last_name', 'phone_number', 'country', 'state', 'city'], 'string', 'max' => 40],
            [['gender', 'postal_code'], 'string', 'max' => 10],
            [['address'], 'string', 'max' => 80],
            [['security_private_profile', 'security_request_following', 'security_account'], 'string', 'max' => 1],
            [['school', 'college', 'degree', 'work', 'position', 'facebook_link', 'instagram_link', 'youtube_link', 'twitter_link', 'google_link', 'snapchat_link'], 'string', 'max' => 255],
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'user_id' => 'User ID',
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'gender' => 'Gender',
            'date_of_birth' => 'Date Of Birth',
            'phone_number' => 'Phone Number',
            'country' => 'Country',
            'state' => 'State',
            'city' => 'City',
            'address' => 'Address',
            'postal_code' => 'Postal Code',
            'security_private_profile' => 'Security Private Profile',
            'security_request_following' => 'Security Request Following',
            'security_account' => 'Security Account',
            'paypal_id' => 'Paypal ID',
            'school' => 'School',
            'college' => 'College',
            'degree' => 'Degree',
            'work' => 'Work',
            'position' => 'Position',
            'facebook_link' => 'Facebook Link',
            'instagram_link' => 'Instagram Link',
            'youtube_link' => 'Youtube Link',
            'twitter_link' => 'Twitter Link',
            'google_link' => 'Google Link',
            'snapchat_link' => 'Snapchat Link',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }
}


text:
package org.eclipse.freemarker.internal.core.documentModel.dom;

import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
import org.eclipse.wst.sse.core.internal.validate.ValidationReporter;
import org.eclipse.wst.xml.core.internal.validate.ValidationComponent;

/**
 * NullValidator class is intended to be a replacement of null for
 * ValidationComponent type.
 */
public class NullValidator extends ValidationComponent {

	public NullValidator() {
		super();
	}

	public void validate(IndexedRegion node) {
		return;
	}

	@Override
	public void setReporter(ValidationReporter reporter) {
		return;
	}

}


text:
/**
 * Created by necklace on 2016/12/28.
 */
import alt from '../../common/altObj';

class PrivateKeyActions {

    addKey(private_key_object, transaction) {
        return (dispatch) => {
            return new Promise( resolve => {
                dispatch({private_key_object, transaction, resolve});
            });
        };
    }

    loadDbData() {
        return (dispatch) => {
            return new Promise( resolve => {
                dispatch(resolve);
            });
        };
    }
}
export default alt.createActions(PrivateKeyActions);


text:
from PyInstaller.hooks.hookutils import matplotlib_backends

# Include only available matplotlib backends.
hiddenimports = matplotlib_backends()


text:
/* eslint-disable no-param-reassign */
const mongoose = require('mongoose');

const User = mongoose.model('User');
const { Schema } = mongoose;

const debug = require('debug')('traveler:review');
const util = require('util');
const logger = require('../lib/loggers').getLogger();

const reviewRequest = new Schema({
  // use the reviewer _id as review request id, in order to use addToSet
  _id: {
    type: String,
    required: true,
  },
  requestedOn: Date,
  requestedBy: String,
});

// result: 1: approve 2: comment
const reviewResult = new Schema({
  reviewerId: {
    type: String,
    required: true,
  },
  result: {
    type: String,
    required: true,
  },
  v: Number,
  submittedOn: Date,
  comment: String,
});

const review = new Schema({
  policy: {
    type: String,
    required: true,
    default: 'all',
    enum: ['all', 'any', 'majority'],
  },
  reviewRequests: [reviewRequest],
  reviewResults: [reviewResult],
});

async function removeReviewRequest(doc, id) {
  try {
    doc.__review.reviewRequests.id(id).remove();
    await doc.save();
    debug(`${id} removed from ${doc._id}`);
    const pull = { reviews: doc._id };
    await User.findByIdAndUpdate(id, {
      $pull: pull,
    });
    debug(`${doc._id} removed from user ${id}`);
  } catch (error) {
    logger.error(`request review db error: ${error}`);
    throw error;
  }
}

async function closeReviewRequests(doc) {
  const requests = doc.__review.reviewRequests;
  const pull = { reviews: doc._id };
  let i;
  const actions = [];
  for (i = 0; i < requests.length; i += 1) {
    actions.push(
      User.findByIdAndUpdate(requests[i]._id, {
        $pull: pull,
      })
    );
  }
  try {
    await Promise.all(actions);
  } catch (error) {
    logger.error(`request review db error: ${error}`);
    throw error;
  }
}

const Review = mongoose.model('Review', review);

function addReview(schema) {
  schema.add({
    __review: review,
  });

  schema.methods.requestReview = async function(requesterId, reviewer) {
    const doc = this;
    try {
      if (!doc.__review) {
        doc.__review = {
          policy: 'all',
          reviewRequests: [],
          reviewResults: [],
        };
      }
      doc.__review.reviewRequests.addToSet({
        _id: reviewer._id,
        requestedOn: Date.now(),
        requestedBy: requesterId,
      });
      const newDoc = await doc.save();
      debug(`doc saved as ${newDoc}`);
      reviewer.reviews.addToSet(newDoc._id);
      const newReviewer = await reviewer.save();
      debug(`reviewer saved as ${newReviewer}`);
      return newDoc;
    } catch (error) {
      logger.error(`request review db error: ${error}`);
      throw error;
    }
  };

  schema.methods.removeReviewRequest = async function(id) {
    const doc = this;
    await removeReviewRequest(doc, id);
  };

  schema.methods.closeReviewRequests = async function() {
    const doc = this;
    await closeReviewRequests(doc);
  };

  schema.methods.addReviewResult = async function(
    reviewerId,
    result,
    comment,
    v
  ) {
    const doc = this;
    try {
      doc.__review.reviewResults.push({
        reviewerId,
        result,
        comment,
        submittedOn: Date.now(),
        v,
      });

      // if rework (result = 2), then
      // 0. set doc status to 0
      // 1. remove doc from reviewer's review list
      // 2. remove reviewer from reviewer list
      if (result === '2') {
        doc.status = 0;
        closeReviewRequests(doc);
        doc.__review.reviewRequests = [];
      }
      const newDoc = await doc.save();
      debug(`doc saved as ${newDoc}`);
      return newDoc;
    } catch (error) {
      logger.error(`update review db error: ${error}`);
      throw error;
    }
  };

  schema.methods.allApproved = function() {
    const doc = this;
    if (!doc.__review) {
      return false;
    }
    const { reviewRequests = [], reviewResults = [] } = doc.__review;
    if (reviewRequests.length === 0) {
      return false;
    }
    const approval = new Map();
    let i;
    debug(`has ${reviewResults.length} results`);
    debug(`has ${reviewRequests.length} requests`);
    // filter to the current version
    const docVersion = doc._v;
    const currentReviewResults = reviewResults.filter(r => r.v === docVersion);
    // the last is the latest
    for (i = currentReviewResults.length - 1; i >= 0; i -= 1) {
      debug(
        `${i} : ${currentReviewResults[i].reviewerId} , ${currentReviewResults[i].result}`
      );
      if (!approval.has(currentReviewResults[i].reviewerId)) {
        approval.set(
          currentReviewResults[i].reviewerId,
          currentReviewResults[i].result
        );
      }
    }
    debug(`filtered list ${util.inspect(approval)}`);
    for (i = 0; i < reviewRequests.length; i += 1) {
      if (approval.get(reviewRequests[i]._id) !== '1') {
        return false;
      }
    }
    return true;
  };
}

module.exports = {
  review,
  reviewResult,
  addReview,
};


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:autoSkin="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentRight="true">

        <LinearLayout
            android:id="@id/bg_top_4space"
            android:layout_width="@dimen/auto_dimen2_26"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:gravity="center_horizontal"
            android:orientation="vertical"
            android:visibility="invisible">

            <ImageView
                android:layout_width="@dimen/auto_dimen2_20"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="@dimen/auto_dimen2_2"
                android:src="@drawable/auto_ic_navi_tmc_top" />
        </LinearLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:background="@drawable/auto_bg_navi_tmc_shadow"
            android:orientation="vertical">

            <RelativeLayout
                android:id="@id/tmc_bar_container"
                android:layout_width="@dimen/auto_dimen2_22"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:background="@drawable/auto_bg_navi_tmc"
                android:orientation="vertical">

                <ImageView
                    android:id="@id/bg_top"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/auto_dimen2_2"
                    android:layout_marginRight="@dimen/auto_dimen2_2"
                    android:layout_marginTop="@dimen/auto_dimen2_2"
                    android:scaleType="fitXY"
                    android:src="@drawable/auto_ic_navi_tmc_top" />

                <!--<com.autonavi.navi.naviwidget.TmcBarView-->
                <!--android:id="@id/tmc_bar_view"-->
                <!--android:layout_width="fill_parent"-->
                <!--android:layout_height="@dimen/auto_dimen2_200"-->
                <!--android:layout_below="@id/bg_top"-->
                <!--android:layout_marginBottom="@dimen/auto_dimen2_2"-->
                <!--android:layout_marginLeft="@dimen/auto_dimen2_2"-->
                <!--android:layout_marginRight="@dimen/auto_dimen2_2" />-->
            </RelativeLayout>
        </RelativeLayout>

        <RelativeLayout
            android:id="@id/navi_tmc_cursor_container"
            android:layout_width="@dimen/auto_dimen2_32"
            android:layout_height="fill_parent"
            android:layout_below="@id/bg_top_4space"
            android:layout_centerHorizontal="true">

            <ImageView
                android:id="@id/navi_tmc_cursor"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:src="@drawable/auto_ic_navi_tmc_icon"
                android:translationY="@dimen/auto_dimen2_358"
                android:visibility="visible" />
        </RelativeLayout>
    </RelativeLayout>

    <RelativeLayout
        android:id="@id/tmc_tag_container"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentRight="true"
        android:visibility="visible">

        <TextView
            android:id="@id/tmc_bottom_tag"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/auto_dimen2_28"
            android:background="@drawable/auto_bg_tmc_block_day"
            android:gravity="center"
            android:minWidth="@dimen/auto_dimen2_80"
            android:singleLine="true"
            android:textSize="@dimen/auto_font_size_22"
            android:translationY="0.0dip" />
    </RelativeLayout>
</RelativeLayout>


text:
{-# OPTIONS -cpp #-}
module Main where

import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (putMVar, takeMVar, newEmptyMVar)
import Control.Monad
import Control.Exception
import Data.Maybe (isNothing)
import System.Environment (getArgs)
import System.Exit
import System.IO (hPutStrLn, stderr)

#if !defined(mingw32_HOST_OS)
import System.Posix hiding (killProcess)
import System.IO.Error hiding (try,catch)
#endif

#if defined(mingw32_HOST_OS)
import System.Process
import WinCBindings
import Foreign
import System.Win32.DebugApi
import System.Win32.Types
#endif

main :: IO ()
main = do
  args <- getArgs
  case args of
      [secs,cmd] ->
          case reads secs of
          [(secs', "")] -> run secs' cmd
          _ -> die ("Can't parse " ++ show secs ++ " as a number of seconds")
      _ -> die ("Bad arguments " ++ show args)

timeoutMsg :: String -> String
timeoutMsg cmd = "Timeout happened...killing process "++cmd++"..."

run :: Int -> String -> IO ()
#if !defined(mingw32_HOST_OS)
run secs cmd = do
        m <- newEmptyMVar
        mp <- newEmptyMVar
        installHandler sigINT (Catch (putMVar m Nothing)) Nothing
        forkIO $ do threadDelay (secs * 1000000)
                    putMVar m Nothing
        forkIO $ do ei <- try $ do pid <- systemSession cmd
                                   return pid
                    putMVar mp ei
                    case ei of
                       Left _ -> return ()
                       Right pid -> do
                           r <- getProcessStatus True False pid
                           putMVar m r
        ei_pid_ph <- takeMVar mp
        case ei_pid_ph of
            Left e -> do hPutStrLn stderr
                                   ("Timeout:\n" ++ show (e :: IOException))
                         exitWith (ExitFailure 98)
            Right pid -> do
                r <- takeMVar m
                case r of
                  Nothing -> do
                        hPutStrLn stderr (timeoutMsg cmd)
                        killProcess pid
                        exitWith (ExitFailure 99)
                  Just (Exited r) -> exitWith r
                  Just (Terminated s) -> raiseSignal s
                  Just _ -> exitWith (ExitFailure 1)

systemSession cmd =
 forkProcess $ do
   createSession
   executeFile "/bin/sh" False ["-c", cmd] Nothing
   -- need to use exec() directly here, rather than something like
   -- System.Process.system, because we are in a forked child and some
   -- pthread libraries get all upset if you start doing certain
   -- things in a forked child of a pthread process, such as forking
   -- more threads.

killProcess pid = do
  ignoreIOExceptions (signalProcessGroup sigTERM pid)
  checkReallyDead 10
  where
    checkReallyDead 0 = hPutStrLn stderr "checkReallyDead: Giving up"
    checkReallyDead (n+1) =
      do threadDelay (3*100000) -- 3/10 sec
         m <- tryJust (guard . isDoesNotExistError) $
                 getProcessStatus False False pid
         case m of
            Right Nothing -> return ()
            Left _ -> return ()
            _ -> do
              ignoreIOExceptions (signalProcessGroup sigKILL pid)
              checkReallyDead n

ignoreIOExceptions :: IO () -> IO ()
ignoreIOExceptions io = io `catch` ((\_ -> return ()) :: IOException -> IO ())

#else
run secs cmd =
    let escape '\\' = "\\\\"
        escape '"'  = "\\\""
        escape c    = [c]
        cmd' = "sh -c \"" ++ concatMap escape cmd ++ "\"" in
    alloca $ \p_startupinfo ->
    alloca $ \p_pi ->
    withTString cmd' $ \cmd'' ->
    do job <- createJobObjectW nullPtr nullPtr
       let creationflags = 0
       b <- createProcessW nullPtr cmd'' nullPtr nullPtr True
                           creationflags
                           nullPtr nullPtr p_startupinfo p_pi
       unless b $ errorWin "createProcessW"
       pi <- peek p_pi
       assignProcessToJobObject job (piProcess pi)
       resumeThread (piThread pi)

       -- The program is now running

       let handle = piProcess pi
       let millisecs = secs * 1000
       rc <- waitForSingleObject handle (fromIntegral millisecs)
       if rc == cWAIT_TIMEOUT
           then do hPutStrLn stderr (timeoutMsg cmd)
                   terminateJobObject job 99
                   exitWith (ExitFailure 99)
           else alloca $ \p_exitCode ->
                do r <- getExitCodeProcess handle p_exitCode
                   if r then do ec <- peek p_exitCode
                                let ec' = if ec == 0
                                          then ExitSuccess
                                          else ExitFailure $ fromIntegral ec
                                exitWith ec'
                        else errorWin "getExitCodeProcess"
#endif


text:
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>

#include <rte_per_lcore.h>
#include <rte_errno.h>
#include <rte_string_fns.h>

RTE_DEFINE_PER_LCORE(int, _rte_errno);

const char *
rte_strerror(int errnum)
{
#define RETVAL_SZ 256
	static RTE_DEFINE_PER_LCORE(char[RETVAL_SZ], retval);

	/* since some implementations of strerror_r throw an error
	 * themselves if errnum is too big, we handle that case here */
	if (errnum > RTE_MAX_ERRNO)
		snprintf(RTE_PER_LCORE(retval), RETVAL_SZ,
#ifdef RTE_EXEC_ENV_BSDAPP
				"Unknown error: %d", errnum);
#else
				"Unknown error %d", errnum);
#endif
	else
		switch (errnum){
		case E_RTE_SECONDARY:
			return "Invalid call in secondary process";
		case E_RTE_NO_CONFIG:
			return "Missing rte_config structure";
		default:
			strerror_r(errnum, RTE_PER_LCORE(retval), RETVAL_SZ);
		}

	return RTE_PER_LCORE(retval);
}


text:
C    Copyright(C) 2008-2017 National Technology & Engineering Solutions of
C    Sandia, LLC (NTESS).  Under the terms of Contract DE-NA0003525 with
C    NTESS, the U.S. Government retains certain rights in this software.
C
C    Redistribution and use in source and binary forms, with or without
C    modification, are permitted provided that the following conditions are
C    met:
C
C    * Redistributions of source code must retain the above copyright
C       notice, this list of conditions and the following disclaimer.
C
C    * Redistributions in binary form must reproduce the above
C      copyright notice, this list of conditions and the following
C      disclaimer in the documentation and/or other materials provided
C      with the distribution.
C
C    * Neither the name of NTESS nor the names of its
C      contributors may be used to endorse or promote products derived
C      from this software without specific prior written permission.
C
C    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
C    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
C    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
C    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
C    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
C    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
C    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
C    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
C    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
C    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
C    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
C

C=======================================================================
      SUBROUTINE SORTID (STYP, ITOTAL, IBEGIN, IEND)
C=======================================================================

C   --*** SORTID *** (ALGEBRA) Gather equation variables of one type
C   --   Written by Amy Gilkey - revised 08/19/87
C   --
C   --SORTID gathers the variables of the specified type into one area
C   --of the /VAR../ arrays and orders these variables by IDVAR.
C   --The variables are sorted at the start of the specified range.
C   --
C   --Parameters:
C   --   STYP   - IN - the variable type to be sorted
C   --   ITOTAL - IN - the ending /VAR../ index of the variables to be ordered
C   --   IBEGIN - IN - the starting /VAR../ index of the variables of type STYP
C   --   IEND   - OUT - the ending /VAR../ index of the variables of type STYP
C   --
C   --Common Variables:
C   --   Sets NAMVAR, TYPVAR, IDVAR, ISTVAR, IEVVAR of /VAR../

      include 'ag_namlen.blk'
      include 'exodusII.inc'
      include 'ag_var.blk'

      CHARACTER STYP

      CHARACTER*(maxnam) NAMTMP
      CHARACTER TYPTMP
      INTEGER ISTTMP(3)

      IEND = IBEGIN - 1

      DO 110 NVAR = IBEGIN, ITOTAL

         NID = 0
         DO 100 I = NVAR, ITOTAL
            IF (TYPVAR(I) .EQ. STYP) THEN
               IF (NID .EQ. 0) NID = I
               IF (IDVAR(I) .LT. IDVAR(NID)) NID = I
            END IF
  100    CONTINUE
         IF (NID .EQ. 0) GOTO 120

         IEND = IEND + 1

         IF (NID .NE. NVAR) THEN
            NAMTMP = NAMVAR(NVAR)
            TYPTMP = TYPVAR(NVAR)
            IDTMP = IDVAR(NVAR)
            ISTTMP(1) = ISTVAR(1,NVAR)
            ISTTMP(2) = ISTVAR(2,NVAR)
            ISTTMP(3) = ISTVAR(3,NVAR)
            IEVTMP = IEVVAR(NVAR)

            NAMVAR(NVAR) = NAMVAR(NID)
            TYPVAR(NVAR) = TYPVAR(NID)
            IDVAR(NVAR) = IDVAR(NID)
            ISTVAR(1,NVAR) = ISTVAR(1,NID)
            ISTVAR(2,NVAR) = ISTVAR(2,NID)
            ISTVAR(3,NVAR) = ISTVAR(3,NID)
            IEVVAR(NVAR) = IEVVAR(NID)

            NAMVAR(NID) = NAMTMP
            TYPVAR(NID) = TYPTMP
            IDVAR(NID) = IDTMP
            ISTVAR(1,NID) = ISTTMP(1)
            ISTVAR(2,NID) = ISTTMP(2)
            ISTVAR(3,NID) = ISTTMP(3)
            IEVVAR(NID) = IEVTMP
         END IF
  110 CONTINUE

  120 CONTINUE
      RETURN
      END


text:
export function createDelay(ctx: Object) {
  const merger = ctx.createChannelMerger(2)
  const input = ctx.createGain()
  const output = ctx.createGain()
  const feedbackL = ctx.createGain()
  const feedbackR = ctx.createGain()
  const delayL = ctx.createDelay()
  const delayR = ctx.createDelay()

  input.connect(output)
  input.connect(delayL)
  input.connect(delayR)

  delayL.connect(feedbackL)
  delayR.connect(feedbackR)

  feedbackL.connect(delayL)
  feedbackR.connect(delayR)

  feedbackL.connect(merger, 0, 0)
  feedbackR.connect(merger, 0, 1)

  merger.connect(output)

  const setters = {
    feedback(value) {
      feedbackL.gain.value = value
      feedbackR.gain.value = value
    },
    delayTime(value) {
      delayL.delayTime.value = value
      delayR.delayTime.value = value / 2
    }
  }

  return {
    input,
    __setters: setters,
    set(key, val) {
      this.__setters[key](val)
    },
    connect(node) { output.connect(node) },
    init(patch) {
      feedbackL.gain.value = patch.feedback
      feedbackR.gain.value = patch.feedback * 1.2

      delayL.delayTime.value = patch.delayTime
      delayR.delayTime.value = patch.delayTime / 2
    }
  }
}


text:
require 'test_helper'
require 'google-analytics/rails/view_helpers'

class ViewHelpersTest < Test::Unit::TestCase
  include GoogleAnalytics::Rails::ViewHelpers

  VALID_JS_INCLUDE = <<-JAVASCRIPT
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  JAVASCRIPT

  VALID_INIT = <<-JAVASCRIPT
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create','TEST','auto');
ga('send','pageview');
</script>
  JAVASCRIPT

  def test_analytics_init
    assert_equal(VALID_INIT, analytics_init)
  end

  def test_analytics_init_with_special_name
    str = analytics_init(:name => 't2').to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','TEST',\{.+\}\);.+/m, str)
    assert_match(/.+"cookieDomain":"auto".+/m, str)
    assert_match(/.+"name":"t2".+/m, str)
    assert_match(/.+ga\('t2.send','pageview'\);.+/m, str)
  end

  def test_analytics_init_with_virtual_pageview
    str = analytics_init(:page => '/some/virtual/url').to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','TEST','auto'\);.+/m, str)
    assert_match(/.+ga\('send','pageview','\/some\/virtual\/url'\);.+/m, str)
  end

  def test_analytics_init_with_virtual_pageview_and_custom_title
    str = analytics_init(:page => '/some/virtual/url', :title => 'Hello World').to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','TEST','auto'\);.+/m, str)
    assert_match(/.+ga\('send','pageview'.+/m, str)
    assert_match(/.+"page":"\/some\/virtual\/url".+/m, str)
    assert_match(/.+"title":"Hello World".+/m, str)
  end

  def test_analytics_init_with_custom_tracker
    str = analytics_init(:tracker => 'UA-CUSTOM-XX').to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','UA-CUSTOM-XX','auto'\);.+/m, str)
    assert_match(/.+ga\('send','pageview'\);.+/m, str)
  end

  def test_analytics_init_with_custom_domain
    str = analytics_init(:domain => 'example.com').to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','TEST',\{"cookieDomain":"example.com"\}\);.+/m, str)
    assert_match(/.+ga\('send','pageview'\);.+/m, str)
  end

  def test_local_analytics_init
    str = analytics_init(:local => true).to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','TEST',\{.+\}\);.+/m, str)
    assert_match(/.+"cookieDomain":"none".+/m, str)
    assert_match(/.+"allowLinker":true.+/m, str)
    assert_match(/.+ga\('send','pageview'\);.+/m, str)
  end

  def test_analytics_init_with_anonymized_ip
    str = analytics_init(:anonymize => true).to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','TEST','auto'\);.+/m, str)
    assert_match(/.+ga\('set','anonymizeIp',true\);.+/m, str)
    assert_match(/.+ga\('send','pageview'\);.+/m, str)
  end

  def test_analytics_init_with_link_attribution
    str = analytics_init(:enhanced_link_attribution => true).to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','TEST','auto'\);.+/m, str)
    assert_match(/.+ga\('require','linkid'\);.+/m, str)
    assert_match(/.+ga\('send','pageview'\);.+/m, str)
  end

  def test_analytics_init_with_events
    str = analytics_init(:add_events => GA::Events::SetAllowLinker.new(true)).to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','TEST',\{.+\}\);.+/m, str)
    assert_match(/.+"cookieDomain":"auto".+/m, str)
    assert_match(/.+"allowLinker":true.+/m, str)
    assert_match(/.+ga\('send','pageview'\);.+/m, str)
  end

  def test_analytics_init_with_samplerate_events
    str = analytics_init(:add_events => GA::Events::SetSiteSpeedSampleRate.new(5)).to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','TEST',\{.+\}\);.+/m, str)
    assert_match(/.+"cookieDomain":"auto".+/m, str)
    assert_match(/.+"siteSpeedSampleRate":5.+/m, str)
    assert_match(/.+ga\('send','pageview'\);.+/m, str)
  end

  def test_analytics_init_with_custom_vars
    str = analytics_init(:custom_vars => GA::Events::SetCustomVar.new(1, 'test', 'hoge',1)).to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','TEST','auto'\);.+/m, str)
    assert_match(/.+ga\('set','dimension1','hoge'\);.+/m, str)
    assert_match(/.+ga\('send','pageview'\);.+/m, str)
  end

  def test_analytics_init_with_custom_dimension
    str = analytics_init(:custom_vars => GA::Events::SetCustomDimension.new(1, 'hoge')).to_s
    assert(str.include?(VALID_JS_INCLUDE))
    assert_match(/.+ga\('create','TEST','auto'\);.+/m, str)
    assert_match(/.+ga\('set','dimension1','hoge'\);.+/m, str)
    assert_match(/.+ga\('send','pageview'\);.+/m, str)
  end

  VALID_TRACK_EVENT = "ga('send','event','Videos','Play','Gone With the Wind',null);"

  def test_analytics_track_event
    event = analytics_track_event("Videos", "Play", "Gone With the Wind")
    assert_equal(VALID_TRACK_EVENT, event)
  end
end