text:
package com.google.api.ads.adwords.jaxws.v201409.rm;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Represents a UserList object that is sent over the wire.
 *             This is a list of users an account may target.
 *
 *
 *
Java class for UserList complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="UserList">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
 *         <element name="isReadOnly" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="status" type="{https://adwords.google.com/api/adwords/rm/v201409}UserListMembershipStatus" minOccurs="0"/>
 *         <element name="integrationCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="accessReason" type="{https://adwords.google.com/api/adwords/rm/v201409}AccessReason" minOccurs="0"/>
 *         <element name="accountUserListStatus" type="{https://adwords.google.com/api/adwords/rm/v201409}AccountUserListStatus" minOccurs="0"/>
 *         <element name="membershipLifeSpan" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
 *         <element name="size" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
 *         <element name="sizeRange" type="{https://adwords.google.com/api/adwords/rm/v201409}SizeRange" minOccurs="0"/>
 *         <element name="sizeForSearch" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
 *         <element name="sizeRangeForSearch" type="{https://adwords.google.com/api/adwords/rm/v201409}SizeRange" minOccurs="0"/>
 *         <element name="listType" type="{https://adwords.google.com/api/adwords/rm/v201409}UserListType" minOccurs="0"/>
 *         <element name="UserList.Type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UserList", propOrder = {
    "id",
    "isReadOnly",
    "name",
    "description",
    "status",
    "integrationCode",
    "accessReason",
    "accountUserListStatus",
    "membershipLifeSpan",
    "size",
    "sizeRange",
    "sizeForSearch",
    "sizeRangeForSearch",
    "listType",
    "userListType"
})
@XmlSeeAlso({
    BasicUserList.class,
    SimilarUserList.class,
    LogicalUserList.class,
    RuleBasedUserList.class,
    ExternalRemarketingUserList.class
})
public class UserList {

    protected Long id;
    protected Boolean isReadOnly;
    protected String name;
    protected String description;
    protected UserListMembershipStatus status;
    protected String integrationCode;
    protected AccessReason accessReason;
    protected AccountUserListStatus accountUserListStatus;
    protected Long membershipLifeSpan;
    protected Long size;
    protected SizeRange sizeRange;
    protected Long sizeForSearch;
    protected SizeRange sizeRangeForSearch;
    protected UserListType listType;
    @XmlElement(name = "UserList.Type")
    protected String userListType;

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getId() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setId(Long value) {
        this.id = value;
    }

    /**
     * Gets the value of the isReadOnly property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isIsReadOnly() {
        return isReadOnly;
    }

    /**
     * Sets the value of the isReadOnly property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setIsReadOnly(Boolean value) {
        this.isReadOnly = value;
    }

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the description property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDescription() {
        return description;
    }

    /**
     * Sets the value of the description property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDescription(String value) {
        this.description = value;
    }

    /**
     * Gets the value of the status property.
     *
     * @return
     *     possible object is
     *     {@link UserListMembershipStatus }
     *
     */
    public UserListMembershipStatus getStatus() {
        return status;
    }

    /**
     * Sets the value of the status property.
     *
     * @param value
     *     allowed object is
     *     {@link UserListMembershipStatus }
     *
     */
    public void setStatus(UserListMembershipStatus value) {
        this.status = value;
    }

    /**
     * Gets the value of the integrationCode property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getIntegrationCode() {
        return integrationCode;
    }

    /**
     * Sets the value of the integrationCode property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setIntegrationCode(String value) {
        this.integrationCode = value;
    }

    /**
     * Gets the value of the accessReason property.
     *
     * @return
     *     possible object is
     *     {@link AccessReason }
     *
     */
    public AccessReason getAccessReason() {
        return accessReason;
    }

    /**
     * Sets the value of the accessReason property.
     *
     * @param value
     *     allowed object is
     *     {@link AccessReason }
     *
     */
    public void setAccessReason(AccessReason value) {
        this.accessReason = value;
    }

    /**
     * Gets the value of the accountUserListStatus property.
     *
     * @return
     *     possible object is
     *     {@link AccountUserListStatus }
     *
     */
    public AccountUserListStatus getAccountUserListStatus() {
        return accountUserListStatus;
    }

    /**
     * Sets the value of the accountUserListStatus property.
     *
     * @param value
     *     allowed object is
     *     {@link AccountUserListStatus }
     *
     */
    public void setAccountUserListStatus(AccountUserListStatus value) {
        this.accountUserListStatus = value;
    }

    /**
     * Gets the value of the membershipLifeSpan property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getMembershipLifeSpan() {
        return membershipLifeSpan;
    }

    /**
     * Sets the value of the membershipLifeSpan property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setMembershipLifeSpan(Long value) {
        this.membershipLifeSpan = value;
    }

    /**
     * Gets the value of the size property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getSize() {
        return size;
    }

    /**
     * Sets the value of the size property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setSize(Long value) {
        this.size = value;
    }

    /**
     * Gets the value of the sizeRange property.
     *
     * @return
     *     possible object is
     *     {@link SizeRange }
     *
     */
    public SizeRange getSizeRange() {
        return sizeRange;
    }

    /**
     * Sets the value of the sizeRange property.
     *
     * @param value
     *     allowed object is
     *     {@link SizeRange }
     *
     */
    public void setSizeRange(SizeRange value) {
        this.sizeRange = value;
    }

    /**
     * Gets the value of the sizeForSearch property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getSizeForSearch() {
        return sizeForSearch;
    }

    /**
     * Sets the value of the sizeForSearch property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setSizeForSearch(Long value) {
        this.sizeForSearch = value;
    }

    /**
     * Gets the value of the sizeRangeForSearch property.
     *
     * @return
     *     possible object is
     *     {@link SizeRange }
     *
     */
    public SizeRange getSizeRangeForSearch() {
        return sizeRangeForSearch;
    }

    /**
     * Sets the value of the sizeRangeForSearch property.
     *
     * @param value
     *     allowed object is
     *     {@link SizeRange }
     *
     */
    public void setSizeRangeForSearch(SizeRange value) {
        this.sizeRangeForSearch = value;
    }

    /**
     * Gets the value of the listType property.
     *
     * @return
     *     possible object is
     *     {@link UserListType }
     *
     */
    public UserListType getListType() {
        return listType;
    }

    /**
     * Sets the value of the listType property.
     *
     * @param value
     *     allowed object is
     *     {@link UserListType }
     *
     */
    public void setListType(UserListType value) {
        this.listType = value;
    }

    /**
     * Gets the value of the userListType property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUserListType() {
        return userListType;
    }

    /**
     * Sets the value of the userListType property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUserListType(String value) {
        this.userListType = value;
    }

}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @fileoverview Enforce no accesskey attribute on element.
 * @author Ethan Cohen
 */

// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------

import { getProp, getPropValue } from 'jsx-ast-utils';

const errorMessage = 'No access key attribute allowed. Inconsistencies ' +
  'between keyboard shortcuts and keyboard comments used by screenreader ' +
  'and keyboard only users create a11y complications.';

module.exports = context => ({
  JSXOpeningElement: node => {
    const accessKey = getProp(node.attributes, 'accesskey');
    const accessKeyValue = getPropValue(accessKey);

    if (accessKey && accessKeyValue) {
      context.report({
        node,
        message: errorMessage,
      });
    }
  },
});

module.exports.schema = [
  { type: 'object' },
];


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

<title>Clickjacking</title>

Clickjacking

<button type="button">Click me!</button>


text:
var logfmt = require('../logfmt'),
    assert = require('assert');

suite('logfmt.parse', function() {
  test("simple flag parses", function(){
    assert.deepEqual({'hello':true}, logfmt.parse('hello'));
  })

  test("simple key/value parses", function(){
    assert.deepEqual({'hello':'kitty'}, logfmt.parse('hello=kitty'));
  })

  test("simple boolean parses", function(){
    assert.deepEqual({'foo':true, 'bar':false},
      logfmt.parse('foo=true bar=false'));
  })

  test('big numbers dont lose precision', function(){
    var parsed = logfmt.parse("thing=90071992547409934");
    assert.equal(parsed.thing.toString(), '90071992547409934');
  })

  test("number parse to strings", function(){
    assert.deepEqual({'foo':'123', 'bar':'456.789'},
      logfmt.parse('foo=123 bar=456.789'));
  })

  test("string with escapes", function(){
    assert.deepEqual({'hello':"\'kitty\'"},
      logfmt.parse('hello="\'kitty\'"'));
    assert.deepEqual({'hello':"\'kitty\'"},
      logfmt.parse('hello=\'kitty\''));
  })

  test("string with equals", function(){
    assert.deepEqual({foo:"hello=kitty"}, logfmt.parse('foo="hello=kitty"'));
  })

  test("readme string parses", function(){
    var test_string = "foo=bar a=14 baz=\"hello kitty\" "
    test_string += "cool%story=bro f %^asdf ";
    test_string += "code=H12 path=/hello/user@foo.com/close";
    var result = logfmt.parse(test_string)
    assert.equal( "H12", result["code"])
    assert.equal( "bar", result["foo"])
    assert.equal(14, result.a)
    assert.equal("hello kitty", result['baz'])
    assert.equal('bro', result['cool%story'])
    assert.equal(true, result.f)
    assert.equal(true, result['%^asdf'])
    assert.equal('/hello/user@foo.com/close', result['path'])
  })
})


text:
/*
 * require.jsのコンフィグファイルです。

 * サーバ上で各ファイルが配置されたパスに合わせて書き換えて使用してください。

 * "%SND_BASE_URL%"で置換すると便利です。

 * 実例はディレクトリ Samples 以下の各サンプル内にありますので、参照してみて下さい。

 *

 * コメント * Plugins * 以下は各種プラグイン用の定義です。

 *

 * 使用しない行は消してしまって問題ありません。
 */
var require = {
//    baseUrl: "%BASE_URL%"
    paths: {
        /* snd */
        'snd': '%SND_BASE_URL%/class/snd',
        'snd.util': '%SND_BASE_URL%/class/snd.util',
        'snd.AudioDataManager': '%SND_BASE_URL%/class/required/snd.AudioDataManager',
        'snd.AudioMaster': '%SND_BASE_URL%/class/required/snd.AudioMaster',
        'snd.AudioUnit': '%SND_BASE_URL%/class/required/snd.AudioUnit',
        'snd.Exception': '%SND_BASE_URL%/class/required/snd.Exception',
        'snd.Source': '%SND_BASE_URL%/class/required/snd.Source',
        'snd.Analyser': '%SND_BASE_URL%/class/optional/snd.Analyser',
        'snd.BiquadFilter': '%SND_BASE_URL%/class/optional/snd.BiquadFilter',
        'snd.BufferSource': '%SND_BASE_URL%/class/optional/snd.BufferSource',
        'snd.Convolver': '%SND_BASE_URL%/class/optional/snd.Convolver',
        'snd.Delay': '%SND_BASE_URL%/class/optional/snd.Delay',
        'snd.DynamicsCompressor': '%SND_BASE_URL%/class/optional/snd.DynamicsCompressor',
        'snd.Envelope': '%SND_BASE_URL%/class/optional/snd.Envelope',
        'snd.Gain': '%SND_BASE_URL%/class/optional/snd.Gain',
        'snd.MediaElementAudioSource': '%SND_BASE_URL%/class/optional/snd.MediaElementAudioSource',
        'snd.MediaStreamAudioSource': '%SND_BASE_URL%/class/optional/snd.MediaStreamAudioSource',
        'snd.MediaStreamAudioDestination': '%SND_BASE_URL%/class/optional/snd.MediaStreamAudioDestination',
        'snd.OscillatorSource': '%SND_BASE_URL%/class/optional/snd.OscillatorSource',
        'snd.ScriptProcessor': '%SND_BASE_URL%/class/optional/snd.ScriptProcessor',
        'snd.Synth': '%SND_BASE_URL%/class/optional/snd.Synth',
        'snd.TimeLine': '%SND_BASE_URL%/class/optional/TimeLine/snd.TimeLine',
        'snd.TimeLineEvent': '%SND_BASE_URL%/class/optional/TimeLine/snd.TimeLineEvent',
        'snd.WaveShaper': '%SND_BASE_URL%/class/optional/snd.WaveShaper',
        'snd.Noise': '%SND_BASE_URL%/class/optional/snd.Noise',
        'snd.VinylNoise': '%SND_BASE_URL%/class/optional/snd.VinylNoise',
        'snd.MIDI': '%SND_BASE_URL%/class/optional/MIDI/snd.MIDI',
        'snd.MIDIIn': '%SND_BASE_URL%/class/optional/MIDI/snd.MIDIIn',
        'snd.MIDIOut': '%SND_BASE_URL%/class/optional/MIDI/snd.MIDIOut',
        'snd.MIDI.util': '%SND_BASE_URL%/class/optional/MIDI/snd.MIDI.util',
        /* Plugins */
        /* snd.invalid.js */
        'snd.invalid': '%SND_BASE_URL%/plugins/invalid/snd.invalid',
        'snd.invalid.Analyser': '%SND_BASE_URL%/plugins/invalid/snd.invalid.Analyser',
        'snd.invalid.BiquadFilter': '%SND_BASE_URL%/plugins/invalid/snd.invalid.BiquadFilter',
        'snd.invalid.BufferSource': '%SND_BASE_URL%/plugins/invalid/snd.invalid.BufferSource',
        'snd.invalid.Convolver': '%SND_BASE_URL%/plugins/invalid/snd.invalid.Convolver',
        'snd.invalid.Delay': '%SND_BASE_URL%/plugins/invalid/snd.invalid.Delay',
        'snd.invalid.Gain': '%SND_BASE_URL%/plugins/invalid/snd.invalid.Gain',
        'snd.invalid.Noise': '%SND_BASE_URL%/plugins/invalid/snd.invalid.Noise',
        'snd.invalid.Oscillator': '%SND_BASE_URL%/plugins/invalid/snd.invalid.Oscillator',
        /* snd.Peer.js */
        'snd.Peer': '%SND_BASE_URL%/plugins/peer/snd.Peer',
        /* snd.encrypt.js */
        'snd.encrypt': '%SND_BASE_URL%/plugins/encript/snd.encrypt',
        /* snd.three.js */
        'snd.three': '%SND_BASE_URL%/plugins/three/snd.three',
        'snd.three.util': '%SND_BASE_URL%/plugins/three/snd.three.util',
        'snd.PosDir': '%SND_BASE_URL%/plugins/three/snd.PosDir',
        'snd.Listener': '%SND_BASE_URL%/plugins/three/snd.Listener',
        'snd.SoundEnvironment': '%SND_BASE_URL%/plugins/three/snd.SoundEnvironment',
        'snd.SoundNode': '%SND_BASE_URL%/plugins/three/snd.SoundNode',
        'snd.BufferSoundNode': '%SND_BASE_URL%/plugins/three/snd.BufferSoundNode',
        'snd.MediaElementAudioNode': '%SND_BASE_URL%/plugins/three/snd.MediaElementAudioNode'
    }
};


text:
#include "imageio.h"
#include "unittest.h"

OIIO_NAMESPACE_USING;

void test_get_rest_arguments ()
{
    int ret;
    std::map <std::string, std::string> result;
    std::string base;
    std::string url = "someplace?arg1=value1&arg2=value2";
    ret = Strutil::get_rest_arguments (url, base, result);
    OIIO_CHECK_EQUAL (ret, true);
    OIIO_CHECK_EQUAL (base, "someplace");
    OIIO_CHECK_EQUAL (result["arg1"], "value1");
    OIIO_CHECK_EQUAL (result["arg2"], "value2");
    OIIO_CHECK_EQUAL (result["arg3"], "");

    result.clear();
    url = "?arg1=value1&arg2=value2";
    ret = Strutil::get_rest_arguments (url, base, result);
    OIIO_CHECK_EQUAL (ret, true);
    OIIO_CHECK_EQUAL (base, "");
    OIIO_CHECK_EQUAL (result["arg1"], "value1");
    OIIO_CHECK_EQUAL (result["arg2"], "value2");

    result.clear();
    url = "arg1=value1&arg2=value2";
    ret = Strutil::get_rest_arguments (url, base, result);
    OIIO_CHECK_EQUAL (ret, true);
    OIIO_CHECK_EQUAL (base, "arg1=value1&arg2=value2");
    OIIO_CHECK_EQUAL (result["arg1"], "");
    OIIO_CHECK_EQUAL (result["arg2"], "");

    result.clear();
    url = "";
    ret = Strutil::get_rest_arguments (url, base, result);
    OIIO_CHECK_EQUAL (ret, true);
    OIIO_CHECK_EQUAL (base, "");
    OIIO_CHECK_EQUAL (result["arg1"], "");
    OIIO_CHECK_EQUAL (result["arg2"], "");

    result.clear();
    url = "sometextwithoutasense????&&&&&arg4=val1";
    ret = Strutil::get_rest_arguments (url, base, result);
    OIIO_CHECK_EQUAL (ret, false);
    OIIO_CHECK_EQUAL (base, "sometextwithoutasense");
    OIIO_CHECK_EQUAL (result["arg1"], "");
    OIIO_CHECK_EQUAL (result["arg2"], "");
    OIIO_CHECK_EQUAL (result["arg4"], "");

    result.clear();
    url = "atext?arg1value1&arg2value2";
    ret = Strutil::get_rest_arguments (url, base, result);
    OIIO_CHECK_EQUAL (ret, false);
    OIIO_CHECK_EQUAL (base, "atext");
    OIIO_CHECK_EQUAL (result["arg1"], "");
    OIIO_CHECK_EQUAL (result["arg2"], "");

    result.clear();
    url = "atext?arg1=value1&arg2value2";
    result["arg2"] = "somevalue";
    ret = Strutil::get_rest_arguments (url, base, result);
    OIIO_CHECK_EQUAL (ret, false);
    OIIO_CHECK_EQUAL (base, "atext");
    OIIO_CHECK_EQUAL (result["arg1"], "value1");
    OIIO_CHECK_EQUAL (result["arg2"], "somevalue");
}

void test_escape_sequences ()
{
    OIIO_CHECK_EQUAL (Strutil::unescape_chars("\\\\ \\n \\r \\017"),
                      "\\ \n \r \017");
    OIIO_CHECK_EQUAL (Strutil::escape_chars("\\ \n \r"),
                      "\\\\ \\n \\r");
}

int main (int argc, char *argv[])
{
    test_get_rest_arguments ();
    test_escape_sequences ();

    return unit_test_failures;
}


text:
package eagle.jfaster.org.codec.support;

import com.google.common.base.Strings;

import static eagle.jfaster.org.constant.EagleConstants.*;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import eagle.jfaster.org.codec.Codec;
import eagle.jfaster.org.codec.Serialization;
import eagle.jfaster.org.exception.EagleFrameException;
import eagle.jfaster.org.rpc.support.EagleRequest;
import eagle.jfaster.org.rpc.support.EagleResponse;
import eagle.jfaster.org.rpc.Request;
import eagle.jfaster.org.rpc.Response;
import eagle.jfaster.org.spi.SpiInfo;
import eagle.jfaster.org.util.ReflectUtil;

import static eagle.jfaster.org.util.RequestUtil.*;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 编解码器
 *
 * 请求协议:magicCode(2个字节) + opaque(4个字节)
 * + interfaceName长度(2个字节) +interfaceName
 * + methodName长度(2个字节) + methodName
 * + parameterDesc长度(4个字节)  + parameterDesc
 * + parameterList(长度+值)
 *
 * 返回协议:magicCode(2个字节) + opaque(4个字节)
 * + className长度(2个字节) + className
 * + value
 *
 * Created by fangyanpeng1 on 2017/7/28.
 */
@SpiInfo(name = "eagle")
public class EagleCodec implements Codec {

    private static final byte[] EMPTY_BYTES = new byte[0];

    @Override
    public ByteBuffer encode(Object message, Serialization serialization) throws IOException {
        if (Response.class.isInstance(message)) { //编码response
            try {
                return encodeResponse((Response) message, serialization);
            } catch (Throwable e) {
                return encodeExceptionResponse((Response) message, serialization, e);
            }
        } else {
            return encodeRequest((Request) message, serialization);
        }
    }

    private ByteBuffer encodeExceptionResponse(Response messageRes, Serialization serialization, Throwable e) throws IOException {
        EagleResponse response = new EagleResponse();
        response.setOpaque(messageRes.getOpaque());
        response.setNeedCompress(false);
        response.setException(new EagleFrameException(e.getMessage()));
        return encodeResponse(response, serialization);
    }

    private ByteBuffer encodeResponse(Response response, Serialization serialization) throws IOException {
        short magicCode = EAGLE_MAGIC_CODE;
        if (response.isNeedCompress()) {
            magicCode |= EAGLE_COMPRESS_TYPE;
        }
        int dataLen = 10;//totalLen+magic+opaque 4+2+4
        ByteBuffer content;
        if (response.getException() != null) {
            content = encodeResponseCommon(response.getException(), dataLen, magicCode, response.getOpaque(), serialization, response.isNeedCompress(), EAGLE_RESPONSE_EXCEPTION);
        } else if (response.getValue() != null) {
            content = encodeResponseCommon(response.getValue(), dataLen, magicCode, response.getOpaque(), serialization, response.isNeedCompress(), EAGLE_RESPONSE_NORMAL);
        } else {
            content = ByteBuffer.allocate(dataLen);
            content.putInt(dataLen);
            content.putShort(magicCode);
            content.putInt(response.getOpaque());
        }
        content.flip();
        return content;

    }

    private ByteBuffer encodeResponseCommon(Object res, int dataLen, short magicCode, int opaque, Serialization serialization, boolean compress, short flag) throws IOException {
        magicCode |= flag;
        String className = res.getClass().getName();
        byte[] nameData = className.getBytes(CHARSET_UTF8);
        dataLen += nameData.length + 2;
        byte[] valData = serialization.serialize(res);
        int originLen = valData.length;
        if (compress) {
            valData = compress(valData);
            dataLen += 4;
        }
        dataLen += valData.length + 4;
        ByteBuffer content = ByteBuffer.allocate(dataLen);
        content.putInt(dataLen);
        content.putShort(magicCode);
        content.putInt(opaque);
        content.putShort((short) nameData.length);
        content.put(nameData);
        content.putInt(valData.length);
        content.put(valData);
        if (compress) {
            content.putInt(originLen);
        }
        return content;
    }

    private ByteBuffer encodeRequest(Request request, Serialization serialization) throws IOException {
        short magicCode = EAGLE_MAGIC_CODE;
        magicCode |= EAGLE_TYPE_REQ;
        if (request.isNeedCompress()) {
            magicCode |= EAGLE_COMPRESS_TYPE;
        }
        int dataLen = 14;//totalLen+magic+opaque+attachments 4+2+4+4
        String interfaceName = request.getInterfaceName();
        byte[] iNameData = interfaceName.getBytes(CHARSET_UTF8);
        dataLen += iNameData.length + 2;
        String mName = request.getMethodName();
        byte[] mNameData = mName.getBytes(CHARSET_UTF8);
        dataLen += mNameData.length + 2;
        ByteBuffer content;
        byte[] extFieldsBytes = null;
        if (request.getAttachments() != null && !request.getAttachments().isEmpty()) {
            extFieldsBytes = encodeAttachments(request.getAttachments());
            dataLen += extFieldsBytes.length;
        }
        if (!Strings.isNullOrEmpty(request.getParameterDesc())) {
            magicCode |= EAGLE_REQ_PARAMETER;
            String paramDesc = request.getParameterDesc();
            byte[] paramDescData = paramDesc.getBytes(CHARSET_UTF8);
            dataLen += paramDescData.length + 4;
            Object[] params = request.getParameters();
            List<byte[]> paramsData = Lists.newArrayListWithExpectedSize(8);
            for (Object param : params) {
                byte[] data = EMPTY_BYTES;
                if (param != null) {
                    data = serialization.serialize(param);
                }
                dataLen += data.length + 4;
                paramsData.add(data);

            }
            content = encodeReqCommon(dataLen, magicCode, request.getOpaque(), iNameData, mNameData);
            content.putInt(paramDescData.length);
            content.put(paramDescData);
            for (byte[] data : paramsData) {
                content.putInt(data.length);
                content.put(data);
            }
        } else {
            content = encodeReqCommon(dataLen, magicCode, request.getOpaque(), iNameData, mNameData);
        }
        if (extFieldsBytes != null) {
            content.putInt(extFieldsBytes.length);
            content.put(extFieldsBytes);
        } else {
            content.putInt(0);
        }
        content.flip();
        return content;
    }

    private ByteBuffer encodeReqCommon(int dataLen, short magicCode, int opaque, byte[] iNameData, byte[] mNameData) {
        ByteBuffer content = ByteBuffer.allocate(dataLen);
        content.putInt(dataLen);
        content.putShort(magicCode);
        content.putInt(opaque);
        content.putShort((short) iNameData.length);
        content.put(iNameData);
        content.putShort((short) mNameData.length);
        content.put(mNameData);
        return content;
    }

    public static byte[] encodeAttachments(Map<String, String> map) {
        int totalLength = 0;
        int kvLength;
        Map<byte[], byte[]> byteMap = Maps.newHashMapWithExpectedSize(map.size());
        byte[] key;
        byte[] val;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey() != null && entry.getValue() != null) {
                key = entry.getKey().getBytes(CHARSET_UTF8);
                val = entry.getValue().getBytes(CHARSET_UTF8);
                kvLength =
                        // keySize + Key
                        2 + key.length
                                // valSize + val
                                + 4 + val.length;
                totalLength += kvLength;
                byteMap.put(key, val);
            }
        }

        ByteBuffer content = ByteBuffer.allocate(totalLength);
        for (Map.Entry<byte[], byte[]> entry : byteMap.entrySet()) {
            key = entry.getKey();
            val = entry.getValue();

            content.putShort((short) key.length);
            content.put(key);

            content.putInt(entry.getValue().length);
            content.put(val);

        }

        return content.array();
    }

    @Override
    public Object decode(ByteBuffer buffer, Serialization serialization, int opaque, short magicCode) throws IOException {
        try {
            if (isRequest(magicCode)) {
                return decodeRequest(buffer, serialization, opaque, magicCode);
            } else {
                return decodeResponse(buffer, serialization, opaque, magicCode);
            }
        } catch (Exception e) {
            throw new EagleFrameException(e.getMessage());
        }
    }

    private Object decodeRequest(ByteBuffer buffer, Serialization serialization, int opaque, short magicCode)
            throws IOException, ClassNotFoundException {
        EagleRequest request = new EagleRequest();
        request.setOpaque(opaque);
        request.setNeedCompress(isCompress(magicCode));

        /*解码interfaceName最大长度127*/
        short len = buffer.getShort();
        byte[] data = new byte[len];
        buffer.get(data);
        request.setInterfaceName(new String(data, CHARSET_UTF8));

        /*解码methodName最大长度127*/
        len = buffer.getShort();
        data = new byte[len];
        buffer.get(data);
        request.setMethodName(new String(data, CHARSET_UTF8));

        /*解码方法参数*/
        if (isRequestWithParameter(magicCode)) {
            // 方法参数描述
            int paramDescLen = buffer.getInt();
            byte[] paramDescData = new byte[paramDescLen];
            buffer.get(paramDescData);
            String paramDesc = new String(paramDescData, CHARSET_UTF8);
            request.setParameterDesc(paramDesc);
            request.setParameters(decodeRequestParameter(buffer, paramDesc, serialization));
        }
        request.setAttachments(decodeRequestAttachments(buffer));
        return request;
    }

    private Object[] decodeRequestParameter(ByteBuffer buffer, String parameterDesc, Serialization serialization) throws IOException, ClassNotFoundException {
        Class<?>[] classTypes = ReflectUtil.forNames(parameterDesc);
        Object[] paramObjs = new Object[classTypes.length];
        int dataLen;
        byte[] data;
        for (int i = 0; i < classTypes.length; i++) {
            dataLen = buffer.getInt();
            if (dataLen != 0) {
                data = new byte[dataLen];
                buffer.get(data);
                paramObjs[i] = serialization.deserialize(data, classTypes[i]);
            }
        }

        return paramObjs;
    }

    private Map<String, String> decodeRequestAttachments(ByteBuffer buffer) throws IOException, ClassNotFoundException {
        int size = buffer.getInt();
        if (size <= 0) {
            return null;
        }
        /*byte[] data = new byte[size];
        buffer.get(data);
        ByteBuffer attachBuffer = ByteBuffer.wrap(data);*/
        short keySize;
        byte[] keyContent;
        int valSize;
        byte[] valContent;
        Map<String, String> attachments = new HashMap();
        while (buffer.hasRemaining()) {
            keySize = buffer.getShort();
            keyContent = new byte[keySize];
            buffer.get(keyContent);

            valSize = buffer.getInt();
            valContent = new byte[valSize];
            buffer.get(valContent);

            attachments.put(new String(keyContent, CHARSET_UTF8), new String(valContent, CHARSET_UTF8));
        }
        return attachments;
    }

    public Object decodeResponse(ByteBuffer buffer, Serialization serialization, int opaque, short magicCode)
            throws ClassNotFoundException, IOException {
        EagleResponse response = new EagleResponse();
        response.setOpaque(opaque);
        if (isVoidValue(magicCode)) {
            return response;
        }
        //解析返回的类型
        short len = buffer.getShort();
        byte[] data = new byte[len];
        buffer.get(data);
        String className = new String(data, CHARSET_UTF8);
        Class<?> clz = ReflectUtil.forName(className);
        //解析值
        int valLen = buffer.getInt();
        data = new byte[valLen];
        buffer.get(data);
        Object val;
        if (isCompress(magicCode)) {//需要对内容进行解压
            data = unCompress(data, buffer.getInt());
        }
        val = serialization.deserialize(data, clz);
        if (isNormalValue(magicCode)) {
            response.setValue(val);
        } else {
            response.setException((Exception) val);
        }
        return response;
    }
}


text:
#ifndef SEMPASS_H_
#define SEMPASS_H_

namespace staple {

class Sempass {
public:
  Sempass(CompilerContext*);
  void doit();

  CompilerContext* mCtx;
};

/**
 * Semantic Pass 1 job is to:
 * (1) parse all import files and add them to the parse tree.
 * (2) discover all class and function types and add entries to the CompilerContext->mKnownTypes
 */
class Sempass1Visitor : public Visitor {
public:
  Sempass1Visitor(CompilerContext& ctx);

  CompilerContext& mCtx;
  std::vector<NCompileUnit*> mCompileUnitCtx;

  void visit(NCompileUnit*);
  void visit(NImport*);
  void visit(NClassDecl*);
  void visit(NExternFunctionDecl*);
  void visit(NFunctionDecl*);

};

/**
 * Semantic Pass 2 job is to perform static type analysis
 * for all function arguments and statements. Specifically,
 * for each node, determine the correct Type and add it to the
 * CompilerContext->mTypeTable
 */
class Sempass2Visitor : public Visitor {
public:
  Sempass2Visitor(CompilerContext& ctx);
  ~Sempass2Visitor();

  Type* getType(Node*);

  void push();
  void pop();

  void visit(NCompileUnit*);
  void visit(NImport*);
  void visit(NClassDecl*);
  void visit(NFieldDecl*);
  void visit(NExternFunctionDecl*);
  void visit(NFunctionDecl*);
  void visit(NType*);
  void visit(NNamedType*);
  void visit(NPointerType*);
  void visit(NArrayType*);
  void visit(NLocalVar*);
  void visit(NAssign*);
  void visit(NSymbolRef*);
  void visit(NFieldRef*);
  void visit(NArrayRef*);
  void visit(NIntLiteral*);
  void visit(NStringLiteral*);
  void visit(NCall*);
  void visit(NReturn*);
  void visit(NIfStmt*);
  void visit(NOperation*);
  void visit(NLoad*);
  void visit(NBlock*) override;

  class Scope;

  CompilerContext& mCtx;
  FQPath* mCurrentPackage;
  NImport* mCurrentImport;
  FunctionType* mCurrentFunctionType;
  ClassType* mCurrentClassType;
  Scope* mScope;
};

} // namespace staple

#endif // SEMPASS_H_


text:
<?php
namespace Neos\Flow\ObjectManagement\Proxy;

use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Proxy\Proxy as OrmProxy;
use Neos\Flow\Core\Bootstrap;
use Neos\Flow\ObjectManagement\Configuration\Configuration;
use Neos\Flow\ObjectManagement\DependencyInjection\DependencyProxy;
use Neos\Flow\Persistence\Aspect\PersistenceMagicInterface;
use Neos\Flow\Persistence\PersistenceManagerInterface;
use Neos\Utility\ObjectAccess;
use Neos\Utility\Arrays;

/**
 * Methods used to serialize objects used by proxy classes.
 *
 */
trait ObjectSerializationTrait
{
    /**
     * Code to find and serialize entities on sleep
     *
     * @param array $transientProperties
     * @param array $propertyVarTags
     * @return array
     */
    private function Flow_serializeRelatedEntities(array $transientProperties, array $propertyVarTags)
    {
        $reflectedClass = new \ReflectionClass(__CLASS__);
        $allReflectedProperties = $reflectedClass->getProperties();
        foreach ($allReflectedProperties as $reflectionProperty) {
            $propertyName = $reflectionProperty->name;
            if (in_array($propertyName, [
                'Flow_Aop_Proxy_targetMethodsAndGroupedAdvices',
                'Flow_Aop_Proxy_groupedAdviceChains',
                'Flow_Aop_Proxy_methodIsInAdviceMode'
            ])) {
                continue;
            }
            if (isset($this->Flow_Injected_Properties) && is_array($this->Flow_Injected_Properties) && in_array($propertyName, $this->Flow_Injected_Properties)) {
                continue;
            }
            if ($reflectionProperty->isStatic() || in_array($propertyName, $transientProperties)) {
                continue;
            }
            if (is_array($this->$propertyName) || (is_object($this->$propertyName) && ($this->$propertyName instanceof \ArrayObject || $this->$propertyName instanceof \SplObjectStorage || $this->$propertyName instanceof Collection))) {
                if (count($this->$propertyName) > 0) {
                    foreach ($this->$propertyName as $key => $value) {
                        $this->Flow_searchForEntitiesAndStoreIdentifierArray((string)$key, $value, $propertyName);
                    }
                }
            }
            if (is_object($this->$propertyName) && !$this->$propertyName instanceof Collection) {
                if ($this->$propertyName instanceof OrmProxy) {
                    $className = get_parent_class($this->$propertyName);
                } else {
                    if (isset($propertyVarTags[$propertyName])) {
                        $className = trim($propertyVarTags[$propertyName], '\\');
                    }
                    if (Bootstrap::$staticObjectManager->isRegistered($className) === false) {
                        $className = Bootstrap::$staticObjectManager->getObjectNameByClassName(get_class($this->$propertyName));
                    }
                }
                if ($this->$propertyName instanceof PersistenceMagicInterface && !Bootstrap::$staticObjectManager->get(PersistenceManagerInterface::class)->isNewObject($this->$propertyName) || $this->$propertyName instanceof OrmProxy) {
                    if (!property_exists($this, 'Flow_Persistence_RelatedEntities') || !is_array($this->Flow_Persistence_RelatedEntities)) {
                        $this->Flow_Persistence_RelatedEntities = [];
                        $this->Flow_Object_PropertiesToSerialize[] = 'Flow_Persistence_RelatedEntities';
                    }
                    $identifier = Bootstrap::$staticObjectManager->get(PersistenceManagerInterface::class)->getIdentifierByObject($this->$propertyName);
                    if (!$identifier && $this->$propertyName instanceof OrmProxy) {
                        $identifier = current(ObjectAccess::getProperty($this->$propertyName, '_identifier', true));
                    }
                    $this->Flow_Persistence_RelatedEntities[$propertyName] = [
                        'propertyName' => $propertyName,
                        'entityType' => $className,
                        'identifier' => $identifier
                    ];
                    continue;
                }
                if ($className !== false && (Bootstrap::$staticObjectManager->getScope($className) === Configuration::SCOPE_SINGLETON || $className === DependencyProxy::class)) {
                    continue;
                }
            }
            $this->Flow_Object_PropertiesToSerialize[] = $propertyName;
        }

        return $this->Flow_Object_PropertiesToSerialize;
    }

    /**
     * Serialize entities that are inside an array or SplObjectStorage
     *
     * @param string $path
     * @param mixed $propertyValue
     * @param string $originalPropertyName
     * @return void
     */
    private function Flow_searchForEntitiesAndStoreIdentifierArray($path, $propertyValue, $originalPropertyName)
    {
        if (is_array($propertyValue) || (is_object($propertyValue) && ($propertyValue instanceof \ArrayObject || $propertyValue instanceof \SplObjectStorage))) {
            foreach ($propertyValue as $key => $value) {
                $this->Flow_searchForEntitiesAndStoreIdentifierArray($path . '.' . $key, $value, $originalPropertyName);
            }
        } elseif ($propertyValue instanceof PersistenceMagicInterface && !Bootstrap::$staticObjectManager->get(PersistenceManagerInterface::class)->isNewObject($propertyValue) || $propertyValue instanceof OrmProxy) {
            if (!property_exists($this, 'Flow_Persistence_RelatedEntities') || !is_array($this->Flow_Persistence_RelatedEntities)) {
                $this->Flow_Persistence_RelatedEntities = [];
                $this->Flow_Object_PropertiesToSerialize[] = 'Flow_Persistence_RelatedEntities';
            }
            if ($propertyValue instanceof OrmProxy) {
                $className = get_parent_class($propertyValue);
            } else {
                $className = Bootstrap::$staticObjectManager->getObjectNameByClassName(get_class($propertyValue));
            }
            $identifier = Bootstrap::$staticObjectManager->get(PersistenceManagerInterface::class)->getIdentifierByObject($propertyValue);
            if (!$identifier && $propertyValue instanceof OrmProxy) {
                $identifier = current(ObjectAccess::getProperty($propertyValue, '_identifier', true));
            }
            $this->Flow_Persistence_RelatedEntities[$originalPropertyName . '.' . $path] = [
                'propertyName' => $originalPropertyName,
                'entityType' => $className,
                'identifier' => $identifier,
                'entityPath' => $path
            ];
            $this->$originalPropertyName = Arrays::setValueByPath($this->$originalPropertyName, $path, null);
        }
    }

    /**
     * Reconstitues related entities to an unserialized object in __wakeup.
     * Used in __wakeup methods of proxy classes.
     *
     * Note: This method adds code which ignores objects of type Neos\Flow\ResourceManagement\ResourcePointer in order to provide
     * backwards compatibility data generated with Flow 2.2.x which still provided that class.
     *
     * @return void
     */
    private function Flow_setRelatedEntities()
    {
        if (property_exists($this, 'Flow_Persistence_RelatedEntities') && is_array($this->Flow_Persistence_RelatedEntities)) {
            $persistenceManager = Bootstrap::$staticObjectManager->get(PersistenceManagerInterface::class);
            foreach ($this->Flow_Persistence_RelatedEntities as $entityInformation) {
                $entity = $persistenceManager->getObjectByIdentifier($entityInformation['identifier'], $entityInformation['entityType'], true);
                if (isset($entityInformation['entityPath'])) {
                    $this->{$entityInformation['propertyName']} = Arrays::setValueByPath($this->{$entityInformation['propertyName']}, $entityInformation['entityPath'], $entity);
                } else {
                    $this->{$entityInformation['propertyName']} = $entity;
                }
            }
            unset($this->Flow_Persistence_RelatedEntities);
        }
    }
}


text:
#ifndef __LINUX_MAIN_LOGIC_THREAD_INCLUDE__
#define __LINUX_MAIN_LOGIC_THREAD_INCLUDE__

#include "LErrorWriter.h"
#include "LThreadBase.h"
class LNetWorkServices;

class LMainLogicThread : public LThreadBase
{
public:
	LMainLogicThread();
	~LMainLogicThread();
public:
	virtual int ThreadDoing(void* pParam);
	virtual bool OnStart();
	virtual void OnStop();

public:
	bool Initialize();
	void SetNetWorkServices(LNetWorkServices* pNetWorkServices);
private:
	LNetWorkServices* m_pNetWorkServices;

public://	for test
	void PrintNetWorkServicesStatus();
private:
	time_t m_tLastWriteTime;
	LErrorWriter m_SendStatusWriter;
	LErrorWriter m_RecvStatusWriter;
};
#endif


text:
use std::io;
use std::u8;
use std::io::Write;

use message::protocol::Protocol;
use message::extensions::{self, Extensions};

use bip_util::bt::{self, InfoHash, PeerId};
use nom::{IResult};

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct HandshakeMessage {
    prot: Protocol,
    ext:  Extensions,
    hash: InfoHash,
    pid:  PeerId
}

impl HandshakeMessage {
    /// Create a new `HandshakeMessage` from the given components.
    pub fn from_parts(prot: Protocol, ext: Extensions, hash: InfoHash, pid: PeerId) -> HandshakeMessage {
        if let Protocol::Custom(ref custom) = prot {
            if custom.len() > u8::max_value() as usize {
                panic!("bip_handshake: Handshake Message With Protocol Length Greater Than {} Found", u8::max_value())
            }
        }

        HandshakeMessage{ prot: prot, ext: ext, hash: hash, pid: pid }
    }

    pub fn from_bytes(bytes: &[u8]) -> IResult<&[u8], HandshakeMessage> {
        parse_remote_handshake(bytes)
    }

    pub fn write_bytes<W>(&self, mut writer: W) -> io::Result<()>
        where W: Write {
        try!(self.prot.write_bytes(&mut writer));
        try!(self.ext.write_bytes(&mut writer));
        try!(writer.write_all(self.hash.as_ref()));

        try!(writer.write_all(self.pid.as_ref()));

        Ok(())
    }

    pub fn write_len(&self) -> usize {
        write_len_with_protocol_len(self.prot.write_len() as u8)
    }

    pub fn into_parts(self) -> (Protocol, Extensions, InfoHash, PeerId) {
        (self.prot, self.ext, self.hash, self.pid)
    }
}

pub fn write_len_with_protocol_len(protocol_len: u8) -> usize {
    1 + (protocol_len as usize) + extensions::NUM_EXTENSION_BYTES + bt::INFO_HASH_LEN + bt::PEER_ID_LEN
}

fn parse_remote_handshake(bytes: &[u8]) -> IResult<&[u8], HandshakeMessage> {
    do_parse!(bytes,
        prot: call!(Protocol::from_bytes)   >>
        ext:  call!(Extensions::from_bytes) >>
        hash: call!(parse_remote_hash)      >>
        pid:  call!(parse_remote_pid)       >>
        (HandshakeMessage::from_parts(prot, ext, hash, pid))
    )
}

fn parse_remote_hash(bytes: &[u8]) -> IResult<&[u8], InfoHash> {
    do_parse!(bytes,
        hash: take!(bt::INFO_HASH_LEN) >>
        (InfoHash::from_hash(hash).unwrap())
    )
}

fn parse_remote_pid(bytes: &[u8]) -> IResult<&[u8], PeerId> {
    do_parse!(bytes,
        pid: take!(bt::PEER_ID_LEN) >>
        (PeerId::from_hash(pid).unwrap())
    )
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    use super::{HandshakeMessage};
    use message::extensions::{self, Extensions};
    use message::protocol::Protocol;

    use bip_util::bt::{self, PeerId, InfoHash};

    fn any_peer_id() -> PeerId {
        [22u8; bt::PEER_ID_LEN].into()
    }

    fn any_info_hash() -> InfoHash {
        [55u8; bt::INFO_HASH_LEN].into()
    }

    fn any_extensions() -> Extensions {
        [255u8; extensions::NUM_EXTENSION_BYTES].into()
    }

    #[test]
    fn positive_decode_zero_bytes_protocol() {
        let mut buffer = Vec::new();

        let exp_protocol = Protocol::Custom(Vec::new());
        let exp_extensions = any_extensions();
        let exp_hash = any_info_hash();
        let exp_pid = any_peer_id();

        let exp_message = HandshakeMessage::from_parts(exp_protocol.clone(),
            exp_extensions, exp_hash, exp_pid);

        exp_protocol.write_bytes(&mut buffer).unwrap();
        exp_extensions.write_bytes(&mut buffer).unwrap();
        buffer.write_all(exp_hash.as_ref()).unwrap();
        buffer.write_all(exp_pid.as_ref()).unwrap();

        let recv_message = HandshakeMessage::from_bytes(&buffer).unwrap().1;

        assert_eq!(exp_message, recv_message);
    }

    #[test]
    fn positive_many_bytes_protocol() {
        let mut buffer = Vec::new();

        let exp_protocol = Protocol::Custom(b"My Protocol".to_vec());
        let exp_extensions = any_extensions();
        let exp_hash = any_info_hash();
        let exp_pid = any_peer_id();

        let exp_message = HandshakeMessage::from_parts(exp_protocol.clone(),
            exp_extensions, exp_hash, exp_pid);

        exp_protocol.write_bytes(&mut buffer).unwrap();
        exp_extensions.write_bytes(&mut buffer).unwrap();
        buffer.write_all(exp_hash.as_ref()).unwrap();
        buffer.write_all(exp_pid.as_ref()).unwrap();

        let recv_message = HandshakeMessage::from_bytes(&buffer).unwrap().1;

        assert_eq!(exp_message, recv_message);
    }

    #[test]
    fn positive_bittorrent_protocol() {
        let mut buffer = Vec::new();

        let exp_protocol = Protocol::BitTorrent;
        let exp_extensions = any_extensions();
        let exp_hash = any_info_hash();
        let exp_pid = any_peer_id();

        let exp_message = HandshakeMessage::from_parts(exp_protocol.clone(),
            exp_extensions, exp_hash, exp_pid);

        exp_protocol.write_bytes(&mut buffer).unwrap();
        exp_extensions.write_bytes(&mut buffer).unwrap();
        buffer.write_all(exp_hash.as_ref()).unwrap();
        buffer.write_all(exp_pid.as_ref()).unwrap();

        let recv_message = HandshakeMessage::from_bytes(&buffer).unwrap().1;

        assert_eq!(exp_message, recv_message);
    }

    #[test]
    #[should_panic]
    fn negative_create_overflow_protocol() {
        let overflow_protocol = Protocol::Custom(vec![0u8; 256]);

        HandshakeMessage::from_parts(overflow_protocol, any_extensions(), any_info_hash(), any_peer_id());
    }
}


text:
package dockertools

import (
	"errors"
	"fmt"
	"reflect"
	"sort"
	"testing"
	"time"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client/record"
	kubecontainer "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/container"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/network"
	kubeprober "github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/prober"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/probe"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/types"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	uexec "github.com/GoogleCloudPlatform/kubernetes/pkg/util/exec"
	"github.com/fsouza/go-dockerclient"
)

func newTestDockerManager() (*DockerManager, *FakeDockerClient) {
	fakeDocker := &FakeDockerClient{Errors: make(map[string]error), RemovedImages: util.StringSet{}}
	fakeRecorder := &record.FakeRecorder{}
	readinessManager := kubecontainer.NewReadinessManager()
	containerRefManager := kubecontainer.NewRefManager()
	networkPlugin, _ := network.InitNetworkPlugin([]network.NetworkPlugin{}, "", network.NewFakeHost(nil))
	dockerManager := NewFakeDockerManager(
		fakeDocker,
		fakeRecorder,
		readinessManager,
		containerRefManager,
		PodInfraContainerImage,
		0, 0, "",
		kubecontainer.FakeOS{},
		networkPlugin,
		nil,
		nil,
		nil)

	return dockerManager, fakeDocker
}

func TestSetEntrypointAndCommand(t *testing.T) {
	cases := []struct {
		name      string
		container *api.Container
		expected  *docker.CreateContainerOptions
	}{
		{
			name:      "none",
			container: &api.Container{},
			expected: &docker.CreateContainerOptions{
				Config: &docker.Config{},
			},
		},
		{
			name: "command",
			container: &api.Container{
				Command: []string{"foo", "bar"},
			},
			expected: &docker.CreateContainerOptions{
				Config: &docker.Config{
					Entrypoint: []string{"foo", "bar"},
				},
			},
		},
		{
			name: "args",
			container: &api.Container{
				Args: []string{"foo", "bar"},
			},
			expected: &docker.CreateContainerOptions{
				Config: &docker.Config{
					Cmd: []string{"foo", "bar"},
				},
			},
		},
		{
			name: "both",
			container: &api.Container{
				Command: []string{"foo"},
				Args:    []string{"bar", "baz"},
			},
			expected: &docker.CreateContainerOptions{
				Config: &docker.Config{
					Entrypoint: []string{"foo"},
					Cmd:        []string{"bar", "baz"},
				},
			},
		},
	}

	for _, tc := range cases {
		actualOpts := &docker.CreateContainerOptions{
			Config: &docker.Config{},
		}
		setEntrypointAndCommand(tc.container, actualOpts)

		if e, a := tc.expected.Config.Entrypoint, actualOpts.Config.Entrypoint; !api.Semantic.DeepEqual(e, a) {
			t.Errorf("%v: unexpected entrypoint: expected %v, got %v", tc.name, e, a)
		}
		if e, a := tc.expected.Config.Cmd, actualOpts.Config.Cmd; !api.Semantic.DeepEqual(e, a) {
			t.Errorf("%v: unexpected command: expected %v, got %v", tc.name, e, a)
		}
	}
}

// verifyPods returns true if the two pod slices are equal.
func verifyPods(a, b []*kubecontainer.Pod) bool {
	if len(a) != len(b) {
		return false
	}

	// Sort the containers within a pod.
	for i := range a {
		sort.Sort(containersByID(a[i].Containers))
	}
	for i := range b {
		sort.Sort(containersByID(b[i].Containers))
	}

	// Sort the pods by UID.
	sort.Sort(podsByID(a))
	sort.Sort(podsByID(b))

	return reflect.DeepEqual(a, b)
}

func TestGetPods(t *testing.T) {
	manager, fakeDocker := newTestDockerManager()
	dockerContainers := []docker.APIContainers{
		{
			ID:    "1111",
			Names: []string{"/k8s_foo_qux_new_1234_42"},
		},
		{
			ID:    "2222",
			Names: []string{"/k8s_bar_qux_new_1234_42"},
		},
		{
			ID:    "3333",
			Names: []string{"/k8s_bar_jlk_wen_5678_42"},
		},
	}

	// Convert the docker containers. This does not affect the test coverage
	// because the conversion is tested separately in convert_test.go
	containers := make([]*kubecontainer.Container, len(dockerContainers))
	for i := range containers {
		c, err := toRuntimeContainer(&dockerContainers[i])
		if err != nil {
			t.Fatalf("unexpected error %v", err)
		}
		containers[i] = c
	}

	expected := []*kubecontainer.Pod{
		{
			ID:         types.UID("1234"),
			Name:       "qux",
			Namespace:  "new",
			Containers: []*kubecontainer.Container{containers[0], containers[1]},
		},
		{
			ID:         types.UID("5678"),
			Name:       "jlk",
			Namespace:  "wen",
			Containers: []*kubecontainer.Container{containers[2]},
		},
	}

	fakeDocker.ContainerList = dockerContainers
	actual, err := manager.GetPods(false)
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if !verifyPods(expected, actual) {
		t.Errorf("expected %#v, got %#v", expected, actual)
	}
}

func TestListImages(t *testing.T) {
	manager, fakeDocker := newTestDockerManager()
	dockerImages := []docker.APIImages{{ID: "1111"}, {ID: "2222"}, {ID: "3333"}}
	expected := util.NewStringSet([]string{"1111", "2222", "3333"}...)

	fakeDocker.Images = dockerImages
	actualImages, err := manager.ListImages()
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	actual := util.NewStringSet()
	for _, i := range actualImages {
		actual.Insert(i.ID)
	}
	// We can compare the two sets directly because util.StringSet.List()
	// returns a "sorted" list.
	if !reflect.DeepEqual(expected.List(), actual.List()) {
		t.Errorf("expected %#v, got %#v", expected.List(), actual.List())
	}
}

func apiContainerToContainer(c docker.APIContainers) kubecontainer.Container {
	dockerName, hash, err := ParseDockerName(c.Names[0])
	if err != nil {
		return kubecontainer.Container{}
	}
	return kubecontainer.Container{
		ID:   types.UID(c.ID),
		Name: dockerName.ContainerName,
		Hash: hash,
	}
}

func dockerContainersToPod(containers DockerContainers) kubecontainer.Pod {
	var pod kubecontainer.Pod
	for _, c := range containers {
		dockerName, hash, err := ParseDockerName(c.Names[0])
		if err != nil {
			continue
		}
		pod.Containers = append(pod.Containers, &kubecontainer.Container{
			ID:    types.UID(c.ID),
			Name:  dockerName.ContainerName,
			Hash:  hash,
			Image: c.Image,
		})
		// TODO(yifan): Only one evaluation is enough.
		pod.ID = dockerName.PodUID
		name, namespace, _ := kubecontainer.ParsePodFullName(dockerName.PodFullName)
		pod.Name = name
		pod.Namespace = namespace
	}
	return pod
}

func TestKillContainerInPod(t *testing.T) {
	manager, fakeDocker := newTestDockerManager()

	pod := &api.Pod{
		ObjectMeta: api.ObjectMeta{
			UID:       "12345678",
			Name:      "qux",
			Namespace: "new",
		},
		Spec: api.PodSpec{Containers: []api.Container{{Name: "foo"}, {Name: "bar"}}},
	}
	containers := []docker.APIContainers{
		{
			ID:    "1111",
			Names: []string{"/k8s_foo_qux_new_1234_42"},
		},
		{
			ID:    "2222",
			Names: []string{"/k8s_bar_qux_new_1234_42"},
		},
	}
	containerToKill := &containers[0]
	containerToSpare := &containers[1]
	fakeDocker.ContainerList = containers
	// Set all containers to ready.
	for _, c := range fakeDocker.ContainerList {
		manager.readinessManager.SetReadiness(c.ID, true)
	}

	if err := manager.KillContainerInPod(pod.Spec.Containers[0], pod); err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	// Assert the container has been stopped.
	if err := fakeDocker.AssertStopped([]string{containerToKill.ID}); err != nil {
		t.Errorf("container was not stopped correctly: %v", err)
	}

	// Verify that the readiness has been removed for the stopped container.
	if ready := manager.readinessManager.GetReadiness(containerToKill.ID); ready {
		t.Errorf("exepcted container entry ID '%v' to not be found. states: %+v", containerToKill.ID, ready)
	}
	if ready := manager.readinessManager.GetReadiness(containerToSpare.ID); !ready {
		t.Errorf("exepcted container entry ID '%v' to be found. states: %+v", containerToSpare.ID, ready)
	}
}

func TestKillContainerInPodWithError(t *testing.T) {
	manager, fakeDocker := newTestDockerManager()

	pod := &api.Pod{
		ObjectMeta: api.ObjectMeta{
			UID:       "12345678",
			Name:      "qux",
			Namespace: "new",
		},
		Spec: api.PodSpec{Containers: []api.Container{{Name: "foo"}, {Name: "bar"}}},
	}
	containers := []docker.APIContainers{
		{
			ID:    "1111",
			Names: []string{"/k8s_foo_qux_new_1234_42"},
		},
		{
			ID:    "2222",
			Names: []string{"/k8s_bar_qux_new_1234_42"},
		},
	}
	containerToKill := &containers[0]
	containerToSpare := &containers[1]
	fakeDocker.ContainerList = containers
	fakeDocker.Errors["stop"] = fmt.Errorf("sample error")

	// Set all containers to ready.
	for _, c := range fakeDocker.ContainerList {
		manager.readinessManager.SetReadiness(c.ID, true)
	}

	if err := manager.KillContainerInPod(pod.Spec.Containers[0], pod); err == nil {
		t.Errorf("expected error, found nil")
	}

	// Verify that the readiness has been removed even though the stop failed.
	if ready := manager.readinessManager.GetReadiness(containerToKill.ID); ready {
		t.Errorf("exepcted container entry ID '%v' to not be found. states: %+v", containerToKill.ID, ready)
	}
	if ready := manager.readinessManager.GetReadiness(containerToSpare.ID); !ready {
		t.Errorf("exepcted container entry ID '%v' to be found. states: %+v", containerToSpare.ID, ready)
	}
}

type fakeExecProber struct {
	result probe.Result
	err    error
}

func (p fakeExecProber) Probe(_ uexec.Cmd) (probe.Result, error) {
	return p.result, p.err
}

func replaceProber(dm *DockerManager, result probe.Result, err error) {
	fakeExec := fakeExecProber{
		result: result,
		err:    err,
	}

	dm.prober = kubeprober.NewTestProber(fakeExec, dm.readinessManager, dm.containerRefManager, &record.FakeRecorder{})
	return
}

// TestProbeContainer tests the functionality of probeContainer.
// Test cases are:
//
// No probe.
// Only LivenessProbe.
// Only ReadinessProbe.
// Both probes.
//
// Also, for each probe, there will be several cases covering whether the initial
// delay has passed, whether the probe handler will return Success, Failure,
// Unknown or error.
//
func TestProbeContainer(t *testing.T) {
	manager, _ := newTestDockerManager()
	dc := &docker.APIContainers{
		ID:      "foobar",
		Created: time.Now().Unix(),
	}
	tests := []struct {
		testContainer     api.Container
		expectError       bool
		expectedResult    probe.Result
		expectedReadiness bool
	}{
		// No probes.
		{
			testContainer:     api.Container{},
			expectedResult:    probe.Success,
			expectedReadiness: true,
		},
		// Only LivenessProbe.
		{
			testContainer: api.Container{
				LivenessProbe: &api.Probe{InitialDelaySeconds: 100},
			},
			expectedResult:    probe.Success,
			expectedReadiness: true,
		},
		{
			testContainer: api.Container{
				LivenessProbe: &api.Probe{InitialDelaySeconds: -100},
			},
			expectedResult:    probe.Unknown,
			expectedReadiness: false,
		},
		{
			testContainer: api.Container{
				LivenessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
			},
			expectedResult:    probe.Failure,
			expectedReadiness: false,
		},
		{
			testContainer: api.Container{
				LivenessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
			},
			expectedResult:    probe.Success,
			expectedReadiness: true,
		},
		{
			testContainer: api.Container{
				LivenessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
			},
			expectedResult:    probe.Unknown,
			expectedReadiness: false,
		},
		{
			testContainer: api.Container{
				LivenessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
			},
			expectError:       true,
			expectedResult:    probe.Unknown,
			expectedReadiness: false,
		},
		// Only ReadinessProbe.
		{
			testContainer: api.Container{
				ReadinessProbe: &api.Probe{InitialDelaySeconds: 100},
			},
			expectedResult:    probe.Success,
			expectedReadiness: false,
		},
		{
			testContainer: api.Container{
				ReadinessProbe: &api.Probe{InitialDelaySeconds: -100},
			},
			expectedResult:    probe.Success,
			expectedReadiness: false,
		},
		{
			testContainer: api.Container{
				ReadinessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
			},
			expectedResult:    probe.Success,
			expectedReadiness: true,
		},
		{
			testContainer: api.Container{
				ReadinessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
			},
			expectedResult:    probe.Success,
			expectedReadiness: true,
		},
		{
			testContainer: api.Container{
				ReadinessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
			},
			expectedResult:    probe.Success,
			expectedReadiness: true,
		},
		{
			testContainer: api.Container{
				ReadinessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
			},
			expectError:       false,
			expectedResult:    probe.Success,
			expectedReadiness: true,
		},
		// Both LivenessProbe and ReadinessProbe.
		{
			testContainer: api.Container{
				LivenessProbe:  &api.Probe{InitialDelaySeconds: 100},
				ReadinessProbe: &api.Probe{InitialDelaySeconds: 100},
			},
			expectedResult:    probe.Success,
			expectedReadiness: false,
		},
		{
			testContainer: api.Container{
				LivenessProbe:  &api.Probe{InitialDelaySeconds: 100},
				ReadinessProbe: &api.Probe{InitialDelaySeconds: -100},
			},
			expectedResult:    probe.Success,
			expectedReadiness: false,
		},
		{
			testContainer: api.Container{
				LivenessProbe:  &api.Probe{InitialDelaySeconds: -100},
				ReadinessProbe: &api.Probe{InitialDelaySeconds: 100},
			},
			expectedResult:    probe.Unknown,
			expectedReadiness: false,
		},
		{
			testContainer: api.Container{
				LivenessProbe:  &api.Probe{InitialDelaySeconds: -100},
				ReadinessProbe: &api.Probe{InitialDelaySeconds: -100},
			},
			expectedResult:    probe.Unknown,
			expectedReadiness: false,
		},
		{
			testContainer: api.Container{
				LivenessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
				ReadinessProbe: &api.Probe{InitialDelaySeconds: -100},
			},
			expectedResult:    probe.Unknown,
			expectedReadiness: false,
		},
		{
			testContainer: api.Container{
				LivenessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
				ReadinessProbe: &api.Probe{InitialDelaySeconds: -100},
			},
			expectedResult:    probe.Failure,
			expectedReadiness: false,
		},
		{
			testContainer: api.Container{
				LivenessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
				ReadinessProbe: &api.Probe{
					InitialDelaySeconds: -100,
					Handler: api.Handler{
						Exec: &api.ExecAction{},
					},
				},
			},
			expectedResult:    probe.Success,
			expectedReadiness: true,
		},
	}

	for _, test := range tests {
		if test.expectError {
			replaceProber(manager, test.expectedResult, errors.New("error"))
		} else {
			replaceProber(manager, test.expectedResult, nil)
		}
		result, err := manager.prober.Probe(&api.Pod{}, api.PodStatus{}, test.testContainer, dc.ID, dc.Created)
		if test.expectError && err == nil {
			t.Error("Expected error but did no error was returned.")
		}
		if !test.expectError && err != nil {
			t.Errorf("Expected error but got: %v", err)
		}
		if test.expectedResult != result {
			t.Errorf("Expected result was %v but probeContainer() returned %v", test.expectedResult, result)
		}
		if test.expectedReadiness != manager.readinessManager.GetReadiness(dc.ID) {
			t.Errorf("Expected readiness was %v but probeContainer() set %v", test.expectedReadiness, manager.readinessManager.GetReadiness(dc.ID))
		}
	}
}


text:
For newer changes please look at the comments for the Git tags:
https://github.com/WoLpH/portalocker/tags

For more details the commit log for the master branch could be useful:
https://github.com/WoLpH/portalocker/commits/master

1.5:

 * Moved tests to prevent collisions with other packages

1.4:

 * Added optional file open parameters

1.3:

 * Improved documentation
 * Added file handle to locking exceptions

1.2:

 * Added signed releases and tags to PyPI and Git

1.1:

 * Added support for Python 3.6+
 * Using real time to calculate timeout

1.0:

 * Complete code refactor.

   - Splitting of code in logical classes
   - 100% test coverage and change in API behaviour
   - The default behavior of the `Lock` class has changed to append instead of
     write/truncate.

0.6:

 * Added msvcrt support for Windows

0.5:

 * Python 3 support

0.4:

 * Fixing a few bugs, added coveralls support, switched to py.test and added
   100% test coverage.

    - Fixing exception thrown when fail_when_locked is true
    - Fixing exception "Lock object has no attribute '_release_lock'" when
      fail_when_locked is true due to the call to Lock._release_lock() which
      fails because _release_lock is not defined.

0.3:

 * Now actually returning the file descriptor from the `Lock` class

0.2:

 * Added `Lock` class to help prevent cache race conditions

0.1:

 * Initial release


text:
class Animal {
    constructor(public name: string) { }
    move(meters: number) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move() {
        alert("Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);


text:
'use strict';

exports.__esModule = true;

var _bigi = require('bigi');

var _bigi2 = _interopRequireDefault(_bigi);

var _ecurve = require('ecurve');

var _bs = require('bs58');

var _hash = require('./hash');

var _assetfunjsWs = require('assetfunjs-ws');

var _assert = require('assert');

var _assert2 = _interopRequireDefault(_assert);

var _deepEqual = require('deep-equal');

var _deepEqual2 = _interopRequireDefault(_deepEqual);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var secp256k1 = (0, _ecurve.getCurveByName)('secp256k1');
var G = secp256k1.G,
    n = secp256k1.n;

var PublicKey = function () {

    /** @param {Point} public key */
    function PublicKey(Q) {
        _classCallCheck(this, PublicKey);

        this.Q = Q;
    }

    PublicKey.fromBinary = function fromBinary(bin) {
        return PublicKey.fromBuffer(new Buffer(bin, 'binary'));
    };

    PublicKey.fromBuffer = function fromBuffer(buffer) {
        if (buffer.toString('hex') === '000000000000000000000000000000000000000000000000000000000000000000') return new PublicKey(null);
        return new PublicKey(_ecurve.Point.decodeFrom(secp256k1, buffer));
    };

    PublicKey.prototype.toBuffer = function toBuffer() {
        var compressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.Q ? this.Q.compressed : null;

        if (this.Q === null) return new Buffer('000000000000000000000000000000000000000000000000000000000000000000', 'hex');
        return this.Q.getEncoded(compressed);
    };

    PublicKey.fromPoint = function fromPoint(point) {
        return new PublicKey(point);
    };

    PublicKey.prototype.toUncompressed = function toUncompressed() {
        var buf = this.Q.getEncoded(false);
        var point = _ecurve.Point.decodeFrom(secp256k1, buf);
        return PublicKey.fromPoint(point);
    };

    /** bts::blockchain::address (unique but not a full public key) */

    PublicKey.prototype.toBlockchainAddress = function toBlockchainAddress() {
        var pub_buf = this.toBuffer();
        var pub_sha = (0, _hash.sha512)(pub_buf);
        return (0, _hash.ripemd160)(pub_sha);
    };

    /** Alias for {@link toPublicKeyString} */

    PublicKey.prototype.toString = function toString() {
        var address_prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _assetfunjsWs.ChainConfig.address_prefix;

        return this.toPublicKeyString(address_prefix);
    };

    /**
        Full public key
        {return} string
    */

    PublicKey.prototype.toPublicKeyString = function toPublicKeyString() {
        var address_prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _assetfunjsWs.ChainConfig.address_prefix;

        var pub_buf = this.toBuffer();
        var checksum = (0, _hash.ripemd160)(pub_buf);
        var addy = Buffer.concat([pub_buf, checksum.slice(0, 4)]);
        return address_prefix + (0, _bs.encode)(addy);
    };

    /**
        @arg {string} public_key - like FIDXyz...
        @arg {string} address_prefix - like AFT
        @return PublicKey or `null` (if the public_key string is invalid)
    */

    PublicKey.fromPublicKeyString = function fromPublicKeyString(public_key) {
        var address_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _assetfunjsWs.ChainConfig.address_prefix;

        try {
            return PublicKey.fromStringOrThrow(public_key, address_prefix);
        } catch (e) {
            return null;
        }
    };

    /**
        @arg {string} public_key - like FIDXyz...
        @arg {string} address_prefix - like AFT
        @throws {Error} if public key is invalid
        @return PublicKey
    */

    PublicKey.fromStringOrThrow = function fromStringOrThrow(public_key) {
        var address_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _assetfunjsWs.ChainConfig.address_prefix;

        var prefix = public_key.slice(0, address_prefix.length);
        _assert2.default.equal(address_prefix, prefix, 'Expecting key to begin with ' + address_prefix + ', instead got ' + prefix);
        public_key = public_key.slice(address_prefix.length);

        public_key = new Buffer((0, _bs.decode)(public_key), 'binary');
        var checksum = public_key.slice(-4);
        public_key = public_key.slice(0, -4);
        var new_checksum = (0, _hash.ripemd160)(public_key);
        new_checksum = new_checksum.slice(0, 4);
        var isEqual = (0, _deepEqual2.default)(checksum, new_checksum); //, 'Invalid checksum'
        if (!isEqual) {
            throw new Error("Checksum did not match");
        }
        return PublicKey.fromBuffer(public_key);
    };

    PublicKey.prototype.toAddressString = function toAddressString() {
        var address_prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _assetfunjsWs.ChainConfig.address_prefix;

        var pub_buf = this.toBuffer();
        var pub_sha = (0, _hash.sha512)(pub_buf);
        var addy = (0, _hash.ripemd160)(pub_sha);
        var checksum = (0, _hash.ripemd160)(addy);
        addy = Buffer.concat([addy, checksum.slice(0, 4)]);
        return address_prefix + (0, _bs.encode)(addy);
    };

    PublicKey.prototype.toPtsAddy = function toPtsAddy() {
        var pub_buf = this.toBuffer();
        var pub_sha = (0, _hash.sha256)(pub_buf);
        var addy = (0, _hash.ripemd160)(pub_sha);
        addy = Buffer.concat([new Buffer([0x38]), addy]); //version 56(decimal)

        var checksum = (0, _hash.sha256)(addy);
        checksum = (0, _hash.sha256)(checksum);

        addy = Buffer.concat([addy, checksum.slice(0, 4)]);
        return (0, _bs.encode)(addy);
    };

    PublicKey.prototype.child = function child(offset) {

        (0, _assert2.default)(Buffer.isBuffer(offset), "Buffer required: offset");
        _assert2.default.equal(offset.length, 32, "offset length");

        offset = Buffer.concat([this.toBuffer(), offset]);
        offset = (0, _hash.sha256)(offset);

        var c = _bigi2.default.fromBuffer(offset);

        if (c.compareTo(n) >= 0) throw new Error("Child offset went out of bounds, try again");

        var cG = G.multiply(c);
        var Qprime = this.Q.add(cG);

        if (secp256k1.isInfinity(Qprime)) throw new Error("Child offset derived to an invalid key, try again");

        return PublicKey.fromPoint(Qprime);
    };

    /* <HEX> */

    PublicKey.prototype.toByteBuffer = function toByteBuffer() {
        var b = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN);
        this.appendByteBuffer(b);
        return b.copy(0, b.offset);
    };

    PublicKey.fromHex = function fromHex(hex) {
        return PublicKey.fromBuffer(new Buffer(hex, 'hex'));
    };

    PublicKey.prototype.toHex = function toHex() {
        return this.toBuffer().toString('hex');
    };

    PublicKey.fromPublicKeyStringHex = function fromPublicKeyStringHex(hex) {
        return PublicKey.fromPublicKeyString(new Buffer(hex, 'hex'));
    };

    /* </HEX> */

    return PublicKey;
}();

exports.default = PublicKey;
module.exports = exports['default'];


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- log4j2.xml - Example log4j configuration file

     Place this file in the same directory as your server.jar, edit
     to taste, and add -Dlog4j.configurationFile=log4j2.xml to your
     server startup flags.

     More log4j example configs can be found at
     <http://logging.apache.org/log4j/2.x/manual/appenders.html>.
-->

<Configuration status="WARN" packages="net.minecraft,com.mojang">
	<Appenders>

		<!-- DEFAULT APPENDERS -->

		<!-- console logging - logs to stdout -->
		<Console name="SysOut" target="SYSTEM_OUT">
			<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg%n" />
		</Console>

		<!-- GUI logging - ignored if you use `java -jar server.jar nogui` -->
		<Queue name="ServerGuiConsole">
			<PatternLayout pattern="[%d{HH:mm:ss} %level]: %msg%n" />
		</Queue>

		<!-- file logging - stuff under the logs/ dir -->
		<RollingRandomAccessFile name="File" fileName="logs/latest.log"
			                     filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
			<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg%n" />
			<Policies>
				<TimeBasedTriggeringPolicy />
				<OnStartupTriggeringPolicy />
				<!-- <SizeBasedTriggeringPolicy size="250 MB"/> -->
			</Policies>
			<!-- keep up to 20 files before removing them -->
			<!-- <DefaultRolloverStrategy max="20"/> -->
		</RollingRandomAccessFile>

		<!-- EXAMPLE APPENDERS -->

		<!-- legacy logging - logs to server.log -->
		<File name="LegacyServerLog" fileName="server.log">
			<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%level] %msg%n" />
		</File>

	</Appenders>
	<Loggers>
		<Root level="info">

			<!-- DEFAULT LOGGERS -->

			<filters>
				<MarkerFilter marker="NETWORK_PACKETS" onMatch="DENY"
				              onMismatch="NEUTRAL" />
			</filters>
			<AppenderRef ref="SysOut"/>
			<AppenderRef ref="File"/>
			<AppenderRef ref="ServerGuiConsole"/>

			<!-- EXAMPLE LOGGERS -->

			<!-- <AppenderRef ref="LegacyServerLog"/> -->
		</Root>
	</Loggers>
</Configuration>


text:
'use strict';

describe('unitaste.view2 module', function() {

  beforeEach(module('unitaste.view2'));

  describe('view2 controller', function(){

    it('should ....', inject(function($controller) {
      //spec body
      var view2Ctrl = $controller('View2Ctrl');
      expect(view2Ctrl).toBeDefined();
    }));

  });
});


text:
layout: default
footerlogos: yes
title: "Rednerinnen"

---

Franz-Reinhard Habbel

                Franz-Reinhard Habbel ist ein deutscher Schriftsteller und Sprecher des Deutschen Städte- und Gemeindebundes mit Sitz in Berlin. Er gehört als Herausgeber von Sachbüchern, Redner und Mitglied hochkarätiger Fachgremien zu den führenden Köpfen der Einführung von E-Government in Deutschland.

                Habbel hält am 28.04.2017 einen Vortrag zu E-Government.

                Zum Programm Tag 1

For everyone who missed the lecture


text:
class Vote < AbstractModel
  belongs_to :user
  belongs_to :naming
  belongs_to :observation

  # ----------------------------
  #  :section: Values
  # ----------------------------

  DELETE_VOTE    = 0
  MINIMUM_VOTE   = -3
  MIN_NEG_VOTE   = -1
  MIN_POS_VOTE   =  1
  NEXT_BEST_VOTE =  2
  MAXIMUM_VOTE   =  3

  def self.construct(args, naming)
    now = Time.zone.now
    vote = Vote.new
    vote.assign_attributes(args.permit(:favorite, :value)) if args
    vote.created_at = now
    vote.updated_at = now
    vote.user = @user
    vote.naming = naming
    vote.observation = naming.observation
    vote
  end

  # Override the default show_controller
  def self.show_controller
    "observer"
  end

  # This is used to mean "delete my vote".
  def self.delete_vote
    DELETE_VOTE
  end

  # Weakest nonzero vote.
  def self.minimum_vote
    MINIMUM_VOTE
  end

  # Least-negative vote.
  def self.min_neg_vote
    MIN_NEG_VOTE
  end

  # Least-positive vote.
  def self.min_pos_vote
    MIN_POS_VOTE
  end

  # Next-to-best vote.
  def self.next_best_vote
    NEXT_BEST_VOTE
  end

  # Strongest vote.
  def self.maximum_vote
    MAXIMUM_VOTE
  end

  # minimum owner's vote needed to display owner_id
  def self.owner_id_min_confidence
    min_pos_vote
  end

  # Convert a given Vote value to a percentage.
  def self.percent(val)
    return 0.0 if val.blank?

    val.to_f * 100 / 3
  end

  # Convert Vote's value to a percentage.
  def percent
    self.class.percent(value)
  end

  # Validate a vote value.  Returns Float value if valid, nil otherwise.
  def self.validate_value(val)
    val = val.to_f
    val && val >= MINIMUM_VOTE && val <= MAXIMUM_VOTE ? val : nil
  rescue StandardError
    nil
  end

  # ----------------------------
  #  :section: Labels
  # ----------------------------

  CONFIDENCE_VALS = [
    [:vote_confidence_100,  3.0],
    [:vote_confidence_80,   2.0],
    [:vote_confidence_60,   1.0],
    [:vote_confidence_40,  -1.0],
    [:vote_confidence_20,  -2.0],
    [:vote_confidence_0,   -3.0]
  ].freeze

  NO_OPINION_VAL = [:vote_no_opinion, 0].freeze

  # Force unit tests to verify existence of these translations.
  if false
    :vote_confidence_100.l
    :vote_confidence_80.l
    :vote_confidence_60.l
    :vote_confidence_40.l
    :vote_confidence_20.l
    :vote_confidence_0.l
    :vote_no_opinion.l
  end

  # List of options interpreted as "confidence".
  #
  #   for label, value in Vote.confidence_menu
  #     puts "#{label.l} #{value}"
  #   end
  #
  def self.confidence_menu
    translate_menu(CONFIDENCE_VALS)
  end

  def self.no_opinion
    :vote_no_opinion.l
  end

  def self.opinion_menu
    translate_menu([NO_OPINION_VAL] + confidence_menu)
  end

  # Find label of closest value in the "confidence" menu.
  def self.confidence(val)
    lookup_value(val, confidence_menu)
  end

  # ----------------------------
  #  :section: Other
  # ----------------------------

  LOG10 = Math.log(10)

  # Calculate user weight from contribution score.  Weight is logarithmic:
  #
  #   weight = log10(contribution) + 1   # owner of observation
  #   weight = log10(contribution)       # all other users
  #   weight = 0                         # if contribution <= 1
  #
  def user_weight
    contrib = user ? user.contribution : 0
    contrib = contrib < 1 ? 0 : Math.log(contrib) / LOG10
    contrib += 1 if observation && user == observation.user
    contrib
  end

  # I want to turn this silly logic into an explicit boolean in the table.
  # This is the first step: abstracting it as a method on Vote instance.
  # Now we are free to change the implementation later.
  def anonymous?
    (user.votes_anonymous == :no) ||
      (user.votes_anonymous == :old &&
       updated_at > Time.zone.parse(MO.vote_cutoff))
  end

  ##############################################################################

  protected

  # Find label of closest value in a given enumerated lists.
  def self.lookup_value(val, list) # :nodoc:
    last_pair = nil
    for pair in list
      next unless pair[1] != 0
      if !last_pair.nil? && val > (last_pair[1] + pair[1]) / 2
        return last_pair[0]
      end

      last_pair = pair
    end
    last_pair[0]
  end

  validate :check_requirements
  def check_requirements # :nodoc:
    errors.add(:naming, :validate_vote_naming_missing.t) unless naming
    errors.add(:user, :validate_vote_user_missing.t) if !user && !User.current

    if value.nil?
      errors.add(:value, :validate_vote_value_missing.t)
    elsif !/^[+-]?\d+(\.\d+)?$/.match?(value_before_type_cast.to_s)
      errors.add(:value, :validate_vote_value_not_integer.t)
    elsif value < MINIMUM_VOTE || value > MAXIMUM_VOTE
      errors.add(:value, :validate_vote_value_out_of_bounds.t)
    end
  end

  private

  def self.translate_menu(menu)
    result = []
    for k, v in menu
      result << [(k.is_a?(Symbol) ? k.l : k.to_s), v]
    end
    result
  end
end


text:
use heck::{KebabCase};
use quote::{ToTokens, Tokens, Ident};

use ast::*;

pub struct Routes {
    routes: Vec<Route>,
    assets: Tokens,
}

impl Routes {
    pub fn new(assets: Tokens, resources: &[RouteItem]) -> Routes {
        Routes {
            routes: Route::build(resources),
            assets,
        }
    }
}

impl ToTokens for Routes {
    fn to_tokens(&self, tokens: &mut Tokens) {
        let routes = &self.routes;
        let assets = &self.assets;
        tokens.append(quote! ({
            use ::cargonauts::server::NewService;
            let mut routes = ::cargonauts::routing::RouteBuilder::default();
            #(#routes)*
            #assets
            routes.build(env, timer)
        }));
    }
}

#[derive(Clone)]
struct Route {
    resource: String,
    endpoint: String,
    method: String,
    format: String,
    rel: Option<String>,
    rel_endpoint: Option<String>,
    middleware: Option<String>,
}

impl Route {
    fn build(routes: &[RouteItem]) -> Vec<Route> {
        fn routes_for_resource(vec: &mut Vec<Route>, resource: &Resource, module: Option<&str>) {
            let endpoint = match module {
                Some(module)    => {
                    match resource.header.endpoint.as_ref() {
                        Some(endpoint)  => [module, endpoint].join("/"),
                        None            => {
                            let endpoint = resource.header.ty.to_kebab_case();
                            [module, &endpoint].join("/")
                        }
                    }
                }
                None            => {
                    resource.header.endpoint.clone().unwrap_or_else(|| {
                        resource.header.ty.to_kebab_case()
                    })
                }
            };

            let resource_ty = &resource.header.ty;

            for (method, attrs) in resource.members.iter().filter_map(|m| m.as_method()) {
                let middleware = attrs.iter().filter_map(|attr| attr.as_middleware()).next();
                for m in &method.methods {
                    vec.push(Route {
                        resource: resource_ty.clone(),
                        endpoint: endpoint.clone(),
                        method: m.clone(),
                        format: method.format.clone(),
                        rel: None,
                        rel_endpoint: None,
                        middleware: middleware.clone(),
                    })
                }
            }

            for relation in resource.members.iter().filter_map(|m| m.as_relation()) {
                for (method, attrs) in relation.members.iter().filter_map(|m| m.as_method()) {
                    let middleware = attrs.iter().filter_map(|attr| attr.as_middleware()).next();
                    for m in &method.methods {
                        vec.push(Route {
                            resource: resource_ty.clone(),
                            endpoint: endpoint.clone(),
                            method: m.clone(),
                            format: method.format.clone(),
                            rel: Some(relation.rel.clone()),
                            rel_endpoint: relation.endpoint.clone().or_else(|| Some(relation.rel.to_kebab_case())),
                            middleware: middleware.clone(),
                        })
                    }
                }
            }
        }

        fn routes_for_item(vec: &mut Vec<Route>, item: &RouteItem, module: Option<&str>) {
            match *item {
                RouteItem::Resource(ref resource) => {
                    routes_for_resource(vec, resource, module);
                }
                RouteItem::Module(ref inner, ref items) => {
                    let module = match module {
                        Some(module) => [module, &inner.to_kebab_case()].join("/"),
                        None         => inner.to_owned()
                    };

                    for item in items {
                        routes_for_item(vec, item, Some(&module))
                    }
                }
            }
        }

        let mut vec = vec![];

        for item in routes {
            routes_for_item(&mut vec, item, None);
        }

        vec
    }
}

impl ToTokens for Route {
    fn to_tokens(&self, tokens: &mut Tokens) {
        let endpoint = &self.endpoint;
        let resource = Ident::new(&self.resource[..]);
        let format = Ident::new(&self.format[..]);
        let method = method_for(&self.method, self.rel.as_ref(), &resource);

        let http_method = quote!(<#method as ::cargonauts::methods::def::Method<#resource>>::ROUTE.method);

        let path = if let Some(ref rel) = self.rel_endpoint {
            quote!(::cargonauts::routing::path(<#method as ::cargonauts::methods::def::Method<#resource>>::ROUTE.kind, #endpoint, Some(#rel)))
        } else {
            quote!(::cargonauts::routing::path(<#method as ::cargonauts::methods::def::Method<#resource>>::ROUTE.kind, #endpoint, None))
        };

        let template_key = {
            let r = &self.resource;
            let m = &self.method;
            match self.rel {
                Some(ref rel)   => quote!(::cargonauts::formats::def::TemplateKey::new_rel(#r, #rel, #m)),
                None            => quote!(::cargonauts::formats::def::TemplateKey::new(#r, #m)),
            }
        };

        if let Some(ref middleware) = self.middleware {
            let middleware = Ident::new(&middleware[..]);
            tokens.append(quote!({
                let service = ::cargonauts::routing::EndpointService::<_, _, #resource, #format, #method, _>::new(#template_key, formats.get::<#format>());
                let service = ::cargonauts::middleware::Middleware::wrap(<#middleware as Default>::default(), service);
                routes.add(#http_method, #path, Box::new(service) as ::cargonauts::routing::Handler);
            }));
        } else {
            tokens.append(quote!({
                let service = ::cargonauts::routing::EndpointService::<_, _, #resource, #format, #method, _>::new(#template_key, formats.get::<#format>());
                routes.add(#http_method, #path, Box::new(service) as ::cargonauts::routing::Handler);
            }));
        }

    }
}

fn method_for(method: &str, rel: Option<&String>, resource: &Ident) -> Tokens {
    // Special cases to allow mainsail methods to have associated types
    match method {
        "Post"  => {
            quote!(Post<Identifier = <#resource as ::cargonauts::Resource>::Identifier, Post = <#resource as ::cargonauts::methods::Post>::Post>)
        }
        "Patch" => {
            quote!(Patch<Identifier = <#resource as ::cargonauts::Resource>::Identifier, Patch = <#resource as ::cargonauts::methods::Patch>::Patch>)
        }
        "PostRelated" => {
            let rel = Ident::new(&rel.unwrap()[..]);
            quote!(PostRelated<#rel, Identifier = <#resource as ::cargonauts::Resource>::Identifier, Post = <#resource as ::cargonauts::methods::PostRelated<#rel>::Post>)
        }
        "UpdateRelated" => {
            let rel = Ident::new(&rel.unwrap()[..]);
            quote!(UpdateRelated<#rel, Identifier = <#resource as ::cargonauts::Resource>::Identifier, Update = <#resource as ::cargonauts::methods::UpdateRelated<#rel>::Update>)
        }
        _       => {
            let method = Ident::new(method);
            match rel {
                Some(rel)   => {
                    let rel = Ident::new(&rel[..]);
                    quote!(#method<#rel, Identifier = <#resource as ::cargonauts::Resource>::Identifier>)
                }
                None        => {
                    quote!(#method<Identifier = <#resource as ::cargonauts::Resource>::Identifier>)
                }
            }
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import django.utils.timezone
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('ct', '0014_fsmgroup'),
        ('lti', '0002_auto_20150429_0310'),
    ]

    operations = [
        migrations.CreateModel(
            name='CourseRef',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('date', models.DateTimeField(default=django.utils.timezone.now, verbose_name=b'Creation date and time')),
                ('context_id', models.CharField(max_length=254, verbose_name=b'LTI context_id')),
                ('tc_guid', models.CharField(max_length=128, verbose_name=b'LTI tool_consumer_instance_guid')),
                ('course', models.ForeignKey(verbose_name=b'Courslet Course', to='ct.Course')),
                ('instructors', models.ManyToManyField(to=settings.AUTH_USER_MODEL, verbose_name=b'Course Instructors')),
            ],
            options={
                'verbose_name': 'CourseRef',
                'verbose_name_plural': 'CourseRefs',
            },
            bases=(models.Model,),
        ),
        migrations.AlterUniqueTogether(
            name='courseref',
            unique_together=set([('context_id', 'course')]),
        ),
        migrations.AlterField(
            model_name='ltiuser',
            name='course_id',
            field=models.CharField(max_length=255),
            preserve_default=True,
        ),
    ]


text:
This project is financial data and stadistics application using [AngularJS](http://angularjs.org/) and [Bootstrap](http://getbootstrap.com/).

The website is currently under development and I use to add new features in my free time and just for fun in order to improve my web programming skills. As you can clearly see under the demo site below, there is still so much work to do.

## Demo Site

You can take a look to some of these features here: [FinWallet](https://rawgit.com/ferpsanta/FinWallet/master/app/index.html).

| User        | Password           |
| ------------- |:-------------:|
| demo      | demo      |

You can also register but register is NonRestFull for the moment, so changes done are not permanent.

## JS modules
Under this section I'll describe briefly the diferent AngularJS modules or HTML views I have developed for FinWallet.

### Services

### Directives

### Controllers

### Views


text:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

// AppModule
import { AppModule } from './app';

// common styles
import './common/styles.scss';

if (process.env.NODE_ENV === 'production') {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);


text:
description: Upgrade Docker Universal Control Plane.
keywords:
- docker, ucp, upgrade
title: docker/ucp upgrade
---

Upgrade the UCP components on this Docker Engine.

## Usage

```
docker run --rm -it \
  --name ucp \
  -v /var/run/docker.sock:/var/run/docker.sock \
  docker/ucp \
  upgrade [OPTIONS]
```

## Description

When upgrading UCP, you must run the 'upgrade' command against every
engine in your cluster.  You should upgrade your controller and replica
nodes first, followed by your compute nodes.  If you plan to upgrade your
engine as well, upgrade the engine first, before upgrading UCP on the node.

After upgrading each node, confirm the node is present in the UCP console
before proceeding to the next node.

## Options

| Option                | Description                                                                             |
|:----------------------|:----------------------------------------------------------------------------------------|
| `--debug, -D`         | Enable debug                                                                            |
| `--jsonlog`           | Produce json formatted output for easier parsing                                        |
| `--interactive, -i`   | Enable interactive mode.,You will be prompted to enter all required information         |
| `--admin-username`    | Specify the UCP admin username [$UCP_ADMIN_USER]                                        |
| `--admin-password`    | Specify the UCP admin password [$UCP_ADMIN_PASSWORD]                                    |
| `--registry-username` | Specify the username to pull required images with [$REGISTRY_USERNAME]                  |
| `--registry-password` | Specify the password to pull required images with [$REGISTRY_PASSWORD]                  |
| `--id`                | The ID of the UCP instance to upgrade                                                   |
| `--pull "always"`     | Specify image pull behavior ('always', when 'missing', or 'never') (default: "missing") |