text:
using System;
using System.ComponentModel;
using System.Diagnostics;
using MigraDoc.DocumentObjectModel.Internals;

namespace MigraDoc.DocumentObjectModel
{
  ///
  /// An Unit consist of a numerical value and an UnitType like Centimeter, Millimeter or Inch.
  /// Several conversion between different measures are supported.
  ///
  public struct Unit : IFormattable, INullableValue
  {
    ///
    /// Initializes a new instance of the Unit class with type set to point.
    ///
    public Unit(double point)
    {
      this.value = (float)point;
      this.type = UnitType.Point;
      this.initialized = true;
    }

    ///
    /// Initializes a new instance of the Unit class.
    /// Throws System.ArgumentException if type is invalid.
    ///
    public Unit(double value, UnitType type)
    {
      if (!Enum.IsDefined(typeof(UnitType), type))
        throw new InvalidEnumArgumentException("type", (int)type, type.GetType());

      this.value = (float)value;
      this.type = type;
      this.initialized = true;
    }

    ///
    /// Determines whether this instance is empty.
    ///
    public bool IsEmpty
    {
      get { return IsNull; }
    }

    ///
    /// Gets the value of the unit.
    ///
    object INullableValue.GetValue()
    {
      return this;
    }

    ///
    /// Sets the unit to the given value.
    ///
    void INullableValue.SetValue(object value)
    {
      if (value == null)
        throw new ArgumentNullException("value");

      if (value is Unit)
        this = (Unit)value;
      else
        this = value.ToString();
    }

    ///
    /// Resets this instance,
    /// i.e. IsNull() will return true afterwards.
    ///
    void INullableValue.SetNull()
    {
      this.value = 0;
      this.type = UnitType.Point;
      this.initialized = false;
    }

    // Explicit interface implementations cannot contain access specifiers, i.e. they are accessible by a
    // cast operator only, e.g. ((IDomValue)obj).IsNull.
    // Therefore the second IsNull-Property is used as a handy shortcut.
    ///
    /// Determines whether this instance is null (not set).
    ///
    bool INullableValue.IsNull
    {
      get { return IsNull; }
    }

    ///
    /// Determines whether this instance is null (not set).
    ///
    internal bool IsNull
    {
      get { return !this.initialized; }
    }

    #region Properties
    ///
    /// Gets or sets the raw value of the object without any conversion.
    /// To determine the UnitType use property Type.
    ///
    public double Value
    {
      get { return (IsNull ? 0 : this.value); }
      set
      {
        this.value = (float)value;
        this.initialized = true;
      }
    }

    ///
    /// Gets the UnitType of the object.
    ///
    public UnitType Type
    {
      get { return this.type; }
    }

    ///
    /// Gets or sets the value in point.
    ///
    public double Point
    {
      get
      {
        if (IsNull)
          return 0;

        switch (this.type)
        {
          case UnitType.Centimeter:
            return this.value * 72 / 2.54;

          case UnitType.Inch:
            return this.value * 72;

          case UnitType.Millimeter:
            return this.value * 72 / 25.4;

          case UnitType.Pica:
            return this.value * 12;

          case UnitType.Point:
            return this.value;

          default:
            Debug.Assert(false, "Missing unit type.");
            return 0;
        }
      }
      set
      {
        this.value = (float)value;
        this.type = UnitType.Point;
        this.initialized = true;
      }
    }

    [Obsolete("Use Point")]
    public double Pt
    {
      get { return Point; }
      set { Point = value; }
    }

    ///
    /// Gets or sets the value in centimeter.
    ///
    public double Centimeter
    {
      get
      {
        if (IsNull)
          return 0;

        switch (this.type)
        {
          case UnitType.Centimeter:
            return this.value;

          case UnitType.Inch:
            return this.value * 2.54;

          case UnitType.Millimeter:
            return this.value / 10;

          case UnitType.Pica:
            return this.value * 12 * 2.54 / 72;

          case UnitType.Point:
            return this.value * 2.54 / 72;

          default:
            Debug.Assert(false, "Missing unit type");
            return 0;
        }
      }
      set
      {
        this.value = (float)value;
        this.type = UnitType.Centimeter;
        this.initialized = true;
      }
    }

    [Obsolete("Use Centimeter")]
    public double Cm
    {
      get { return Centimeter; }
      set { Centimeter = value; }
    }

    ///
    /// Gets or sets the value in inch.
    ///
    public double Inch
    {
      get
      {
        if (IsNull)
          return 0;

        switch (this.type)
        {
          case UnitType.Centimeter:
            return this.value / 2.54;

          case UnitType.Inch:
            return this.value;

          case UnitType.Millimeter:
            return this.value / 25.4;

          case UnitType.Pica:
            return this.value * 12 / 72;

          case UnitType.Point:
            return this.value / 72;

          default:
            Debug.Assert(false, "Missing unit type");
            return 0;
        }
      }
      set
      {
        this.value = (float)value;
        this.type = UnitType.Inch;
        this.initialized = true;
      }
    }

    [Obsolete("Use Inch")]
    public double In
    {
      get { return Inch; }
      set { Inch = value; }
    }

    ///
    /// Gets or sets the value in millimeter.
    ///
    public double Millimeter
    {
      get
      {
        if (IsNull)
          return 0;

        switch (this.type)
        {
          case UnitType.Centimeter:
            return this.value * 10;

          case UnitType.Inch:
            return this.value * 25.4;

          case UnitType.Millimeter:
            return this.value;

          case UnitType.Pica:
            return this.value * 12 * 25.4 / 72;

          case UnitType.Point:
            return this.value * 25.4 / 72;

          default:
            Debug.Assert(false, "Missing unit type");
            return 0;
        }
      }
      set
      {
        this.value = (float)value;
        this.type = UnitType.Millimeter;
        this.initialized = true;
      }
    }

    [Obsolete("Use Millimeter")]
    public double Mm
    {
      get { return Millimeter; }
      set { Millimeter = value; }
    }

    ///
    /// Gets or sets the value in pica.
    ///
    public double Pica
    {
      get
      {
        if (IsNull)
          return 0;

        switch (this.type)
        {
          case UnitType.Centimeter:
            return this.value * 72 / 2.54 / 12;

          case UnitType.Inch:
            return this.value * 72 / 12;

          case UnitType.Millimeter:
            return this.value * 72 / 25.4 / 12;

          case UnitType.Pica:
            return this.value;

          case UnitType.Point:
            return this.value / 12;

          default:
            Debug.Assert(false, "Missing unit type");
            return 0;
        }
      }
      set
      {
        this.value = (float)value;
        this.type = UnitType.Pica;
        this.initialized = true;
      }
    }

    [Obsolete("Use Pica")]
    public double Pc
    {
      get { return Pica; }
      set { Pica = value; }
    }
    #endregion

    #region Methods
    ///
    /// Returns the object as string using the format information.
    /// Measure will be added to the end of the string.
    ///
    public string ToString(System.IFormatProvider formatProvider)
    {
      if (IsNull)
        return 0.ToString(formatProvider); // TODO: ?? can it be anything other than "0"??

      string valuestring;
      valuestring = this.value.ToString(formatProvider) + GetSuffix();
      return valuestring;
    }

    ///
    /// Returns the object as string using the format.
    /// Measure will be added to the end of the string.
    ///
    public string ToString(string format)
    {
      if (IsNull)
        return 0.ToString(format); // TODO: ?? can it be anything other than "0"??

      string valuestring;
      valuestring = this.value.ToString(format) + GetSuffix();
      return valuestring;
    }

    ///
    /// Returns the object as string using the specified format and format information.
    /// Measure will be added to the end of the string.
    ///
    string System.IFormattable.ToString(string format, IFormatProvider formatProvider)
    {
      if (IsNull)
        return 0.ToString(format, formatProvider);

      string valuestring;
      valuestring = this.value.ToString(format, formatProvider) + GetSuffix();
      return valuestring;
    }

    ///
    /// Returns the object as string. Measure will be added to the end of the string.
    ///
    public override string ToString()
    {
      if (IsNull)
        return 0.ToString(System.Globalization.CultureInfo.InvariantCulture);

      string valuestring;
      valuestring = this.value.ToString(System.Globalization.CultureInfo.InvariantCulture) + GetSuffix();
      return valuestring;
    }

    ///
    /// Returns the type of the object as a string like 'pc', 'cm', or 'in'. Empty string is equal to 'pt'.
    ///
    string GetSuffix()
    {
      switch (this.type)
      {
        case UnitType.Centimeter:
          return "cm";

        case UnitType.Inch:
          return "in";

        case UnitType.Millimeter:
          return "mm";

        case UnitType.Pica:
          return "pc";

        case UnitType.Point:
          //Point is default, so leave this blank.
          return "";

        default:
          Debug.Assert(false, "Missing unit type");
          return "";
      }
    }

    ///
    /// Returns an Unit object. Sets type to centimeter.
    ///
    public static Unit FromCentimeter(double value)
    {
      Unit unit = Unit.Zero;
      unit.value = (float)value;
      unit.type = UnitType.Centimeter;
      return unit;
    }

    [Obsolete("Use FromCentimer")]
    public static Unit FromCm(double value)
    {
      return FromCentimeter(value);
    }

    ///
    /// Returns an Unit object. Sets type to millimeter.
    ///
    public static Unit FromMillimeter(double value)
    {
      Unit unit = Unit.Zero;
      unit.value = (float)value;
      unit.type = UnitType.Millimeter;
      return unit;
    }

    ///
    /// Returns an Unit object. Sets type to millimeter.
    ///
    [Obsolete("Use FromMillimeter")]
    public static Unit FromMm(double value)
    {
      return FromMillimeter(value);
    }

    ///
    /// Returns an Unit object. Sets type to point.
    ///
    public static Unit FromPoint(double value)
    {
      Unit unit = Unit.Zero;
      unit.value = (float)value;
      unit.type = UnitType.Point;
      return unit;
    }

    ///
    /// Returns an Unit object. Sets type to inch.
    ///
    public static Unit FromInch(double value)
    {
      Unit unit = Unit.Zero;
      unit.value = (float)value;
      unit.type = UnitType.Inch;
      return unit;
    }

    ///
    /// Returns an Unit object. Sets type to pica.
    ///
    public static Unit FromPica(double value)
    {
      Unit unit = Unit.Zero;
      unit.value = (float)value;
      unit.type = UnitType.Pica;
      return unit;
    }
    #endregion

    ///
    /// Converts a string to an Unit object.
    /// If the string contains a suffix like 'cm' or 'in' the object will be converted
    /// to the appropriate type, otherwise point is assumed.
    ///
    public static implicit operator Unit(string value)
    {
      Unit unit = Unit.Zero;
      value = value.Trim();

      // For Germans...
      value = value.Replace(',', '.');

      int count = value.Length;
      int valLen = 0;
      for (; valLen < count; )
      {
        char ch = value[valLen];
        if (ch == '.' || ch == '-' || ch == '+' || Char.IsNumber(ch))
          valLen++;
        else
          break;
      }

      unit.value = 1;
      try
      {
        unit.value = float.Parse(value.Substring(0, valLen).Trim(), System.Globalization.CultureInfo.InvariantCulture);
      }
      catch (FormatException ex)
      {
        throw new ArgumentException(DomSR.InvalidUnitValue(value), ex);
      }

      string typeStr = value.Substring(valLen).Trim().ToLower();
      unit.type = UnitType.Point;
      switch (typeStr)
      {
        case "cm":
          unit.type = UnitType.Centimeter;
          break;

        case "in":
          unit.type = UnitType.Inch;
          break;

        case "mm":
          unit.type = UnitType.Millimeter;
          break;

        case "pc":
          unit.type = UnitType.Pica;
          break;

        case "":
        case "pt":
          unit.type = UnitType.Point;
          break;

        default:
          throw new ArgumentException(DomSR.InvalidUnitType(typeStr));
      }

      return unit;
    }

    ///
    /// Converts an int to an Unit object with type set to point.
    ///
    public static implicit operator Unit(int value)
    {
      Unit unit = Unit.Zero;
      unit.value = value;
      unit.type = UnitType.Point;
      return unit;
    }

    ///
    /// Converts a float to an Unit object with type set to point.
    ///
    public static implicit operator Unit(float value)
    {
      Unit unit = Unit.Zero;
      unit.value = value;
      unit.type = UnitType.Point;
      return unit;
    }

    ///
    /// Converts a double to an Unit object with type set to point.
    ///
    public static implicit operator Unit(double value)
    {
      Unit unit = Unit.Zero;
      unit.value = (float)value;
      unit.type = UnitType.Point;
      return unit;
    }

    ///
    /// Returns a double value as point.
    ///
    public static implicit operator double(Unit value)
    {
      return value.Point;
    }

    ///
    /// Returns a float value as point.
    ///
    public static implicit operator float(Unit value)
    {
      return (float)value.Point;
    }

    ///
    /// Memberwise comparison. To compare by value,
    /// use code like Math.Abs(a.Point - b.Point) < 1e-5.
    ///
    public static bool operator ==(Unit l, Unit r)
    {
      return (l.initialized == r.initialized && l.type == r.type && l.value == r.value);
    }

    ///
    /// Memberwise comparison. To compare by value,
    /// use code like Math.Abs(a.Point - b.Point) < 1e-5.
    ///
    public static bool operator !=(Unit l, Unit r)
    {
      return !(l == r);
    }

    ///
    /// Calls base class Equals.
    ///
    public override bool Equals(Object obj)
    {
      return base.Equals(obj);
    }

    ///
    /// Calls base class GetHashCode.
    ///
    public override int GetHashCode()
    {
      return base.GetHashCode();
    }

    ///
    /// This member is intended to be used by XmlDomainObjectReader only.
    ///
    public static Unit Parse(string value)
    {
      Unit unit = Unit.Zero;
      unit = value;
      return unit;
    }

    ///
    /// Converts an existing object from one unit into another unit type.
    ///
    public void ConvertType(UnitType type)
    {
      if (this.type == type)
        return;

      if (!Enum.IsDefined(typeof(UnitType), type))
        throw new ArgumentException(DomSR.InvalidUnitType(type.ToString()));

      switch (type)
      {
        case UnitType.Centimeter:
          this.value = (float)this.Centimeter;
          this.type = UnitType.Centimeter;
          break;

        case UnitType.Inch:
          this.value = (float)this.Inch;
          this.type = UnitType.Inch;
          break;

        case UnitType.Millimeter:
          this.value = (float)this.Millimeter;
          this.type = UnitType.Millimeter;
          break;

        case UnitType.Pica:
          this.value = (float)this.Pica;
          this.type = UnitType.Pica;
          break;

        case UnitType.Point:
          this.value = (float)this.Point;
          this.type = UnitType.Point;
          break;

        default:
          //Remember missing unit type!!!
          Debug.Assert(false, "Missing unit type");
          break;
      }
    }

    ///
    /// Represents the uninitialized Unit object.
    ///
    public static readonly Unit Empty = new Unit();

    ///
    /// Represents an initialized Unit object with value 0 and unit type point.
    ///
    public static readonly Unit Zero = new Unit(0);

    ///
    /// Represents the uninitialized Unit object. Same as Unit.Empty.
    ///
    internal static readonly Unit NullValue = Unit.Empty;

    bool initialized;
    float value;
    UnitType type;
  }
}


text:
package org.assertj.core.internal.comparables;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.error.ShouldBeBetween.shouldBeBetween;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.mockito.Mockito.verify;

import java.math.BigInteger;

import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.ComparablesBaseTest;
import org.junit.Test;

public class Comparables_isBetween_Test extends ComparablesBaseTest {

  @Test
  public void succeeds_if_actual_is_between_start_and_end() {
    assertThat(BigInteger.ONE).isBetween(BigInteger.ZERO, BigInteger.TEN);
  }

  @Test
  public void succeeds_if_actual_is_equal_to_start() {
    comparables.assertIsBetween(someInfo(), 8, 8, 10, true, true);
  }

  @Test
  public void succeeds_if_actual_is_equal_to_end() {
    comparables.assertIsBetween(someInfo(), 10, 8, 10, true, true);
  }

  @Test
  public void fails_if_actual_is_less_than_start() {
    thrown.expectAssertionError("%nExpecting:%n <6>%nto be between:%n [8, 10]");
    comparables.assertIsBetween(someInfo(), 6, 8, 10, true, true);
  }

  @Test
  public void fails_if_actual_is_greater_than_end() {
    thrown.expectAssertionError("%nExpecting:%n <12>%nto be between:%n [8, 10]");
    comparables.assertIsBetween(someInfo(), 12, 8, 10, true, true);
  }

  @Test
  public void should_fail_if_actual_is_null() {
    thrown.expectAssertionError(actualIsNull());
    comparables.assertIsBetween(someInfo(), null, 8, 10, true, true);
  }

  @Test
  public void should_fail_if_start_is_null() {
    thrown.expectNullPointerException("The start range to compare actual with should not be null");
    comparables.assertIsBetween(someInfo(), 8, null, 10, true, true);
  }

  @Test
  public void should_fail_if_end_is_null() {
    thrown.expectNullPointerException("The end range to compare actual with should not be null");
    comparables.assertIsBetween(someInfo(), 8, 10, null, true, true);
  }

  @Test
  public void should_fail_if_end_is_less_than_start() {
    thrown.expectIllegalArgumentException("The end value <8> must not be less than the start value <10>!");
    comparables.assertIsBetween(someInfo(), 8, 10, 8, true, true);
  }

  @Test
  public void succeeds_if_end_is_equal_to_start() {
    comparables.assertIsBetween(someInfo(), 8, 8, 8, true, true);
  }

  // ------------------------------------------------------------------------------------------------------------------
  // tests using a custom comparison strategy
  // ------------------------------------------------------------------------------------------------------------------

  @Test
  public void succeeds_if_actual_is_between_start_and_end_according_to_custom_comparison_strategy() {
    comparablesWithCustomComparisonStrategy.assertIsBetween(someInfo(), -7, 6, 8, true, true);
  }

  @Test
  public void fails_if_actual_is_is_greater_than_end_according_to_custom_comparison_strategy() {
    AssertionInfo info = someInfo();
    try {
      comparablesWithCustomComparisonStrategy.assertIsBetween(someInfo(), -12, 8, 10, true, true);
    } catch (AssertionError e) {
      verify(failures).failure(info, shouldBeBetween(-12, 8, 10, true, true, customComparisonStrategy));
      return;
    }
    failBecauseExpectedAssertionErrorWasNotThrown();
  }

  @Test
  public void fails_if_actual_is_is_less_than_start_according_to_custom_comparison_strategy() {
    AssertionInfo info = someInfo();
    try {
      comparablesWithCustomComparisonStrategy.assertIsBetween(someInfo(), 6, -8, 10, true, true);
    } catch (AssertionError e) {
      verify(failures).failure(info, shouldBeBetween(6, -8, 10, true, true, customComparisonStrategy));
      return;
    }
    failBecauseExpectedAssertionErrorWasNotThrown();
  }

  @Test
  public void fails_if_end_is_less_than_start_according_to_custom_comparison_strategy() {
    thrown.expectIllegalArgumentException("The end value <8> must not be less than the start value <-10> (using 'AbsValueComparator')!");
    comparablesWithCustomComparisonStrategy.assertIsBetween(someInfo(), 8, -10, 8, true, true);
  }

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<title>Emerging Mapping Technologies – NACIS 2012</title>
	<link rel="stylesheet" type="text/css" href="css/style.css" />

Emerging Mapping Technologies – NACIS 2012

	<embed src="emerging-web-mapping-donohue-et-al-nacis2012.pdf" width="90%" height="768px">


text:
@implementation orderStatusTableViewCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.header=[[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 70*WidthScale, 70*WidthScale)];
        self.header.layer.cornerRadius=35*WidthScale;
        self.header.clipsToBounds=YES;
        [self.contentView addSubview:self.header];

        self.name=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.header.frame)+10, 35*WidthScale, 80, 15)];
        self.name.textColor=[UIColor blackColor];
        self.name.textAlignment=NSTextAlignmentLeft;
        [self.contentView addSubview:self.name];

        self.time=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-160, 35*WidthScale, 150, 15)];
        self.time.font=[UIFont systemFontOfSize:14];
        self.time.textColor=Color(221, 221, 221);
        self.time.textAlignment=NSTextAlignmentRight;
        [self.contentView addSubview:self.time];

        UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0, 99*WidthScale-1, ScreenWidth, 1)];
        line.backgroundColor=Color(221, 221, 221);
        [self.contentView addSubview:line];
    }
    return self;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------
namespace Weixin\Api;
use \Common\Api\Api;
use \Common\Model\VoteOptionResultModel;

class VoteOptionResultApi extends Api{
	protected function _init(){
		$this->model = new VoteOptionResultModel();
	}

	/**
	 * 单人投票数
	 *
	 */
	public function myVoteCount($map){
		$result = $this->model->field("count(option_id) as option_cnt,vote_id ,option_id")->where($map)->group("option_id,vote_id")->order(' option_cnt desc')->select();
		if($result === false){
			return $this->apiReturnErr($this->model->getDbError());
		}

		return $this->apiReturnSuc($result);
	}

	/**
	 * 各选项投票人数统计
	 */
	public function voteCount($option_ids){
		$map = array();

		$map['option_id'] = array('in',$option_ids);
		$result = $this->model->field("option_id,vote_id ,count(real_ip) as cnt")->where($map)->group("option_id,vote_id")->order(' cnt desc')->select();

		if($result === false){
			return $this->apiReturnErr($this->model->getDbError());
		}

		return $this->apiReturnSuc($result);

	}
}


text:
Tutorial: Ping
==============

One of the benefits of Python is the ease with which interfacing is possible.
In this tutorial we'll look at interfacing the standard GNU `ping`_ command
to the simulator. Using Python we can ping our DUT with fewer than 50 lines of
code.

For the impatient this tutorial is provided as an example with Cocotb. You can
run this example from a fresh checkout::

    cd examples/ping_tun_tap/tests
    sudo make

.. note:: To create a virtual interface the test either needs root permissions or have CAP_NET_ADMIN capability.

Architecture
------------

We have a simple RTL block that takes ICMP echo requests and generates an ICMP
echo response.  To verify this behaviour we want to run the `ping`_ utility
against our RTL running in the simulator.

In order to achieve this we need to capture the packets that are created by
ping, drive them onto the pins of our DUT in simulation, monitor the output of
the DUT and send any responses back to the ping process.

Linux has a `TUN/TAP`_ virtual network device which we can use for this
purpose, allowing `ping`_ to run unmodified and unaware that it is
communicating with our simulation rather than a remote network endpoint.

.. image:: diagrams/svg/ping_tun_tap.svg

Implementation
--------------

First of all we need to work out how to create a virtual interface. Python has
a huge developer base and a quick search of the web reveals a `TUN example`_
that looks like an ideal starting point for our testbench. Using this example
we write a function that will create our virtual interface:

.. code-block:: python

    import subprocess, fcntl, struct

    def create_tun(name="tun0", ip="192.168.255.1"):
        TUNSETIFF = 0x400454ca
        TUNSETOWNER = TUNSETIFF + 2
        IFF_TUN = 0x0001
        IFF_NO_PI = 0x1000
        tun = open('/dev/net/tun', 'r+b')
        ifr = struct.pack('16sH', name, IFF_TUN | IFF_NO_PI)
        fcntl.ioctl(tun, TUNSETIFF, ifr)
        fcntl.ioctl(tun, TUNSETOWNER, 1000)
        subprocess.check_call('ifconfig tun0 %s up pointopoint 192.168.255.2 up' % ip, shell=True)
        return tun

Now we can get started on the actual test.  First of all we'll create a clock
signal and connect up the Avalon driver and monitor to the DUT.  To help debug
the testbench we'll enable verbose debug on the drivers and monitors by setting
the log level to **logging.DEBUG**.

.. code-block:: python

    import cocotb
    from cocotb.clock import Clock
    from cocotb.drivers.avalon import AvalonSTPkts as AvalonSTDriver
    from cocotb.monitors.avalon import AvalonSTPkts as AvalonSTMonitor

    @cocotb.test()
    def tun_tap_example_test(dut):
        cocotb.fork(Clock(dut.clk, 5000).start())

        stream_in  = AvalonSTDriver(dut, "stream_in", dut.clk)
        stream_out = AvalonSTMonitor(dut, "stream_out", dut.clk)

        # Enable verbose logging on the streaming interfaces
        stream_in.log.setLevel(logging.DEBUG)
        stream_out.log.setLevel(logging.DEBUG)

We also need to reset the DUT and drive some default values onto some of the
bus signals.  Note that we'll need to import the **Timer** and **RisingEdge**
triggers.

.. code-block:: python

        # Reset the DUT
        dut.log.debug("Resetting DUT")
        dut.reset_n <= 0
        stream_in.bus.valid <= 0
        yield Timer(10000)
        yield RisingEdge(dut.clk)
        dut.reset_n <= 1
        dut.stream_out_ready <= 1

The rest of the test becomes fairly straightforward.  We create our TUN
interface using our function defined previously.  We'll also use the
**subprocess** module to actually start the ping command.

We then wait for a packet by calling a blocking read call on the TUN file
descriptor and simply append that to the queue on the driver. We wait for
a packet to arrive on the monitor by yielding on wait_for_recv() and then
write the received packet back to the TUN file descriptor.

.. code-block:: python

    # Create our interface (destroyed at the end of the test)
    tun = create_tun()
    fd = tun.fileno()

    # Kick off a ping...
    subprocess.check_call('ping -c 5 192.168.255.2 &', shell=True)

    # Respond to 5 pings, then quit
    for i in xrange(5):

        cocotb.log.info("Waiting for packets on tun interface")
        packet = os.read(fd, 2048)
        cocotb.log.info("Received a packet!")

        stream_in.append(packet)
        result = yield stream_out.wait_for_recv()

        os.write(fd, str(result))

That's it - simple!

Further work
------------

This example is deliberately simplistic to focus on the fundamentals of
interfacing to the simulator using TUN/TAP. As an exercise for the reader a
useful addition would be to make the file descriptor non-blocking and spawn
out separate coroutines for the monitor / driver, thus decoupling the sending
and receiving of packets.

.. _TUN example: https://gist.github.com/glacjay/585369

.. _Ping: http://www.gnu.org/software/inetutils/manual/html_node/ping-invocation.html

.. _TUN/TAP: http://en.wikipedia.org/wiki/TUN/TAP