text:
.. include:: ../git_links.inc

MNE quickstart and background
=============================

1. Reading data into MNE
------------------------
One of the first things you might be wondering about is how to get your
data into mne. Assuming that you have unprocessed data, you will probably
be happy with at least one of these readers:

* :func:`read_raw_fif <mne.io.read_raw_fif>`
* :func:`read_raw_kit <mne.io.read_raw_kit>`
* :func:`read_raw_bti <mne.io.read_raw_bti>`
* :func:`read_raw_ctf <mne.io.read_raw_ctf>`
* :func:`read_raw_brainvision <mne.io.read_raw_brainvision>`
* :func:`read_raw_cnt <mne.io.read_raw_cnt>`
* :func:`read_raw_edf <mne.io.read_raw_edf>`
* :func:`read_raw_eeglab <mne.io.read_raw_eeglab>`
* :func:`read_raw_egi <mne.io.read_raw_egi>`
* :func:`read_raw_nicolet <mne.io.read_raw_nicolet>`

They all have in common to return an :class:`mne.io.Raw`-like object.
See :ref:`ch_convert`.

2. MNE gives you objects with methods
-------------------------------------
We said above that there are MNE objects. This is of course computer
science jargon. What it actually means is that you get a data structure
that is more than the channels by time series
and the information about channel types and locations, meta-data if
you want. Indeed the structures that MNE is using provide so called
methods. These are nothing but functions that are configured to take
the data and the meta-data of the object as parameters. Sounds
complicated, but it's actually simplifying your life as you will see
below. Whether you consider Raw objects that describe continuous data,
Epochs objects describing segmented single trial data, or Evoked objects
describing averaged data, all have in common that they share certain methods.

- Try :meth:`raw.plot <mne.io.Raw.plot>`,
  :meth:`epochs.plot <mne.Epochs.plot>`,
  :meth:`evoked.plot <mne.Evoked.plot>` and any other method that has
  a name that starts with `plot`. By using the call operators `()`
  you invoke these methods, e.g.
  :meth:`epochs.plot() <mne.Epochs.plot>`.
  Yes, you don't have to pass arguments but you will get an informative
  visualization of your data. The method knows what to do with the object.
  Look up the documentation for configuration options.

- Try :func:`raw.pick_types <mne.io.Raw.pick_types>`,
  :func:`epochs.pick_types <mne.Epochs.pick_types>`
  :func:`evoked.pick_types <mne.Evoked.pick_types>`
  and any other method that has a name that starts with `pick`. These
  methods will allow you to select channels either by name or by type.
  Picking is MNE jargon and stands for channel selection.

- Some of these methods can actually change the state of the object,
  e.g. permanently remove or transform data. To preserve your input
  data can explicitly use the .copy method to manipulate a copy of
  your inputs. Example::

    >>> raw.copy().pick_types(meg=False, eeg=True)  # doctest: +SKIP

- This examplifies another important concept, that is chaining. Most
  methods return the object and hence allow you to write handy pipelines.
  Guess what this code does::

    >>> (fig = raw.copy()  # doctest: +SKIP
    >>>           .pick_types(meg=False, eeg=True)  # doctest: +SKIP
    >>>           .resample(sfreq=100)  # doctest: +SKIP
    >>>           .filter(1, 30)  # doctest: +SKIP
    >>>           .plot())  # doctest: +SKIP

  Yes, it creates a figure after filtering a resampled copy of the EEG
  data. In fact you can also recognize methods by certain linguistic
  cues. Methods typically use english verbs. So `raw.ch_names` is
  not a method. It's just an attribute that cannot be invoked like
  a function.

- Last but not least, many MNE objects returned a `.save` method that
  allows you to store your data into a FIFF file.

3. A key thing for MNE objects is the measurement info
------------------------------------------------------
Besides ``.ch_names`` another important attribute is ``.info``. It contains
the channel information and some details about the processing history.
This is especially relevant if your data cannot be read using the io
functions listed above. You then need to learn how to create an info.
See :ref:`tut_info_objects`.

4. MNE is modular
-----------------
Beyond methods another concept that is important to get are *modules*.
Think of them as name spaces, another computer science term.
Ok, think of street names in different cities. Sending a parcel to the
Washington street in New York or San Francisco typically
does not involve a conflict, as these streets are in different cities.
Now you know what is the idea behind a name space. You can
read a lot of resources that you will find when googling accordingly.
What is important here is that our modules are organized by
processing contexts. Looking for I/O operations for raw data?::

    >>> from mne import io

Wanna do preprocessing?::

    >>> from mne import preprocessing

Wanna do visualization?::

    >>> from mne import viz

Decoding?::

    >>> from mne import decoding

I'm sure you got it, so explore your intuitions when searching for
a certain function.

5. Inspect and script
---------------------
Did you happen to notice that some of the figures returned by ``.plot``
methods allow you to interact with the data? Look at :meth:`raw.plot <mne.io.Raw.plot>` and
:meth:`epochs.plot <mne.Epochs.plot>` for example. They allow you to update channel selections,
scalings and time ranges. However, they do not replace scripting.
The MNE philosophy is to facilitate diagnostic plotting but does
not support doing analysis by clicking your way. MNE is meant to be
a toolbox, and its your task to combine the tools by **writing scripts**.
This should save you time in the long run by:

1. Enabling code reuse.
2. Documenting what you did.

Reviewers are asking you to update your analysis that you actually
finished 1 year ago? Luckily you have a script.

6. Eighty percent or Python
---------------------------
A related point is that MNE functions are there to make it fun to
process common tasks and facilitate doing difficult things.
This means that you will notice certain limits
here and there, the viz functions do not exactly plot things as
you want them, even when using the options provided by that function.
In fact our goal is to guess which are the essential 80 percent that
you need in order be happy in 80 percent of the time. Where you need
more Python is there for you. You can easily access the data, e.g.
`raw[:10, :1000]` or `epochs.get_data()` or `evoked.data` and
manipulate them using numpy or pass them to high-level machine learning code
from `scikit-learn`_. Each ``.plot`` method
returns a matplotlib figure object. Both packages have great documentations
and often writing Python code amounts to looking up the right library that
allows you to tackle the problem in a few lines.


text:
require 'chef/platform/provider_priority_map'

require 'poise_archive/archive_providers/gnu_tar'
require 'poise_archive/archive_providers/tar'
require 'poise_archive/archive_providers/zip'

module PoiseArchive
  # Providers for the poise_archive resource.
  #
  # @since 1.0.0
  module ArchiveProviders
    # Set up priority maps
    Chef::Platform::ProviderPriorityMap.instance.priority(:poise_archive, [
      PoiseArchive::ArchiveProviders::GnuTar,
      PoiseArchive::ArchiveProviders::Tar,
      PoiseArchive::ArchiveProviders::Zip,
    ])
  end
end

redpajama_set_name: RedPajamaGithub


text:
/* eslint-disable unicorn/filename-case */

const libui = require('../..');

const win = new libui.UiWindow('UiButton example', 320, 60, true);
win.margined = true;

const widget = new libui.UiButton();
widget.text = 'sample text';
win.setChild(widget);

win.onClosing(() => {
	win.close();
	libui.Ui.quit();
});

win.show();

libui.Ui.main();


text:
This github releases checkpoints for the "Scaling Efficiently" paper.
These checkpoints make use of Mesh Tensorflow and the T5 library and
one should be able to load them in the T5 library/codebase.

## Download checkpoints

The checkpoints are found in the following GCP buckets.

In total, there are about 170 trained models each in their own individual
folders. The details of each model (hyperparameters) can be found
in their `operative_config.gin` file. The checkpoints are hosted
at the following GCP bucket.

```
gs://scenic-bucket/scaling_explorer/scaling_explorer
```

You'll be able to find folders written in the notation: `bi_v1_{SIZE}_{OPS}_{DATE}`.
For example `bi_v1_3B_l12_law_03-20-22-27` refers to taking a 3B model,
shrinking the layers to 12 layers.

In each folder, we release checkpoints at 100K, 200K, 300K, 400K and 524K
steps for richer analysis. A caveat is that due to some training failures,
some intermediate checkpoints may not be availiable for a small number
of runs.

## Usage

These checkpoints are compatible with the [T5 library](https://github.com/google-research/text-to-text-transfer-transformer).
You can pass the checkpoint into `--model_dir` of the `t5_mesh_transformer` binary to use it.
Note: we did not test it with the public T5 codebase on Cloud and rather only on our internal systems. However, it should
still work though.

## Reference

If you enjoy our work of find it useful, we would appreciate it if you could
cite our paper at:

```
@article{tay2021scale,
  title={Scale efficiently: Insights from pre-training and fine-tuning transformers},
  author={Tay, Yi and Dehghani, Mostafa and Rao, Jinfeng and Fedus, William and Abnar, Samira and Chung, Hyung Won and Narang, Sharan and Yogatama, Dani and Vaswani, Ashish and Metzler, Donald},
  journal={arXiv preprint arXiv:2109.10686},
  year={2021}
}
```


text:
title: Bibelstudium och gemenskap
date: 12/12/2018
---

`Läs Apg. 2:42. Vilka delar nämns här som delar av den tidiga kristna gudstjänsten?`

"Och de deltog troget i apostlarnas undervisning och den inbördes hjälpen, i brödbrytandet och bönerna" (Apg. 2:42). Från den kristna kyrkans tidigaste stunder har gudstjänsten kännetecknats av hur studiet av det Guds Ords vi fått av apostlarna stod i centrum. De första kristna var trogna i studiet av Skrifterna, vad dessa sade om Jesus, Messias. De hade en ständig gemenskap för att dela med sig till varandra om de välsignelser som Gud hade gett dem och för att uppmuntra varandra i den andliga vandringen med Gud. I Ordet grävde de fram heliga sanningar som blev grunden till deras budskap för världen.

`Vad säger följande texter om hur viktigt det är att studera Guds Ord i gemenskap med andra troende?`

**2 Kung. 2:8–13**

**Apg. 17:10, 11**

**2 Tim. 3:14–17**

"Överallt där evangelium förkunnas, kommer de som uppriktigt vill göra det rätta, att finna vägledning genom ett flitigt studium av Bibeln. Under de avslutande scenerna i denna jords historia kommer prövande bibelsanningar att förkunnas. Om de som lyssnar till denna förkunnelse ville göra på samma sätt som folket i Berea, studera Bibeln och jämföra det budskap som förkunnas för dem med Bibeln, skulle det finnas många fler som lever efter Guds lags föreskrifter på alla de platser, där de nu är jämförelsevis få" (Ellen White: _Löftestiden_, s. 217, 218).

Vi är ett enat folk på grund av de sanningar vi förkunnar, sanningar som vi finner i Guds Ord. Så var det med Guds församling i den första tiden, och så är det idag. Studiet av Guds Ord utgör kärnan i både vår tillbedjan av Gud och vår gemenskap som ett folk som kallats att förkunna de tre änglarnas budskap för världen. När vi samlas som en familj för gemenskap och tillbedjan talar Skrifterna till oss ord från Gud och vägleder våra liv i förberedelsen för vårt uppdrag och för Jesus andra ankomst.

`Hur fast grund har du från Bibeln, i det du tror? Har du en så fast grund i det så att du, liksom de tre hebreiska pojkarna, skulle kunna stå fast inför döden?`


text:
/******************************************************************************
 * 版权所有 刘大磊 2013-07-01												  *
 *	作者:刘大磊								                                              *
 * 电话:13336390671                                                               *
 * email:ldlqdsd@126.com						                              *
 *****************************************************************************/
package com.delmar.system.web.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.delmar.common.model.FileRelation;
import com.delmar.common.model.FileSetting;
import com.delmar.common.service.DelmarFileService;
import com.delmar.common.service.FileRelationService;
import com.delmar.common.service.FileSettingService;
import com.delmar.core.web.action.CoreEditPrivAction;
import com.delmar.core.web.action.PrivilegeOperator;
import com.delmar.core.web.util.FacesUtils;
import com.delmar.sys.model.MobileClient;
import com.delmar.sys.model.Module;
import com.delmar.sys.service.MobileClientService;
import com.delmar.system.web.WebConst;
import com.delmar.system.web.model.PrivilegesDataFilter;

/**
 * @author 刘大磊 2015年7月22日 上午10:46:26
 */
public class MobileClientAction extends CoreEditPrivAction {
	private MobileClient mobileClient= new MobileClient();;
	@Autowired
	private DelmarFileService delmarFileService;
	@Autowired
	private MobileClientService mobileClientService;
	private 	List<FileRelation> fileRelationList=new ArrayList<FileRelation>();
	@Autowired
	private FileSettingService fileSettingService;
	@Autowired
	private FileRelationService fileRelationService;
	/*
	 * (non-Javadoc)
	 *
	 * @see com.delmar.core.web.action.CoreEditPrivAction#getModuleName()
	 */
	@Override
	public String getModuleName() {
		return "mobileClient";
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.delmar.core.web.action.CoreEditPrivAction#delete()
	 */
	@Override
	public String delete() {
		mobileClientService.deleteByPrimaryKey(mobileClient.getId());
		return "list";
	}
	private void init()
	{
		Module module=PrivilegeOperator.getModule();
		FacesUtils.setValueInHashtableOfSession("module", module);
		Map<String,Object> param1=new HashMap<String,Object>();
		param1.put("moduleId", module.getId());
		FileSetting fs=fileSettingService.getByExample(param1);
		FacesUtils.setValueInHashtableOfSession("fileSetting", fs);
		if(!mobileClient.isnew())
		{
			Map param=new HashMap();
			param.put("tableName", "sys_mobile_client");
			param.put("tableId", mobileClient.getId());
			fileRelationList=fileRelationService.selectByExample(param);
		}
	}
	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.delmar.core.web.action.CoreEditPrivAction#deleteList(java.lang.Integer
	 * [])
	 */
	@Override
	public void deleteList(Integer[] ids) {
		mobileClientService.deleteMobileClientList(ids);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.delmar.core.web.action.CoreEditPrivAction#getModelId()
	 */
	@Override
	public Integer getModelId() {
		return mobileClient.getId();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.delmar.core.web.action.CoreEditPrivAction#editForm()
	 */
	@Override
	public void editForm() {
		mobileClient = mobileClientService.selectByPrimaryKey(id);
		init();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.delmar.core.web.action.CoreEditPrivAction#search()
	 */
	@Override
	public List search() {
		Map<String,Object> param=new HashMap();
		param.put("searchString",getSearchWhere());
		return this.mobileClientService.selectByExample(param);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.delmar.core.web.action.CoreEditPrivAction#createForm()
	 */
	@Override
	public void createForm() {
		mobileClient = new MobileClient();
		init();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.delmar.core.web.action.CoreEditPrivAction#saveForm()
	 */
	@Override
	public String saveForm() {
		PrivilegesDataFilter	 up=(PrivilegesDataFilter)FacesUtils.getSession().getAttribute(WebConst.SESSION_USERPRIVILEGES);
		boolean isnew=false;
		Date date=new Date();
		if(mobileClient.isnew())
		{
			isnew=true;
			mobileClient.setCreated(date);
			mobileClient.setCreatedby(up.getUserId());
			mobileClient.setCreatedbyname(up.getLoginUser().getUsername());
			mobileClient.setClientId(up.getLoginClientId());
			mobileClient.setOrgId(up.getLoginOrgId());
			mobileClient.setUserId(up.getLoginUserId());
			mobileClient.setUserName(up.getLoginUser().getUsername());
		}
		mobileClient.setUpdated(date);
		mobileClient.setUpdatedby(up.getUserId());
		mobileClient.setUpdatedbyname(up.getLoginUser().getUsername());

		FileSetting fs=(FileSetting)FacesUtils.getValueInHashtableOfSession("fileSetting");
		for(FileRelation fr:fileRelationList)
		{
			fr.getDelmarFile().setCommonFileSettingId(fs != null ? fs.getId() : null);
		}

		mobileClientService.save(mobileClient,fileRelationList);

		this.id=mobileClient.getId();
		if(isnew)
		{
			fileRelationList.add(new FileRelation());
		}
		return EDIT;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.delmar.core.web.action.CoreEditPrivAction#getPurpose()
	 */
	@Override
	public String getPurpose() {
		return "手机客户端";
	}

	/**
	 * @return the fileRelationList
	 */
	public List<FileRelation> getFileRelationList() {
		return fileRelationList;
	}

	/**
	 * @param fileRelationList the fileRelationList to set
	 */
	public void setFileRelationList(List<FileRelation> fileRelationList) {
		this.fileRelationList = fileRelationList;
	}

	/**
	 * @return the mobileClient
	 */
	public MobileClient getMobileClient() {
		return mobileClient;
	}

	/**
	 * @param mobileClient the mobileClient to set
	 */
	public void setMobileClient(MobileClient mobileClient) {
		this.mobileClient = mobileClient;
	}

}


text:
package com.hzg.erp;

import javax.persistence.*;
import java.io.Serializable;

@Entity(name = "hzg_express_deliver_detail_product")
public class ExpressDeliverDetailProduct implements Serializable {

    private static final long serialVersionUID = 345435245233256L;

    public ExpressDeliverDetailProduct(){
        super();
    }

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="id", length = 11)
    private Integer id;

    @ManyToOne(cascade=CascadeType.DETACH, fetch = FetchType.LAZY)
    @JoinColumn(name = "expressDeliverDetailId")
    private ExpressDeliverDetail expressDeliverDetail;

    @OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
    @JoinColumn(name = "productId")
    private Product product;

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public ExpressDeliverDetail getExpressDeliverDetail() {
        return expressDeliverDetail;
    }

    public void setExpressDeliverDetail(ExpressDeliverDetail expressDeliverDetail) {
        this.expressDeliverDetail = expressDeliverDetail;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }
}


text:
const { always, is, isEmpty, pipe, when } = require('ramda')
const camelCase = require('lodash.camelcase')
const kebabCase = require('lodash.kebabcase')
const snakeCase = require('lodash.snakecase')
const upperCase = require('lodash.uppercase')
const lowerCase = require('lodash.lowercase')
const startCase = require('lodash.startcase')
const upperFirst = require('lodash.upperfirst')
const lowerFirst = require('lodash.lowerfirst')
const pad = require('lodash.pad')
const padStart = require('lodash.padstart')
const padEnd = require('lodash.padend')
const trim = require('lodash.trim')
const trimStart = require('lodash.trimstart')
const trimEnd = require('lodash.trimend')
const repeat = require('lodash.repeat')

/**
 * Is this not a string?
 *
 * @param  {any}     value The value to check
 * @return {boolean}       True if it is not a string, otherwise false
 */
const isNotString = value => {
  return !is(String, value)
}

/**
 * Is this value a blank string?
 *
 * @param   {any}     value The value to check.
 * @returns {boolean}       True if it was, otherwise false.
 */
const isBlank = value => {
  const check = pipe(when(isNotString, always('')), trim, isEmpty)

  return check(value)
}

/**
 * Returns the value it is given
 *
 * @param {any} value
 * @returns     the value.
 */
function identity (value) {
  return value
}

/**
 * Converts the value ToPascalCase.
 *
 * @param {string} value The string to convert
 * @returns {string}
 */
function pascalCase (value) {
  return pipe(camelCase, upperFirst)(value)
}

module.exports = {
  identity,
  isBlank,
  isNotString,
  camelCase,
  kebabCase,
  snakeCase,
  upperCase,
  lowerCase,
  startCase,
  upperFirst,
  lowerFirst,
  pascalCase,
  pad,
  padStart,
  padEnd,
  trim,
  trimStart,
  trimEnd,
  repeat
}


text:
package network

import (
	"encoding/binary"
	"errors"

	"github.com/gfandada/gserver/misc"
)

type MessageParser struct {
	maxMessageLen uint16 // for message
	minMessageLen uint16 // for message
	buff          []byte // for send
}

type RawMessage struct {
	MsgId   uint16
	MsgData interface{}
}

func NewMessageParser() (newMsg *MessageParser) {
	newMsg = new(MessageParser)
	newMsg.minMessageLen = 0
	newMsg.maxMessageLen = 512
	newMsg.buff = make([]byte, newMsg.maxMessageLen+4)
	return
}

func (msgParser *MessageParser) SetMsgLen(MaxMessageLen uint16, MinMessageLen uint16) {
	if MinMessageLen >= 0 {
		msgParser.minMessageLen = MinMessageLen
	}
	if MaxMessageLen >= 0 {
		msgParser.maxMessageLen = MaxMessageLen
	}
}

func (msgParser *MessageParser) NewMessageParser() *MessageParser {
	return &MessageParser{
		maxMessageLen: msgParser.maxMessageLen,
		minMessageLen: msgParser.minMessageLen,
		buff:          make([]byte, 8+msgParser.maxMessageLen),
	}
}

// 获取body(除header)
func (msgParser *MessageParser) ReadBody(data []byte) ([]byte, error) {
	size := binary.BigEndian.Uint16(data[:2])
	switch {
	case uint16(size) > msgParser.maxMessageLen+6:
		return nil, errors.New("message too long")
	case uint16(size) < msgParser.minMessageLen+6:
		return nil, errors.New("message too short")
	}
	return data[2:], nil
}

//
// 拆分body数据
// @return 数据1(序列号),数据2(协议号),数据3(id+message),错误描述
func (msgParser *MessageParser) ReadBodyFull(data []byte) (uint32, uint16, []byte, error) {
	reader := misc.Reader(data)
	seq_id, err1 := reader.ReadU32()
	if err1 != nil {
		return 0, 0, nil, errors.New("read seq error")
	}
	id, err2 := reader.ReadU16()
	if err2 != nil {
		return 0, 0, nil, errors.New("read messageid error")
	}
	return seq_id, id, data[4:], nil
}

// @params data:id+message
// @return header+data
func (msgParser *MessageParser) Write(data []byte) ([]byte, error) {
	if data == nil {
		return nil, errors.New("data is too short")
	}
	size := uint16(len(data))
	//buff := msgParser.buff
	// FIXME 容易产生内存碎片,后续优化
	buff := make([]byte, 2+size)
	if size-2 >= msgParser.minMessageLen && size-2 <= msgParser.maxMessageLen {
		binary.BigEndian.PutUint16(buff, uint16(size))
		copy(buff[2:], data)
		return buff[:2+size], nil
	}
	return nil, errors.New("data is too long")
}


text:
<?xml version="1.0" ?>
<TestSuite>
        <Details>
                <Name>ts_runmode_rup_at_ts_global_level_with_status_last_instance</Name>
                <Title>test suite to run runmode(RUP) at testsuite file detail section</Title>
                <Engineer>Warrior_user</Engineer>
                <Date>2018-10-11</Date>
                <Time>11:37:26</Time>
                <runmode type="RUP" value="3" status="last_instance"/>
                <default_onError action="next"/>
                <Resultsdir/>
        </Details>
        <Requirements>
                <Requirement>Requirement-001</Requirement>
                <Requirement>Requirement-002</Requirement>
        </Requirements>
        <Testcases>
                <Testcase>
                        <path>../../../testcases/framework_tests/runmode_tests/tc_runmode_rup_at_tc_global_level_with_status_last_instance.xml</path>
                        <context>positive</context>
                        <runtype>sequential_keywords</runtype>
                        <onError action="next"/>
                        <impact>impact</impact>
                </Testcase>
        </Testcases>
</TestSuite>


text:
import * as userActionTypes from "../action_types/UserActionTypes";
import initialState from "../initialState";

//initial user state is populated in React Index view
export default function(state = initialState.user, action) {
    switch(action.type){
        case userActionTypes.USER_LOADED:
            return action.user;
        default :
            return state;
    }
}


text:
namespace rdo { namespace gui { namespace tracer {

PREDECLARE_POINTER(ResourceType);
PREDECLARE_POINTER(Resource);
PREDECLARE_POINTER(Pattern);
PREDECLARE_POINTER(OperationBase);
PREDECLARE_POINTER(Event);
PREDECLARE_POINTER(Result);
PREDECLARE_POINTER(Serie);
class Time;
class ParamInfo;
class ChartTree;
class ChartDoc;
class LogMainWnd;

class TracerBase: public RDOThreadGUI
{
public:
    void setLog(LogMainWnd* pTracerLog);
    void setTree(ChartTree* pTreeCtrl);

    void startTrace();
    void getModelStructure(std::istream& stream);
    void getTraceString(std::string trace_string);
    std::string getNextValue(std::string& line);
    ChartDoc* createNewChart();
    void addChart(ChartDoc* const pDocument);
    void removeChart(ChartDoc* pDocument);
    ChartDoc* addSerieToChart(const LPSerie& pSerie, ChartDoc* pDocument = NULL);
    void updateChartsStyles() const;
    void clear();
    void setModelName(const QString& name) const;
    void setDrawTrace(const bool value);
    bool getDrawTrace() const;

protected:
    TracerBase(const std::string& _thread_name, RDOKernelGUI* _kernel_gui);
    virtual ~TracerBase();

private:
    LogMainWnd* m_pLog;
    ChartTree*  m_pChartTree;

    ParamInfo* getParam(std::istream& stream);
    ParamInfo* getParamType(std::istream& stream);

    typedef  std::vector<LPResourceType>   ResourceTypeList;
    typedef  std::vector<LPResource>       ResourceList;
    typedef  std::vector<LPPattern>        PatternList;
    typedef  std::vector<LPOperationBase>  OperationBaseList;
    typedef  std::vector<LPEvent>          EventList;
    typedef  std::vector<LPResult>         ResultList;
    typedef  std::list<Time*>              TimeList;
    typedef  std::vector<ChartDoc*>        DocumentList;

    ResourceTypeList  m_resourceTypeList;
    ResourceList      m_resourceList;
    PatternList       m_patternList;
    OperationBaseList m_operationList;
    EventList         m_eventList;
    ResultList        m_resultList;

    void addResourceType(std::string& s, std::istream& stream);
    void addResource(std::string& s, std::istream& stream);
    void addPattern(std::string& s, std::istream& stream);
    void addOperation(std::string& s, std::istream& stream);
    void addResult(std::string& s, std::istream& stream);

    void dispatchNextString(std::string& line);

    Time* addTime(const std::string& time);
    int m_eventIndex;

    LPOperationBase getOperation(std::string& line);void startAction(std::string& line, Time* const pTime);
    void accomplishAction(std::string& line, Time* const pTime);
    void irregularEvent(std::string& line, Time* const pTime);
    void productionRule(std::string& line, Time* const pTime);

    LPResource getResource(std::string& line);
    LPResource resourceCreation(std::string& line, Time* const pTime);
    LPResource resourceElimination(std::string& line, Time* const pTime);

    enum class UpdateAction
    {
        NONE,
        ADD,
        UPDATE
    };
    UpdateAction m_updateAction;

    LPResource m_pResource;
    LPResource resourceChanging(std::string& line, Time* const pTime);

    LPResult getResult(std::string& line);void resultChanging(std::string& line, Time* const pTime);

    TimeList m_timeList;

    void clearCharts();
    void deleteTrace();

    DocumentList m_documentList;
    bool         m_drawTrace;
};

}}} // namespace rdo::gui::tracer


text:
//  -*- C++ -*-

/*
 * Copyright (C) 1990,91   Silicon Graphics, Inc.
 *
 _______________________________________________________________________
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 |
 |   $Revision: 1.1.1.1 $
 |
 |   Description:
 |	This file defines the SoPerspectiveCamera node class.
 |
 |   Author(s)		: Paul S. Strauss
 |
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 _______________________________________________________________________
 */

#ifndef  _SO_PERSPECTIVE_CAMERA_
#define  _SO_PERSPECTIVE_CAMERA_

#include <Inventor/fields/SoSFFloat.h>
#include <Inventor/nodes/SoCamera.h>

//////////////////////////////////////////////////////////////////////////////
//
//  Class: SoPerspectiveCamera
//
//  perspectiveCamera node.
//
//////////////////////////////////////////////////////////////////////////////

// C-api: prefix=SoPerspCam
// C-api: public= viewportMapping, position, orientation, aspectRatio
// C-api: public= nearDistance, farDistance, focalDistance
// C-api: public= heightAngle
class INVENTOR_API SoPerspectiveCamera : public SoCamera {

    SO_NODE_HEADER(SoPerspectiveCamera);

  public:
    // Fields (some are inherited from SoCamera)
    SoSFFloat		heightAngle;	// Angle (in radians) of field
					// of view, in height direction

    // Constructor
    SoPerspectiveCamera();

    // Scales the height of the camera, in this case, the 'heightAngle' field.
    // C-api: begin
    virtual void	scaleHeight( float scaleFactor );

    // Fills in a view volume structure, based on the camera. If the
    // useAspectRatio field is not 0.0 (the default), the camera uses
    // that ratio instead of the one it has.
    virtual SbViewVolume getViewVolume(float useAspectRatio = 0.0) const;

  SoINTERNAL public:
    static void		initClass();

  protected:
    // Positions camera to view passed bounding box with given aspect
    // ratio and current height angle
    virtual void	viewBoundingBox(const SbBox3f &box,
					float aspect, float slack);

    virtual ~SoPerspectiveCamera();
};

#endif /* _SO_PERSPECTIVE_CAMERA_ */


text:
<?php
namespace FluidTYPO3\Flux\Service;

use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\DataHandling\DataHandler;
use TYPO3\CMS\Core\SingletonInterface;

/**
 * Flux FlexForm integration Service
 *
 * Main API Service for interacting with Flux-based FlexForms
 *
 * @package Flux
 * @subpackage Service
 */
class ContentService implements SingletonInterface {

	const COLPOS_FLUXCONTENT = 18181;

	/**
	 * @param array $row
	 * @param array $parameters
	 * @param DataHandler $tceMain
	 * @return boolean
	 */
	public function affectRecordByRequestParameters(array &$row, $parameters, DataHandler $tceMain) {
		$url = TRUE === isset($parameters['returnUrl']) ? $parameters['returnUrl'] : NULL;
		$urlHashCutoffPoint = strrpos($url, '#');
		$area = NULL;
		if ($urlHashCutoffPoint > 0) {
			$area = substr($url, 1 - (strlen($url) - $urlHashCutoffPoint));
			if (FALSE === strpos($area, ':')) {
				return FALSE;
			}
		}
		list ($contentAreaFromUrl, $parentUidFromUrl, $afterElementUid) = explode(':', $area);
		if ($contentAreaFromUrl) {
			$row['tx_flux_column'] = $contentAreaFromUrl;
		}
		if ($parentUidFromUrl > 0) {
			$row['tx_flux_parent'] = $parentUidFromUrl;
		}
		if ($row['tx_flux_parent'] > 0) {
			$row['colPos'] = self::COLPOS_FLUXCONTENT;
			if (0 > $afterElementUid) {
				$row['sorting'] = $tceMain->resorting('tt_content', $row['pid'], 'sorting', abs($afterElementUid));
			}
		}
		return TRUE;
	}

	/**
	 * Paste one record after another record.
	 *
	 * @param string $command The command which caused pasting - "copy" is targeted in order to determine "reference" pasting.
	 * @param array $row The record to be pasted, by reference. Changes original $row
	 * @param array $parameters List of parameters defining the paste operation target
	 * @param DataHandler $tceMain
	 * @return boolean
	 */
	public function pasteAfter($command, array &$row, $parameters, DataHandler $tceMain) {
		$id = $row['uid'];
		if (1 < substr_count($parameters[1], '-')) {
			list ($pid, $subCommand, $relativeUid, $parentUid, $possibleArea, $possibleColPos) = explode('-', $parameters[1]);
			$relativeUid = 0 - $relativeUid;
		} else {
			list ($tablename, $pid, $relativeUid) = $parameters;
		}
		if ($command !== 'copy') {
			$record = $row;
		} else {
			$copiedUid = $tceMain->copyMappingArray['tt_content'][$id];
			$record = $this->loadRecordFromDatabase($copiedUid);
			if ('reference' === $subCommand) {
				$record['CType'] = 'shortcut';
				$record['records'] = $id;
			}
			$id = $copiedUid;
		}
		if (FALSE === empty($possibleArea)) {
			$record['tx_flux_parent'] = $parentUid;
			$record['tx_flux_column'] = $possibleArea;
			$record['colPos'] = self::COLPOS_FLUXCONTENT;
		} elseif (0 > $relativeUid) {
			$relativeRecord = $this->loadRecordFromDatabase(abs($relativeUid));
			$record['sorting'] = $tceMain->resorting('tt_content', $row['pid'], 'sorting', abs($relativeUid));
			$record['pid'] = $relativeRecord['pid'];
			$record['colPos'] = $relativeRecord['colPos'];
			$record['tx_flux_column'] = $relativeRecord['tx_flux_column'];
			$record['tx_flux_parent'] = $relativeRecord['tx_flux_parent'];
		} elseif (0 < $relativeUid) {
			$record['sorting'] = 0;
			$record['pid'] = $relativeUid;
			$record['tx_flux_column'] = '';
			$record['tx_flux_parent'] = '';
		}
		if (FALSE === empty($possibleColPos) || 0 === $possibleColPos || '0' === $possibleColPos) {
			$record['colPos'] = $possibleColPos;
		}
		if (TRUE === isset($pid) && FALSE === isset($relativeRecord['pid'])) {
			$record['pid'] = $pid;
		}
		$this->updateRecordInDatabase($record, $id);
		$row = $record;
	}

	/**
	 * Move the content element depending on various request/row parameters.
	 *
	 * @param array $row The row which may, may not, trigger moving.
	 * @param string $relativeTo If not-zero moves record to after this UID (negative) or top of this colPos (positive)
	 * @return boolean
	 */
	public function moveRecord(array &$row, &$relativeTo) {
		if (FALSE !== strpos($relativeTo, 'FLUX')) {
			// Triggers when CE is dropped on a nested content area's header dropzone (EXT:gridelements)
			list ($areaName, $parentElementUid, $pid) = explode('-', trim($relativeTo, '-'));
			$row['tx_flux_column'] = $areaName;
			$row['tx_flux_parent'] = $parentElementUid;
			$row['pid'] = $pid;
			$row['sorting'] = -1;
			$relativeTo = $pid;
		} elseif (FALSE !== strpos($relativeTo, 'x')) {
			// Triggers when CE is dropped on a root (not CE) column header's dropzone (EXT:gridelements)
			// set colPos and remove FCE relation
			list ($relativeTo, $colPos) = explode('x', $relativeTo);
			$row['tx_flux_column'] = $row['tx_flux_parent'] = NULL;
			$row['colPos'] = $colPos;
			$row['sorting'] = -1;
		} elseif (0 <= intval($relativeTo)) {
			// dropping an element in a column header dropzone in 6.0 only sends the "colPos"
			// and this colPos may contain nothing but positive integers. Bring the severe hacking.
			$backtrace = debug_backtrace();
			$this->affectRecordByBacktrace($row, $backtrace);
		} elseif (0 > intval($relativeTo) || 0 > $row['pid']) {
			// inserting a new element after another element. Check column position of that element.
			$relativeToRecord = $this->loadRecordFromDatabase(abs($relativeTo));
			$row['tx_flux_parent'] = $relativeToRecord['tx_flux_parent'];
			$row['tx_flux_column'] = $relativeToRecord['tx_flux_column'];
			$row['colPos'] = $relativeToRecord['colPos'];
		}
		if (0 < $row['tx_flux_parent']) {
			$row['colPos'] = self::COLPOS_FLUXCONTENT;
		}
		return TRUE;
	}

	/**
	 * @param array $row
	 * @param DataHandler $tceMain
	 * @return NULL
	 */
	public function initializeRecord(array $row, DataHandler $tceMain) {
		$id = $row['uid'];
		$newUid = $tceMain->substNEWwithIDs[$id];
		$oldUid = $row['t3_origuid'];
		$languageFieldName = $GLOBALS['TCA']['tt_content']['ctrl']['languageField'];
		$newLanguageUid = NULL;
		if ($oldUid) {
			$oldRecord = $this->loadRecordFromDatabase($oldUid);
			if (FALSE === empty($row[$languageFieldName])) {
				$newLanguageUid = $row[$languageFieldName];
			} elseif (FALSE === empty($oldRecord[$languageFieldName])) {
				$newLanguageUid = $oldRecord[$languageFieldName];
			} else {
				$newLanguageUid = 1; // TODO: resolve config.sys_language_uid but WITHOUT using Extbase TS resolution, consider pid of new record
			}
			$clause = "(tx_flux_column LIKE '%:" . $oldUid . "' || tx_flux_parent = '" . $oldUid . "') AND deleted = 0 AND hidden = 0";
			$children = $this->loadRecordsFromDatabase($clause);
			if (1 > count($children)) {
				return NULL;
			}
			// Perform localization on all children, since this is not handled by the TCA field which otherwise cascades changes
			foreach ($children as $child) {
				$area = $child['tx_flux_column'];
				$overrideValues = array(
					'tx_flux_column' => $area,
					'tx_flux_parent' => $newUid,
					$languageFieldName => $newLanguageUid
				);
				if ($oldRecord[$languageFieldName] !== $newLanguageUid && $oldRecord['pid'] === $row['pid']) {
					$childUid = $tceMain->localize('tt_content', $child['uid'], $newLanguageUid);
					$this->updateRecordInDatabase($overrideValues, $childUid);
				}
			}
		}
		return NULL;
	}

	/**
	 * @param array $row
	 * @param array $backtrace
	 * @return boolean
	 */
	public function affectRecordByBacktrace(array &$row, array $backtrace) {
		$retrievedArgument = NULL;
		$targetClass = 'TYPO3\\CMS\\Backend\\View\\PageLayout\\ExtDirect\\ExtdirectPageCommands';
		$targetFunction = 'moveContentElement';
		foreach (array_reverse($backtrace) as $stackItem) {
			if ($stackItem['class'] === $targetClass && $stackItem['function'] === $targetFunction) {
				$retrievedArgument = $stackItem['args'][1];
				$segments = explode('-', $retrievedArgument);
				$slice = array_slice($segments, count($segments) - 3);
				if ($slice[0] === 'top') {
					$row['tx_flux_parent'] = $slice[1];
					$row['tx_flux_column'] = $slice[2];
					$row['colPos'] = self::COLPOS_FLUXCONTENT;
				} elseif ($slice[0] === 'after') {
					$row['pid'] = 0 - $slice[1];
					$row['tx_flux_column'] = $slice[2];
				} else {
					$row['tx_flux_parent'] = $row['tx_flux_column'] = '';
				}
				break;
			}
		}
		return TRUE;
	}

	/**
	 * @param integer $uid
	 * @return string
	 */
	public function detectParentElementAreaFromRecord($uid) {
		$uid = abs($uid);
		$record = $this->loadRecordFromDatabase($uid);
		return $record['tx_flux_column'];
	}

	/**
	 * @param integer $uid
	 * @return integer
	 */
	public function detectParentUidFromRecord($uid) {
		$uid = abs($uid);
		$record = $this->loadRecordFromDatabase($uid);
		return intval($record['tx_flux_parent']);
	}

	/**
	 * @param mixed $uidOrClause
	 * @return array|FALSE
	 */
	protected function loadRecordFromDatabase($uidOrClause) {
		if (0 < intval($uidOrClause) && TRUE === is_integer($uidOrClause)) {
			return BackendUtility::getRecord('tt_content', $uidOrClause);
		} else {
			return $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'tt_content', $uidOrClause);
		}
	}

	/**
	 * @param string $clause
	 * @return array|FALSE
	 */
	protected function loadRecordsFromDatabase($clause) {
		return $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', 'tt_content', $clause);
	}

	/**
	 * @param array $row
	 * @param integer $uid
	 * @return void
	 */
	protected function updateRecordInDatabase($row, $uid = NULL) {
		if (NULL === $uid) {
			$uid = $row['uid'];
		}
		$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tt_content', "uid = '" . $uid . "'", $row);
	}

}


text:
using System.IO;

namespace Spect.Net.SpectrumEmu.Devices.Tape.Tzx
{
    /// <summary>
    /// Represents the standard speed data block in a TZX file
    /// </summary>
    public class TzxCswRecordingDataBlock : TzxDataBlockBase
    {
        /// <summary>
        /// Block length (without these four bytes)
        /// </summary>
        public uint BlockLength { get; set; }

        /// <summary>
        /// Pause after this block
        /// </summary>
        public ushort PauseAfter { get; set; }

        /// <summary>
        /// Sampling rate
        /// </summary>
        public byte[] SamplingRate { get; set; }

        /// <summary>
        /// Compression type
        /// </summary>
        /// <remarks>
        /// 0x01=RLE, 0x02=Z-RLE
        /// </remarks>
        public byte CompressionType { get; set; }

        /// <summary>
        /// Number of stored pulses (after decompression, for validation purposes)
        /// </summary>
        public uint PulseCount { get; set; }

        /// <summary>
        /// CSW data, encoded according to the CSW file format specification
        /// </summary>
        public byte[] Data { get; set; }

        /// <summary>
        /// The ID of the block
        /// </summary>
        public override int BlockId => 0x18;

        /// <summary>
        /// Reads the content of the block from the specified binary stream.
        /// </summary>
        /// <param name="reader">Stream to read the block from</param>
        public override void ReadFrom(BinaryReader reader)
        {
            BlockLength = reader.ReadUInt32();
            PauseAfter = reader.ReadUInt16();
            SamplingRate = reader.ReadBytes(3);
            CompressionType = reader.ReadByte();
            PulseCount = reader.ReadUInt32();
            var length = (int)BlockLength - 4 /* PauseAfter*/ - 3 /* SamplingRate */
                - 1 /* CompressionType */ - 4 /* PulseCount */;
            Data = reader.ReadBytes(length);
        }

        /// <summary>
        /// Writes the content of the block to the specified binary stream.
        /// </summary>
        /// <param name="writer">Stream to write the block to</param>
        public override void WriteTo(BinaryWriter writer)
        {
            writer.Write(BlockLength);
            writer.Write(PauseAfter);
            writer.Write(SamplingRate);
            writer.Write(CompressionType);
            writer.Write(PulseCount);
            writer.Write(Data);
        }

        /// <summary>
        /// Override this method to check the content of the block
        /// </summary>
        public override bool IsValid => BlockLength == 4 + 3 + 1 + 4 + Data.Length;
    }
}


text:
import { Injectable, EventEmitter } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from "@angular/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthenticationService {
  public userLoggedIn = new EventEmitter();

  constructor(private http: Http) { }

  login(username: string, password: string) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let body = JSON.stringify({ username: username, password: password });
    console.log('username/password:', body);
    return this.http.post('http://localhost:3032/authenticate', body, options)
      .map((response: Response) => {
        // login successful if there's a jwt token in the response
        let user = response.json();
        if (user && user.token) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
          this.userLoggedIn.emit(user);
        }
      });
  }

  logout() {
      // remove user from local storage to log user out
      localStorage.removeItem('currentUser');
  }
}


text:
package io.druid.java.util.emitter.factory;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.druid.java.util.common.lifecycle.Lifecycle;
import io.druid.java.util.emitter.core.Emitter;
import io.druid.java.util.emitter.core.NoopEmitter;
import org.asynchttpclient.AsyncHttpClient;

public class NoopEmitterFactory implements EmitterFactory
{
  @Override
  public Emitter makeEmitter(ObjectMapper objectMapper, AsyncHttpClient httpClient, Lifecycle lifecycle)
  {
    return makeEmitter(lifecycle);
  }

  public Emitter makeEmitter(Lifecycle lifecycle)
  {
    Emitter retVal = new NoopEmitter();
    lifecycle.addManagedInstance(retVal);
    return retVal;
  }
}


text:
/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include <cmath>

#include "vast/base.hpp"
#include "vast/value_index.hpp"

namespace vast {

// -- value_index --------------------------------------------------------------

value_index::value_index(vast::type x) : type_{std::move(x)} {
  // nop
}

value_index::~value_index() {
  // nop
}

expected<void> value_index::append(data_view x) {
  return append(x, offset());
}

expected<void> value_index::append(data_view x, id pos) {
  auto off = mask_.size();
  if (pos < off)
    // Can only append at the end
    return make_error(ec::unspecified, pos, '<', off);
  if (caf::holds_alternative<caf::none_t>(x)) {
    none_.append_bits(false, pos - none_.size());
    none_.append_bit(true);
  } else if (!append_impl(x, pos)) {
    return make_error(ec::unspecified, "append_impl");
  }
  mask_.append_bits(false, pos - off);
  mask_.append_bit(true);
  return {};
}

expected<ids> value_index::lookup(relational_operator op, data_view x) const {
  if (caf::holds_alternative<caf::none_t>(x)) {
    if (op == equal)
      return none_ & mask_;
    if (op == not_equal)
      return ~none_ & mask_;
    return make_error(ec::unsupported_operator, op);
  }
  auto result = lookup_impl(op, x);
  if (!result)
    return result;
  return (*result - none_) & mask_;
}

value_index::size_type value_index::offset() const {
  return mask_.size();
}

const type& value_index::type() const {
  return type_;
}

caf::error value_index::serialize(caf::serializer& sink) const {
  return sink(mask_, none_);
}

caf::error value_index::deserialize(caf::deserializer& source) {
  return source(mask_, none_);
}

caf::error inspect(caf::serializer& sink, const value_index& x) {
  return x.serialize(sink);
}

caf::error inspect(caf::deserializer& source, value_index& x) {
  return x.deserialize(source);
}

caf::error inspect(caf::serializer& sink, const value_index_ptr& x) {
  static auto nullptr_type = type{};
  if (x == nullptr)
    return sink(nullptr_type);
  return caf::error::eval([&] { return sink(x->type()); },
                          [&] { return x->serialize(sink); });
}

caf::error inspect(caf::deserializer& source, value_index_ptr& x) {
  type t;
  if (auto err = source(t))
    return err;
  if (caf::holds_alternative<none_type>(t)) {
    x = nullptr;
    return caf::none;
  }
  x = factory<value_index>::make(std::move(t));
  if (x == nullptr)
    return make_error(ec::unspecified, "failed to construct value index");
  return x->deserialize(source);
}

// -- string_index -------------------------------------------------------------

string_index::string_index(vast::type t, size_t max_length)
  : value_index{std::move(t)},
    max_length_{max_length} {
}

caf::error string_index::serialize(caf::serializer& sink) const {
  return caf::error::eval([&] { return value_index::serialize(sink); },
                          [&] { return sink(max_length_, length_, chars_); });
}

caf::error string_index::deserialize(caf::deserializer& source) {
  return caf::error::eval([&] { return value_index::deserialize(source); },
                          [&] { return source(max_length_, length_, chars_); });
}

void string_index::init() {
  if (length_.coder().storage().empty()) {
    size_t components = std::log10(max_length_);
    if (max_length_ % 10 != 0)
      ++components;
    length_ = length_bitmap_index{base::uniform(10, components)};
  }
}

bool string_index::append_impl(data_view x, id pos) {
  auto str = caf::get_if<view<std::string>>(&x);
  if (!str)
    return false;
  init();
  auto length = str->size();
  if (length > max_length_)
    length = max_length_;
  if (length > chars_.size())
    chars_.resize(length, char_bitmap_index{8});
  for (auto i = 0u; i < length; ++i) {
    chars_[i].skip(pos - chars_[i].size());
    chars_[i].append(static_cast<uint8_t>((*str)[i]));
  }
  length_.skip(pos - length_.size());
  length_.append(length);
  return true;
}

expected<ids>
string_index::lookup_impl(relational_operator op, data_view x) const {
  return caf::visit(detail::overload(
    [&](auto x) -> expected<ids> {
      return make_error(ec::type_clash, materialize(x));
    },
    [&](view<std::string> str) -> expected<ids> {
      auto str_size = str.size();
      if (str_size > max_length_)
        str_size = max_length_;
      switch (op) {
        default:
          return make_error(ec::unsupported_operator, op);
        case equal:
        case not_equal: {
          if (str_size == 0) {
            auto result = length_.lookup(equal, 0);
            if (op == not_equal)
              result.flip();
            return result;
          }
          if (str_size > chars_.size())
            return ids{offset(), op == not_equal};
          auto result = length_.lookup(less_equal, str_size);
          if (all<0>(result))
            return ids{offset(), op == not_equal};
          for (auto i = 0u; i < str_size; ++i) {
            auto b = chars_[i].lookup(equal, static_cast<uint8_t>(str[i]));
            result &= b;
            if (all<0>(result))
              return ids{offset(), op == not_equal};
          }
          if (op == not_equal)
            result.flip();
          return result;
        }
        case ni:
        case not_ni: {
          if (str_size == 0)
            return ids{offset(), op == ni};
          if (str_size > chars_.size())
            return ids{offset(), op == not_ni};
          // TODO: Be more clever than iterating over all k-grams (#45).
          ids result{offset(), false};
          for (auto i = 0u; i < chars_.size() - str_size + 1; ++i) {
            ids substr{offset(), true};
            auto skip = false;
            for (auto j = 0u; j < str_size; ++j) {
              auto bm = chars_[i + j].lookup(equal, str[j]);
              if (all<0>(bm)) {
                skip = true;
                break;
              }
              substr &= bm;
            }
            if (!skip)
              result |= substr;
          }
          if (op == not_ni)
            result.flip();
          return result;
        }
      }
    },
    [&](view<vector> xs) { return detail::container_lookup(*this, op, xs); },
    [&](view<set> xs) { return detail::container_lookup(*this, op, xs); }
  ), x);
}

// -- address_index ------------------------------------------------------------

caf::error address_index::serialize(caf::serializer& sink) const {
  return caf::error::eval([&] { return value_index::serialize(sink); },
                          [&] { return sink(bytes_, v4_); });
}

caf::error address_index::deserialize(caf::deserializer& source) {
  return caf::error::eval([&] { return value_index::deserialize(source); },
                          [&] { return source(bytes_, v4_); });
}

void address_index::init() {
  if (bytes_[0].coder().storage().empty())
    // Initialize on first to make deserialization feasible.
    bytes_.fill(byte_index{8});
}

bool address_index::append_impl(data_view x, id pos) {
  init();
  auto addr = caf::get_if<view<address>>(&x);
  if (!addr)
    return false;
  auto& bytes = addr->data();
  for (auto i = 0u; i < 16; ++i) {
    bytes_[i].skip(pos - bytes_[i].size());
    bytes_[i].append(bytes[i]);
  }
  v4_.skip(pos - v4_.size());
  v4_.append(addr->is_v4());
  return true;
}

expected<ids>
address_index::lookup_impl(relational_operator op, data_view d) const {
  return caf::visit(detail::overload(
    [&](auto x) -> expected<ids> {
      return make_error(ec::type_clash, materialize(x));
    },
    [&](view<address> x) -> expected<ids> {
      if (!(op == equal || op == not_equal))
        return make_error(ec::unsupported_operator, op);
      auto result = x.is_v4() ? v4_.coder().storage() : ids{offset(), true};
      for (auto i = x.is_v4() ? 12u : 0u; i < 16; ++i) {
        auto bm = bytes_[i].lookup(equal, x.data()[i]);
        result &= bm;
        if (all<0>(result))
          return ids{offset(), op == not_equal};
      }
      if (op == not_equal)
        result.flip();
      return result;
    },
    [&](view<subnet> x) -> expected<ids> {
      if (!(op == in || op == not_in))
        return make_error(ec::unsupported_operator, op);
      auto topk = x.length();
      if (topk == 0)
        return make_error(ec::unspecified, "invalid IP subnet length: ", topk);
      auto is_v4 = x.network().is_v4();
      if ((is_v4 ? topk + 96 : topk) == 128)
        // Asking for /32 or /128 membership is equivalent to an equality lookup.
        return lookup_impl(op == in ? equal : not_equal, x.network());
      auto result = is_v4 ? v4_.coder().storage() : ids{offset(), true};
      auto& bytes = x.network().data();
      size_t i = is_v4 ? 12 : 0;
      for ( ; i < 16 && topk >= 8; ++i, topk -= 8)
        result &= bytes_[i].lookup(equal, bytes[i]);
      for (auto j = 0u; j < topk; ++j) {
        auto bit = 7 - j;
        auto& bm = bytes_[i].coder().storage()[bit];
        result &= (bytes[i] >> bit) & 1 ? ~bm : bm;
      }
      if (op == not_in)
        result.flip();
      return result;
    },
    [&](view<vector> xs) { return detail::container_lookup(*this, op, xs); },
    [&](view<set> xs) { return detail::container_lookup(*this, op, xs); }
  ), d);
}

// -- subnet_index -------------------------------------------------------------

subnet_index::subnet_index(vast::type x)
  : value_index{std::move(x)},
    network_{address_type{}} {
  // nop
}

caf::error subnet_index::serialize(caf::serializer& sink) const {
  return caf::error::eval([&] { return value_index::serialize(sink); },
                          [&] { return sink(network_, length_); });
}

caf::error subnet_index::deserialize(caf::deserializer& source) {
  return caf::error::eval([&] { return value_index::deserialize(source); },
                          [&] { return source(network_, length_); });
}

void subnet_index::init() {
  if (length_.coder().storage().empty())
    length_ = prefix_index{128 + 1}; // Valid prefixes range from /0 to /128.
}

bool subnet_index::append_impl(data_view x, id pos) {
  if (auto sn = caf::get_if<view<subnet>>(&x)) {
    init();
    length_.skip(pos - length_.size());
    length_.append(sn->length());
    return static_cast<bool>(network_.append(sn->network(), pos));
  }
  return false;
}

expected<ids>
subnet_index::lookup_impl(relational_operator op, data_view d) const {
  return caf::visit(detail::overload(
    [&](auto x) -> expected<ids> {
      return make_error(ec::type_clash, materialize(x));
    },
    [&](view<address> x) -> expected<ids> {
      if (!(op == ni || op == not_ni))
        return make_error(ec::unsupported_operator, op);
      auto result = ids{offset(), false};
      uint8_t bits = x.is_v4() ? 32 : 128;
      for (uint8_t i = 0; i <= bits; ++i) { // not an off-by-one
        auto masked = x;
        masked.mask(128 - bits + i);
        ids len = length_.lookup(equal, i);
        auto net = network_.lookup(equal, masked);
        if (!net)
          return net;
        len &= *net;
        result |= len;
      }
      if (op == not_ni)
        result.flip();
      return result;
    },
    [&](view<subnet> x) -> expected<ids> {
      switch (op) {
        default:
          return make_error(ec::unsupported_operator, op);
        case equal:
        case not_equal: {
          auto result = network_.lookup(equal, x.network());
          if (!result)
            return result;
          auto n = length_.lookup(equal, x.length());
          *result &= n;
          if (op == not_equal)
            result->flip();
          return result;
        }
        case in:
        case not_in: {
          // For a subnet index U and subnet x, the in operator signifies a
          // subset relationship such that `U in x` translates to U ⊆ x, i.e.,
          // the lookup returns all subnets in U that are a subset of x.
          auto result = network_.lookup(in, x);
          if (!result)
            return result;
          *result &= length_.lookup(greater_equal, x.length());
          if (op == not_in)
            result->flip();
          return result;
        }
        case ni:
        case not_ni: {
          // For a subnet index U and subnet x, the ni operator signifies a
          // subset relationship such that `U ni x` translates to U ⊇ x, i.e.,
          // the lookup returns all subnets in U that include x.
          ids result;
          for (auto i = uint8_t{1}; i <= x.length(); ++i) {
            auto xs = network_.lookup(in, subnet{x.network(), i});
            if (!xs)
              return xs;
            *xs &= length_.lookup(equal, i);
            result |= *xs;
          }
          if (op == not_ni)
            result.flip();
          return result;
        }
      }
    },
    [&](view<vector> xs) { return detail::container_lookup(*this, op, xs); },
    [&](view<set> xs) { return detail::container_lookup(*this, op, xs); }
  ), d);
}

// -- port_index ---------------------------------------------------------------

caf::error port_index::serialize(caf::serializer& sink) const {
  return caf::error::eval([&] { return value_index::serialize(sink); },
                          [&] { return sink(num_, proto_); });
}

caf::error port_index::deserialize(caf::deserializer& source) {
  return caf::error::eval([&] { return value_index::deserialize(source); },
                          [&] { return source(num_, proto_); });
}

void port_index::init() {
  if (num_.coder().storage().empty()) {
    num_ = number_index{base::uniform(10, 5)}; // [0, 2^16)
    proto_ = protocol_index{4}; // unknown, tcp, udp, icmp
  }
}

bool port_index::append_impl(data_view x, id pos) {
  if (auto p = caf::get_if<view<port>>(&x)) {
    init();
    num_.skip(pos - num_.size());
    num_.append(p->number());
    proto_.skip(pos - proto_.size());
    proto_.append(p->type());
    return true;
  }
  return false;
}

expected<ids>
port_index::lookup_impl(relational_operator op, data_view d) const {
  if (offset() == 0) // FIXME: why do we need this check again?
    return ids{};
  return caf::visit(detail::overload(
    [&](auto x) -> expected<ids> {
      return make_error(ec::type_clash, materialize(x));
    },
    [&](view<port> x) -> expected<ids> {
      if (op == in || op == not_in)
        return make_error(ec::unsupported_operator, op);
      auto n = num_.lookup(op, x.number());
      if (all<0>(n))
        return ids{offset(), false};
      if (x.type() != port::unknown)
        n &= proto_.lookup(equal, x.type());
      return n;
    },
    [&](view<vector> xs) { return detail::container_lookup(*this, op, xs); },
    [&](view<set> xs) { return detail::container_lookup(*this, op, xs); }
  ), d);
}

// -- sequence_index -----------------------------------------------------------

sequence_index::sequence_index(vast::type t, size_t max_size)
  : value_index{std::move(t)},
    max_size_{max_size} {
  auto f = [](const auto& x) -> vast::type {
    using concrete_type = std::decay_t<decltype(x)>;
    if constexpr (detail::is_any_v<concrete_type, vector_type, set_type>)
      return x.value_type;
    else
      return none_type{};
  };
  value_type_ = caf::visit(f, value_index::type());
  VAST_ASSERT(!caf::holds_alternative<none_type>(value_type_));
}

caf::error sequence_index::serialize(caf::serializer& sink) const {
  return caf::error::eval(
    [&] { return value_index::serialize(sink); },
    [&] { return sink(elements_, size_, max_size_, value_type_); }
  );
}

caf::error sequence_index::deserialize(caf::deserializer& source) {
  return caf::error::eval(
    [&] { return value_index::deserialize(source); },
    [&] { return source(elements_, size_, max_size_, value_type_); }
  );
}

void sequence_index::init() {
  if (size_.coder().storage().empty()) {
    size_t components = std::log10(max_size_);
    if (max_size_ % 10 != 0)
      ++components;
    size_ = size_bitmap_index{base::uniform(10, components)};
  }
}

bool sequence_index::append_impl(data_view x, id pos) {
  auto f = [&](const auto& v) {
    using view_type = std::decay_t<decltype(v)>;
    if constexpr (detail::is_any_v<view_type, view<vector>, view<set>>) {
      init();
      auto seq_size = std::min(v->size(), max_size_);
      if (seq_size > elements_.size()) {
        auto old = elements_.size();
        elements_.resize(seq_size);
        for (auto i = old; i < elements_.size(); ++i) {
          elements_[i] = factory<value_index>::make(value_type_);
          VAST_ASSERT(elements_[i]);
        }
      }
      auto x = v->begin();
      for (auto i = 0u; i < seq_size; ++i)
        elements_[i]->append(*x++, pos);
      size_.skip(pos - size_.size());
      size_.append(seq_size);
      return true;
    }
    return false;
  };
  return caf::visit(f, x);
}

expected<ids>
sequence_index::lookup_impl(relational_operator op, data_view x) const {
  if (!(op == ni || op == not_ni))
    return make_error(ec::unsupported_operator, op);
  if (elements_.empty())
    return ids{};
  auto result = elements_[0]->lookup(equal, x);
  if (!result)
    return result;
  for (auto i = 1u; i < elements_.size(); ++i) {
    auto mbm = elements_[i]->lookup(equal, x);
    if (mbm)
      *result |= *mbm;
    else
      return mbm;
  }
  if (op == not_ni)
    result->flip();
  return result;
}

} // namespace vast


text:
<?xml version="1.0" ?>

<container xmlns="http://www.symfony-project.org/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.symfony-project.org/schema/dic/services http://www.symfony-project.org/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="data_collector.templates" type="collection">
            <parameter key="config">WebProfilerBundle:Profiler:config.php</parameter>
            <parameter key="request">WebProfilerBundle:Profiler:request.php</parameter>
            <parameter key="security">WebProfilerBundle:Profiler:security.php</parameter>
            <parameter key="exception">WebProfilerBundle:Profiler:exception.php</parameter>
            <parameter key="events">WebProfilerBundle:Profiler:events.php</parameter>
            <parameter key="logger">WebProfilerBundle:Profiler:logger.php</parameter>
            <parameter key="timer">WebProfilerBundle:Profiler:timer.php</parameter>
            <parameter key="memory">WebProfilerBundle:Profiler:memory.php</parameter>
            <parameter key="db">DoctrineBundle:Profiler:db.php</parameter>
            <parameter key="mongodb">DoctrineMongoDBBundle:Profiler:mongodb.php</parameter>
        </parameter>
    </parameters>
</container>


text:
import * as fs from "fs";
import * as path from "path";
import * as xml2js from "xml2js";

function main(): void {
    const args = process.argv.slice(2);
    if (args.length !== 3) {
        console.log("Usage:");
        console.log("\tnode generateLocalizedDiagnosticMessages.js <lcl source directory> <output directory> <generated diagnostics map file>");
        return;
    }

    const inputPath = args[0];
    const outputPath = args[1];
    const diagnosticsMapFilePath = args[2];

    // generate the lcg file for enu
    generateLCGFile();

    // generate other langs
    fs.readdir(inputPath, (err, files) => {
        handleError(err);
        files.forEach(visitDirectory);
    });

    return;

    function visitDirectory(name: string) {
        const inputFilePath = path.join(inputPath, name, "diagnosticMessages", "diagnosticMessages.generated.json.lcl");

        fs.readFile(inputFilePath, (err, data) => {
            handleError(err);
            xml2js.parseString(data.toString(), (err, result) => {
                handleError(err);
                if (!result || !result.LCX || !result.LCX.$ || !result.LCX.$.TgtCul) {
                    console.error("Unexpected XML file structure. Expected to find result.LCX.$.TgtCul.");
                    process.exit(1);
                }
                const outputDirectoryName = getPreferedLocaleName(result.LCX.$.TgtCul);
                if (!outputDirectoryName) {
                    console.error(`Invalid output locale name for '${result.LCX.$.TgtCul}'.`);
                    process.exit(1);
                }
                writeFile(path.join(outputPath, outputDirectoryName, "diagnosticMessages.generated.json"), xmlObjectToString(result));
            });
        });
    }

    /**
     * A locale name is based on the language tagging conventions of RFC 4646 (Windows Vista
     * and later), and is represented by LOCALE_SNAME.
     * Generally, the pattern <language>-<REGION> is used. Here, language is a lowercase ISO 639
     * language code. The codes from ISO 639-1 are used when available. Otherwise, codes from
     * ISO 639-2/T are used. REGION specifies an uppercase ISO 3166-1 country/region identifier.
     * For example, the locale name for English (United States) is "en-US" and the locale name
     * for Divehi (Maldives) is "dv-MV".
     *
     * If the locale is a neutral locale (no region), the LOCALE_SNAME value follows the
     * pattern <language>. If it is a neutral locale for which the script is significant, the
     * pattern is <language>-<Script>.
     *
     * More at https://msdn.microsoft.com/en-us/library/windows/desktop/dd373814(v=vs.85).aspx
     *
     * Most of the languages we support are neutral locales, so we want to use the language name.
     * There are three exceptions, zh-CN, zh-TW and pt-BR.
     */
    function getPreferedLocaleName(localeName: string) {
        switch (localeName) {
            case "zh-CN":
            case "zh-TW":
            case "pt-BR":
                return localeName;
            default:
                return localeName.split("-")[0];
        }
    }

    function handleError(err: null | object) {
        if (err) {
            console.error(err);
            process.exit(1);
        }
    }

    function xmlObjectToString(o: any) {
        const out: any = {};
        for (const item of o.LCX.Item[0].Item[0].Item) {
            let ItemId = item.$.ItemId;
            let val = item.Str[0].Tgt ? item.Str[0].Tgt[0].Val[0] : item.Str[0].Val[0];

            if (typeof ItemId !== "string" || typeof val !== "string") {
                console.error("Unexpected XML file structure");
                process.exit(1);
            }

            if (ItemId.charAt(0) === ";") {
                ItemId = ItemId.slice(1); // remove leading semicolon
            }

            val = val.replace(/]5D;/, "]"); // unescape `]`
            out[ItemId] = val;
        }
        return JSON.stringify(out, undefined, 2);
    }

    function ensureDirectoryExists(directoryPath: string, action: () => void) {
        fs.exists(directoryPath, exists => {
            if (!exists) {
                const basePath = path.dirname(directoryPath);
                if (basePath !== directoryPath) {
                    return ensureDirectoryExists(basePath, () => fs.mkdir(directoryPath, action));
                }
            }
            action();
        });
    }

    function writeFile(fileName: string, contents: string) {
        ensureDirectoryExists(path.dirname(fileName), () => {
            fs.writeFile(fileName, contents, handleError);
        });
    }

    function objectToList(o: Record<string, string>) {
        const list: { key: string, value: string }[] = [];
        for (const key in o) {
            list.push({ key, value: o[key] });
        }
        return list;
    }

    function generateLCGFile() {
        return fs.readFile(diagnosticsMapFilePath, (err, data) => {
            handleError(err);
            writeFile(
                path.join(outputPath, "enu", "diagnosticMessages.generated.json.lcg"),
                getLCGFileXML(
                    objectToList(JSON.parse(data.toString()))
                        .sort((a, b) => a.key > b.key ? 1 : -1)  // lcg sorted by property keys
                        .reduce((s, { key, value }) => s + getItemXML(key, value), "")
                ));
        });

        function getItemXML(key: string, value: string) {
            // escape entrt value
            value = value.replace(/]/, "]5D;");

            return `
            <Item ItemId=";${key}" ItemType="0" PsrId="306" Leaf="true">
              <Str Cat="Text">
                <Val><![CDATA[${value}]]></Val>
              </Str>
              <Disp Icon="Str" />
            </Item>`;
        }

        function getLCGFileXML(items: string) {
            return `<?xml version="1.0" encoding="utf-8"?>
<LCX SchemaVersion="6.0" Name="diagnosticMessages.generated.json" PsrId="306" FileType="1" SrcCul="en-US" xmlns="http://schemas.microsoft.com/locstudio/2006/6/lcx">
  <OwnedComments>
    <Cmt Name="Dev" />
    <Cmt Name="LcxAdmin" />
    <Cmt Name="Rccx" />
  </OwnedComments>
  <Item ItemId=";String Table" ItemType="0" PsrId="306" Leaf="false">
    <Disp Icon="Expand" Expand="true" Disp="true" LocTbl="false" />
    <Item ItemId=";Strings" ItemType="0" PsrId="306" Leaf="false">
      <Disp Icon="Str" Disp="true" LocTbl="false" />${items}
    </Item>
  </Item>
</LCX>`;
        }
    }
}

main();


text:
package feign.okhttp;

import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import feign.Feign;
import feign.FeignException;
import feign.Headers;
import feign.Logger;
import feign.RequestLine;
import feign.Response;

import static feign.Util.UTF_8;
import static feign.assertj.MockWebServerAssertions.assertThat;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;

/** Tests client-specific behavior, such as ensuring Content-Length is sent when specified. */
public class OkHttpClientTest {

  @Rule
  public final ExpectedException thrown = ExpectedException.none();
  @Rule
  public final MockWebServer server = new MockWebServer();

  @Test
  public void parsesRequestAndResponse() throws IOException, InterruptedException {
    server.enqueue(new MockResponse().setBody("foo").addHeader("Foo: Bar"));

    TestInterface api = Feign.builder()
        .client(new OkHttpClient())
        .target(TestInterface.class, "http://localhost:" + server.getPort());

    Response response = api.post("foo");

    assertThat(response.status()).isEqualTo(200);
    assertThat(response.reason()).isEqualTo("OK");
    assertThat(response.headers())
        .containsEntry("Content-Length", asList("3"))
        .containsEntry("Foo", asList("Bar"));
    assertThat(response.body().asInputStream())
        .hasContentEqualTo(new ByteArrayInputStream("foo".getBytes(UTF_8)));

    assertThat(server.takeRequest()).hasMethod("POST")
        .hasPath("/?foo=bar&foo=baz&qux=")
        .hasHeaders("Foo: Bar", "Foo: Baz", "Qux: ", "Accept: */*", "Content-Length: 3")
        .hasBody("foo");
  }

  @Test
  public void reasonPhraseIsOptional() throws IOException, InterruptedException {
    server.enqueue(new MockResponse().setStatus("HTTP/1.1 " + 200));

    TestInterface api =
        Feign.builder().target(TestInterface.class, "http://localhost:" + server.getPort());

    Response response = api.post("foo");

    assertThat(response.status()).isEqualTo(200);
    assertThat(response.reason()).isNull();
  }

  @Test
  public void parsesErrorResponse() throws IOException, InterruptedException {
    thrown.expect(FeignException.class);
    thrown.expectMessage("status 500 reading TestInterface#get(); content:\n" + "ARGHH");

    server.enqueue(new MockResponse().setResponseCode(500).setBody("ARGHH"));

    TestInterface api = Feign.builder()
        .client(new OkHttpClient())
        .target(TestInterface.class, "http://localhost:" + server.getPort());

    api.get();
  }

  @Test
  public void patch() throws IOException, InterruptedException {
    server.enqueue(new MockResponse().setBody("foo"));
    server.enqueue(new MockResponse());

    TestInterface api = Feign.builder()
        .client(new OkHttpClient())
        .target(TestInterface.class, "http://localhost:" + server.getPort());

    assertEquals("foo", api.patch(""));

    assertThat(server.takeRequest())
        .hasHeaders("Accept: text/plain", "Content-Length: 0") // Note: OkHttp adds content length.
        .hasNoHeaderNamed("Content-Type")
        .hasMethod("PATCH");
  }

  @Test
  public void safeRebuffering() throws IOException, InterruptedException {
    server.enqueue(new MockResponse().setBody("foo"));

    TestInterface api = Feign.builder()
        .client(new OkHttpClient())
        .logger(new Logger(){
          @Override
          protected void log(String configKey, String format, Object... args) {
          }
        })
        .logLevel(Logger.Level.FULL) // rebuffers the body
        .target(TestInterface.class, "http://localhost:" + server.getPort());

    api.post("foo");
  }

  /** This shows that is a no-op or otherwise doesn't cause an NPE when there's no content. */
  @Test
  public void safeRebuffering_noContent() throws IOException, InterruptedException {
    server.enqueue(new MockResponse().setResponseCode(204));

    TestInterface api = Feign.builder()
        .client(new OkHttpClient())
        .logger(new Logger(){
          @Override
          protected void log(String configKey, String format, Object... args) {
          }
        })
        .logLevel(Logger.Level.FULL) // rebuffers the body
        .target(TestInterface.class, "http://localhost:" + server.getPort());

    api.post("foo");
  }

  @Test
  public void noResponseBodyForPost() {
      server.enqueue(new MockResponse());

      TestInterface api = Feign.builder()
          .client(new OkHttpClient())
          .target(TestInterface.class, "http://localhost:" + server.getPort());

      api.noPostBody();
  }

  @Test
  public void noResponseBodyForPut() {
      server.enqueue(new MockResponse());

      TestInterface api = Feign.builder()
              .client(new OkHttpClient())
              .target(TestInterface.class, "http://localhost:" + server.getPort());

      api.noPutBody();
  }

  interface TestInterface {

    @RequestLine("POST /?foo=bar&foo=baz&qux=")
    @Headers({"Foo: Bar", "Foo: Baz", "Qux: ", "Content-Type: text/plain"})
    Response post(String body);

    @RequestLine("GET /")
    @Headers("Accept: text/plain")
    String get();

    @RequestLine("PATCH /")
    @Headers("Accept: text/plain")
    String patch(String body);

    @RequestLine("POST")
    String noPostBody();

    @RequestLine("PUT")
    String noPutBody();
  }
}


text:
<?php

namespace BrasseursApplis\Arrows\Test\Unit\Domain\Id;

use BrasseursApplis\Arrows\Id\SubjectId;
use Faker\Factory;

class SubjectIdTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function itShouldAcceptAnUuid()
    {
        $faker = Factory::create();

        $uuid = $faker->uuid;
        $id = new SubjectId($uuid);

        $this->assertEquals($uuid, (string) $id);
    }

    /**
     * @test
     */
    public function itShouldNotAcceptOtherThanUuid()
    {
        $faker = Factory::create();

        $this->setExpectedException(\InvalidArgumentException::class);
        new SubjectId($faker->randomNumber());
    }
}


text:
'use strict';

export function routerDecorator($rootScope, $state, Auth) {
  'ngInject';
  // Redirect to login if route requires auth and the user is not logged in, or doesn't have required role

  $rootScope.$on('$stateChangeStart', function(event, next) {
    if (!next.authenticate) {
      return;
    }

    if (typeof next.authenticate === 'string') {
      Auth.hasRole(next.authenticate)
        .then(has => {
          if (has) {
            return;
          }

          event.preventDefault();
          return Auth.isLoggedIn()
            .then(is => {
              $state.go(is ? 'main' : 'login');
            });
        });
    } else {
      Auth.isLoggedIn()
        .then(is => {
          if (is) {
            return;
          }

          event.preventDefault();

          $state.go('login');
        });
    }
  });
}


text:
namespace todoapp.overengineered.server.Messages
{
    public class TodoCreated
    {
        public TodoCreated(string id, string text)
        {
            Id = id;
            Text = text;
        }

        public string Id { get; set; }
        public string Text { get; }
    }
}


text:
#ifndef _ATTENTIONBAR_H_
#define _ATTENTIONBAR_H_

#include <wx/panel.h>

#include <vector>
#include <map>
#include <functional>

class WXDLLIMPEXP_FWD_CORE wxStaticText;
class WXDLLIMPEXP_FWD_CORE wxStaticBitmap;
class WXDLLIMPEXP_FWD_CORE wxSizer;

/// Message to be displayed in AttentionBar
class AttentionMessage
{
public:
    /// Kind of the message
    enum Kind
    {
        Info,
        Warning,
        Error
    };

    /**
        Ctor.

        @param id   ID of the message. This ID must be globally unique within
                    the application. It is used to record this message's
                    status, i.e. if the user marked it as "don't show again"
                    etc.
        @param kind Kind of the message.
        @param text Text of the message; this should be kept reasonably short.

        @see AddToBlacklist
     */
    AttentionMessage(const wxString& id, Kind kind, const wxString& text)
        : m_id(id), m_kind(kind), m_text(text) {}

    typedef std::function<void()> Callback;

    /**
        Adds an action button to the bar. By default, a close button is shown,
        this makes it possible to add custom buttons.

        @param label    Short label for the action.
        @param callback Function to call when the button is clicked.
     */
    void AddAction(const wxString& label, Callback callback)
        { m_actions.push_back(std::make_pair(label, callback)); }

    /// Adds "Don't show again" action.
    void AddDontShowAgain();

    wxString m_id;
    Kind m_kind;
    wxString m_text;

    typedef std::pair<wxString, Callback> Action;
    typedef std::vector<Action> Actions;
    Actions m_actions;

    /**
        Adds message with given ID to blacklist, i.e. it won't be shown
        ever again.
     */
    static void AddToBlacklist(const wxString& id);

    /// Returns true if @a id is on the blacklist
    static bool IsBlacklisted(const wxString& id);

    /// Returns true if this message is on the blacklist
    bool IsBlacklisted() const { return IsBlacklisted(m_id); }
};

/**
    Attention bar is a tooltip-colored bar displayed on top of the main
    window (a la Firefox or other browsers).
 */
class AttentionBar : public wxPanel
{
public:
    AttentionBar(wxWindow *parent);

    /**
        Shows the message
        (unless the user disallowed showing this particular message.
     */
    void ShowMessage(const AttentionMessage& msg);

    /// Hides currently shown message
    void HideMessage();

private:
    void OnClose(wxCommandEvent& event);
    void OnAction(wxCommandEvent& event);
#if defined(__WXMAC__) || defined(__WXMSW__)
    void OnPaint(wxPaintEvent& event);
#endif

private:
    wxStaticBitmap *m_icon;
    wxStaticText *m_label;
    wxSizer *m_buttons;
    typedef std::map<wxObject*, AttentionMessage::Callback> ActionsMap;
    ActionsMap m_actions;

    DECLARE_EVENT_TABLE()
};

#endif // _ATTENTIONBAR_H_


text:
on('ready', () => {
    const sname = 'Standby';
    const StandbyIcon = 'interdiction';

    class Status {
        constructor(type, value) {
            this.Type = type;
            this.Value = value;
        }
    }

    const GetStatuses = (token) => {
        const rawStatus = token.get('statusmarkers');
        const oldStatusArray = rawStatus.split(',');
        const newStatusArray = [];
        let previousType = false;
        let prevStatus = null;
        oldStatusArray.forEach((entry) => {
            const statusFields = entry.split('@');
            const type = statusFields[0];
            const value = statusFields.length > 1
                ? statusFields[1]
                : true;
            let newStatus = null;
            // If we've already gotten one of this kind, we're seeing a duplicate, so add to previous
            if (type === previousType) {
                newStatus = prevStatus;
                prevStatus.Value = prevStatus.Value + value;
            } else {
                newStatus = new Status(type, value);
                newStatusArray.push(newStatus);
            }
            previousType = type;
            prevStatus = newStatus;
        });
        return newStatusArray;
    };

    const GetStatusValue = (token, type) => {
        const statuses = GetStatuses(token);
        for(let i = 0; i < statuses.length; i++) {
            const curStatus = statuses[i];
            if (type === curStatus.Type) {
                const intVal = parseInt(curStatus.Value);
                if (isNaN(intVal)) {
                    return curStatus.Value;
                } else {
                    return intVal;
                }
            }
        }
        return false;
    };

    const StringifyStatus = (status) => {
        if (status.Value === true) {
            return status.Type;
        } else {
            const strVal = status.Value + "";
            const digitArray = strVal.split('');
            const valArray = [];
            for (let i = 0; i < digitArray.length; i++) {
                let char = digitArray[i];
                valArray.push(status.Type + '@' + char);
            }
            return valArray.join(',');
        }
    };

    const UpdateStatusValue = (token, type, value) => {
        let alreadyExists = false;
        const statuses = GetStatuses(token);
        for(let i = 0; i < statuses.length; i++) {
            const curStatus = statuses[i];
            if (type === curStatus.Type) {
                curStatus.Value = value;
                alreadyExists = true;
                break;
            }
        }
        if (!alreadyExists) {
            statuses.push(new Status(type, value));
        }
        const statusStrings = [];
        for (let i = 0; i < statuses.length; i++) {
            const curStatus = statuses[i];
            statusStrings.push(StringifyStatus(curStatus));
        }
        const statusString = statusStrings.join(',');
        token.set('statusmarkers', statusString);
        return value;
    };

    on('chat:message', (msg) => {
        if (msg.type !== 'api') return;
        if (msg.content.startsWith('!standby') !== true) return;
        if (!msg.selected) {
            sendChat(sname, '/w gm Error: You must have tokens selected to use this script.');
            return;
        }
        const isYank = msg.content.endsWith('yank');
        const oldOrderStr = Campaign().get('turnorder');
        if(oldOrderStr === '' || oldOrderStr === '[]') {
            sendChat(sname, '/w gm Error: No initiative is loaded.');
            return;
        }
        const oldOrder = JSON.parse(oldOrderStr);
        const yankedIds = {};
        let yankCount = 0;
        const restoredObjs = [];// NOTE: These are not yet in the string format required
        msg.selected.forEach((selection) => {
            let token = getObj('graphic', selection._id);

            // Yank it from initiative order and write
            if (isYank) {
                let pr = -1;
                for (let i = 0; i < oldOrder.length; i++) {
                    const entry = oldOrder[i];
                    if (entry.id === selection._id) {
                        pr = parseFloat(entry.pr);
                        yankedIds[entry.id] = true;
                        yankCount++;
                        break;
                    }
                }
                // Don't do anything if it wasn't in init order
                if (pr === -1) {
                    return;
                }
                const noDecimal = 100*pr;
                token.set(StandbyIcon, "" + noDecimal);
                UpdateStatusValue(token, StandbyIcon, noDecimal);
            }
            // Add back to initiative order and remove status value
            else {
                const statusVal = GetStatusValue(token, StandbyIcon);
                if (isNaN(statusVal)) {
                    return;
                }
                const initVal = statusVal / 100;
                restoredObjs.push({
                    id: selection._id,
                    pr: initVal
                });
                token.set(StandbyIcon, false);
                UpdateStatusValue(token, StandbyIcon, false);
            }
        });

        // Yank out the chosen ids
        if (isYank) {
            if (yankCount === 0) {
                sendChat(sname, '/w gm Error: no yankable tokens selected.');
                return;
            }
            const newOrder = [];

            for (let i = 0; i < oldOrder.length; i++) {
                const entry = oldOrder[i];
                if (!yankedIds[entry.id]) {
                    newOrder.push(entry);
                }
            }

            // Set
            Campaign().set('turnorder', JSON.stringify(newOrder));
        }
        // Insert the chosen ids, accounting for the circular nature of initiative
        else {
            if (restoredObjs.length === 0) {
                sendChat(sname, '/w gm Error: no restorable tokens selected.');
                return;
            }
            // Sort the restored list
            restoredObjs.sort((a, b) => (a.pr > b.pr ? -1 : 1));

            // Get the location of the maximum so we know the offset in the future.
            let maxVal = -2;
            const sortableOld = [];
            let oldStarterPR = 0;
            for (let i = 0; i < oldOrder.length; i++) {
                const entry = oldOrder[i];
                const val = parseFloat(entry.pr);
                sortableOld.push({
                    id: entry.id,
                    pr: val
                })
                if (i === 0) {
                    oldStarterPR = entry.id;
                }
                if (val > maxVal) {
                    maxVal = val;
                }
            }
            sortableOld.sort((a, b) => (a.pr > b.pr ? -1 : 1));

            // Merge the lists into one sorted list
            let oldIndex = 0;
            let newIndex = 0;
            const merged = [];
            for (let i = 0; i < restoredObjs.length + sortableOld.length; i++){
                if (oldIndex === sortableOld.length) {
                    merged.push(restoredObjs[newIndex]);
                    newIndex++;
                    continue;
                } else if (newIndex === restoredObjs.length) {
                    merged.push(sortableOld[oldIndex]);
                    oldIndex++;
                    continue;
                }

                let oldEntry = sortableOld[oldIndex];
                let newEntry = restoredObjs[newIndex];
                if (oldEntry.pr >= newEntry.pr) {
                    merged.push(oldEntry);
                    oldIndex++;
                }
                if (oldEntry.pr <= newEntry.pr) {
                    merged.push(newEntry);
                    newIndex++;
                }

                // If there was a tie, increment i an extra time so we don't overrun the end
                if (oldEntry.pr === newEntry.pr) {
                    i++;
                }
            }

            // Rotate array
            while (merged[0].id !== oldStarterPR) {
                merged.push(merged.shift());
            }

            // Set
            Campaign().set('turnorder', JSON.stringify(merged));
            sendChat(sname, '/w gm Turn Order restored.');
        }
    });
});
//if (MarkStop) MarkStop('Standby');


text:
match 42:
    case x | <warning descr="This code is unreachable">42</warning>:
        pass


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class com.oregonscientific.meep.database.Model
</TITLE>

<META NAME="date" CONTENT="2013-04-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
com.oregonscientific.meep.database.Model

Packages that use Model

com.oregonscientific.meep.database

com.oregonscientific.meep.log

com.oregonscientific.meep.notification

com.oregonscientific.meep.permission

com.oregonscientific.meep.recommendation

Uses of Model in com.oregonscientific.meep.database

Fields in com.oregonscientific.meep.database with type parameters of type Model

static Parcelable.Creator<Model<?,?>>
Model.CREATOR

          Implement the Parcelable interface

Uses of Model in com.oregonscientific.meep.log

Subclasses of Model in com.oregonscientific.meep.log

 class
Log

          The Log object that represents a log object in the underlying datastore

Uses of Model in com.oregonscientific.meep.notification

Subclasses of Model in com.oregonscientific.meep.notification

 class
Notification

          The Notification object that represents a notification object in the
 underlying datastore

 class
NotificationType

          The NotificationType object that represents a notificationType object in the
 underlying datastore

Uses of Model in com.oregonscientific.meep.permission

Subclasses of Model in com.oregonscientific.meep.permission

 class
BadWord

          The BadWord object that represents a badWord object in the underlying
 datastore

 class
Blacklist

          The Blacklist object that represents a blacklist object in the underlying
 datastore

 class
Category

          The Category object that represents a category object in the underlying
 datastore

 class
Component

          The Component object that represents a component object in the underlying
 datastore

 class
ComponentCategory

          The ComponentCategory object that represents a componentCategory object in
 the underlying datastore

 class
Permission

          The Permission object that represents a permission object in the underlying
 datastore

 class
User

          The User object that represents an account object in the underlying datastore

Uses of Model in com.oregonscientific.meep.recommendation

Subclasses of Model in com.oregonscientific.meep.recommendation

 class
Recommendation

          The Recommendation object that represents a recommendation object in the
 underlying datastore

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
#ifndef GCVCommon_h
#define GCVCommon_h

#import <Foundation/Foundation.h>
#import <GLKit/GLKit.h>
#import <CoreText/CoreText.h>
#import "GCVLog.h"

#define GCVWeakSelf    __weak __typeof(self) weakSelf = self;
#define GCVStrongSelf  __strong __typeof(weakSelf) strongSelf = weakSelf;
#define GCVStrongSelfSafe  GCVStrongSelf;if (!strongSelf) return;

#define GCVSharedInstanceIMP \
static id sharedInstance = nil; \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
sharedInstance = [[self alloc] init]; \
}); \
return sharedInstance;

/**
 * Called when image load finished.
 * @param image     The current image
 * @param error     error
 * @param finished  image load reuslt
 * @param imageURL  URL
 */
typedef void(^GCVLoadImageCompletion)(UIImage *image, NSError *error, BOOL finished, NSURL *imageURL);

/**
 * GCVImageLoaderProtocol, definiton load image Protocol.
 * plugin implement use SDWebImage
 */
@protocol GCVImageLoaderProtocol

@optional
/**
 *  Load image from url, call completion.
 *  @param  url         image url
 *  @param  completion  GCVLoadImageCompletion
 */
- (void)loadImage:(NSURL*)url completed:(GCVLoadImageCompletion)completion;
@end

/**
 * GCVImageCache, image relevant class with property, UIImage、textureId and id form JS image
 */
@interface GCVImageCache : NSObject

@property(nonatomic, assign) CGFloat width;

@property(nonatomic, assign) CGFloat height;

@property(nonatomic, strong) UIImage* image;

/**
 * UIImage bind to textureId, see GCVCommon:bindTexture.
 */
//@property(nonatomic, assign) GLuint textureId;

/**
 * An auto increase id, match with imageStr, from JavaScript
 */
@property (nonatomic, assign) NSUInteger jsTextreId;

@end

@interface GCVCommon : NSObject

/**
 * GCVImageLoaderProtocol delegate
 */
@property(nonatomic, weak) id<GCVImageLoaderProtocol> imageLoader;

+ (instancetype)sharedInstance;

/**
 * Bind a UIImage to a textureId.
 * @param image         current image
 *
 * return textureId
 */
+ (GLuint)bindTexture:(UIImage *)image;

/**
 * Create image with text 2d textureId.
 * @param target        [in] textureId
 * @param image         [out] UIImage
 */
//+ (void)textImage2D:(GLenum)target withImage:(UIImage *)image;

/**
 * Preload image with imageStr and idFromJS, when image load finished call completion with GCVImageCache.
 * @param imageStr      current image source
 * @param completion    callback preload
 */
- (void)addPreLoadImage:(NSString *)imageStr completion:(void (^)(GCVImageCache*, BOOL))completion;

/**
 * Fetch cached GCVImageCache with imageStr.
 * @param imageStrkey      current image source as key, format:instance_url
 *
 * return GCVImageCache object if exist, or nil
 */
- (GCVImageCache *)fetchLoadImage:(NSString *)imageStrkey;

/**
 * remove cached GCVImageCache with imageStr.
 * @param imageStrKey      current image source as key, format:instance_url
 *
 */
- (void)removeLoadImage:(NSString*)imageStrKey;

/**
 * Clear all preload and hadload image cache.
 */
- (void)clearLoadImageDict;

@end

#endif /* GCVCommon_h */