text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Nez
{
	///
	/// MarkupText lets you set fonts, textures and conditionals and provide some XML text to render that uses them. You must first
	/// set the fonts, textures and conditionals before you can use them in your markup.
	///
	/// <![CDATA[
	/// <markuptext face="RegularFont" color="#ffffff" align="left">
	/// 	Lorem Ipsum
	///
Some more text <text color='#ff9900'>with color</text> in the middle

	///
Images are inlined too

	/// 	<if condition="isTrue"></if>
	///
conditions can be negated as well <if condition="!isTrue">isTrue isnt true<else>isTrue is true</else></if>

	/// </markuptext>
	/// ]]>
	///
	public class MarkupText : RenderableComponent
	{
		public override float width { get { return _textWidth; } }
		public override float height { get { return _textHeight; } }

		public string text { get { return _text; } }
		public float textWidth { get { return _textWidth; } }

		string _text;
		float _textWidth, _textHeight;

		List<ICompiledElement> _compiledMarkup;
		Dictionary<string,IFont> _fontDict = new Dictionary<string,IFont>();
		Dictionary<string,Texture2D> _textureDict = new Dictionary<string,Texture2D>();
		Dictionary<string,bool> _conditionalDict = new Dictionary<string,bool>();

		public MarkupText()
		{
			setFont( "default", Graphics.instance.bitmapFont );
		}

		public MarkupText( float textWidth ) : this()
		{
			_textWidth = textWidth;
		}

		///
		/// sets the text used for the run. Text should be valid XML.
		///
		/// <returns>The text.</returns>
		/// <param name="text">Text.</param>
		public MarkupText setText( string text )
		{
			_text = text;
			return this;
		}

		///
		/// sets the width that the run will fill
		///
		/// <returns>The width.</returns>
		/// <param name="textWidth">Width.</param>
		public MarkupText setTextWidth( float textWidth )
		{
			_textWidth = textWidth;
			return this;
		}

		///
		/// sets a font that can be used in a text tag via the font attribute
		///
		/// <returns>The font.</returns>
		/// <param name="name">Name.</param>
		/// <param name="font">Font.</param>
		public MarkupText setFont( string name, IFont font )
		{
			_fontDict[name] = font;
			return this;
		}

		///
		/// sets a texture which can be used in an img tag via the source attribute
		///
		/// <returns>The texture.</returns>
		/// <param name="name">Name.</param>
		/// <param name="texture">Texture.</param>
		public MarkupText setTexture( string name, Texture2D texture )
		{
			_textureDict[name] = texture;
			return this;
		}

		///
		/// sets a conditional which can be used in an if tag with a condition attribute. It is also valid to negate the condition by
		/// prepending a ! to the name in the if tag
		///
		/// <returns>The conditional.</returns>
		/// <param name="name">Name.</param>
		/// <param name="conditional">Conditional.</param>
		public MarkupText setConditional( string name, bool conditional )
		{
			_conditionalDict[name] = conditional;
			return this;
		}

		///
		/// renders the MarkupText
		///
		/// <param name="graphics">Graphics.</param>
		/// <param name="camera">Camera.</param>
		public override void render( Graphics graphics, Camera camera )
		{
			if( _compiledMarkup == null )
				return;

			for( var i = 0; i < _compiledMarkup.Count; i++ )
				_compiledMarkup[i].render( graphics, transform.position + _localOffset );
		}

		///
		/// compiles the current text to prepare it for rendering
		///
		public void compile()
		{
			if( _compiledMarkup == null )
				_compiledMarkup = new List<ICompiledElement>();
			else
				_compiledMarkup.Clear();

			var reader = XmlReader.Create( new StringReader( _text ) );
			var position = Vector2.Zero;
			var formatingStack = new Stack<FormatInstruction>();
			var conditionalsStack = new Stack<bool>();
			var alignStack = new Stack<HorizontalAlign>();
			var lineBuffer = new List<ICompiledElement>();
			var currentLineHeight = 0f;
			var currentTotalHeight = 0f;
			var currentLineWidth = 0f;

			while( reader.Read() )
			{
				if( reader.NodeType == XmlNodeType.Element )
				{
					switch( reader.Name )
					{
						case "font":
						case "markuptext":
						{
							IFont font;
							var s = reader.GetAttribute( "face" );
							if( !string.IsNullOrEmpty( s ) )
								font = _fontDict[s];
							else if( formatingStack.Count > 0 )
								font = formatingStack.Peek().font;
							else
								font = _fontDict["default"];

							var color = Color.White;
							s = reader.GetAttribute( "color" );
							if( !string.IsNullOrEmpty( s ) )
								color = parseColor( s );
							else if( formatingStack.Count > 0 )
								color = formatingStack.Peek().color;

							var scale = Vector2.One;
							s = reader.GetAttribute( "scale" );
							if( !string.IsNullOrEmpty( s ) )
								scale = parseVector2( s );

							if( reader.Name == "markuptext" )
							{
								var value = reader.GetAttribute( "align" );
								var align = HorizontalAlign.Left;
								Enum.TryParse( value, out align );
								alignStack.Push( align );
							}

							formatingStack.Push( new FormatInstruction( font, color, scale ) );
							break;
						}

						case "if":
						{
							var condition = reader.GetAttribute( "condition" );
							var negateCondition = condition[0] == '!';
							if( negateCondition )
								condition = condition.Substring( 1 );

							var value = _conditionalDict[condition];
							conditionalsStack.Push( negateCondition ? !value : value );
							break;
						}

						case "else":
						{
							var value = conditionalsStack.Pop();
							conditionalsStack.Push( !value );
							break;
						}

						case "p":
						case "br":
						{
							if( lineBuffer.Count > 0 )
							{
								position = wrapLine( position, lineBuffer, alignStack.Peek(), out currentLineHeight );
								currentTotalHeight += currentLineHeight;
							}
							else
							{
								var currentFormatting = formatingStack.Peek();
								position.Y += currentFormatting.font.lineSpacing * currentFormatting.scale.Y;
								currentTotalHeight += currentFormatting.font.lineSpacing * currentFormatting.scale.Y;
							}
							currentLineWidth = 0;

							if( reader.Name == "p" )
							{
								var value = reader.GetAttribute( "align" );
								if( string.IsNullOrEmpty( value ) )
									value = "Left";
								value = char.ToUpper( value[0] ) + value.Substring( 1 );

								HorizontalAlign align;
								if( Enum.TryParse( value, out align ) )
									alignStack.Push( align );
								else
									throw new InvalidOperationException( "Invalid alignemnt: " + value );
							}
							break;
						}

						case "img":
						{
							if( conditionalsStack.Count != 0 && !conditionalsStack.Peek() )
								continue;

							var imgSrc = reader.GetAttribute( "src" );
							var color = Color.White;
							var s = reader.GetAttribute( "color" );
							if( !string.IsNullOrEmpty( s ) )
								color = parseColor( s );

							var scale = Vector2.One;
							s = reader.GetAttribute( "scale" );
							if( !string.IsNullOrEmpty( s ) )
								scale = parseVector2( s );

							var image = _textureDict[imgSrc];
							var imageWidth = image.Width * scale.X;
							if( position.X + imageWidth > _textWidth )
							{
								position = wrapLine( position, lineBuffer, alignStack.Peek(), out currentLineHeight );
								currentTotalHeight += currentLineHeight;
							}

							lineBuffer.Add( new CompiledImageElement( image, color, position, scale ) );
							position.X += imageWidth;
							currentLineWidth += imageWidth;
							break;
						}

						case "nbsp":
						{
							var currentFormatting = formatingStack.Peek();
							var spaceX = currentFormatting.font.measureString( " " ).X * currentFormatting.scale.X;
							if( position.X + spaceX < _textWidth )
							{
								position.X += spaceX;
								currentLineWidth += spaceX;
							}
							break;
						}
					}
				}
				else if( reader.NodeType == XmlNodeType.Text )
				{
					if( conditionalsStack.Count != 0 && !conditionalsStack.Peek() )
						continue;

					var currentFormatting = formatingStack.Peek();
					var re = new Regex( @"\s+" );
					var words = re.Split( reader.Value );
					var spaceX = currentFormatting.font.measureString( " " ).X * currentFormatting.scale.X;

					var wordIndex = 0;
					var wordRunSize = 0f;
					var textRun = new StringBuilder();

					// figure out how many words we can fit on the line and compile them
					while( words.Length > wordIndex )
					{
						var isLastWord = wordIndex == words.Length - 1;
						var word = words[wordIndex];
						var wordSize = currentFormatting.font.measureString( word ) * currentFormatting.scale;

						// make sure the word fits
						var currentWordFits = position.X + wordRunSize + wordSize.X <= _textWidth;

						// if there is only one word and it doesnt fit we are gonna add it anyway else we will have nothing to show
						if( words.Length == 0 && !currentWordFits )
							currentWordFits = true;

						if( currentWordFits )
						{
							textRun.Append( word ).Append( " " );
							wordRunSize += wordSize.X + spaceX;
							wordIndex++;
						}

						// if this is the last word or the current word doesnt fit dump our text run
						if( ( isLastWord || !currentWordFits ) && textRun.Length > 0 )
						{
							// back off and add any words we accrued and remove the last space
							textRun.Length--;
							wordRunSize -= spaceX;

							lineBuffer.Add( new CompiledTextElement( textRun.ToString(), position, currentFormatting ) );
							textRun.Clear();

							position.X += wordRunSize;
							currentLineWidth += wordRunSize;
							wordRunSize = 0;
						}

						// if the current word doesnt fit we need a newline
						if( !currentWordFits )
						{
							position = wrapLine( position, lineBuffer, alignStack.Peek(), out currentLineHeight );
							currentTotalHeight += currentLineHeight;
							currentLineWidth = 0;
						}
					}
				}
				else if( reader.NodeType == XmlNodeType.EndElement )
				{
					switch( reader.Name )
					{
						case "font":
						case "markuptext":
						{
							formatingStack.Pop();
							break;
						}
						case "if":
						{
							conditionalsStack.Pop();
							break;
						}
						case "p":
						{
							if( lineBuffer.Count > 0 )
							{
								position = wrapLine( position, lineBuffer, alignStack.Peek(), out currentLineHeight );
								currentTotalHeight += currentLineHeight;
							}
							else
							{
								var currentFormatting = formatingStack.Peek();
								position.Y += currentFormatting.font.lineSpacing * currentFormatting.scale.Y;
								currentTotalHeight += currentFormatting.font.lineSpacing * currentFormatting.scale.Y;
							}
							currentLineWidth = 0;
							alignStack.Pop();
							break;
						}
					}
				}
			}

			if( lineBuffer.Count > 0 )
			{
				wrapLine( position, lineBuffer, alignStack.Peek(), out currentLineHeight );
				for( var i = 0; i < lineBuffer.Count; i++ )
				{
					var element = lineBuffer[i];
					element.position = new Vector2( element.position.X, position.Y + currentLineHeight / 2f );
				}
				currentTotalHeight += currentLineHeight;
				_compiledMarkup.AddRange( lineBuffer );
				lineBuffer.Clear();
			}

			_textHeight = currentTotalHeight;
		}

		Vector2 wrapLine( Vector2 position, List<ICompiledElement> lineBuffer, HorizontalAlign alignment, out float currentLineHeight )
		{
			currentLineHeight = 0;
			var lineWidth = 0f;

			// figure out the max height for anything in the line
			for( var i = 0; i < lineBuffer.Count; i++ )
			{
				currentLineHeight = Math.Max( currentLineHeight, lineBuffer[i].size.Y );
				lineWidth += lineBuffer[i].size.X;
			}

			// calculate the offset that we will shift each line
			var xOffset = 0f;
			switch( alignment )
			{
				case HorizontalAlign.Right:
					xOffset = _textWidth - lineWidth;
					break;
				case HorizontalAlign.Center:
					xOffset = ( _textWidth - lineWidth ) / 2f;
					break;
			}

			// run back through and reset the y position of all the items to match the currentLineHeight and apply the xOffset
			for( var i = 0; i < lineBuffer.Count; i++ )
				lineBuffer[i].position = new Vector2( lineBuffer[i].position.X + xOffset, position.Y + currentLineHeight / 2f );

			_compiledMarkup.AddRange( lineBuffer );
			lineBuffer.Clear();
			position.X = 0;
			position.Y += currentLineHeight;

			return position;
		}

		static Color parseColor( string hexString )
		{
			if( hexString.StartsWith( "#" ) )
				hexString = hexString.Substring( 1 );

			var hex = uint.Parse( hexString, NumberStyles.HexNumber, CultureInfo.InvariantCulture );
			var color = Color.White;
			if( hexString.Length == 8 )
			{
				color.A = (byte)( hex >> 24 );
				color.R = (byte)( hex >> 16 );
				color.G = (byte)( hex >> 8 );
				color.B = (byte)( hex );
			}
			else if( hexString.Length == 6 )
			{
				color.R = (byte)( hex >> 16 );
				color.G = (byte)( hex >> 8 );
				color.B = (byte)( hex );
			}
			else
			{
				throw new InvalidOperationException();
			}
			return color;
		}

		static Vector2 parseVector2( string vectorString )
		{
			var split = Regex.Split( vectorString, @"[\\s,]+" );
			return new Vector2( float.Parse( split[0], CultureInfo.InvariantCulture ), float.Parse( split[1], CultureInfo.InvariantCulture ) );
		}

	}

	#region Internal helpers

	struct FormatInstruction
	{
		public readonly Color color;
		public readonly IFont font;
		public readonly Vector2 scale;

		public FormatInstruction( IFont font, Color color, Vector2 scale )
		{
			this.font = font;
			this.color = color;
			this.scale = scale;
		}
	}

	interface ICompiledElement
	{
		Vector2 size { get; }
		Vector2 position { get; set; }
		void render( Graphics graphics, Vector2 offset );
	}

	struct CompiledTextElement : ICompiledElement
	{
		public Vector2 position { get; set; }
		public Vector2 size { get; set; }

		readonly FormatInstruction _formatInstruction;
		readonly string _text;

		public CompiledTextElement( string text, Vector2 position, FormatInstruction formatInstruction )
		{
			_text = text;
			this.position = position;
			_formatInstruction = formatInstruction;
			size = formatInstruction.font.measureString( text ) * formatInstruction.scale;
		}

		public void render( Graphics graphics, Vector2 offset )
		{
			var origin = new Vector2( 0, size.Y / ( 2 * _formatInstruction.scale.Y ) );
			graphics.batcher.drawString( _formatInstruction.font, _text, offset + position, _formatInstruction.color, 0, origin, _formatInstruction.scale, SpriteEffects.None, 0 );
		}

	}

	struct CompiledImageElement : ICompiledElement
	{
		public Vector2 position { get; set; }
		public Vector2 size { get; set; }

		readonly Color _color;
		readonly Texture2D _image;
		readonly Vector2 _scale;

		public CompiledImageElement( Texture2D image, Color color, Vector2 position, Vector2 scale )
		{
			_image = image;
			this.position = position;
			_color = color;
			_scale = scale;
			size = new Vector2( image.Width, image.Height ) * scale;
		}

		public void render( Graphics graphics, Vector2 offset )
		{
			var origin = new Vector2( 0, _image.Height / 2f );
			graphics.batcher.draw( _image, offset + position, null, _color, 0, origin, _scale, SpriteEffects.None, 0 );
		}

	}

	#endregion

}


text:
package au.com.fujitsu.trainingcore.services.impl;

import au.com.fujitsu.trainingcore.model.BusinessPartnerModel;
import au.com.fujitsu.trainingcore.services.BusinessPartnerService;
import de.hybris.bootstrap.annotations.IntegrationTest;
import de.hybris.platform.servicelayer.ServicelayerTest;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

import javax.annotation.Resource;

@IntegrationTest
public class DefaultBusinessPartnerServiceTest extends ServicelayerTest {
    private static final Logger LOG = LoggerFactory.getLogger(DefaultBusinessPartnerServiceTest.class);

    @Resource
    private BusinessPartnerService businessPartnerService;

    @Test
    public void testCreateBusinessPartner() {
        LOG.info("This is test create Business partner");

        businessPartnerService.createBusinessPartner("test@test1.com", "tester", 10);
        BusinessPartnerModel businessPartner = businessPartnerService.findBusinessPartner("test@test1.com");

        assertThat("tester", equalTo(businessPartner.getName()));
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Concrete\Core\Html\Service;

use View;

class Lightbox
{
    public function init($selector = '.ccm-overlay')
    {
        $view = View::getInstance();
        $v = View::getInstance();
        $v->requireAsset('core/lightbox');
        if ($selector && strlen($selector)) {
            $js = "<script type=\"text/javascript\">$(function() {
				$('".$selector."-image').magnificPopup({type:'image'});
				$('".$selector."-iframe').magnificPopup({type:'image'});
				$('".$selector."-inline').magnificPopup({type:'image'});
				$('".$selector."-ajax').magnificPopup({type:'image'});
			});</script>";
            $view->addFooterItem($js);
        }
    }
}


text:
require 'chef/knife'

class Chef
  class Knife
    class TagDelete < Knife

      deps do
        require 'chef/node'
      end

      banner "knife tag delete NODE TAG ..."

      def run
        name = @name_args[0]
        tags = @name_args[1..-1]

        if name.nil? || tags.nil? || tags.empty?
          show_usage
          ui.fatal("You must specify a node name and at least one tag.")
          exit 1
        end

        node = Chef::Node.load name
        deleted_tags = Array.new
        tags.each do |tag|
          unless node.tags.delete(tag).nil?
            deleted_tags << tag
          end
        end
        node.save
        message = if deleted_tags.empty?
                    "Nothing has changed. The tags requested to be deleted do not exist."
                  else
                    "Deleted tags #{deleted_tags.join(", ")} for node #{name}."
                  end
        ui.info(message)
      end
    end
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Blockly Demo: Scheme</title>

  <link rel="stylesheet" href="https://codemirror.net/lib/codemirror.css">

  </script>

  <xml id="toolbox" style="display:none"></xml>


text:
#include "proton/container.hpp"
#include "proton/connection_options.hpp"
#include "proton/event.hpp"
#include "proton/connection.hpp"
#include "proton/session.hpp"
#include "proton/acceptor.hpp"
#include "proton/error.hpp"
#include "proton/url.hpp"
#include "proton/sender.hpp"
#include "proton/receiver.hpp"
#include "proton/task.hpp"
#include "proton/ssl.hpp"
#include "proton/sasl.hpp"
#include "proton/transport.hpp"
#include "proton/uuid.hpp"

#include "connector.hpp"
#include "container_impl.hpp"
#include "contexts.hpp"
#include "messaging_adapter.hpp"
#include "messaging_event.hpp"
#include "msg.hpp"

#include "proton/connection.h"
#include "proton/session.h"
#include "proton/handlers.h"
#include "proton/reactor.h"

namespace proton {

namespace {

struct handler_context {
    static handler_context& get(pn_handler_t* h) {
        return *reinterpret_cast<handler_context*>(pn_handler_mem(h));
    }
    static void cleanup(pn_handler_t*) {}

    /*
     * NOTE: this call, at the transition from C to C++ is possibly
     * the biggest performance bottleneck.  "Average" clients ignore
     * 90% of these events.  Current strategy is to create the
     * messaging_event on the stack.  For success, the messaging_event
     * should be small and free of indirect malloc/free/new/delete.
     */

    static void dispatch(pn_handler_t *c_handler, pn_event_t *c_event, pn_event_type_t type)
    {
        handler_context& hc(handler_context::get(c_handler));
        proton_event pevent(c_event, type, hc.container_);
        pevent.dispatch(*hc.handler_);
        return;
    }

    container *container_;
    proton_handler *handler_;
};

} // namespace

// Used to sniff for connector events before the reactor's global handler sees them.
class override_handler : public proton_handler
{
  public:
    internal::pn_ptr<pn_handler_t> base_handler;
    container_impl &container_impl_;

    override_handler(pn_handler_t *h, container_impl &c) : base_handler(h), container_impl_(c) {}

    virtual void on_unhandled(proton_event &pe) {
        proton_event::event_type type = pe.type();
        if (type==proton_event::EVENT_NONE) return;  // Also not from the reactor

        pn_event_t *cevent = pe.pn_event();
        pn_connection_t *conn = pn_event_connection(cevent);
        if (conn) {
            proton_handler *override = connection_context::get(conn).handler.get();
            if (override && type != proton_event::CONNECTION_INIT) {
                // Send event to connector
                pe.dispatch(*override);
            }
            else if (!override && type == proton_event::CONNECTION_INIT) {
                // Newly accepted connection from lister socket
                connection c(conn);
                container_impl_.configure_server_connection(c);
            }
        }
        pn_handler_dispatch(base_handler.get(), cevent, pn_event_type_t(type));
    }
};

internal::pn_ptr<pn_handler_t> container_impl::cpp_handler(proton_handler *h) {
    if (!h->pn_handler_) {
        h->pn_handler_ = internal::take_ownership(
            pn_handler_new(&handler_context::dispatch,
                           sizeof(struct handler_context),
                           &handler_context::cleanup));
        handler_context &hc = handler_context::get(h->pn_handler_.get());
        hc.container_ = &container_;
        hc.handler_ = h;
    }
    return h->pn_handler_;
}

container_impl::container_impl(container& c, messaging_adapter *h, const std::string& id) :
    container_(c), reactor_(reactor::create()), handler_(h),
    id_(id.empty() ? uuid::random().str() : id), id_gen_()
{
    container_context::set(reactor_, container_);

    // Set our own global handler that "subclasses" the existing one
    pn_handler_t *global_handler = reactor_.pn_global_handler();
    override_handler_.reset(new override_handler(global_handler, *this));
    internal::pn_ptr<pn_handler_t> cpp_global_handler(cpp_handler(override_handler_.get()));
    reactor_.pn_global_handler(cpp_global_handler.get());
    if (handler_) {
        reactor_.pn_handler(cpp_handler(handler_).get());
    }

    // Note: we have just set up the following handlers that see
    // events in this order: messaging_adapter, connector override,
    // the reactor's default globalhandler (pn_iohandler)
}

container_impl::~container_impl() {}

connection container_impl::connect(const proton::url &url, const connection_options &user_opts) {
    connection_options opts = client_connection_options(); // Defaults
    opts.update(user_opts);
    proton_handler *h = opts.handler();

    internal::pn_ptr<pn_handler_t> chandler = h ? cpp_handler(h) : internal::pn_ptr<pn_handler_t>();
    connection conn(reactor_.connection(chandler.get()));
    internal::pn_unique_ptr<connector> ctor(new connector(conn, opts));
    ctor->address(url);  // TODO: url vector
    connection_context& cc(connection_context::get(conn));
    cc.handler.reset(ctor.release());
    cc.link_gen.prefix(id_gen_.next() + "/");
    pn_connection_set_container(conn.pn_object(), id_.c_str());

    conn.open();
    return conn;
}

sender container_impl::open_sender(const proton::url &url, const proton::link_options &o1, const connection_options &o2) {
    proton::link_options lopts(link_options_);
    lopts.update(o1);
    connection_options copts(client_connection_options_);
    copts.update(o2);
    connection conn = connect(url, copts);
    std::string path = url.path();
    return conn.default_session().open_sender(path, lopts);
}

receiver container_impl::open_receiver(const proton::url &url, const proton::link_options &o1, const connection_options &o2) {
    proton::link_options lopts(link_options_);
    lopts.update(o1);
    connection_options copts(client_connection_options_);
    copts.update(o2);
    connection conn = connect(url, copts);
    std::string path = url.path();
    return conn.default_session().open_receiver(path, lopts);
}

acceptor container_impl::listen(const proton::url& url, const connection_options &user_opts) {
    connection_options opts = server_connection_options(); // Defaults
    opts.update(user_opts);
    proton_handler *h = opts.handler();
    internal::pn_ptr<pn_handler_t> chandler = h ? cpp_handler(h) : internal::pn_ptr<pn_handler_t>();
    pn_acceptor_t *acptr = pn_reactor_acceptor(reactor_.pn_object(), url.host().c_str(), url.port().c_str(), chandler.get());
    if (!acptr)
        throw error(MSG("accept fail: " <<
                        pn_error_text(pn_io_error(reactor_.pn_io())))
                        << "(" << url << ")");
    // Do not use pn_acceptor_set_ssl_domain().  Manage the incoming connections ourselves for
    // more flexibility (i.e. ability to change the server cert for a long running listener).
    listener_context& lc(listener_context::get(acptr));
    lc.connection_options = opts;
    lc.ssl = url.scheme() == url::AMQPS;
    return acceptor(acptr);
}

task container_impl::schedule(int delay, proton_handler *h) {
    internal::pn_ptr<pn_handler_t> task_handler;
    if (h)
        task_handler = cpp_handler(h);
    return reactor_.schedule(delay, task_handler.get());
}

void container_impl::client_connection_options(const connection_options &opts) {
    client_connection_options_ = opts;
}

void container_impl::server_connection_options(const connection_options &opts) {
    server_connection_options_ = opts;
}

void container_impl::link_options(const proton::link_options &opts) {
    link_options_ = opts;
}

void container_impl::configure_server_connection(connection &c) {
    pn_acceptor_t *pnp = pn_connection_acceptor(connection_options::pn_connection(c));
    listener_context &lc(listener_context::get(pnp));
    connection_context::get(c).link_gen.prefix(id_gen_.next() + "/");
    pn_connection_set_container(c.pn_object(), id_.c_str());
    lc.connection_options.apply(c);
}

}


text:
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Orleans.ApplicationParts;
using Orleans.Serialization;
using Orleans.UnitTest.GrainInterfaces;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;

// ReSharper disable NotAccessedVariable

namespace UnitTests.Serialization
{
    /// <summary>
    /// Test the built-in serializers
    /// </summary>
    [Collection(TestEnvironmentFixture.DefaultCollection)]
    [TestCategory("BVT"), TestCategory("Serialization")]
    public class SerializerGenerationTests
    {
        private readonly TestEnvironmentFixture fixture;

        public SerializerGenerationTests(TestEnvironmentFixture fixture)
        {
            this.fixture = fixture;
        }

        [Fact]
        public void SerializationTests_TypeWithInternalNestedClass()
        {
            var v = new MyTypeWithAnInternalTypeField();

            Assert.NotNull(this.fixture.SerializationManager.GetSerializer(typeof (MyTypeWithAnInternalTypeField)));
            Assert.NotNull(this.fixture.SerializationManager.GetSerializer(typeof(MyTypeWithAnInternalTypeField.MyInternalDependency)));
        }

        /// <summary>
        /// Types with an ancestor marked with <see cref="KnownBaseTypeAttribute"/> should have serializers generated.
        /// </summary>
        [Fact]
        public void SerializationTests_TypeWithWellKnownBaseClass()
        {
            Assert.NotNull(this.fixture.SerializationManager.GetSerializer(typeof(DescendantOfWellKnownBaseClass)));
            Assert.NotNull(this.fixture.SerializationManager.GetSerializer(typeof(ImplementsWellKnownInterface)));
            Assert.Null(this.fixture.SerializationManager.GetSerializer(typeof(NotDescendantOfWellKnownBaseType)));

            var partManager = this.fixture.Services.GetRequiredService<IApplicationPartManager>();
            var serializerFeature = new SerializerFeature();
            partManager.PopulateFeature(serializerFeature);
            Assert.Contains(serializerFeature.SerializerTypes, s => s.Target == typeof(DescendantOfWellKnownBaseClass));
            Assert.Contains(serializerFeature.SerializerTypes, s => s.Target == typeof(ImplementsWellKnownInterface));
            Assert.DoesNotContain(serializerFeature.SerializerTypes, s => s.Target == typeof(NotDescendantOfWellKnownBaseType));
        }
    }
}


text:
import SystemConfigRepository = require("../repository/SystemConfigRepository");
import ISystemConfigBusiness = require("./interfaces/ISystemConfigBusiness");
import ISystemConfig = require("../model/interfaces/ISystemConfig");
import SystemConfig = require("../model/SystemConfig");

class SystemConfigBusiness implements ISystemConfigBusiness {
    private _systemconfigRepository: SystemConfigRepository;

    constructor() {
        this._systemconfigRepository = new SystemConfigRepository();
    }

    create(item: ISystemConfig, callback: (error: any, result: any) => void) {
        this._systemconfigRepository.create(item, callback);
    }

    update(_id: string, item: ISystemConfig, callback: (error: any, result: any) => void) {
        this._systemconfigRepository.findById(_id, (err, res) => {
            if (err) callback(err, res);

            else
                this._systemconfigRepository.update(res._id, item, callback);

        });
    }

    retrieveConfigList(fieldNames: string[], callback: (error: any, result: any) => void) {
        let _options = {};
        _options['cond'] = {};
        _options['cond']['filter'] = { "systemConfigFieldName": { $in: fieldNames } };
        _options['cond']['type'] = '$in';
        _options['cond']['sort'] = { "systemConfigOrder": 1 };

        this._systemconfigRepository.find(callback, _options);
    }

    findByFieldName(fieldName: string, callback: (error: any, result: ISystemConfig) => void) {
        let _options = {};
        _options['cond'] = {};
        _options['cond']['filter'] = { 'systemConfigFieldName': fieldName };

        this._systemconfigRepository.find((error, result) => {
            console.log('resultresultresultresultresult')
            console.log(_options);
            console.log(result);
            callback(error, result[0]);
        }, _options);
    }
}

Object.seal(SystemConfigBusiness);
export = SystemConfigBusiness;


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

[assembly: AssemblyTitle("derpirc.WP7.Data")]
[assembly: AssemblyDescription("")]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("79695b6b-468b-44be-a050-77c14d23cb41")]


text: module.exports = require('./underscore.js');


text:
/**
 *
 */
package org.openforis.collect.persistence.liquibase;

import java.sql.Connection;
import java.util.Map;

import org.openforis.collect.persistence.liquibase.migrations.after.AfterMigrations;
import org.openforis.collect.persistence.liquibase.migrations.before.BeforeMigrations;

import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.DatabaseException;
import liquibase.exception.LiquibaseException;
import liquibase.integration.spring.SpringLiquibase;
import liquibase.integration.spring.SpringResourceAccessor;
import liquibase.resource.ResourceAccessor;

/**
 * @author S. Ricci
 *
 */
public class DatabaseAwareSpringLiquibase extends SpringLiquibase {

	private static final String STANDARD_DIALECT = "standard";
	private static final String DBMS_PLACEHOLDER = "DBMS_ID";

	@Override
	protected Database createDatabase(Connection c, ResourceAccessor resourceAccessor) throws DatabaseException {
		Database database = getDatabase(c);
		if (LiquibaseSupportedDBMS.SQLITE.getProductName().equals(database.getDatabaseProductName())
				|| LiquibaseSupportedDBMS.SQLITE_ANDROID.getProductName().equals(database.getDatabaseProductName())) {
			// schemas are not supported
			return database;
		} else {
			return super.createDatabase(c, resourceAccessor);
		}
	}

	@Override
	protected Liquibase createLiquibase(Connection c) throws LiquibaseException {
		SpringResourceAccessor resourceAccessor = createResourceOpener();
		Database database = createDatabase(c, resourceAccessor);

		String changeLog = getChangeLog().replace(DBMS_PLACEHOLDER, getMigrationDialect(database));
		Liquibase liquibase = new Liquibase(changeLog, resourceAccessor, database);
		if (parameters != null) {
			for (Map.Entry<String, String> entry : parameters.entrySet()) {
				liquibase.setChangeLogParameter(entry.getKey(), entry.getValue());
			}
		}
		if (isDropFirst()) {
			liquibase.dropAll();
		}
		return liquibase;
	}

	@Override
	protected void performUpdate(Liquibase liquibase) throws LiquibaseException {
		try {
			String dbProductName = liquibase.getDatabase().getDatabaseProductName();
			String schemaName = liquibase.getDatabase().getDefaultSchemaName();

			Connection connection = ((JdbcConnection) liquibase.getDatabase().getConnection()).getWrappedConnection();

			// before running Liquibase

			new BeforeMigrations().execute(connection, dbProductName, schemaName);

			super.performUpdate(liquibase);

			// after running Liquibase
			new AfterMigrations().execute(connection, dbProductName, schemaName);
		} catch (Exception e) {
			throw new LiquibaseException(e);
		}
	}

	private String getMigrationDialect(Database database) {
		String dbProductName = database.getDatabaseProductName();
		LiquibaseSupportedDBMS customDialectDb = LiquibaseSupportedDBMS.findByProductName(dbProductName);
		return customDialectDb == null ? STANDARD_DIALECT : customDialectDb.getLiquibaseDbms();
	}

	private Database getDatabase(Connection c) throws DatabaseException {
		return DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(c));
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>TextFaxProducer xref</title>
<link type="text/css" rel="stylesheet" href="../../../stylesheet.css" />

View Javadoc

1   package com.java4less.rfax;
2
3   import java.awt.Image;
4
5   /**
6    * Test Class
7    *
8    * @author Sagie Gur-Ari
9    */
10  public class TextFaxProducer implements FaxProducer {
11      /** Class member */
12      public String text;
13      /** Class member */
14      public Image pageImage;
15
16      /**
17       * Test method.
18       */
19      public void prepare() {
20          // empty
21      }
22  }

Copyright © 2009–2020 fax4j. All rights reserved.


text:
package maker

import org.scalatest.FunSuite
import scala.collection.mutable.{Map => MMap}
import maker.utils.FileUtils._
import java.io.File

class PropsTests extends FunSuite{

  test("Can't have invalid properties in props file"){
    withTempFile{
      file =>
        writeToFile(file, "InvalidPropKey=jfsfksjfks")
        try{
          MakerProps(file)
          fail("expected exception to be thrown")
        } catch {
          case e : AssertionError =>
        }
    }
  }

  test("Comments are ignored"){
    withTempFile{
      file =>
        writeToFile(file, "#InvalidPropKey=jfsfksjfks")
        assert(MakerProps(file) === MakerProps(MMap[String, String]()))
    }
  }

  test("Properties are overriden"){
    withTempFile{
      file =>
        writeToFile(file, "ProjectScalaVersion=Fred")
        assert(MakerProps(file).ProjectScalaVersion() === "Fred")
        assert(MakerProps().ProjectScalaVersion() === MakerProps.DefaultScalaVersion)
    }
  }

  test("Can override a maker property"){
    val props = MakerProps()
    assert(props.VimErrorFile() != file("fred"))
    props.VimErrorFile := "fred"
    assert(props.VimErrorFile() === file("fred"))
  }

  test("Optional property"){
    class Foo(val overrides : MMap[String, String] = MMap()) extends PropsTrait{
      object Bar extends IsOptionalString
      object Baz extends IsOptionalString
    }
    val foo = new Foo()
    assert(foo.Bar() === None)
    assert(foo.Baz() === None)

    foo.Baz := "fred"
    assert(foo.Baz() === Some("fred"))
  }

  test("reflective toString doesn't throw an exception"){
    object Foo extends PropsTrait{
      val overrides : MMap[String, String] = MMap()
      object Bar extends Default("fred") with IsString
      object Baz extends Default("9") with IsInt
      object Buz extends IsOptionalString
      object SP extends SystemProperty("no-such-property") with IsString
    }
    Foo.toString
    MakerProps().toString
  }

  test("Command lines correct"){
    object Foo extends PropsTrait{
      val overrides : MMap[String, String] = MMap()
      object SP extends SystemPropertyWithDefault("prop", "value") with IsString
    }
    assert(Foo.SP.toCommandLine === "-Dprop=value")
  }

}


text:
var http = require('http')
  , https = false
  , tls = false
  , url = require('url')
  , util = require('util')
  , stream = require('stream')
  , qs = require('querystring')
  , oauth = require('./oauth')
  , uuid = require('./uuid')
  , ForeverAgent = require('./forever')
  , Cookie = require('./vendor/cookie')
  , CookieJar = require('./vendor/cookie/jar')
  , cookieJar = new CookieJar
  , tunnel = require('./tunnel')
  , aws = require('./aws')

  , mime = require('mime')
  , FormData = require('form-data')
  ;

if (process.logging) {
  var log = process.logging('request')
}

try {
  https = require('https')
} catch (e) {}

try {
  tls = require('tls')
} catch (e) {}

function toBase64 (str) {
  return (new Buffer(str || "", "ascii")).toString("base64")
}

// Hacky fix for pre-0.4.4 https
if (https && !https.Agent) {
  https.Agent = function (options) {
    http.Agent.call(this, options)
  }
  util.inherits(https.Agent, http.Agent)
  https.Agent.prototype._getConnection = function (host, port, cb) {
    var s = tls.connect(port, host, this.options, function () {
      // do other checks here?
      if (cb) cb()
    })
    return s
  }
}

function isReadStream (rs) {
  if (rs.readable && rs.path && rs.mode) {
    return true
  }
}

function copy (obj) {
  var o = {}
  Object.keys(obj).forEach(function (i) {
    o[i] = obj[i]
  })
  return o
}

var isUrl = /^https?:/

var globalPool = {}

function Request (options) {
  stream.Stream.call(this)
  this.readable = true
  this.writable = true

  if (typeof options === 'string') {
    options = {uri:options}
  }

  var reserved = Object.keys(Request.prototype)
  for (var i in options) {
    if (reserved.indexOf(i) === -1) {
      this[i] = options[i]
    } else {
      if (typeof options[i] === 'function') {
        delete options[i]
      }
    }
  }
  options = copy(options)

  this.init(options)
}
util.inherits(Request, stream.Stream)
Request.prototype.init = function (options) {
  var self = this

  if (!options) options = {}
  if (process.env.NODE_DEBUG && /request/.test(process.env.NODE_DEBUG)) console.error('REQUEST', options)
  if (!self.pool && self.pool !== false) self.pool = globalPool
  self.dests = []
  self.__isRequestRequest = true

  // Protect against double callback
  if (!self._callback && self.callback) {
    self._callback = self.callback
    self.callback = function () {
      if (self._callbackCalled) return // Print a warning maybe?
      self._callback.apply(self, arguments)
      self._callbackCalled = true
    }
    self.on('error', self.callback.bind())
    self.on('complete', self.callback.bind(self, null))
  }

  if (self.url) {
    // People use this property instead all the time so why not just support it.
    self.uri = self.url
    delete self.url
  }

  if (!self.uri) {
    // this will throw if unhandled but is handleable when in a redirect
    return self.emit('error', new Error("options.uri is a required argument"))
  } else {
    if (typeof self.uri == "string") self.uri = url.parse(self.uri)
  }
  if (self.proxy) {
    if (typeof self.proxy == 'string') self.proxy = url.parse(self.proxy)

    // do the HTTP CONNECT dance using koichik/node-tunnel
    if (http.globalAgent && self.uri.protocol === "https:") {
      var tunnelFn = self.proxy.protocol === "http:"
                   ? tunnel.httpsOverHttp : tunnel.httpsOverHttps

      var tunnelOptions = { proxy: { host: self.proxy.hostname
                                   , port: +self.proxy.port
                                   , proxyAuth: self.proxy.auth }
                          , ca: this.ca }

      self.agent = tunnelFn(tunnelOptions)
      self.tunnel = true
    }
  }

  if (!self.uri.host || !self.uri.pathname) {
    // Invalid URI: it may generate lot of bad errors, like "TypeError: Cannot call method 'indexOf' of undefined" in CookieJar
    // Detect and reject it as soon as possible
    var faultyUri = url.format(self.uri)
    var message = 'Invalid URI "' + faultyUri + '"'
    if (Object.keys(options).length === 0) {
      // No option ? This can be the sign of a redirect
      // As this is a case where the user cannot do anything (he didn't call request directly with this URL)
      // he should be warned that it can be caused by a redirection (can save some hair)
      message += '. This can be caused by a crappy redirection.'
    }
    self.emit('error', new Error(message))
    return // This error was fatal
  }

  self._redirectsFollowed = self._redirectsFollowed || 0
  self.maxRedirects = (self.maxRedirects !== undefined) ? self.maxRedirects : 10
  self.followRedirect = (self.followRedirect !== undefined) ? self.followRedirect : true
  self.followAllRedirects = (self.followAllRedirects !== undefined) ? self.followAllRedirects : false
  if (self.followRedirect || self.followAllRedirects)
    self.redirects = self.redirects || []

  self.headers = self.headers ? copy(self.headers) : {}

  self.setHost = false
  if (!self.headers.host) {
    self.headers.host = self.uri.hostname
    if (self.uri.port) {
      if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') &&
           !(self.uri.port === 443 && self.uri.protocol === 'https:') )
      self.headers.host += (':'+self.uri.port)
    }
    self.setHost = true
  }

  self.jar(self._jar || options.jar)

  if (!self.uri.pathname) {self.uri.pathname = '/'}
  if (!self.uri.port) {
    if (self.uri.protocol == 'http:') {self.uri.port = 80}
    else if (self.uri.protocol == 'https:') {self.uri.port = 443}
  }

  if (self.proxy && !self.tunnel) {
    self.port = self.proxy.port
    self.host = self.proxy.hostname
  } else {
    self.port = self.uri.port
    self.host = self.uri.hostname
  }

  self.clientErrorHandler = function (error) {
    if (self._aborted) return

    if (self.setHost) delete self.headers.host
    if (self.req._reusedSocket && error.code === 'ECONNRESET'
        && self.agent.addRequestNoreuse) {
      self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
      self.start()
      self.req.end()
      return
    }
    if (self.timeout && self.timeoutTimer) {
      clearTimeout(self.timeoutTimer)
      self.timeoutTimer = null
    }
    self.emit('error', error)
  }

  self._parserErrorHandler = function (error) {
    if (this.res) {
      if (this.res.request) {
        this.res.request.emit('error', error)
      } else {
        this.res.emit('error', error)
      }
    } else {
      this._httpMessage.emit('error', error)
    }
  }

  if (options.form) {
    self.form(options.form)
  }

  if (options.oauth) {
    self.oauth(options.oauth)
  }

  if (options.aws) {
    self.aws(options.aws)
  }

  if (self.uri.auth && !self.headers.authorization) {
    self.headers.authorization = "Basic " + toBase64(self.uri.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':'))
  }
  if (self.proxy && self.proxy.auth && !self.headers['proxy-authorization'] && !self.tunnel) {
    self.headers['proxy-authorization'] = "Basic " + toBase64(self.proxy.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':'))
  }

  if (options.qs) self.qs(options.qs)

  if (self.uri.path) {
    self.path = self.uri.path
  } else {
    self.path = self.uri.pathname + (self.uri.search || "")
  }

  if (self.path.length === 0) self.path = '/'

  if (self.proxy && !self.tunnel) self.path = (self.uri.protocol + '//' + self.uri.host + self.path)

  if (options.json) {
    self.json(options.json)
  } else if (options.multipart) {
    self.boundary = uuid()
    self.multipart(options.multipart)
  }

  if (self.body) {
    var length = 0
    if (!Buffer.isBuffer(self.body)) {
      if (Array.isArray(self.body)) {
        for (var i = 0; i < self.body.length; i++) {
          length += self.body[i].length
        }
      } else {
        self.body = new Buffer(self.body)
        length = self.body.length
      }
    } else {
      length = self.body.length
    }
    if (length) {
      if(!self.headers['content-length'] && !self.headers['Content-Length'])
      self.headers['content-length'] = length
    } else {
      throw new Error('Argument error, options.body.')
    }
  }

  var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
    , defaultModules = {'http:':http, 'https:':https}
    , httpModules = self.httpModules || {}
    ;
  self.httpModule = httpModules[protocol] || defaultModules[protocol]

  if (!self.httpModule) return this.emit('error', new Error("Invalid protocol"))

  if (options.ca) self.ca = options.ca

  if (!self.agent) {
    if (options.agentOptions) self.agentOptions = options.agentOptions

    if (options.agentClass) {
      self.agentClass = options.agentClass
    } else if (options.forever) {
      self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
    } else {
      self.agentClass = self.httpModule.Agent
    }
  }

  if (self.pool === false) {
    self.agent = false
  } else {
    self.agent = self.agent || self.getAgent()
    if (self.maxSockets) {
      // Don't use our pooling if node has the refactored client
      self.agent.maxSockets = self.maxSockets
    }
    if (self.pool.maxSockets) {
      // Don't use our pooling if node has the refactored client
      self.agent.maxSockets = self.pool.maxSockets
    }
  }

  self.once('pipe', function (src) {
    if (self.ntick && self._started) throw new Error("You cannot pipe to this stream after the outbound request has started.")
    self.src = src
    if (isReadStream(src)) {
      if (!self.headers['content-type'] && !self.headers['Content-Type'])
        self.headers['content-type'] = mime.lookup(src.path)
    } else {
      if (src.headers) {
        for (var i in src.headers) {
          if (!self.headers[i]) {
            self.headers[i] = src.headers[i]
          }
        }
      }
      if (self._json && !self.headers['content-type'] && !self.headers['Content-Type'])
        self.headers['content-type'] = 'application/json'
      if (src.method && !self.method) {
        self.method = src.method
      }
    }

    self.on('pipe', function () {
      console.error("You have already piped to this stream. Pipeing twice is likely to break the request.")
    })
  })

  process.nextTick(function () {
    if (self._aborted) return

    if (self._form) {
      self.setHeaders(self._form.getHeaders())
      self._form.pipe(self)
    }
    if (self.body) {
      if (Array.isArray(self.body)) {
        self.body.forEach(function (part) {
          self.write(part)
        })
      } else {
        self.write(self.body)
      }
      self.end()
    } else if (self.requestBodyStream) {
      console.warn("options.requestBodyStream is deprecated, please pass the request object to stream.pipe.")
      self.requestBodyStream.pipe(self)
    } else if (!self.src) {
      if (self.method !== 'GET' && typeof self.method !== 'undefined') {
        self.headers['content-length'] = 0
      }
      self.end()
    }
    self.ntick = true
  })
}

// Must call this when following a redirect from https to http or vice versa
// Attempts to keep everything as identical as possible, but update the
// httpModule, Tunneling agent, and/or Forever Agent in use.
Request.prototype._updateProtocol = function () {
  var self = this
  var protocol = self.uri.protocol

  if (protocol === 'https:') {
    // previously was doing http, now doing https
    // if it's https, then we might need to tunnel now.
    if (self.proxy) {
      self.tunnel = true
      var tunnelFn = self.proxy.protocol === 'http:'
                   ? tunnel.httpsOverHttp : tunnel.httpsOverHttps
      var tunnelOptions = { proxy: { host: self.proxy.hostname
                                   , post: +self.proxy.port
                                   , proxyAuth: self.proxy.auth }
                          , ca: self.ca }
      self.agent = tunnelFn(tunnelOptions)
      return
    }

    self.httpModule = https
    switch (self.agentClass) {
      case ForeverAgent:
        self.agentClass = ForeverAgent.SSL
        break
      case http.Agent:
        self.agentClass = https.Agent
        break
      default:
        // nothing we can do.  Just hope for the best.
        return
    }

    // if there's an agent, we need to get a new one.
    if (self.agent) self.agent = self.getAgent()

  } else {
    if (log) log('previously https, now http')
    // previously was doing https, now doing http
    // stop any tunneling.
    if (self.tunnel) self.tunnel = false
    self.httpModule = http
    switch (self.agentClass) {
      case ForeverAgent.SSL:
        self.agentClass = ForeverAgent
        break
      case https.Agent:
        self.agentClass = http.Agent
        break
      default:
        // nothing we can do.  just hope for the best
        return
    }

    // if there's an agent, then get a new one.
    if (self.agent) {
      self.agent = null
      self.agent = self.getAgent()
    }
  }
}

Request.prototype.getAgent = function () {
  var Agent = this.agentClass
  var options = {}
  if (this.agentOptions) {
    for (var i in this.agentOptions) {
      options[i] = this.agentOptions[i]
    }
  }
  if (this.ca) options.ca = this.ca

  var poolKey = ''

  // different types of agents are in different pools
  if (Agent !== this.httpModule.Agent) {
    poolKey += Agent.name
  }

  if (!this.httpModule.globalAgent) {
    // node 0.4.x
    options.host = this.host
    options.port = this.port
    if (poolKey) poolKey += ':'
    poolKey += this.host + ':' + this.port
  }

  // ca option is only relevant if proxy or destination are https
  var proxy = this.proxy
  if (typeof proxy === 'string') proxy = url.parse(proxy)


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

using Autodesk.Revit.DB.Structure;

namespace Revit.SDK.Samples.NewRebar.CS
{
    /// <summary>
    /// Bend orientation enum.
    /// </summary>
    enum BendOrientation
    {
        /// <summary>
        /// Turn left.
        /// </summary>
        Left = 1,

        /// <summary>
        /// Turn right.
        /// </summary>
        Right = -1
    }

    /// <summary>
    /// Segment's ends reference enum.
    /// </summary>
    enum EndReference
    {
        /// <summary>
        /// Segment's start reference.
        /// </summary>
        Begin = 0,

        /// <summary>
        /// Segment's end reference.
        /// </summary>
        End = 1
    }

    /// <summary>
    /// Constraint to be added to RebarShapeDefBySegment.
    /// </summary>
    abstract class ConstraintOnSegmentShape : ConstraintOnRebarShape
    {
        public ConstraintOnSegmentShape(RebarShapeDefBySegment def)
            : base(def)
        {
        }

        /// <summary>
        /// Update list value for property grid.
        /// </summary>
        protected void UpdateSegmentIdTypeConverter()
        {
            TypeConverterSegmentId.SegmentCount = GetRebarShapeDefinitionBySegments.NumberOfSegments;
        }

        /// <summary>
        /// Get RebarShapeDefinitionBySegments object.
        /// </summary>
        protected RebarShapeDefinitionBySegments GetRebarShapeDefinitionBySegments
        {
            get
            {
                return m_shapeDef.RebarshapeDefinition as RebarShapeDefinitionBySegments;
            }
        }
    }

    /// <summary>
    /// Default radius dimension of bend.
    /// </summary>
    class ConstraintBendDefaultRadius : ConstraintOnSegmentShape
    {
        /// <summary>
        /// Segment to be added constraint on.
        /// </summary>
        private int m_segment;

        /// <summary>
        /// Bend orientation field.
        /// </summary>
        private BendOrientation m_turn;

        /// <summary>
        /// Bend angle field.
        /// </summary>
        private RebarShapeBendAngle m_bendAngle;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="def"></param>
        public ConstraintBendDefaultRadius(RebarShapeDefBySegment def)
            : base(def)
        {
            m_turn = BendOrientation.Left;
            m_bendAngle = RebarShapeBendAngle.Obtuse;
        }

        /// <summary>
        /// Segment to be added constraint on.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment
        {
            get
            {
                UpdateSegmentIdTypeConverter();

                return m_segment;
            }
            set
            {
                m_segment = value;
            }
        }

        /// <summary>
        /// Bend orientation property.
        /// </summary>
        public BendOrientation Turn
        {
            get
            {
                return m_turn;
            }
            set
            {
                m_turn = value;
            }
        }

        /// <summary>
        /// Bend angle property.
        /// </summary>
        public RebarShapeBendAngle BendAngle
        {
            get
            {
                return m_bendAngle;
            }
            set
            {
                m_bendAngle = value;
            }
        }

        /// <summary>
        /// Add bend default radius constraint to RebarShapeDefinitionBySegments.
        /// </summary>
        public override void Commit()
        {
            GetRebarShapeDefinitionBySegments.AddBendDefaultRadius(
                m_segment, (int)m_turn, m_bendAngle);
        }
    }

    /// <summary>
    /// Variable radius dimension of bend.
    /// </summary>
    class ConstraintBendVariableRadius : ConstraintOnSegmentShape
    {
        /// <summary>
        /// Segment to be added constraint on.
        /// </summary>
        private int m_segment;

        /// <summary>
        /// Bend orientation field.
        /// </summary>
        private BendOrientation m_turn;

        /// <summary>
        /// Bend angle field.
        /// </summary>
        private RebarShapeBendAngle m_bendAngle;

        /// <summary>
        /// Radius dimension field.
        /// </summary>
        private RebarShapeParameter m_radiusParameter;

        /// <summary>
        /// Measure length including bar thickness or not.
        /// </summary>
        private bool m_measureIncludingBarThickness;

        public ConstraintBendVariableRadius(RebarShapeDefBySegment def)
            : base(def)
        {
            m_bendAngle = RebarShapeBendAngle.Obtuse;
            m_turn = BendOrientation.Left;
            m_measureIncludingBarThickness = true;
        }

        /// <summary>
        /// Segment to be added constraint on.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment
        {
            get
            {

                UpdateSegmentIdTypeConverter();

                return m_segment;
            }
            set
            {
                m_segment = value;
            }
        }

        /// <summary>
        /// Bend orientation property.
        /// </summary>
        public BendOrientation Turn
        {
            get { return m_turn; }
            set { m_turn = value; }
        }

        /// <summary>
        /// Bend angle property.
        /// </summary>
        public RebarShapeBendAngle BendAngle
        {
            get { return m_bendAngle; }
            set { m_bendAngle = value; }
        }

        /// <summary>
        /// Radius dimension property.
        /// </summary>
        [TypeConverter(typeof(TypeConverterRebarShapeParameter))]
        public RebarShapeParameter RadiusParameter
        {
            get
            {
                UpdateParameterTypeConverter();
                return m_radiusParameter;
            }
            set
            {
                m_radiusParameter = value;
            }
        }

        /// <summary>
        /// Measure including bar thickness or not.
        /// </summary>
        public bool MeasureIncludingBarThickness
        {
            get
            {
                return m_measureIncludingBarThickness;
            }
            set
            {
                m_measureIncludingBarThickness = value;
            }
        }

        /// <summary>
        /// Add Dimension to constrain the bend radius.
        /// </summary>
        public override void Commit()
        {
            GetRebarShapeDefinitionBySegments.AddBendVariableRadius(
                m_segment, (int)m_turn, m_bendAngle, m_radiusParameter.Parameter,
                m_measureIncludingBarThickness);
        }
    }

    /// <summary>
    /// Parallel dimension to segment.
    /// </summary>
    class ConstraintParallelToSegment : ConstraintOnSegmentShape
    {
        /// <summary>
        /// Segment to be added constraint on.
        /// </summary>
        private int m_segment;

        /// <summary>
        /// Dimension to constrain the length of segment.
        /// </summary>
        private RebarShapeParameter m_parameter;

        /// <summary>
        /// Measure segment's length to outside of bend 0 or not.
        /// </summary>
        private bool m_measureToOutsideOfBend0;

        /// <summary>
        /// Measure segment's length to outside of bend 1 or not.
        /// </summary>
        private bool m_measureToOutsideOfBend1;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="def"></param>
        public ConstraintParallelToSegment(RebarShapeDefBySegment def)
            : base(def)
        {
            m_measureToOutsideOfBend0 = true;
            m_measureToOutsideOfBend1 = true;
        }

        /// <summary>
        /// Segment to be added constraint on.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment
        {
            get
            {

                UpdateSegmentIdTypeConverter();

                return m_segment;
            }
            set
            {
                m_segment = value;
            }
        }

        /// <summary>
        /// Dimension to constrain the length of segment.
        /// </summary>
        [TypeConverter(typeof(TypeConverterRebarShapeParameter))]
        public RebarShapeParameter Parameter
        {
            get
            {
                UpdateParameterTypeConverter();
                return m_parameter;
            }
            set { m_parameter = value; }
        }

        /// <summary>
        /// Measure segment's length to outside of bend 0 or not.
        /// </summary>
        public bool MeasureToOutsideOfBend0
        {
            get { return m_measureToOutsideOfBend0; }
            set { m_measureToOutsideOfBend0 = value; }
        }

        /// <summary>
        /// Measure segment's length to outside of bend 1 or not.
        /// </summary>
        public bool MeasureToOutsideOfBend1
        {
            get { return m_measureToOutsideOfBend1; }
            set { m_measureToOutsideOfBend1 = value; }
        }

        /// <summary>
        /// Add Dimension to constrain the segment length.
        /// </summary>
        public override void Commit()
        {
            GetRebarShapeDefinitionBySegments.AddConstraintParallelToSegment(
                m_segment, m_parameter.Parameter, m_measureToOutsideOfBend0,
                m_measureToOutsideOfBend1);
        }
    }

    /// <summary>
    /// Length dimension of segment in specified direction.
    /// </summary>
    class ConstraintToSegment : ConstraintOnSegmentShape
    {
        /// <summary>
        /// Segment to be added constraint on.
        /// </summary>
        private int m_segment;

        /// <summary>
        /// Dimension to constraint the length of segment in specified direction.
        /// </summary>
        private RebarShapeParameter m_parameter;

        /// <summary>
        /// X coordinate of constraint direction.
        /// </summary>
        private double m_constraintDirCoordX;

        /// <summary>
        /// Y coordinate of constraint direction.
        /// </summary>
        private double m_constraintDirCoordY;

        /// <summary>
        /// Sign of Z coordinate of cross product of constraint direction by segment direction.
        /// </summary>
        private int m_signOfZCoordOfCrossProductOfConstraintDirBySegmentDir;

        /// <summary>
        /// Measure segment's length to outside of bend 0 or not.
        /// </summary>
        private bool m_measureToOutsideOfBend0;

        /// <summary>
        /// Measure segment's length to outside of bend 1 or not.
        /// </summary>
        private bool m_measureToOutsideOfBend1;

        public ConstraintToSegment(RebarShapeDefBySegment def)
            : base(def)
        {
            m_measureToOutsideOfBend0 = true;
            m_measureToOutsideOfBend1 = false;
            m_signOfZCoordOfCrossProductOfConstraintDirBySegmentDir = -1;
        }

        /// <summary>
        /// Segment to be added constraint on.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment
        {
            get
            {

                UpdateSegmentIdTypeConverter();

                return m_segment;
            }
            set
            {
                m_segment = value;
            }
        }

        /// <summary>
        /// Dimension to constraint the length of segment in specified direction.
        /// </summary>
        [TypeConverter(typeof(TypeConverterRebarShapeParameter))]
        public RebarShapeParameter Parameter
        {
            get
            {
                UpdateParameterTypeConverter();
                return m_parameter;
            }
            set { m_parameter = value; }
        }

        /// <summary>
        /// X coordinate of constraint direction.
        /// </summary>
        public double ConstraintDirCoordX
        {
            get { return m_constraintDirCoordX; }
            set { m_constraintDirCoordX = value; }
        }

        /// <summary>
        /// Y coordinate of constraint direction.
        /// </summary>
        public double ConstraintDirCoordY
        {
            get { return m_constraintDirCoordY; }
            set { m_constraintDirCoordY = value; }
        }

        /// <summary>
        /// Sign of Z coordinate of cross product of constraint direction by segment direction.
        /// </summary>
        public int SignOfZCoordOfCrossProductOfConstraintDirBySegmentDir
        {
            get { return m_signOfZCoordOfCrossProductOfConstraintDirBySegmentDir; }
            set { m_signOfZCoordOfCrossProductOfConstraintDirBySegmentDir = value; }
        }

        /// <summary>
        /// Measure segment's length to outside of bend 0 or not.
        /// </summary>
        public bool MeasureToOutsideOfBend0
        {
            get { return m_measureToOutsideOfBend0; }
            set { m_measureToOutsideOfBend0 = value; }
        }

        /// <summary>
        /// Measure segment's length to outside of bend 1 or not.
        /// </summary>
        public bool MeasureToOutsideOfBend1
        {
            get { return m_measureToOutsideOfBend1; }
            set { m_measureToOutsideOfBend1 = value; }
        }

        /// <summary>
        /// Add dimension to constrain the length of segment in the specified direction.
        /// </summary>
        public override void Commit()
        {
            GetRebarShapeDefinitionBySegments.AddConstraintToSegment( m_segment,
                m_parameter.Parameter, m_constraintDirCoordX, m_constraintDirCoordY,
                m_signOfZCoordOfCrossProductOfConstraintDirBySegmentDir,
                m_measureToOutsideOfBend0, m_measureToOutsideOfBend1);
        }
    }

    /// <summary>
    /// Listening length dimension between two bends.
    /// </summary>
    class ListeningDimensionBendToBend : ConstraintOnSegmentShape
    {
        /// <summary>
        /// Dimension to constraint the length of two bends in the specified direction.
        /// </summary>
        private RebarShapeParameter m_parameter;

        /// <summary>
        /// X coordinate of constraint direction.
        /// </summary>
        private double m_constraintDirCoordX;

        /// <summary>
        /// Y coordinate of constraint direction.
        /// </summary>
        private double m_constraintDirCoordY;

        /// <summary>
        /// Reference of segment 0.
        /// </summary>
        private int m_segment;

        /// <summary>
        /// End reference of segment 0.
        /// </summary>
        private EndReference m_end;

        /// <summary>
        /// Reference of segment 1.
        /// </summary>
        private int m_segment1;

        /// <summary>
        /// End reference of segment 1.
        /// </summary>
        private EndReference m_end1;

        public ListeningDimensionBendToBend(RebarShapeDefBySegment def)
            : base(def)
        {
            m_end = EndReference.Begin;
            m_end1 = EndReference.End;
            m_constraintDirCoordX = 0;
            m_constraintDirCoordY = 0;
        }

        /// <summary>
        /// Dimension to constraint the length of two bends in the specified direction.
        /// </summary>
        [TypeConverter(typeof(TypeConverterRebarShapeParameter))]
        public RebarShapeParameter Parameter
        {
            get
            {
                UpdateParameterTypeConverter();

                return m_parameter;
            }
            set { m_parameter = value; }
        }

        /// <summary>
        /// X coordinate of constraint direction.
        /// </summary>
        public double ConstraintDirCoordX
        {
            get { return m_constraintDirCoordX; }
            set { m_constraintDirCoordX = value; }
        }

        /// <summary>
        /// Y coordinate of constraint direction.
        /// </summary>
        public double ConstraintDirCoordY
        {
            get { return m_constraintDirCoordY; }
            set { m_constraintDirCoordY = value; }
        }

        /// <summary>
        /// Reference of segment 0.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment0
        {
            get
            {

                UpdateSegmentIdTypeConverter();

                return m_segment;
            }
            set
            {
                m_segment = value;
            }
        }

        /// <summary>
        /// End reference of segment 0.
        /// </summary>
        public EndReference End0
        {
            get { return m_end; }
            set { m_end = value; }
        }

        /// <summary>
        /// Reference of segment 1.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment1
        {
            get
            {
                UpdateSegmentIdTypeConverter();

                return m_segment1;
            }
            set { m_segment1 = value; }
        }

        /// <summary>
        /// End reference of segment 1.
        /// </summary>
        public EndReference End1
        {
            get { return m_end1; }
            set { m_end1 = value; }
        }

        /// <summary>
        /// Add listening dimension to constrain the length of two bend in the specified direction.
        /// </summary>
        public override void Commit()
        {
            GetRebarShapeDefinitionBySegments.AddListeningDimensionBendToBend(
                m_parameter.Parameter, m_constraintDirCoordX, m_constraintDirCoordY,
                m_segment, (int)m_end, m_segment1, (int)m_end1);
        }
    }

    /// <summary>
    /// Listening length dimension between a segment and a bend.
    /// </summary>
    class ListeningDimensionSegmentToBend : ConstraintOnSegmentShape
    {
        /// <summary>
        /// Dimension to constrain the length between a segment and a bend
        /// in the specified direction.
        /// </summary>
        private RebarShapeParameter m_parameter;

        /// <summary>
        /// X coordinate of constraint direction.
        /// </summary>
        private double m_constraintDirCoordX;

        /// <summary>
        /// Y coordinate of constraint direction.
        /// </summary>
        private double m_constraintDirCoordY;

        /// <summary>
        /// Reference of segment 0.
        /// </summary>
        private int m_segment;

        /// <summary>
        /// Reference of segment 1.
        /// </summary>
        private int m_segment1;

        /// <summary>
        /// End reference of segment 1.
        /// </summary>
        private EndReference m_end1;

        public ListeningDimensionSegmentToBend(RebarShapeDefBySegment def)
            : base(def)
        {
            m_constraintDirCoordX = 0;
            m_constraintDirCoordY = 0;
            m_end1 = EndReference.End;
        }

        /// <summary>
        /// Dimension to constrain the length between a segment and a bend
        /// in the specified direction.
        /// </summary>
        [TypeConverter(typeof(TypeConverterRebarShapeParameter))]
        public RebarShapeParameter Parameter
        {
            get
            {
                UpdateParameterTypeConverter();
                return m_parameter;
            }
            set
            {
                m_parameter = value;
            }
        }

        /// <summary>
        /// X coordinate of constraint direction.
        /// </summary>
        public double ConstraintDirCoordX
        {
            get
            {
                return m_constraintDirCoordX;
            }
            set
            {
                m_constraintDirCoordX = value;
            }
        }

        /// <summary>
        /// Y coordinate of constraint direction.
        /// </summary>
        public double ConstraintDirCoordY
        {
            get
            {
                return m_constraintDirCoordY;
            }
            set
            {
                m_constraintDirCoordY = value;
            }
        }

        /// <summary>
        /// Reference of segment 0.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment0
        {
            get
            {
                UpdateSegmentIdTypeConverter();

                return m_segment;
            }
            set { m_segment = value; }
        }

        /// <summary>
        /// Reference of segment 1.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment1
        {
            get
            {
                UpdateSegmentIdTypeConverter();

                return m_segment1;
            }
            set { m_segment1 = value; }
        }

        /// <summary>
        /// End reference of segment 1.
        /// </summary>
        public EndReference End1
        {
            get { return m_end1; }
            set { m_end1 = value; }
        }

        /// <summary>
        /// Add listening dimension to constrain the length between a segment and a bend
        /// in the specified direction.
        /// </summary>
        public override void Commit()
        {
            GetRebarShapeDefinitionBySegments.AddListeningDimensionSegmentToBend(
                m_parameter.Parameter, m_constraintDirCoordX, m_constraintDirCoordY,
                m_segment, m_segment1, (int)m_end1);
        }
    }

    /// <summary>
    /// Listening length dimension between two segments.
    /// </summary>
    class ListeningDimensionSegmentToSegment : ConstraintOnSegmentShape
    {
        /// <summary>
        /// Dimension to constrain the perpendicular distance between two segment.
        /// The two segment should be parallel.
        /// </summary>
        private RebarShapeParameter m_parameter;

        /// <summary>
        /// X coordinate of constraint direction.
        /// </summary>
        private double m_constraintDirCoordX;

        /// <summary>
        /// Y coordinate of constraint direction.
        /// </summary>
        private double m_constraintDirCoordY;

        /// <summary>
        /// The first segment to be constrained.
        /// </summary>
        private int m_segment;

        /// <summary>
        /// The second segment to be constrained.
        /// </summary>
        private int m_segment1;

        public ListeningDimensionSegmentToSegment(RebarShapeDefBySegment def)
            : base(def)
        {
            m_constraintDirCoordX = 1;
            m_constraintDirCoordY = 0;
        }

        /// <summary>
        /// Dimension to constrain the perpendicular distance between two segment.
        /// </summary>
        [TypeConverter(typeof(TypeConverterRebarShapeParameter))]
        public RebarShapeParameter Parameter
        {
            get
            {
                UpdateParameterTypeConverter();
                return m_parameter;
            }
            set
            {
                m_parameter = value;
            }
        }

        /// <summary>
        /// X coordinate of constraint direction.
        /// </summary>
        public double ConstraintDirCoordX
        {
            get
            {
                return m_constraintDirCoordX;
            }
            set
            {
                m_constraintDirCoordX = value;
            }
        }

        /// <summary>
        /// Y coordinate of constraint direction.
        /// </summary>
        public double ConstraintDirCoordY
        {
            get
            {
                return m_constraintDirCoordY;
            }
            set
            {
                m_constraintDirCoordY = value;
            }
        }

        /// <summary>
        /// The second segment to be constrained.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment0
        {
            get
            {
                UpdateSegmentIdTypeConverter();
                return m_segment;
            }
            set { m_segment = value; }
        }

        /// <summary>
        /// The second segment to be constrained.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment1
        {
            get
            {
                UpdateSegmentIdTypeConverter();
                return m_segment1;
            }
            set { m_segment1 = value; }
        }

        /// <summary>
        /// Add dimension to constrain the perpendicular distance between two segment.
        /// </summary>
        public override void Commit()
        {
            GetRebarShapeDefinitionBySegments.AddListeningDimensionSegmentToSegment(
                m_parameter.Parameter, m_constraintDirCoordX, m_constraintDirCoordY,
                m_segment, m_segment1);
        }
    }

    /// <summary>
    /// Remove a dimension from a segment.
    /// </summary>
    class RemoveParameterFromSegment : ConstraintOnSegmentShape
    {
        /// <summary>
        /// Reference of segment.
        /// </summary>
        private int m_segment;

        /// <summary>
        /// Dimension to be removed.
        /// </summary>
        private RebarShapeParameter m_radiusParameter;

        public RemoveParameterFromSegment(RebarShapeDefBySegment def)
            : base(def)
        {
        }

        /// <summary>
        /// Reference of segment.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment
        {
            get
            {

                UpdateSegmentIdTypeConverter();

                return m_segment;
            }
            set
            {
                m_segment = value;
            }
        }

        /// <summary>
        /// Dimension to be removed.
        /// </summary>
        [TypeConverter(typeof(TypeConverterRebarShapeParameter))]
        public RebarShapeParameter RadiusParameter
        {
            get
            {
                UpdateParameterTypeConverter();
                return m_radiusParameter;
            }
            set
            {
                m_radiusParameter = value;
            }
        }

        /// <summary>
        /// Remove dimension from Rebar shape.
        /// </summary>
        public override void Commit()
        {
            GetRebarShapeDefinitionBySegments.RemoveParameterFromSegment(
                m_segment, m_radiusParameter.Parameter);
        }
    }

    /// <summary>
    /// A 180 degree bend dimension.
    /// </summary>
    class SetSegmentAs180DegreeBend : ConstraintOnSegmentShape
    {
        /// <summary>
        /// Reference of segment.
        /// </summary>
        private int m_segment;

        /// <summary>
        /// Dimension to constrain the bend's radius.
        /// </summary>
        private RebarShapeParameter m_radiusParameter;

        /// <summary>
        /// If measure to outside of bend.
        /// </summary>
        private bool m_measureToOutsideOfBend;

        public SetSegmentAs180DegreeBend(RebarShapeDefBySegment def)
            : base(def)
        {
            m_measureToOutsideOfBend = true;
        }

        /// <summary>
        /// Reference of segment.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment
        {
            get
            {

                UpdateSegmentIdTypeConverter();

                return m_segment;
            }
            set
            {
                m_segment = value;
            }
        }

        /// <summary>
        /// Dimension to constrain the bend's radius.
        /// </summary>
        [TypeConverter(typeof(TypeConverterRebarShapeParameter))]
        public RebarShapeParameter RadiusParameter
        {
            get
            {
                UpdateParameterTypeConverter();
                return m_radiusParameter;
            }
            set { m_radiusParameter = value; }
        }

        /// <summary>
        /// If measure the length to outside of bend.
        /// </summary>
        public bool MeasureToOutsideOfBend
        {
            get { return m_measureToOutsideOfBend; }
            set { m_measureToOutsideOfBend = value; }
        }

        /// <summary>
        /// Add a dimension of 180 degree bend for a segment.
        /// </summary>
        public override void Commit()
        {
            GetRebarShapeDefinitionBySegments.SetSegmentAs180DegreeBend(
                m_segment, m_radiusParameter.Parameter, m_measureToOutsideOfBend);
        }
    }

    /// <summary>
    /// Length dimension of segment in its parallel direction.
    /// </summary>
    class SetSegmentFixedDirection : ConstraintOnSegmentShape
    {
        /// <summary>
        /// Reference of segment.
        /// </summary>
        private int m_segment;

        /// <summary>
        /// X coordinate of constraint direction.
        /// </summary>
        private double m_vecCoordX;

        /// <summary>
        /// Y coordinate of constraint direction.
        /// </summary>
        private double m_vecCoordY;

        public SetSegmentFixedDirection(RebarShapeDefBySegment def)
            : base(def)
        {
            m_vecCoordX = 1;
            m_vecCoordY = 0;
        }

        /// <summary>
        /// Reference of segment.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment
        {
            get
            {

                UpdateSegmentIdTypeConverter();

                return m_segment;
            }
            set
            {
                m_segment = value;
            }
        }

        /// <summary>
        /// X coordinate of constraint direction.
        /// </summary>
        public double VecCoordX
        {
            get
            {
                return m_vecCoordX;
            }
            set
            {
                m_vecCoordX = value;
            }
        }

        /// <summary>
        /// Y coordinate of constraint direction.
        /// </summary>
        public double VecCoordY
        {
            get
            {
                return m_vecCoordY;
            }
            set
            {
                m_vecCoordY = value;
            }
        }

        /// <summary>
        /// Add dimension to constrain the direction of the segment.
        /// </summary>
        public override void Commit()
        {
            GetRebarShapeDefinitionBySegments.SetSegmentFixedDirection(
                m_segment, m_vecCoordX, m_vecCoordY);
        }
    }

    /// <summary>
    /// Remove a dimension from a segment.
    /// </summary>
    class SetSegmentVariableDirection : ConstraintOnSegmentShape
    {
        /// <summary>
        /// Reference of segment.
        /// </summary>
        private int m_segment;

        public SetSegmentVariableDirection(RebarShapeDefBySegment def)
            : base(def)
        {
        }

        /// <summary>
        /// Reference of segment.
        /// </summary>
        [TypeConverter(typeof(TypeConverterSegmentId))]
        public int Segment
        {
            get
            {

                UpdateSegmentIdTypeConverter();

                return m_segment;
            }
            set
            {
                m_segment = value;
            }
        }

        /// <summary>
        /// Remove the direction dimension of segment.
        /// </summary>
        public override void Commit()
        {
            GetRebarShapeDefinitionBySegments.SetSegmentVariableDirection(m_segment);
        }
    }
}


text:
FactoryGirl.define do
  factory :vm_cloud_reconfigure_task
end