text:
package org.newdawn.slick.tools.hiero;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.font.GlyphMetrics;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.RasterFormatException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.newdawn.slick.SlickException;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.font.Glyph;
import org.newdawn.slick.font.GlyphPage;
import org.newdawn.slick.imageout.ImageIOWriter;
import org.newdawn.slick.util.Log;
import org.newdawn.slick.util.ResourceLoader;

/**
 * @author Nathan Sweet <misc@n4te.com>
 */
public class BMFontUtil {
	private final UnicodeFont unicodeFont;

	public BMFontUtil (UnicodeFont unicodeFont) {
		this.unicodeFont = unicodeFont;
	}

	public void save(File f) throws IOException, SlickException {
		save(f, true, true);
	}

	public void save (File outputBMFontFile, boolean flip,
			boolean antiAliasing) throws IOException, SlickException {
		File outputDir = outputBMFontFile.getParentFile();
		String outputName = outputBMFontFile.getName();
		if (outputName.endsWith(".fnt")) outputName = outputName.substring(0, outputName.length() - 4);

		unicodeFont.loadGlyphs();

		PrintStream out = new PrintStream(new FileOutputStream(new File(outputDir, outputName + ".fnt")));
		Font font = unicodeFont.getFont();

		int lineHeight = unicodeFont.getLineHeight();

		int pageWidth = unicodeFont.getGlyphPageWidth();
		int pageHeight = unicodeFont.getGlyphPageHeight();
		out.println("info face=\"" + font.getFontName() + "\" size=" + font.getSize() + " bold=" + (font.isBold() ? 1 : 0)
			+ " italic=" + (font.isItalic() ? 1 : 0)
			+ " charset=\"\" unicode=0 stretchH=100 smooth=1 aa="+(antiAliasing?1:0)+" padding=0,0,0,0 spacing=0,0");
		out.println("common lineHeight=" + lineHeight + " base="+unicodeFont.getAscent()+" scaleW=" + pageWidth + " scaleH=" + pageHeight
			+ " pages=" + unicodeFont.getGlyphPages().size() + " packed=0 ascent="
				+unicodeFont.getAscent()+" descent="+unicodeFont.getDescent()+" leading="+unicodeFont.getLeading());

		int pageIndex = 0, glyphCount = 0;
		for (Iterator pageIter = unicodeFont.getGlyphPages().iterator(); pageIter.hasNext();) {
			GlyphPage page = (GlyphPage)pageIter.next();
			String fileName;
			if (pageIndex == 0 && !pageIter.hasNext())
				fileName = outputName + ".png";
			else
				fileName = outputName + (pageIndex + 1) + ".png";
			out.println("page id=" + pageIndex + " file=\"" + fileName + "\"");
			glyphCount += page.getGlyphs().size();
			pageIndex++;
		}

		out.println("chars count=" + glyphCount);

		// Always output space entry (codepoint 32).
		int[] glyphMetrics = getGlyphMetrics(font, 32);
		int xAdvance = glyphMetrics[1];
		out.println("char id=32   x=0     y=0     width=0     height=0     xoffset=0     yoffset=" + unicodeFont.getAscent()
			+ "    xadvance=" + xAdvance + "     page=0  chnl=0 ");

		pageIndex = 0;
		List allGlyphs = new ArrayList(512);
		for (Iterator pageIter = unicodeFont.getGlyphPages().iterator(); pageIter.hasNext();) {
			GlyphPage page = (GlyphPage)pageIter.next();
			for (Iterator glyphIter = page.getGlyphs().iterator(); glyphIter.hasNext();) {
				Glyph glyph = (Glyph)glyphIter.next();

				glyphMetrics = getGlyphMetrics(font, glyph.getCodePoint());
				int xOffset = glyphMetrics[0];
				xAdvance = glyphMetrics[1];

				out.println("char id=" + glyph.getCodePoint() + "   " + "x="
					+ (int)(glyph.getImage().getTextureOffsetX() * pageWidth) + "     y="
					+ (int)(glyph.getImage().getTextureOffsetY() * pageHeight) + "     width=" + glyph.getWidth() + "     height="
					+ glyph.getHeight() + "     xoffset=" + xOffset + "     yoffset=" + glyph.getYOffset() + "    xadvance="
					+ xAdvance + "     page=" + pageIndex + "  chnl=0 ");
			}
			allGlyphs.addAll(page.getGlyphs());
			pageIndex++;
		}

		String ttfFileRef = unicodeFont.getFontFile();
		if (ttfFileRef == null)
			Log.warn("Kerning information could not be output because a TTF font file was not specified.");
		else {
			Kerning kerning = new Kerning();
			try {
				kerning.load(ResourceLoader.getResourceAsStream(ttfFileRef), font.getSize());
			} catch (IOException ex) {
				Log.warn("Unable to read kerning information from font: " + ttfFileRef);
			}

			Map glyphCodeToCodePoint = new HashMap();
			for (Iterator iter = allGlyphs.iterator(); iter.hasNext();) {
				Glyph glyph = (Glyph)iter.next();
				glyphCodeToCodePoint.put(new Integer(getGlyphCode(font, glyph.getCodePoint())), new Integer(glyph.getCodePoint()));
			}

			List kernings = new ArrayList(256);
			class KerningPair {
				public int firstCodePoint, secondCodePoint, offset;
			}
			for (Iterator iter1 = allGlyphs.iterator(); iter1.hasNext();) {
				Glyph firstGlyph = (Glyph)iter1.next();
				int firstGlyphCode = getGlyphCode(font, firstGlyph.getCodePoint());
				int[] values = kerning.getValues(firstGlyphCode);
				if (values == null) continue;
				for (int i = 0; i < values.length; i++) {
					Integer secondCodePoint = (Integer)glyphCodeToCodePoint.get(new Integer(values[i] & 0xffff));
					if (secondCodePoint == null) continue; // We may not be outputting the second character.
					int offset = values[i] >> 16;
					KerningPair pair = new KerningPair();
					pair.firstCodePoint = firstGlyph.getCodePoint();
					pair.secondCodePoint = secondCodePoint.intValue();
					pair.offset = offset;
					kernings.add(pair);
				}
			}
			out.println("kernings count=" + kerning.getCount());
			for (Iterator iter = kernings.iterator(); iter.hasNext();) {
				KerningPair pair = (KerningPair)iter.next();
				out.println("kerning first=" + pair.firstCodePoint + "  second=" + pair.secondCodePoint + "  amount=" + pair.offset);
			}
		}
		out.close();

		pageIndex = 0;
		ImageIOWriter imageWriter = new ImageIOWriter();
		for (Iterator pageIter = unicodeFont.getGlyphPages().iterator(); pageIter.hasNext();) {
			GlyphPage page = (GlyphPage)pageIter.next();
			String fileName;
			if (pageIndex == 0 && !pageIter.hasNext())
				fileName = outputName + ".png";
			else
				fileName = outputName + (pageIndex + 1) + ".png";
			File imageOutputFile = new File(outputDir, fileName);
			FileOutputStream imageOutput = new FileOutputStream(imageOutputFile);
			try {
				imageWriter.saveImage(page.getImage(), "png", imageOutput, true);
			} finally {
				imageOutput.close();
			}
			// TOOD: fix this for all systems!
			// Flip output image.
			if (flip) { //flips horizontally and re-saves
				Image image = new ImageIcon(imageOutputFile.getAbsolutePath()).getImage();
				BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
				Graphics g = bufferedImage.getGraphics();
				g.drawImage(image, 0, 0, null);
				try {
					AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
                    tx.translate(0, -image.getHeight(null));
                    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
                    bufferedImage = op.filter(bufferedImage, null);
				} catch (RasterFormatException ex) {
					Log.error(ex);
				}
				ImageIO.write(bufferedImage, "png", imageOutputFile);
			}

			pageIndex++;
		}
	}

	private int getGlyphCode (Font font, int codePoint) {
		char[] chars = Character.toChars(codePoint);
		GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
		return vector.getGlyphCode(0);
	}

	private int[] getGlyphMetrics (Font font, int codePoint) {
		// xOffset and xAdvance will be incorrect for unicode characters such as combining marks or non-spacing characters
		// (eg Pnujabi's "\u0A1C\u0A47") that require the context of surrounding glyphs to determine spacing, but thisis the
		// best we can do with the BMFont format.
		char[] chars = Character.toChars(codePoint);
		GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
		GlyphMetrics metrics = vector.getGlyphMetrics(0);
		int xOffset = vector.getGlyphPixelBounds(0, null, 0, 0).x - unicodeFont.getPaddingLeft();
		int xAdvance = (int)(metrics.getAdvanceX() + unicodeFont.getPaddingAdvanceX() + unicodeFont.getPaddingLeft() + unicodeFont
			.getPaddingRight());
		return new int[] {xOffset, xAdvance};
	}
}


text:
using System;
using Xamarin.Auth.Helpers;

namespace Xamarin.Auth.SampleData
{
	public partial class Data
	{
		static partial void SetPublicDemoDataLinkedInOAuth2()
		{
			/*
			https://www.linkedin.com/secure/developer
			https://developer.linkedin.com/docs/oauth2
			https://developer.linkedin.com/docs/
			https://developer.linkedin.com/docs/signin-with-linkedin

			http://forums.xamarin.com/discussion/14883/login-with-linkedin
			https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=***"

			http://forums.xamarin.com/discussion/25457/xamarin-auth

			TODO: need testing... not quite correct

			*/
			oauth2 = new Xamarin.Auth.Helpers.OAuth2()
			{
				Description = "LinkedIn OAuth2",
				OAuth_IdApplication_IdAPI_KeyAPI_IdClient_IdCustomer = "",
				OAuth2_Scope = "r_basicprofile",
				OAuth_UriAuthorization =
							new Uri
								(
									"https://www.linkedin.com/uas/oauth2/authorization?response_type=code"
									+
									"&client_id=" + ""
									+
									"&scope=" + Uri.EscapeDataString("r_basicprofile")
									+
									"&redirect_uri=" + Uri.EscapeDataString("https://xamarin.com/")
								),
				OAuth_UriCallbackAKARedirect = new Uri("https://xamarin.com/"),
				AllowCancel = true,
			};

			if (TestCases.ContainsKey(oauth2.Description))
			{
				TestCases[oauth2.Description] = oauth2;
			}
			else
			{
				TestCases.Add(oauth2.Description, oauth2);
			}

			return;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
@interface CinemaCell : UITableViewCell

@property (nonatomic,strong)UILabel * cinemaName;
@property (nonatomic,strong)UILabel * price;
@property (nonatomic,strong)UILabel * distance;
@property (nonatomic,strong)HomeCinemaListModel * model;
@property (nonatomic,strong)UILabel * discount;
@property (nonatomic,assign)BOOL isdiscount;
@property (nonatomic,strong)UILabel * otherTicketLabel;//通兑票图标
@property (nonatomic,strong)UILabel * seatLabel;//选座图标

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier andDataAry:(NSMutableArray*)dataAry;
@end


text:
package com.google.inject.internal;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.inject.ConfigurationException;
import com.google.inject.Stage;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.InjectionRequest;
import com.google.inject.spi.StaticInjectionRequest;
import java.util.List;
import java.util.Set;

/**
 * Handles {@code Binder.requestInjection} and {@code Binder.requestStaticInjection} commands.
 *
 * @author crazybob@google.com (Bob Lee)
 * @author jessewilson@google.com (Jesse Wilson)
 * @author mikeward@google.com (Mike Ward)
 */
final class InjectionRequestProcessor extends AbstractProcessor {

  private final List<StaticInjection> staticInjections = Lists.newArrayList();
  private final Initializer initializer;

  InjectionRequestProcessor(Errors errors, Initializer initializer) {
    super(errors);
    this.initializer = initializer;
  }

  @Override
  public Boolean visit(StaticInjectionRequest request) {
    staticInjections.add(new StaticInjection(injector, request));
    return true;
  }

  @Override
  public Boolean visit(InjectionRequest<?> request) {
    Set<InjectionPoint> injectionPoints;
    try {
      injectionPoints = request.getInjectionPoints();
    } catch (ConfigurationException e) {
      errors.merge(e.getErrorMessages());
      injectionPoints = e.getPartialValue();
    }

    initializer.requestInjection(
        injector, request.getInstance(), null, request.getSource(), injectionPoints);
    return true;
  }

  void validate() {
    for (StaticInjection staticInjection : staticInjections) {
      staticInjection.validate();
    }
  }

  void injectMembers() {
    /*
     * TODO: If you request both a parent class and one of its
     * subclasses, the parent class's static members will be
     * injected twice.
     */
    for (StaticInjection staticInjection : staticInjections) {
      staticInjection.injectMembers();
    }
  }

  /** A requested static injection. */
  private class StaticInjection {
    final InjectorImpl injector;
    final Object source;
    final StaticInjectionRequest request;
    ImmutableList<SingleMemberInjector> memberInjectors;

    public StaticInjection(InjectorImpl injector, StaticInjectionRequest request) {
      this.injector = injector;
      this.source = request.getSource();
      this.request = request;
    }

    void validate() {
      Errors errorsForMember = errors.withSource(source);
      Set<InjectionPoint> injectionPoints;
      try {
        injectionPoints = request.getInjectionPoints();
      } catch (ConfigurationException e) {
        errorsForMember.merge(e.getErrorMessages());
        injectionPoints = e.getPartialValue();
      }
      if (injectionPoints != null) {
        memberInjectors =
            injector.membersInjectorStore.getInjectors(injectionPoints, errorsForMember);
      } else {
        memberInjectors = ImmutableList.of();
      }

      errors.merge(errorsForMember);
    }

    void injectMembers() {
      try {
        injector.callInContext(
            new ContextualCallable<Void>() {
              @Override
              public Void call(InternalContext context) {
                for (SingleMemberInjector memberInjector : memberInjectors) {
                  // Run injections if we're not in tool stage (ie, PRODUCTION or DEV),
                  // or if we are in tool stage and the injection point is toolable.
                  if (injector.options.stage != Stage.TOOL
                      || memberInjector.getInjectionPoint().isToolable()) {
                    memberInjector.inject(errors, context, null);
                  }
                }
                return null;
              }
            });
      } catch (ErrorsException e) {
        throw new AssertionError();
      }
    }
  }
}


text:
package kornell.server.util

class KornellErr(code: Int, messageKey: String) extends Err {

  def getCode: Int = code
  def getMessageKey: String = messageKey
}

object AccessDeniedErr {
  def apply() = new KornellErr(401, "accessDenied")
}


text:
#ifndef SHARE_VM_CLASSFILE_STACKMAPFRAME_HPP
#define SHARE_VM_CLASSFILE_STACKMAPFRAME_HPP

#include "classfile/verificationType.hpp"
#include "classfile/verifier.hpp"
#include "oops/methodOop.hpp"
#include "runtime/handles.hpp"
#include "runtime/signature.hpp"
#include "utilities/exceptions.hpp"

// A StackMapFrame represents one frame in the stack map attribute.

class TypeContext;

enum {
  FLAG_THIS_UNINIT = 0x01
};

class StackMapFrame : public ResourceObj {
 private:
  int32_t _offset;

  // See comment in StackMapTable about _frame_count about why these
  // fields are int32_t instead of u2.
  int32_t _locals_size;  // number of valid type elements in _locals
  int32_t _stack_size;   // number of valid type elements in _stack

  int32_t _stack_mark;   // Records the size of the stack prior to an
                         // instruction modification, to allow rewinding
                         // when/if an error occurs.

  int32_t _max_locals;
  int32_t _max_stack;

  u1 _flags;
  VerificationType* _locals; // local variable type array
  VerificationType* _stack;  // operand stack type array

  ClassVerifier* _verifier;  // the verifier verifying this method

  StackMapFrame(const StackMapFrame& cp) :
      _offset(cp._offset), _locals_size(cp._locals_size),
      _stack_size(cp._stack_size), _stack_mark(cp._stack_mark),
      _max_locals(cp._max_locals), _max_stack(cp._max_stack),
      _flags(cp._flags) {
    _locals = NEW_RESOURCE_ARRAY(VerificationType, _max_locals);
    for (int i = 0; i < _max_locals; ++i) {
      if (i < _locals_size) {
        _locals[i] = cp._locals[i];
      } else {
        _locals[i] = VerificationType::bogus_type();
      }
    }
    int ss = MAX2(_stack_size, _stack_mark);
    _stack = NEW_RESOURCE_ARRAY(VerificationType, _max_stack);
    for (int i = 0; i < _max_stack; ++i) {
      if (i < ss) {
        _stack[i] = cp._stack[i];
      } else {
        _stack[i] = VerificationType::bogus_type();
      }
    }
    _verifier = NULL;
  }

 public:
  // constructors

  // This constructor is used by the type checker to allocate frames
  // in type state, which have _max_locals and _max_stack array elements
  // in _locals and _stack.
  StackMapFrame(u2 max_locals, u2 max_stack, ClassVerifier* verifier);

  // This constructor is used to initialize stackmap frames in stackmap table,
  // which have _locals_size and _stack_size array elements in _locals and _stack.
  StackMapFrame(int32_t offset,
                u1 flags,
                u2 locals_size,
                u2 stack_size,
                u2 max_locals,
                u2 max_stack,
                VerificationType* locals,
                VerificationType* stack,
                ClassVerifier* v) : _offset(offset), _flags(flags),
                                    _locals_size(locals_size),
                                    _stack_size(stack_size),
                                    _stack_mark(-1),
                                    _max_locals(max_locals),
                                    _max_stack(max_stack),
                                    _locals(locals), _stack(stack),
                                    _verifier(v) { }

  static StackMapFrame* copy(StackMapFrame* smf) {
    return new StackMapFrame(*smf);
  }

  inline void set_offset(int32_t offset)      { _offset = offset; }
  inline void set_verifier(ClassVerifier* v)  { _verifier = v; }
  inline void set_flags(u1 flags)             { _flags = flags; }
  inline void set_locals_size(u2 locals_size) { _locals_size = locals_size; }
  inline void set_stack_size(u2 stack_size)   { _stack_size = _stack_mark = stack_size; }
  inline void clear_stack()                   { _stack_size = 0; }
  inline int32_t offset()   const             { return _offset; }
  inline ClassVerifier* verifier() const      { return _verifier; }
  inline u1 flags() const                     { return _flags; }
  inline int32_t locals_size() const          { return _locals_size; }
  inline VerificationType* locals() const     { return _locals; }
  inline int32_t stack_size() const           { return _stack_size; }
  inline VerificationType* stack() const      { return _stack; }
  inline int32_t max_locals() const           { return _max_locals; }
  inline int32_t max_stack() const            { return _max_stack; }
  inline bool flag_this_uninit() const        { return _flags & FLAG_THIS_UNINIT; }

  // Set locals and stack types to bogus
  inline void reset() {
    int32_t i;
    for (i = 0; i < _max_locals; i++) {
      _locals[i] = VerificationType::bogus_type();
    }
    for (i = 0; i < _max_stack; i++) {
      _stack[i] = VerificationType::bogus_type();
    }
  }

  // Return a StackMapFrame with the same local variable array and empty stack.
  // Stack array is allocate with unused one element.
  StackMapFrame* frame_in_exception_handler(u1 flags);

  // Set local variable type array based on m's signature.
  VerificationType set_locals_from_arg(
    const methodHandle m, VerificationType thisKlass, TRAPS);

  // Search local variable type array and stack type array.
  // Return true if an uninitialized object is found.
  bool has_new_object() const;

  // Search local variable type array and stack type array.
  // Set every element with type of old_object to new_object.
  void initialize_object(
    VerificationType old_object, VerificationType new_object);

  // Copy local variable type array in src into this local variable type array.
  void copy_locals(const StackMapFrame* src);

  // Copy stack type array in src into this stack type array.
  void copy_stack(const StackMapFrame* src);

  // Return true if this stack map frame is assignable to target.
  bool is_assignable_to(
      const StackMapFrame* target, bool is_exception_handler,
      ErrorContext* ctx, TRAPS) const;

  inline void set_mark() {
#ifdef DEBUG
    // Put bogus type to indicate it's no longer valid.
    if (_stack_mark != -1) {
      for (int i = _stack_mark; i >= _stack_size; --i) {
        _stack[i] = VerificationType::bogus_type();
      }
    }
#endif // def DEBUG
    _stack_mark = _stack_size;
  }

  // Used when an error occurs and we want to reset the stack to the state
  // it was before operands were popped off.
  void restore() {
    if (_stack_mark != -1) {
      _stack_size = _stack_mark;
    }
  }

  // Push type into stack type array.
  inline void push_stack(VerificationType type, TRAPS) {
    assert(!type.is_check(), "Must be a real type");
    if (_stack_size >= _max_stack) {
      verifier()->verify_error(
          ErrorContext::stack_overflow(_offset, this),
          "Operand stack overflow");
      return;
    }
    _stack[_stack_size++] = type;
  }

  inline void push_stack_2(
      VerificationType type1, VerificationType type2, TRAPS) {
    assert(type1.is_long() || type1.is_double(), "must be long/double");
    assert(type2.is_long2() || type2.is_double2(), "must be long/double_2");
    if (_stack_size >= _max_stack - 1) {
      verifier()->verify_error(
          ErrorContext::stack_overflow(_offset, this),
          "Operand stack overflow");
      return;
    }
    _stack[_stack_size++] = type1;
    _stack[_stack_size++] = type2;
  }

  // Pop and return the top type on stack without verifying.
  inline VerificationType pop_stack(TRAPS) {
    if (_stack_size <= 0) {
      verifier()->verify_error(
          ErrorContext::stack_underflow(_offset, this),
          "Operand stack underflow");
      return VerificationType::bogus_type();
    }
    VerificationType top = _stack[--_stack_size];
    return top;
  }

  // Pop and return the top type on stack type array after verifying it
  // is assignable to type.
  inline VerificationType pop_stack(VerificationType type, TRAPS) {
    if (_stack_size != 0) {
      VerificationType top = _stack[_stack_size - 1];
      bool subtype = type.is_assignable_from(
        top, verifier(), CHECK_(VerificationType::bogus_type()));
      if (subtype) {
        --_stack_size;
        return top;
      }
    }
    return pop_stack_ex(type, THREAD);
  }

  inline void pop_stack_2(
      VerificationType type1, VerificationType type2, TRAPS) {
    assert(type1.is_long2() || type1.is_double2(), "must be long/double");
    assert(type2.is_long() || type2.is_double(), "must be long/double_2");
    if (_stack_size >= 2) {
      VerificationType top1 = _stack[_stack_size - 1];
      bool subtype1 = type1.is_assignable_from(top1, verifier(), CHECK);
      VerificationType top2 = _stack[_stack_size - 2];
      bool subtype2 = type2.is_assignable_from(top2, verifier(), CHECK);
      if (subtype1 && subtype2) {
        _stack_size -= 2;
        return;
      }
    }
    pop_stack_ex(type1, THREAD);
    pop_stack_ex(type2, THREAD);
  }

  VerificationType local_at(int index) {
    return _locals[index];
  }

  VerificationType stack_at(int index) {
    return _stack[index];
  }

  // Uncommon case that throws exceptions.
  VerificationType pop_stack_ex(VerificationType type, TRAPS);

  // Return the type at index in local variable array after verifying
  // it is assignable to type.
  VerificationType get_local(int32_t index, VerificationType type, TRAPS);
  // For long/double.
  void get_local_2(
    int32_t index, VerificationType type1, VerificationType type2, TRAPS);

  // Set element at index in local variable array to type.
  void set_local(int32_t index, VerificationType type, TRAPS);
  // For long/double.
  void set_local_2(
    int32_t index, VerificationType type1, VerificationType type2, TRAPS);

  // Private auxiliary method used only in is_assignable_to(StackMapFrame).
  // Returns true if src is assignable to target.
  int is_assignable_to(
    VerificationType* src, VerificationType* target, int32_t len, TRAPS) const;

  bool has_flag_match_exception(const StackMapFrame* target) const;

  TypeOrigin stack_top_ctx();

  void print_on(outputStream* str) const;
};

#endif // SHARE_VM_CLASSFILE_STACKMAPFRAME_HPP


text:
class Zip[A, B](underlying: String, other: {*} String) {
  this: {underlying, other} Zip[A, B] =>  // error
}


text:
/**
 * @file
 * PacketEngine tester
 */

/******************************************************************************
 * Copyright (c) 2011-2012, AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for any
 *    purpose with or without fee is hereby granted, provided that the above
 *    copyright notice and this permission notice appear in all copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/
#include <qcc/platform.h>

#include <limits>
#include <signal.h>
#include <netdb.h>
#include <sys/socket.h>

#include <map>

#include <qcc/Debug.h>
#include <qcc/Log.h>
#include <qcc/String.h>
#include <qcc/StringUtil.h>
#include <qcc/Mutex.h>
#include <alljoyn/version.h>

#include "PacketEngine.h"
#include "UDPPacketStream.h"

#define QCC_MODULE "PACKET"

using namespace qcc;
using namespace std;
using namespace ajn;

static bool g_interrupt = false;
static const char* g_ifaceName = "eth0";
static uint16_t g_port = 9911;
static uint32_t g_sendTtl = 0;
static uint32_t g_recvTimeout = 1;

class PacketEngineController : public PacketEngineListener {
  public:
    PacketEngineController(const char* ifaceName, uint16_t port);

    ~PacketEngineController();

    QStatus Start();

    void Stop();

    void Join();

    String GetIPAddr() const { return udpStream.GetIPAddr(); }

    QStatus Connect(const qcc::String& addr, uint16_t port)
    {
        return engine.Connect(GetPacketDest(addr, port), udpStream, *this, NULL);
    }

    void Disconnect(uint32_t connNum);

    void PacketEngineConnectCB(PacketEngine& engine, QStatus status, const PacketEngineStream* stream, const PacketDest& dest, void* context);

    bool PacketEngineAcceptCB(PacketEngine& engine, const PacketEngineStream& stream, const PacketDest& dest);

    void PacketEngineDisconnectCB(PacketEngine& engine, const PacketEngineStream& stream, const PacketDest& dest);

    QStatus Send(uint32_t chanIdx, const String& data, uint32_t ttl = 0);

    QStatus Recv(uint32_t chanIdx, String& data);

    void ListStreams() const;

    QStatus SetSendTimeout(uint32_t chanIdx, uint32_t timeout);

  private:
    UDPPacketStream udpStream;
    PacketEngine engine;
    mutable Mutex streamsLock;
    map<int, PacketEngineStream> streams;
    int nextStreamId;
};

PacketEngineController::PacketEngineController(const char* ifaceName, uint16_t port) :
    udpStream(ifaceName, port),
    engine("pe"),
    nextStreamId(0)
{
}

PacketEngineController::~PacketEngineController()
{
    Stop();
    Join();
}

QStatus PacketEngineController::Start()
{
    /* Start PacketStream */
    QStatus status = udpStream.Start();
    if (status != ER_OK) {
        QCC_LogError(status, ("UDPPacketStream::Start failed"));
    }

    /* Add PacketStream */
    if (status == ER_OK) {
        status = engine.AddPacketStream(udpStream, *this);
        if (status != ER_OK) {
            QCC_LogError(status, ("AddPacketStream failed"));
        }
    }

    /* Start PacketEngine */
    if (status == ER_OK) {
        status = engine.Start(::max(udpStream.GetSourceMTU(), udpStream.GetSinkMTU()));
        if (status != ER_OK) {
            QCC_LogError(status, ("PacketEngine::Start failed"));
        }
    }

    return status;
}

void PacketEngineController::Stop()
{
    engine.Stop();
    udpStream.Stop();
}

void PacketEngineController::Join()
{
    engine.Join();
}

void PacketEngineController::PacketEngineConnectCB(PacketEngine& engine,
                                                   QStatus status,
                                                   const PacketEngineStream* stream,
                                                   const PacketDest& dest,
                                                   void* context)
{
    if (status == ER_OK) {
        printf("Connect to %s succeeded.\n", udpStream.ToString(dest).c_str());
        streamsLock.Lock();
        streams.insert(pair<int, PacketEngineStream>(++nextStreamId, *stream));
        streamsLock.Unlock();
    } else {
        printf("Connect to %s failed with %s\n", udpStream.ToString(dest).c_str(), QCC_StatusText(status));
    }
}

bool PacketEngineController::PacketEngineAcceptCB(PacketEngine& engine, const PacketEngineStream& stream, const PacketDest& dest)
{
    printf("Accepting connect attempt from %s\n", udpStream.ToString(dest).c_str());
    streamsLock.Lock();
    streams.insert(pair<int, PacketEngineStream>(++nextStreamId, stream));
    streamsLock.Unlock();
    return true;
}

void PacketEngineController::PacketEngineDisconnectCB(PacketEngine& engine, const PacketEngineStream& stream, const PacketDest& dest)
{
    bool found = false;
    printf("Disconnect indication from %s\n", udpStream.ToString(dest).c_str());
    streamsLock.Lock();
    map<int, PacketEngineStream>::iterator it = streams.begin();
    while (it != streams.end()) {
        if (it->second == stream) {
            streams.erase(it->first);
            found = true;
            break;
        }
        ++it;
    }
    streamsLock.Unlock();
    if (!found) {
        printf("ERROR: Could not find stream %s\n", udpStream.ToString(dest).c_str());
    }
}

void PacketEngineController::ListStreams() const
{
    streamsLock.Lock();
    map<int, PacketEngineStream>::const_iterator it = streams.begin();
    while (it != streams.end()) {
        printf("#%i: channelId=0x%x\n", it->first, it->second.GetChannelId());
        ++it;
    }
    printf("\n");
    streamsLock.Unlock();
}

QStatus PacketEngineController::SetSendTimeout(uint32_t chanIdx, uint32_t timeout)
{
    QStatus status = ER_FAIL;
    streamsLock.Lock();
    map<int, PacketEngineStream>::iterator it = streams.find(chanIdx);
    if (it != streams.end()) {
        it->second.SetSendTimeout(timeout);
        status = ER_OK;
    }
    streamsLock.Unlock();
    return status;
}

QStatus PacketEngineController::Send(uint32_t chanIdx, const String& data, uint32_t ttl)
{
    QStatus status = ER_FAIL;
    streamsLock.Lock();
    map<int, PacketEngineStream>::iterator it = streams.find(chanIdx);
    if (it != streams.end()) {
        size_t actualBytes;
        PacketEngineStream& stream = it->second;
        streamsLock.Unlock();
        status = stream.PushBytes(data.data(), data.size(), actualBytes, ttl);
        if ((status == ER_OK) && (actualBytes != data.size())) {
            status = ER_FAIL;
            printf("PacketEngineController::Send: short send. expected=%d, actual=%d\n", (int) data.size(), (int) actualBytes);
        }
    } else {
        streamsLock.Unlock();
    }
    return status;
}

QStatus PacketEngineController::Recv(uint32_t chanIdx, String& data)
{
    QStatus status = ER_FAIL;
    streamsLock.Lock();
    map<int, PacketEngineStream>::iterator it = streams.find(chanIdx);
    if (it != streams.end()) {
        size_t actualBytes;
        PacketEngineStream& stream = it->second;
        streamsLock.Unlock();
        status = stream.PullBytes(data.begin(), data.capacity(), actualBytes, g_recvTimeout);
        if (status == ER_OK) {
            data.assign(data.begin(), actualBytes);
        }
    } else {
        streamsLock.Unlock();
    }
    return status;
}

void PacketEngineController::Disconnect(uint32_t chanIdx)
{
    streamsLock.Lock();
    map<int, PacketEngineStream>::iterator it = streams.find(chanIdx);
    if (it != streams.end()) {
        engine.Disconnect(it->second);
    }
    streamsLock.Unlock();
}

static char* get_line(char*str, size_t num, FILE*fp)
{
    char*p = fgets(str, num, fp);

    // fgets will capture the '\n' character if the string entered is shorter than
    // num. Remove the '\n' from the end of the line and replace it with nul '\0'.
    if (p != NULL) {
        size_t last = strlen(str) - 1;
        if (str[last] == '\n') {
            str[last] = '\0';
        }
    }
    return p;
}

static String NextTok(String& inStr)
{
    String ret;
    size_t off = inStr.find_first_of(' ');
    if (off == String::npos) {
        ret = inStr;
        inStr.clear();
    } else {
        ret = inStr.substr(0, off);
        inStr = Trim(inStr.substr(off));
    }
    return Trim(ret);
}

static void SigIntHandler(int sig)
{
    g_interrupt = true;
    ::fclose(stdin);
}

static void usage(void)
{
    printf("Usage: packettest [-h] [-i <iface>]\n\n");
    printf("Options:\n");
    printf("   -h            - Print this help message\n");
    printf("   -i <iface>    - Set the network interface\n");
    printf("   -p <port>     - Set the network port\n");
    printf("\n");
}

static void DoConnect(PacketEngineController& controller, const String& host, uint16_t port)
{
    QStatus status = controller.Connect(host, port);
    if (status != ER_OK) {
        QCC_LogError(status, ("Connect failed"));
    }
}

static void DoDisconnect(PacketEngineController& controller, uint32_t connNum)
{
    controller.Disconnect(connNum);
}

static void DoList(PacketEngineController& controller)
{
    controller.ListStreams();
}

static void DoSend(PacketEngineController& controller, uint32_t chanIdx, const String& data, uint32_t ttl)
{
    QStatus status = controller.Send(chanIdx, data, ttl);
    if (status != ER_OK) {
        printf("controller.Send(%u, <>) failed with %s\n", chanIdx, QCC_StatusText(status));
    }
}

static QStatus DoSendAtRate(PacketEngineController& controller, uint32_t chanIdx, size_t dataSize, uint32_t delay, uint32_t count, uint32_t ttl)
{
    QStatus status = ER_OK;
    char* msg = new char[dataSize];
    for (size_t i = 0; i < dataSize; ++i) {
        msg[i] = 'A' + (i % 52);
    }
    String data(msg, dataSize, dataSize);

    uint32_t i = 0;
    while (i++ < count) {
        uint64_t start = GetTimestamp64();
        status = controller.Send(chanIdx, data, ttl);
        if (status != ER_OK) {
            printf("controller.Send(%u, <>) failed with %s\n", chanIdx, QCC_StatusText(status));
            break;
        }
        if ((i % 1000) == 0) {
            printf("reps=%d\n", i);
        }
        uint64_t now = GetTimestamp64();
        if (now < (start + delay)) {
            qcc::Sleep((start + delay) - now);
        }
    }
    return status;
}

static QStatus DoRecv(PacketEngineController& controller, uint32_t chanIdx, String& data)
{
    QStatus status = controller.Recv(chanIdx, data);
    if (status != ER_OK) {
        printf("controller.Recv(%u, <>) failed with %s\n", chanIdx, QCC_StatusText(status));
    }
    return status;
}

static QStatus DoRecvAtRate(PacketEngineController& controller, uint32_t chanIdx, size_t dataSize, uint32_t delay, uint32_t count, uint32_t ttl)
{
    QStatus status = ER_OK;
    char* msg = new char[dataSize];
    for (size_t i = 0; i < dataSize; ++i) {
        msg[i] = 'A' + (i % 52);
    }
    String compareData(msg, dataSize, dataSize);
    String data;
    data.reserve(dataSize);
    uint32_t rep = 1;
    while (rep++ <= count) {
        uint64_t start = GetTimestamp64();
        status = controller.Recv(chanIdx, data);
        if (status != ER_OK) {
            printf("controller.Recv(%u, <>) failed with %s (rep=%d)\n", chanIdx, QCC_StatusText(status), rep);
            break;
        } else {
            if (data != compareData) {
                unsigned int i;
                for (i = 0; i < ::min(data.length(), compareData.length()); ++i) {
                    if (data[i] != compareData[i]) {
                        break;
                    }
                }
                printf("Recv data miscompare at offset %d. (data.length=%d, compareData.length=%d)\n", i, (int) data.length(), (int) compareData.length());
            }
        }
        if ((rep % 1000) == 0) {
            printf("reps=%d\n", rep);
        }
        uint64_t now = GetTimestamp64();
        if (now < (start + delay)) {
            qcc::Sleep((start + delay) - now);
        }
    }
    return status;
}

int main(int argc, char** argv)
{
    QStatus status = ER_OK;
    printf("AllJoyn Library version: %s\n", ajn::GetVersion());
    printf("AllJoyn Library build info: %s\n", ajn::GetBuildInfo());

    /* Install SIGINT handler */
    signal(SIGINT, SigIntHandler);

    /* Parse command line args */
    for (int i = 1; i < argc; ++i) {
        if (::strcmp("-h", argv[i]) == 0) {
            usage();
            exit(0);
        } else if (::strcmp("-i", argv[i]) == 0) {
            g_ifaceName = argv[++i];
        } else if (::strcmp("-p", argv[i]) == 0) {
            g_port = static_cast<uint16_t>(StringToU32(argv[++i], 10, 0));
        } else {
            status = ER_FAIL;
            printf("Unknown option %s\n", argv[i]);
            usage();
            exit(1);
        }
    }

    /* Create PacketEngine controller */
    PacketEngineController controller(g_ifaceName, g_port);
    status = controller.Start();
    if (status != ER_OK) {
        QCC_LogError(status, ("PacketController::Start failed"));
    } else {
        /* Let user know connect details */
        printf("\nListening on %s:%d\n\n", controller.GetIPAddr().c_str(), g_port);
    }

    /* Parse commands from stdin */
    const int bufSize = 1024;
    char buf[bufSize];
    while ((ER_OK == status) && get_line(buf, bufSize, stdin)) {
        String line(buf);
        String cmd = NextTok(line);
        if (cmd == "debug") {
            String module = NextTok(line);
            String level = NextTok(line);
            if (module.empty() || level.empty()) {
                printf("Usage: debug <modulename> <level>\n");
            } else {
                QCC_SetDebugLevel(module.c_str(), StringToU32(level));
            }
        } else if (cmd == "connect") {
            String host = NextTok(line);
            uint16_t port = static_cast<uint16_t>(StringToU32(NextTok(line), 10, 0));
            if (host.empty() || (port == 0)) {
                printf("Usage: connect <addr> <port>\n");
            } else {
                DoConnect(controller, host, port);
            }
        } else if (cmd == "disconnect") {
            uint32_t connNum = StringToU32(NextTok(line), 10, 0);
            if (connNum == 0) {
                printf("Usage: disconnect <conn_index>\n");
            } else {
                DoDisconnect(controller, connNum);
            }
        } else if (cmd == "list") {
            DoList(controller);
        } else if (cmd == "send") {
            uint32_t idx = StringToU32(NextTok(line), 10, 0);
            String data = NextTok(line);
            if (!data.empty() && (idx != 0)) {
                DoSend(controller, idx, data, g_sendTtl);
            } else {
                printf("Invalid inputs\n");
            }
        } else if (cmd == "sendatrate") {
            uint32_t idx = StringToU32(NextTok(line), 10, 0);
            uint32_t msgSize = StringToU32(NextTok(line), 10, 0);
            uint32_t delay = StringToU32(NextTok(line), 10, numeric_limits<uint32_t>::max());
            uint32_t count = StringToU32(NextTok(line), 10, 0);
            if ((idx != 0) && (msgSize != 0) && (delay != numeric_limits<uint32_t>::max())) {
                QStatus status = DoSendAtRate(controller, idx, msgSize, delay, count, g_sendTtl);
                if (status != ER_OK) {
                    printf("DoSendAtRate failed with %s\n", QCC_StatusText(status));
                }
            } else {
                printf("Invalid args\n");
                printf("sendatrate <stream_idx> <msg_size> <ms_per_msg> <count>\n");
            }
        } else if (cmd == "sendtimeout") {
            uint32_t idx = StringToU32(NextTok(line), 10, 0);
            uint32_t timeout = StringToU32(NextTok(line), 10, 0);
            QStatus status = ER_FAIL;
            if (idx != 0) {
                status = controller.SetSendTimeout(idx, timeout);
                if (status != ER_OK) {
                    printf("SetSendTimeout failed with %s\n", QCC_StatusText(status));
                }
            } else {
                printf("Invalid args\n");
            }
            if (status != ER_OK) {
                printf("sendtimeout <stream_idx> <timeout>\n");
            }
        } else if (cmd == "sendttl") {
            uint32_t ttl = StringToU32(NextTok(line), 10, 58334438);
            if (ttl != 58334438) {
                g_sendTtl = ttl;
            } else {
                printf("Invalid args\n");
            }
            if (status != ER_OK) {
                printf("sendttl <ttl_in_ms>\n");
            }
        } else if (cmd == "recv") {
            uint32_t idx = StringToU32(NextTok(line), 10, 0);
            uint32_t len = StringToU32(NextTok(line), 10, 2048);
            if (idx != 0) {
                String data;
                data.reserve(len);
                QStatus status = DoRecv(controller, idx, data);
                if (status == ER_OK) {
                    printf("Data from #%u: %s\n\n", idx, data.c_str());
                }
            } else {
                printf("Invalid stream index\n");
                printf("recv <stream_idx> [maxLen]\n");
            }
        } else if (cmd == "recvatrate") {
            uint32_t idx = StringToU32(NextTok(line), 10, 0);
            uint32_t msgSize = StringToU32(NextTok(line), 10, 0);
            uint32_t delay = StringToU32(NextTok(line), 10, numeric_limits<uint32_t>::max());
            uint32_t count = StringToU32(NextTok(line), 10, 0);
            if ((idx != 0) && (msgSize != 0) && (delay != numeric_limits<uint32_t>::max())) {
                QStatus status = DoRecvAtRate(controller, idx, msgSize, delay, count, g_sendTtl);
                if (status != ER_OK) {
                    printf("DoRecvAtRate failed with %s\n", QCC_StatusText(status));
                }
            } else {
                printf("Invalid args\n");
                printf("recvatrate <stream_idx> <msg_size> <ms_per_msg> <count>\n");
            }
        } else if (cmd == "recvtimeout") {
            uint32_t timeout = StringToU32(NextTok(line), 10, 58334438);
            String testEnd = NextTok(line);
            if ((timeout != 58334438) && testEnd.empty()) {
                g_recvTimeout = timeout;
            } else {
                printf("Invalid args\n");
            }
            if (status != ER_OK) {
                printf("recvtimeout <timeout_in_ms>\n");
            }
        } else if (cmd == "exit") {
            break;
        } else if (cmd == "help") {
            printf("debug <module_name> <level>                               - Set debug level for a module\n");
            printf("connect <addr> <port>                                     - Connect to another instance of packettest\n");
            printf("disconnect <conn_num>                                     - Disconnect a specified connection\n");
            printf("list                                                      - List port bindings, discovered names and active sessions\n");
            printf("recv <stream_idx>                                         - Recv data from a connected stream\n");
            printf("recvatrate <stream_idx> <msg_size> <ms_per_msg> <count>   - Recv test msgs (from sendatrate)\n");
            printf("send <stream_idx> <data>                                  - Send data to a connected stream\n");
            printf("sendatrate <stream_idx> <msg_size> <ms_per_msg> <count>   - Send test data at specified rate\n");
            printf("sendtimeout <stream_idx> <timeout>                        - Set send timeout to specified ms\n");
            printf("sendttl <ttl_ms>                                          - Set per-message ttl to specified ms or 0 for infinite\n");
            printf("exit                                                      - Exit this program\n");
            printf("\n");
        } else {
            printf("Unknown command: %s\n", cmd.c_str());
        }
    }

    controller.Stop();
    controller.Join();
    return (int) status;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Geastrum hollosii V.J. Stanek

### Remarks
null


text:
package uk.co.real_logic.aeron.driver;

import uk.co.real_logic.aeron.common.FeedbackDelayGenerator;
import uk.co.real_logic.aeron.common.Flyweight;
import uk.co.real_logic.aeron.common.OptimalMulticastDelayGenerator;
import uk.co.real_logic.aeron.common.StaticDelayGenerator;
import uk.co.real_logic.aeron.common.command.CorrelatedMessageFlyweight;
import uk.co.real_logic.aeron.common.command.PublicationMessageFlyweight;
import uk.co.real_logic.aeron.common.command.RemoveMessageFlyweight;
import uk.co.real_logic.aeron.common.command.SubscriptionMessageFlyweight;
import uk.co.real_logic.aeron.common.concurrent.logbuffer.LogBufferDescriptor;
import uk.co.real_logic.aeron.common.event.EventCode;
import uk.co.real_logic.aeron.common.event.EventConfiguration;
import uk.co.real_logic.aeron.common.event.EventLogger;
import uk.co.real_logic.aeron.common.protocol.DataHeaderFlyweight;
import uk.co.real_logic.aeron.driver.buffer.RawLog;
import uk.co.real_logic.aeron.driver.buffer.RawLogFactory;
import uk.co.real_logic.aeron.driver.cmd.DriverConductorCmd;
import uk.co.real_logic.aeron.driver.exceptions.ControlProtocolException;
import uk.co.real_logic.aeron.driver.exceptions.InvalidChannelException;
import uk.co.real_logic.agrona.BitUtil;
import uk.co.real_logic.agrona.MutableDirectBuffer;
import uk.co.real_logic.agrona.TimerWheel;
import uk.co.real_logic.agrona.collections.Long2ObjectHashMap;
import uk.co.real_logic.agrona.concurrent.*;
import uk.co.real_logic.agrona.concurrent.ringbuffer.RingBuffer;
import uk.co.real_logic.agrona.status.BufferPositionIndicator;
import uk.co.real_logic.agrona.status.BufferPositionReporter;

import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;

import static java.util.stream.Collectors.toList;
import static uk.co.real_logic.aeron.common.ErrorCode.*;
import static uk.co.real_logic.aeron.common.command.ControlProtocolEvents.*;
import static uk.co.real_logic.aeron.driver.Configuration.*;
import static uk.co.real_logic.aeron.driver.MediaDriver.Context;

/**
 * Driver Conductor to take commands from publishers and subscribers as well as handle NAKs and retransmissions
 */
public class DriverConductor implements Agent
{
    public static final int HEARTBEAT_TIMEOUT_MS = 1000;  // how often to check liveness & cleanup

    /**
     * Unicast NAK delay is immediate initial with delayed subsequent delay
     */
    public static final StaticDelayGenerator NAK_UNICAST_DELAY_GENERATOR = new StaticDelayGenerator(
        Configuration.NAK_UNICAST_DELAY_DEFAULT_NS, true);

    public static final OptimalMulticastDelayGenerator NAK_MULTICAST_DELAY_GENERATOR = new OptimalMulticastDelayGenerator(
        Configuration.NAK_MAX_BACKOFF_DEFAULT, Configuration.NAK_GROUPSIZE_DEFAULT, Configuration.NAK_GRTT_DEFAULT);

    /**
     * Source uses same for unicast and multicast. For ticks.
     */
    public static final FeedbackDelayGenerator RETRANS_UNICAST_DELAY_GENERATOR = () -> RETRANS_UNICAST_DELAY_DEFAULT_NS;
    public static final FeedbackDelayGenerator RETRANS_UNICAST_LINGER_GENERATOR = () -> RETRANS_UNICAST_LINGER_DEFAULT_NS;

    private final OneToOneConcurrentArrayQueue<DriverConductorCmd> driverConductorCmdQueue;
    private final ReceiverProxy receiverProxy;
    private final SenderProxy senderProxy;
    private final ClientProxy clientProxy;
    private final DriverConductorProxy conductorProxy;
    private final RawLogFactory rawLogFactory;
    private final RingBuffer toDriverCommands;
    private final RingBuffer toEventReader;
    private final HashMap<String, SendChannelEndpoint> sendChannelEndpointByChannelMap = new HashMap<>();
    private final HashMap<String, ReceiveChannelEndpoint> receiveChannelEndpointByChannelMap = new HashMap<>();
    private final TimerWheel timerWheel;
    private final ArrayList<DriverPublication> publications = new ArrayList<>();
    private final Long2ObjectHashMap<PublicationRegistration> publicationRegistrations = new Long2ObjectHashMap<>();
    private final ArrayList<DriverSubscription> subscriptions = new ArrayList<>();
    private final ArrayList<DriverConnection> connections = new ArrayList<>();
    private final ArrayList<AeronClient> clients = new ArrayList<>();

    private final Supplier<SenderFlowControl> unicastSenderFlowControl;
    private final Supplier<SenderFlowControl> multicastSenderFlowControl;

    private final PublicationMessageFlyweight publicationMessage = new PublicationMessageFlyweight();
    private final SubscriptionMessageFlyweight subscriptionMessage = new SubscriptionMessageFlyweight();
    private final CorrelatedMessageFlyweight correlatedMessage = new CorrelatedMessageFlyweight();
    private final RemoveMessageFlyweight removeMessage = new RemoveMessageFlyweight();

    private final int mtuLength;
    private final int capacity;
    private final int initialWindowLength;
    private final long dataLossSeed;
    private final long controlLossSeed;
    private final double dataLossRate;
    private final double controlLossRate;
    private final TimerWheel.Timer checkTimeoutTimer;
    private final CountersManager countersManager;
    private final UnsafeBuffer countersBuffer;
    private final EventLogger logger;

    private final SystemCounters systemCounters;
    private final Consumer<DriverConductorCmd> onDriverConductorCmdFunc = this::onDriverConductorCmd;
    private final MessageHandler onClientCommandFunc  = this::onClientCommand;
    private final MessageHandler onEventFunc;
    private final NanoClock clock;

    public DriverConductor(final Context ctx)
    {
        this.driverConductorCmdQueue = ctx.conductorCommandQueue();
        this.receiverProxy = ctx.receiverProxy();
        this.senderProxy = ctx.senderProxy();
        this.rawLogFactory = ctx.rawLogBuffersFactory();
        this.mtuLength = ctx.mtuLength();
        this.initialWindowLength = ctx.initialWindowLength();
        this.capacity = ctx.termBufferLength();
        this.unicastSenderFlowControl = ctx.unicastSenderFlowControl();
        this.multicastSenderFlowControl = ctx.multicastSenderFlowControl();
        this.countersManager = ctx.countersManager();
        this.countersBuffer = ctx.countersBuffer();

        timerWheel = ctx.conductorTimerWheel();
        this.clock = timerWheel.clock();
        checkTimeoutTimer = timerWheel.newTimeout(HEARTBEAT_TIMEOUT_MS, TimeUnit.MILLISECONDS, this::onHeartbeatCheckTimeouts);

        toDriverCommands = ctx.toDriverCommands();
        toEventReader = ctx.toEventReader();
        clientProxy = ctx.clientProxy();
        conductorProxy = ctx.driverConductorProxy();
        logger = ctx.eventLogger();
        dataLossRate = ctx.dataLossRate();
        dataLossSeed = ctx.dataLossSeed();
        controlLossRate = ctx.controlLossRate();
        controlLossSeed = ctx.controlLossSeed();

        systemCounters = ctx.systemCounters();

        final Consumer<String> eventConsumer = ctx.eventConsumer();
        onEventFunc =
            (typeId, buffer, offset, length) -> eventConsumer.accept(EventCode.get(typeId).decode(buffer, offset, length));

        final AtomicBuffer buffer = toDriverCommands.buffer();
        publicationMessage.wrap(buffer, 0);
        subscriptionMessage.wrap(buffer, 0);
        correlatedMessage.wrap(buffer, 0);
        removeMessage.wrap(buffer, 0);

        toDriverCommands.consumerHeartbeatTimeNs(clock.time());
    }

    public void onClose()
    {
        rawLogFactory.close();
        publications.forEach(DriverPublication::close);
        connections.forEach(DriverConnection::close);
        sendChannelEndpointByChannelMap.values().forEach(SendChannelEndpoint::close);
        receiveChannelEndpointByChannelMap.values().forEach(ReceiveChannelEndpoint::close);
    }

    public String roleName()
    {
        return "driver-conductor";
    }

    public SendChannelEndpoint senderChannelEndpoint(final UdpChannel channel)
    {
        return sendChannelEndpointByChannelMap.get(channel.canonicalForm());
    }

    public ReceiveChannelEndpoint receiverChannelEndpoint(final UdpChannel channel)
    {
        return receiveChannelEndpointByChannelMap.get(channel.canonicalForm());
    }

    public int doWork() throws Exception
    {
        int workCount = 0;

        workCount += toDriverCommands.read(onClientCommandFunc);
        workCount += driverConductorCmdQueue.drain(onDriverConductorCmdFunc);
        workCount += toEventReader.read(onEventFunc, EventConfiguration.EVENT_READER_FRAME_LIMIT);
        workCount += processTimers();

        final ArrayList<DriverConnection> connections = this.connections;
        for (int i = 0, size = connections.size(); i < size; i++)
        {
            final DriverConnection connection = connections.get(i);
            workCount += connection.trackCompletion();
        }

        final ArrayList<DriverPublication> publications = this.publications;
        for (int i = 0, size = publications.size(); i < size; i++)
        {
            final DriverPublication publication = publications.get(i);
            workCount += publication.updatePublishersLimit() + publication.cleanLogBuffer();
        }

        return workCount;
    }

    private void onHeartbeatCheckTimeouts()
    {
        final long now = clock.time();

        toDriverCommands.consumerHeartbeatTimeNs(now);

        onCheckClients(now);
        onCheckPublications(now);
        onCheckPublicationRegistrations(now);
        onCheckSubscriptions(now);
        onCheckConnections(now);

        timerWheel.rescheduleTimeout(HEARTBEAT_TIMEOUT_MS, TimeUnit.MILLISECONDS, checkTimeoutTimer);
    }

    private void onClientCommand(final int msgTypeId, final MutableDirectBuffer buffer, final int index, final int length)
    {
        Flyweight flyweight = null;

        try
        {
            switch (msgTypeId)
            {
                case ADD_PUBLICATION:
                {
                    logger.log(EventCode.CMD_IN_ADD_PUBLICATION, buffer, index, length);

                    final PublicationMessageFlyweight publicationMessageFlyweight = publicationMessage;
                    publicationMessageFlyweight.offset(index);
                    flyweight = publicationMessageFlyweight;

                    onAddPublication(
                        publicationMessageFlyweight.channel(),
                        publicationMessageFlyweight.sessionId(),
                        publicationMessageFlyweight.streamId(),
                        publicationMessageFlyweight.correlationId(),
                        publicationMessageFlyweight.clientId());
                    break;
                }

                case REMOVE_PUBLICATION:
                {
                    logger.log(EventCode.CMD_IN_REMOVE_PUBLICATION, buffer, index, length);

                    final RemoveMessageFlyweight removeMessageFlyweight = removeMessage;
                    removeMessageFlyweight.offset(index);
                    flyweight = removeMessageFlyweight;

                    onRemovePublication(removeMessageFlyweight.registrationId(), removeMessageFlyweight.correlationId());
                    break;
                }

                case ADD_SUBSCRIPTION:
                {
                    logger.log(EventCode.CMD_IN_ADD_SUBSCRIPTION, buffer, index, length);

                    final SubscriptionMessageFlyweight subscriptionMessageFlyweight = subscriptionMessage;
                    subscriptionMessageFlyweight.offset(index);
                    flyweight = subscriptionMessageFlyweight;

                    onAddSubscription(
                        subscriptionMessageFlyweight.channel(),
                        subscriptionMessageFlyweight.streamId(),
                        subscriptionMessageFlyweight.correlationId(),
                        subscriptionMessageFlyweight.clientId());
                    break;
                }

                case REMOVE_SUBSCRIPTION:
                {
                    logger.log(EventCode.CMD_IN_REMOVE_SUBSCRIPTION, buffer, index, length);

                    final RemoveMessageFlyweight removeMessageFlyweight = removeMessage;
                    removeMessageFlyweight.offset(index);
                    flyweight = removeMessageFlyweight;

                    onRemoveSubscription(removeMessageFlyweight.registrationId(), removeMessageFlyweight.correlationId());
                    break;
                }

                case CLIENT_KEEPALIVE:
                {
                    logger.log(EventCode.CMD_IN_KEEPALIVE_CLIENT, buffer, index, length);

                    final CorrelatedMessageFlyweight correlatedMessageFlyweight = correlatedMessage;
                    correlatedMessageFlyweight.offset(index);
                    flyweight = correlatedMessageFlyweight;

                    onClientKeepalive(correlatedMessageFlyweight.clientId());
                    break;
                }
            }
        }
        catch (final ControlProtocolException ex)
        {
            clientProxy.onError(ex.errorCode(), ex.getMessage(), flyweight, length);
            logger.logException(ex);
        }
        catch (final InvalidChannelException ex)
        {
            clientProxy.onError(INVALID_CHANNEL, ex.getMessage(), flyweight, length);
            logger.logException(ex);
        }
        catch (final Exception ex)
        {
            clientProxy.onError(GENERIC_ERROR, ex.getMessage(), flyweight, length);
            logger.logException(ex);
        }
    }

    private int processTimers()
    {
        int workCount = 0;

        if (timerWheel.computeDelayInMs() <= 0)
        {
            workCount = timerWheel.expireTimers();
        }

        return workCount;
    }

    private void onAddPublication(
        final String channel, final int sessionId, final int streamId, final long correlationId, final long clientId)
    {
        final UdpChannel udpChannel = UdpChannel.parse(channel);
        logger.logChannelCreated(udpChannel.description());

        SendChannelEndpoint channelEndpoint = sendChannelEndpointByChannelMap.get(udpChannel.canonicalForm());
        if (null == channelEndpoint)
        {
            channelEndpoint = new SendChannelEndpoint(
                udpChannel,
                logger,
                Configuration.createLossGenerator(controlLossRate, controlLossSeed),
                systemCounters);

            channelEndpoint.validateMtuLength(mtuLength);
            sendChannelEndpointByChannelMap.put(udpChannel.canonicalForm(), channelEndpoint);
            senderProxy.registerSendChannelEndpoint(channelEndpoint);
        }

        final AeronClient aeronClient = getOrAddClient(clientId);
        DriverPublication publication = channelEndpoint.getPublication(sessionId, streamId);
        if (publication == null)
        {
            final int initialTermId = BitUtil.generateRandomisedId();
            final String canonicalForm = udpChannel.canonicalForm();
            final RawLog rawLog = rawLogFactory.newPublication(canonicalForm, sessionId, streamId, correlationId);

            final MutableDirectBuffer header = DataHeaderFlyweight.createDefaultHeader(sessionId, streamId, initialTermId);
            final UnsafeBuffer logMetaData = rawLog.logMetaData();
            LogBufferDescriptor.storeDefaultFrameHeaders(logMetaData, header);
            LogBufferDescriptor.initialTermId(logMetaData, initialTermId);

            final int senderPositionId = allocatePositionCounter("sender pos", channel, sessionId, streamId, correlationId);
            final int publisherLimitId = allocatePositionCounter("publisher limit", channel, sessionId, streamId, correlationId);
            final SenderFlowControl senderFlowControl =
                udpChannel.isMulticast() ? multicastSenderFlowControl.get() : unicastSenderFlowControl.get();

            publication = new DriverPublication(
                channelEndpoint,
                clock,
                rawLog,
                new BufferPositionReporter(countersBuffer, senderPositionId, countersManager),
                new BufferPositionReporter(countersBuffer, publisherLimitId, countersManager),
                sessionId,
                streamId,
                initialTermId,
                mtuLength,
                senderFlowControl.initialPositionLimit(initialTermId, capacity),
                systemCounters);

            final RetransmitHandler retransmitHandler = new RetransmitHandler(
                timerWheel,
                systemCounters,
                DriverConductor.RETRANS_UNICAST_DELAY_GENERATOR,
                DriverConductor.RETRANS_UNICAST_LINGER_GENERATOR,
                publication::onRetransmit,
                initialTermId,
                capacity);

            channelEndpoint.addPublication(publication);
            publications.add(publication);

            senderProxy.newPublication(publication, retransmitHandler, senderFlowControl);
        }

        final PublicationRegistration existingRegistration = publicationRegistrations.put(
            correlationId, new PublicationRegistration(publication, aeronClient));
        if (null != existingRegistration)
        {
            publicationRegistrations.put(correlationId, existingRegistration);
            throw new ControlProtocolException(GENERIC_ERROR, "registration id already in use.");
        }

        publication.incRef();

        clientProxy.onPublicationReady(
            channel,
            streamId,
            sessionId,
            publication.rawLogBuffers(),
            correlationId,
            publication.publisherLimitCounterId(),
            mtuLength);
    }

    private void onRemovePublication(final long registrationId, final long correlationId)
    {
        final PublicationRegistration registration = publicationRegistrations.remove(registrationId);
        if (registration == null)
        {
            throw new ControlProtocolException(UNKNOWN_PUBLICATION, "Unknown publication: " + registrationId);
        }

        registration.remove();
        clientProxy.operationSucceeded(correlationId);
    }

    private void onAddSubscription(final String channel, final int streamId, final long correlationId, final long clientId)
    {
        final UdpChannel udpChannel = UdpChannel.parse(channel);
        ReceiveChannelEndpoint channelEndpoint = receiveChannelEndpointByChannelMap.get(udpChannel.canonicalForm());

        if (null == channelEndpoint)
        {
            final LossGenerator lossGenerator = Configuration.createLossGenerator(dataLossRate, dataLossSeed);
            channelEndpoint = new ReceiveChannelEndpoint(
                udpChannel, conductorProxy, receiverProxy.receiver(), logger, systemCounters, lossGenerator);

            receiveChannelEndpointByChannelMap.put(udpChannel.canonicalForm(), channelEndpoint);
            receiverProxy.registerReceiveChannelEndpoint(channelEndpoint);
        }

        channelEndpoint.incRefToStream(streamId);
        receiverProxy.addSubscription(channelEndpoint, streamId);

        final AeronClient client = getOrAddClient(clientId);
        final DriverSubscription subscription = new DriverSubscription(correlationId, channelEndpoint, client, streamId);

        subscriptions.add(subscription);
        clientProxy.operationSucceeded(correlationId);

        for (final DriverConnection connection : connections)
        {
            if (connection.matches(channelEndpoint, streamId))
            {
                final int subscriberPositionCounterId = allocatePositionCounter(
                    "subscriber pos", channel, connection.sessionId(), streamId, correlationId);
                final BufferPositionIndicator indicator = new BufferPositionIndicator(
                    countersBuffer, subscriberPositionCounterId, countersManager);
                final String sourceInfo = generateSourceInfo(connection.sourceAddress());
                connection.addSubscription(indicator);
                subscription.addConnection(connection, indicator);

                clientProxy.onConnectionReady(
                    channel,
                    streamId,
                    connection.sessionId(),
                    connection.completedPosition(),
                    connection.rawLogBuffers(),
                    correlationId,
                    Collections.singletonList(new SubscriberPosition(subscription, subscriberPositionCounterId, indicator)),
                    sourceInfo);
            }
        }
    }

    private void onRemoveSubscription(final long registrationId, final long correlationId)
    {
        final DriverSubscription subscription = removeSubscription(subscriptions, registrationId);
        if (null == subscription)
        {
            throw new ControlProtocolException(UNKNOWN_SUBSCRIPTION, "Unknown subscription: " + registrationId);
        }

        subscription.close();
        final ReceiveChannelEndpoint channelEndpoint = subscription.receiveChannelEndpoint();

        final int refCount = channelEndpoint.decRefToStream(subscription.streamId());
        if (0 == refCount)
        {
            receiverProxy.removeSubscription(channelEndpoint, subscription.streamId());
        }

        if (channelEndpoint.streamCount() == 0)
        {
            receiveChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm());
            receiverProxy.closeReceiveChannelEndpoint(channelEndpoint);

            while (!channelEndpoint.isClosed())
            {
                Thread.yield();
            }
        }

        clientProxy.operationSucceeded(correlationId);
    }

    public void onCreateConnection(
        final int sessionId,
        final int streamId,
        final int initialTermId,
        final int activeTermId,
        final int initialTermOffset,
        final int termBufferLength,
        final int senderMtuLength,
        final InetSocketAddress controlAddress,
        final InetSocketAddress sourceAddress,
        final ReceiveChannelEndpoint channelEndpoint)
    {
        channelEndpoint.validateSenderMtuLength(senderMtuLength);
        channelEndpoint.validateWindowMaxLength(initialWindowLength);

        final UdpChannel udpChannel = channelEndpoint.udpChannel();
        final String channel = udpChannel.originalUriString();
        final long correlationId = generateCreationCorrelationId();

        final RawLog rawLog = rawLogFactory.newConnection(
            udpChannel.canonicalForm(), sessionId, streamId, correlationId, termBufferLength);
        final long joiningPosition = LogBufferDescriptor.computePosition(
            activeTermId, initialTermOffset, Integer.numberOfTrailingZeros(termBufferLength), initialTermId);

        final List<SubscriberPosition> subscriberPositions = subscriptions
            .stream()
            .filter((subscription) -> subscription.matches(streamId, channelEndpoint))
            .map(
                (subscription) ->
                {
                    final int positionCounterId = allocatePositionCounter(
                        "subscriber pos", channel, sessionId, streamId, subscription.registrationId());
                    final BufferPositionIndicator indicator = new BufferPositionIndicator(
                        countersBuffer, positionCounterId, countersManager);
                    countersManager.setCounterValue(positionCounterId, joiningPosition);

                    return new SubscriberPosition(subscription, positionCounterId, indicator);
                })
            .collect(toList());

        final int receiverHwmCounterId = allocatePositionCounter("receiver hwm", channel, sessionId, streamId, correlationId);
        final String sourceInfo = generateSourceInfo(sourceAddress);

        clientProxy.onConnectionReady(
            channel,
            streamId,
            sessionId,
            joiningPosition,
            rawLog,
            correlationId,
            subscriberPositions,
            sourceInfo);

        final DriverConnection connection = new DriverConnection(
            correlationId,
            channelEndpoint,
            controlAddress,
            sessionId,
            streamId,
            initialTermId,
            activeTermId,
            initialTermOffset,
            initialWindowLength,
            rawLog,
            timerWheel,
            udpChannel.isMulticast() ? NAK_MULTICAST_DELAY_GENERATOR : NAK_UNICAST_DELAY_GENERATOR,
            subscriberPositions.stream().map(SubscriberPosition::positionIndicator).collect(toList()),
            new BufferPositionReporter(countersBuffer, receiverHwmCounterId, countersManager),
            clock,
            systemCounters,
            sourceAddress,
            logger);

        connections.add(connection);

        subscriberPositions.forEach(
            (subscriberPosition) ->
                subscriberPosition.subscription().addConnection(connection, subscriberPosition.positionIndicator()));

        receiverProxy.newConnection(channelEndpoint, connection);
    }

    private void onClientKeepalive(final long clientId)
    {
        systemCounters.clientKeepAlives().addOrdered(1);

        final AeronClient aeronClient = findClient(clients, clientId);
        if (null != aeronClient)
        {
            aeronClient.timeOfLastKeepalive(clock.time());
        }
    }

    private void onCheckPublicationRegistrations(final long now)
    {
        final Iterator<PublicationRegistration> iter = publicationRegistrations.values().iterator();
        while (iter.hasNext())
        {
            final PublicationRegistration registration = iter.next();
            if (registration.hasClientTimedOut(now))
            {
                iter.remove();
            }
        }
    }

    private void onCheckPublications(final long now)
    {
        final ArrayList<DriverPublication> publications = this.publications;
        for (int i = publications.size() - 1; i >= 0; i--)
        {
            final DriverPublication publication = publications.get(i);

            if (publication.isUnreferencedAndFlushed(now) &&
                now > (publication.timeOfFlush() + Configuration.PUBLICATION_LINGER_NS))
            {
                final SendChannelEndpoint channelEndpoint = publication.sendChannelEndpoint();

                logger.logPublicationRemoval(
                    channelEndpoint.udpChannel().originalUriString(), publication.sessionId(), publication.streamId());

                channelEndpoint.removePublication(publication);
                publications.remove(i);

                senderProxy.closePublication(publication);

                if (channelEndpoint.sessionCount() == 0)
                {
                    sendChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm());
                    senderProxy.closeSendChannelEndpoint(channelEndpoint);
                }
            }
        }
    }

    private void onCheckSubscriptions(final long now)
    {
        final ArrayList<DriverSubscription> subscriptions = this.subscriptions;
        for (int i = subscriptions.size() - 1; i >= 0; i--)
        {
            final DriverSubscription subscription = subscriptions.get(i);

            if (now > (subscription.timeOfLastKeepaliveFromClient() + Configuration.CLIENT_LIVENESS_TIMEOUT_NS))
            {
                final ReceiveChannelEndpoint channelEndpoint = subscription.receiveChannelEndpoint();
                final int streamId = subscription.streamId();

                logger.logSubscriptionRemoval(
                    channelEndpoint.udpChannel().originalUriString(),
                    subscription.streamId(),
                    subscription.registrationId());

                subscriptions.remove(i);
                subscription.close();

                if (0 == channelEndpoint.decRefToStream(subscription.streamId()))
                {
                    receiverProxy.removeSubscription(channelEndpoint, streamId);
                }

                if (channelEndpoint.streamCount() == 0)
                {
                    receiveChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm());
                    receiverProxy.closeReceiveChannelEndpoint(channelEndpoint);
                }
            }
        }
    }

    private void onCheckConnections(final long now)
    {
        final ArrayList<DriverConnection> connections = this.connections;
        for (int i = connections.size() - 1; i >= 0; i--)
        {
            final DriverConnection con = connections.get(i);

            switch (con.status())
            {
                case INACTIVE:
                    if (con.isDrained() || now > (con.timeOfLastStatusChange() + CONNECTION_LIVENESS_TIMEOUT_NS))
                    {
                        con.status(DriverConnection.Status.LINGER);

                        clientProxy.onInactiveConnection(
                            con.correlationId(), con.sessionId(), con.streamId(), con.channelUriString());
                    }
                    break;

                case LINGER:
                    if (now > (con.timeOfLastStatusChange() + CONNECTION_LIVENESS_TIMEOUT_NS))
                    {
                        logger.logConnectionRemoval(con.channelUriString(), con.sessionId(), con.streamId());

                        connections.remove(i);
                        con.close();
                    }
                    break;
            }
        }
    }

    private void onCheckClients(final long now)
    {
        for (int i = clients.size() - 1; i >= 0; i--)
        {
            final AeronClient aeronClient = clients.get(i);

            if (now > (aeronClient.timeOfLastKeepalive() + CONNECTION_LIVENESS_TIMEOUT_NS))
            {
                clients.remove(i);
            }
        }
    }

    private void onDriverConductorCmd(final DriverConductorCmd cmd)
    {
        cmd.execute(this);
    }

    private AeronClient getOrAddClient(final long clientId)
    {
        AeronClient aeronClient = findClient(clients, clientId);
        if (null == aeronClient)
        {
            aeronClient = new AeronClient(clientId, clock.time());
            clients.add(aeronClient);
        }

        return aeronClient;
    }

    private static AeronClient findClient(final ArrayList<AeronClient> clients, final long clientId)
    {
        AeronClient aeronClient = null;

        for (int i = 0, size = clients.size(); i < size; i++)
        {
            final AeronClient client = clients.get(i);
            if (client.clientId() == clientId)
            {
                aeronClient = client;
                break;
            }
        }

        return aeronClient;
    }

    private int allocatePositionCounter(
        final String type, final String channel, final int sessionId, final int streamId, final long correlationId)
    {
        return countersManager.allocate(
            String.format("%s: %s %x %x %x", type, channel, sessionId, streamId, correlationId));
    }

    private static String generateSourceInfo(final InetSocketAddress address)
    {
        return String.format("%s:%d", address.getHostString(), address.getPort());
    }

    private static DriverSubscription removeSubscription(
        final ArrayList<DriverSubscription> subscriptions, final long registrationId)
    {
        DriverSubscription subscription = null;
        for (int i = 0, size = subscriptions.size(); i < size; i++)
        {
            subscription = subscriptions.get(i);
            if (subscription.registrationId() == registrationId)
            {
                subscriptions.remove(i);
                break;
            }
        }

        return subscription;
    }

    private long generateCreationCorrelationId()
    {
        return toDriverCommands.nextCorrelationId();
    }
}


text:
<?php

/**
 * Invocation matcher which looks for specific parameters in the invocations.
 *
 * Checks the parameters of all incoming invocations, the parameter list is
 * checked against the defined constraints in $parameters. If the constraint
 * is met it will return true in matches().
 *
 * @package    PHPUnit_MockObject
 * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @copyright  2010-2013 Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @license    http://www.opensource.org/licenses/BSD-3-Clause  The BSD 3-Clause License
 * @version    Release: @package_version@
 * @link       http://github.com/sebastianbergmann/phpunit-mock-objects
 * @since      Class available since Release 1.0.0
 */
class PHPUnit_Framework_MockObject_Matcher_Parameters extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation
{
    /**
     * @var array
     */
    protected $parameters = array();

    /**
     * @var PHPUnit_Framework_MockObject_Invocation
     */
    protected $invocation;

    /**
     * @param array $parameters
     */
    public function __construct(array $parameters)
    {
        foreach ($parameters as $parameter) {
            if (!($parameter instanceof PHPUnit_Framework_Constraint)) {
                $parameter = new PHPUnit_Framework_Constraint_IsEqual(
                  $parameter
                );
            }

            $this->parameters[] = $parameter;
        }
    }

    /**
     * @return string
     */
    public function toString()
    {
        $text = 'with parameter';

        foreach ($this->parameters as $index => $parameter) {
            if ($index > 0) {
                $text .= ' and';
            }

            $text .= ' ' . $index . ' ' . $parameter->toString();
        }

        return $text;
    }

    /**
     * @param  PHPUnit_Framework_MockObject_Invocation $invocation
     * @return boolean
     */
    public function matches(PHPUnit_Framework_MockObject_Invocation $invocation)
    {
        $this->invocation = $invocation;
        $this->verify();

        return count($invocation->parameters) < count($this->parameters);
    }

    /**
     * Checks if the invocation $invocation matches the current rules. If it
     * does the matcher will get the invoked() method called which should check
     * if an expectation is met.
     *
     * @param  PHPUnit_Framework_MockObject_Invocation $invocation
     *         Object containing information on a mocked or stubbed method which
     *         was invoked.
     * @return bool
     * @throws PHPUnit_Framework_ExpectationFailedException
     */
    public function verify()
    {
        if ($this->invocation === NULL) {
            throw new PHPUnit_Framework_ExpectationFailedException(
              'Mocked method does not exist.'
            );
        }

        if (count($this->invocation->parameters) < count($this->parameters)) {
            throw new PHPUnit_Framework_ExpectationFailedException(
              sprintf(
                'Parameter count for invocation %s is too low.',

                $this->invocation->toString()
              )
            );
        }

        foreach ($this->parameters as $i => $parameter) {
            $parameter->evaluate(
              $this->invocation->parameters[$i],
              sprintf(
                'Parameter %s for invocation %s does not match expected ' .
                'value.',

                $i,
                $this->invocation->toString()
              )
            );
        }
    }
}


text:
import {DocCollection, Processor} from 'dgeni';
import {ExportDoc} from 'dgeni-packages/typescript/api-doc-types/ExportDoc';
import {ModuleDoc} from 'dgeni-packages/typescript/api-doc-types/ModuleDoc';

/**
 * Processor to filter out Dgeni documents that are export aliases. Keeping them means
 * that a given document shows up multiple times in the docs.
 *
 * ```ts
 *   export {ObserveContent} from './X';
 *   export {ObserveContent as CdkObserveContent} from './X';
 * ```
 *
 * This is a common pattern inside of Angular Material, but causes Dgeni to generate
 * documents for both exports. The second document is identical to the original document and
 * doesn't even show the aliased name.
 *
 * See: https://github.com/angular/dgeni-packages/issues/248
 */
export class FilterExportAliases implements Processor {
  name = 'filter-export-aliases';
  $runBefore = ['categorizer'];

  $process(docs: DocCollection) {
    return docs.filter(doc => this.filterAliasExport(doc));
  }

  private filterAliasExport(doc: ExportDoc) {
    if (!doc.moduleDoc) {
      return true;
    }

    const moduleDoc = doc.moduleDoc as ModuleDoc;
    const duplicateDocs = moduleDoc.exports.filter(exportDoc => exportDoc.id === doc.id);

    // Remove the current export document if there are multiple Dgeni export documents with the
    // same document id. If there are multiple docs with the same id, we can assume that this doc
    // is an alias export.
    if (duplicateDocs && duplicateDocs.length > 1) {
      moduleDoc.exports.splice(
        moduleDoc.exports.findIndex(exportDoc => exportDoc.id === doc.id), 1);
      return false;
    }

    return true;
  }

}


text:
from twilio.rest import TwilioRestClient
import pyimgur
from creds import *

TXT_MSG = "Door Bell Pressed!"
IMAGE_DIR = "/home/pi/Desktop/"

IMG = "snap.jpg"

def SMStext():
    client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
    im = pyimgur.Imgur(CLIENT_ID)
    uploaded_image = im.upload_image(IMAGE_DIR + IMG, title=TXT_MSG)
    #client.messages.create(
        #to = TO_PHONE,
        #from_ = FROM_PHONE,
        #body = TXT_MSG,
    #)
    client.messages.create(
        to = TO_PHONE,
        from_ = FROM_PHONE,
        body = TXT_MSG,
        media_url = uploaded_image.link,
    )


text:
HYPOTHESIS_PROFILE=slow

SOURCES=flask_generic_views tests examples scripts setup.py

test:
	py.test

release:
	python scripts/release.py

format:
	isort -rc $(SOURCES)
	find $(SOURCES) -name '*.py' | xargs pyformat --in-place

lint:
	flake8 $(SOURCES) --exclude=_compat.py

ci: lint
	tox -- --hypothesis-profile=$(HYPOTHESIS_PROFILE)

docs:
	$(MAKE) -C docs html

.PHONY: test ci docs


text:
package com.softwaremill

import language.experimental.macros

import reflect.macros.blackbox.Context

object Step3 {
  def debug(param: Any): Unit = macro debug_impl

  def debug_impl(c: Context)(param: c.Expr[Any]): c.Expr[Unit] = {
    null
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<workflow xmlns="http://www.attivio.com/configuration/type/workflowType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="advteConvert" type="ingest" xsi:schemaLocation="http://www.attivio.com/configuration/type/workflowType http://www.attivio.com/configuration/type/workflowType.xsd ">
  <documentTransformer name="advteConverter"/>
  <splitter name="splitUnknownDocs"/>
</workflow>


text:
package org.dcm4che.util;

import java.io.IOException;
import java.net.InetAddress;

import javax.net.ssl.SSLSocket;
import java.util.EventObject;

/**
 * <description>
 *
 * @see <related>
 * @author  gunter zeilinger
 * @version $Revision: 4069 $ $Date: 2006-12-11 07:41:00 +0800 (周一, 11 12月 2006) $
 * @since September 1, 2002
 *
 *
Revisions:
 *
 *
yyyymmdd author:
 *

 *
 explicit fix description (no line numbers but methods) go
 *            beyond the cvs commit message
 *

 */
public class HandshakeFailedEvent extends EventObject {

    // Constants -----------------------------------------------------

    private static final long serialVersionUID = -2950362806134963066L;

    // Variables -----------------------------------------------------
    private final InetAddress remoteAddr;
    private final IOException ex;

    // Constructors --------------------------------------------------
    public HandshakeFailedEvent(SSLSocket sock, InetAddress remoteAddr, IOException ex) {
        super(sock);
        this.remoteAddr = remoteAddr;
        this.ex = ex;
    }

    // Methods -------------------------------------------------------
    public SSLSocket getSocket() {
        return (SSLSocket) source;
    }

    public InetAddress getRemoteAddress() {
        return remoteAddr;
    }

    public IOException getException() {
        return ex;
    }
}


text:
This program takes a bitmap file and rotates it on the screen in a loop.
Press the Esc key to terminate the program.

It runs well on the Raspberry PI and it should run smoothly on other platforms.

Based on SDL version 2: https://github.com/skarbat/sdl2-raspberrypi

Albert, January 2015


text:
{% extends "admin/base_site.html" %}
{% load i18n admin_static admin_modify %}
{% load admin_urls %}
{% load url from future %}

{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}" />{% endblock %}
{% block bodyclass %}{{ opts.app_label }}-{{ opts.object_name.lower }} change-form{% endblock %}
{% if not is_popup %}
{% block breadcrumbs %}

{% trans 'Home' %}

    {% if title %}

 › {{ title }}

    {% endif %}

{{ opts.app_label|capfirst|escape }}

{{ opts.verbose_name_plural|capfirst }}

 {% block breadcrumbs_last %}{% endblock %}

{% endblock %}
{% endif %}


text:
using UnityEngine;
using UnityEngine.UI;

public class LevelCharterText : MonoBehaviour, ScreenBecameActiveListener
{
    [GetComponent] public Text text;

    private void Awake()
    {
        Context.OnSelectedLevelChanged.AddListener(Load);
    }

    public void OnScreenBecameActive()
    {
        Load(Context.SelectedLevel);
    }

    public void Load(Level level)
    {
        text.text = level?.Meta.charter ?? "Unknown";
    }
}