text:
// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias

(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.hcdlightBox = function(settings) {
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (string) Background color to overlay
			overlayOpacity:			0.7,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to navigation
			fixedNavigation:		true,		// (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
			// Configuration related to images
			imageLoading:			'/lib/cssimages/black-loading.gif',		// (string) Path and the name of the loading icon
			imageBtnPrev:			'/lib/cssimages/lightbox-btn-prev.png',			// (string) Path and the name of the prev button image
			imageBtnNext:			'/lib/cssimages/lightbox-btn-next.png',			// (string) Path and the name of the next button image
			imageBtnClose:			'/lib/cssimages/lightbox-btn-close.png',		// (string) Path and the name of the close btn
			imageBlank:				'/lib/cssimages/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
			// Configuration related to container image box
			containerBorderSize:	16,			// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
			containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
			// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
			txtImage:				'',	// (string) Specify text "Image"
			txtOf:					'of',		// (string) Specify text "of"
			// Configuration related to keyboard navigation
			keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
			keyToPrev:				'p',		// (string) (p = previous) Letter to show the previous image
			keyToNext:				'n',		// (string) (n = next) Letter to show the next image.
			// Don´t alter these variables in any way
			imageArray:				[],
			activeImage:			0
		},settings);

		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		/**
		 * Initializing the plugin calling the start function
		 * @return boolean false
		 */

		function _initialize() {
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}

		// Start the jQuery lightBox plugin
		// @param object objClicked The object (link) whick the user have clicked
		// @param object jQueryMatchedObj The jQuery object with all elements matched
		function _start(objClicked,jQueryMatchedObj) {

			// Hide some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'hidden' });

			// Call the function to create the markup structure; style some elements; assign events in some elements.
			_set_interface();

			// Unset total images in imageArray
			settings.imageArray.length = 0;

			// Unset image active information
			settings.activeImage = 0;

			// We have an image set? Or just one image? Let´s see...
			if ( jQueryMatchedObj.length == 1 ) {
				settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
			} else {
				// Add an Array (as many as we have), with href and title atributes inside the Array to store images references
				for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
					settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));
				}
			}
			while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
				settings.activeImage++;
			}
			// Call the function that prepares image exibition
			_set_image_to_view();
		}

// Here is the main fun stuff... this is what we customized

		function _set_interface() {
			// Apply the HTML markup into body tag
			$('body').append('

close

');

			// Get page sizes
			var arrPageSizes = ___getPageSize();

			// Style overlay and show it
			$('#hcdligbox-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity,
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn();

			// Get page scroll
			var arrPageScroll = ___getPageScroll();

			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#hcdligbox-lightbox').css({
				top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
				left:	arrPageScroll[0]
			}).show();

			// Assigning click events in elements to close overlay
			$('#hcdligbox-overlay,#hcdligbox-lightbox').click(function() {
				_finish();
			});

			// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
			$('#hcdligbox-loading-link,#hcdligbox-secNav-btnClose').click(function() {
				_finish();
				return false;
			});

			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				// Get page sizes
				var arrPageSizes = ___getPageSize();
				// Style overlay and show it
				$('#hcdligbox-overlay').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				// Get page scroll
				var arrPageScroll = ___getPageScroll();
				// Calculate top and left offset for the jquery-lightbox div object and show it
				$('#hcdligbox-lightbox').css({
					top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
					left:	arrPageScroll[0]
				});
			});
		}

// Prepares image exhibition; doing a image´s preloader to calculate it´s size
		function _set_image_to_view() { // show the loading
			// Show the loading
			$('#hcdligbox-loading').show();
			if ( settings.fixedNavigation ) {
				$('#hcdligbox-image,#hcdligbox-container-image-data-box,#hcdligbox-image-details-currentNumber').hide();
			} else {
				// Hide some elements
				// old version $('#hcdligbox-image,#hcdligbox-nav,#hcdligbox-nav-btnPrev,#hcdligbox-nav-btnNext,#hcdligbox-container-image-data-box,#hcdligbox-image-details-currentNumber').hide();
				$('#hcdligbox-image,#hcdligbox-container-image-data-box').hide();
			}
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				$('#hcdligbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
				// Preform an effect in the image container resizing it
				_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			};
			objImagePreloader.src = settings.imageArray[settings.activeImage][0];
		};

// Preform an effect in the image container resizing it
		//@param integer intImageWidth The image´s width that will be showed
		// @param integer intImageHeight The image´s height that will be showed
		function _resize_container_image_box(intImageWidth,intImageHeight) {
			// Get current width and height
			var intCurrentWidth = $('#hcdligbox-container-image-box').width();
			var intCurrentHeight = $('#hcdligbox-container-image-box').height();
			// Get the width and height of the selected image plus the padding
			var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image´s width and the left and right padding value
			var intHeight = (intImageHeight + (settings.containerBorderSize * 2) + 18); // Plus the image´s height and the left and right padding value

																			// Hacked! We added the '28' above as we now have the navigation inside this container, therefore, we need to account for it's height... the height of the padding should do it.

			// Diferences
			var intDiffW = intCurrentWidth - intWidth;
			var intDiffH = intCurrentHeight - intHeight;
			// Preform the effect
			$('#hcdligbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); });
			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
				if ( $.browser.msie ) {
					___pause(250);
				} else {
					___pause(100);
				}
			}
			$('#hcdligbox-container-image-data-box').css({ width: intImageWidth });
			// $('#hcdligbox-nav-btnPrev,#hcdligbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
		};

		//Show the prepared image
		function _show_image() {
			$('#hcdligbox-loading').hide();
			$('#hcdligbox-image').fadeIn(function() {
				_show_image_data();
				_set_navigation();
			});
			_preload_neighbor_images();
		};

		// Show the image information
		function _show_image_data() {

			$('#hcdligbox-image-details-caption').hide();
			if ( settings.imageArray[settings.activeImage][1] ) {
				$('#hcdligbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
			}
			// If we have a image set, display 'Image X of X'
			if ( settings.imageArray.length > 1 ) {
				$('#hcdligbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
			}

			// Hack! moved this after the text is set, so it doesn't overshoot when the last caption was taller than the current one
			$('#hcdligbox-container-image-data-box').slideDown('fast');
		}

		// Display the button navigations
		function _set_navigation() {
			$('#hcdligbox-nav').show();

			// Instead to define this configuration in CSS file, we define here. And it´s need to IE. Just.
			//$('#hcdligbox-nav-btnPrev,#hcdligbox-nav-btnNext').css({ 'background' : ' ' });
			//$('#hcdligbox-nav-btnPrev,#hcdligbox-nav-btnNext').css({ 'display' : 'none' });

			// Show the prev button, if not the first image in set
			if ( settings.activeImage != 0 ) {
				if ( settings.fixedNavigation ) {
					$('#hcdligbox-nav-btnPrev').html('prev / ')
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage - 1;
							_set_image_to_view();
							return false;
						});
				}
			}

			// Show the next button, if not the last image in set
			if ( settings.activeImage != ( settings.imageArray.length -1 ) ) {
				if ( settings.fixedNavigation ) {
					$('#hcdligbox-nav-btnNext').html('next')
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage + 1;
							_set_image_to_view();
							return false;
						});
				}
			} else {
				// We need this else... so, if we are on the last image, the button does something different
				$('#hcdligbox-nav-btnPrev').html('prev')
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage - 1;
							_set_image_to_view();
							return false;
						});
				$('#hcdligbox-nav-btnNext').html('')
					.unbind()
					.bind('click',function() {
						settings.activeImage = settings.activeImage + 1;
						_set_image_to_view();
						return false;
					});
			}

			// Enable keyboard navigation
			_enable_keyboard_navigation();
		}

// Advanced Stuff past this point... not much to hack into

		// Enable a support to keyboard navigation
		function _enable_keyboard_navigation() {
			$(document).keydown(function(objEvent) {
				_keyboard_action(objEvent);
			});
		}
		// Disable the support to keyboard navigation
		function _disable_keyboard_navigation() {
			$(document).unbind();
		}
		// Perform the keyboard actions
		function _keyboard_action(objEvent) {
			// To ie
			if ( objEvent == null ) {
				keycode = event.keyCode;
				escapeKey = 27;
			// To Mozilla
			} else {
				keycode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}
			// Get the key in lower case form
			key = String.fromCharCode(keycode).toLowerCase();
			// Verify the keys to close the ligthBox
			if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
				_finish();
			}
			// Verify the key to show the previous image
			if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
				// If we´re not showing the first image, call the previous
				if ( settings.activeImage != 0 ) {
					settings.activeImage = settings.activeImage - 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
			// Verify the key to show the next image
			if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
				// If we´re not showing the last image, call the next
				if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
					settings.activeImage = settings.activeImage + 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
		}
		// Preload prev and next images being showed
		function _preload_neighbor_images() {
			if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][0];
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = settings.imageArray[settings.activeImage -1][0];
			}
		}
		// Remove jQuery lightBox plugin HTML markup
		function _finish() {
			$('#hcdligbox-lightbox').remove();
			$('#hcdligbox-overlay').fadeOut(function() { $('#hcdligbox-overlay').remove(); });
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
		// THIRD FUNCTION
		// getPageSize() by quirksmode.com
		// @return Array Return an array with page width, height and window width, height
		function ___getPageSize() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth;
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else {
				pageHeight = yScroll + 100;
											// HCd note *** We Added this in (the +100)... the image window wasn't adding the height of the captions before it rendered the page, causing the black overlay to leave a gap at the bottom of the page ***

			}
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){
				pageWidth = xScroll;
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
			return arrayPageSize;
		};
		// FOURTH FUNCTION
		//getPageScroll() by quirksmode.com
		//@return Array Return an array with x,y page scroll values.
		function ___getPageScroll() {
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
		};
		 //Stop the code execution from a presribed time in milisecond
		 function ___pause(ms) {
			var date = new Date();
			curDate = null;
			do { var curDate = new Date(); }
			while ( curDate - date < ms);
		 };
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object


text:
template<typename _Object>
class CStateBloodsuckerVampireHide : public CState<_Object> {
	typedef CState<_Object>		inherited;
	typedef CState<_Object>*	state_ptr;

public:
						CStateBloodsuckerVampireHide	(_Object *obj);

	virtual	void		reselect_state					();
	virtual void		setup_substates					();
	virtual bool		check_completion				();
};

#include "bloodsucker_vampire_hide_inline.h"

redpajama_set_name: RedPajamaGithub


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

#include "transmission.h"
#include "bencode.h"
#include "makemeta.h"
#include "metainfo.h" /* tr_metainfoFree */
#include "tr-getopt.h"
#include "utils.h" /* tr_wait */
#include "web.h" /* tr_webRun */

#define LINEWIDTH 80
#define MY_NAME "transmission-cli"

static int          showInfo         = 0;
static int          showScrape       = 0;
static int          isPrivate        = 0;
static int          verboseLevel     = 0;
static int          encryptionMode   = TR_DEFAULT_ENCRYPTION;
static int          peerPort         = TR_DEFAULT_PORT;
static int          peerSocketTOS    = TR_DEFAULT_PEER_SOCKET_TOS;
static int          blocklistEnabled = TR_DEFAULT_BLOCKLIST_ENABLED;
static int          uploadLimit      = 20;
static int          downloadLimit    = -1;
static int          natTraversal     = TR_DEFAULT_PORT_FORWARDING_ENABLED;
static int          verify           = 0;
static sig_atomic_t gotsig           = 0;
static sig_atomic_t manualUpdate     = 0;

static const char * torrentPath  = NULL;
static const char * downloadDir  = NULL;
static const char * finishCall   = NULL;
static const char * announce     = NULL;
static const char * configdir    = NULL;
static const char * sourceFile   = NULL;
static const char * comment      = NULL;

static const struct tr_option options[] =
{
    { 'a', "announce",             "Set the new torrent's announce URL",
      "a",  1, "<url>"     },
    { 'b', "blocklist",            "Enable peer blocklists",
      "b",  0, NULL        },
    { 'B', "no-blocklist",         "Disable peer blocklists",
      "B",  0, NULL        },
    { 'c', "comment",              "Set the new torrent's comment",
      "c",  1, "<comment>" },
    { 'd', "downlimit",            "Set max download speed in KB/s",
      "d",  1, "<speed>"   },
    { 'D', "no-downlimit",         "Don't limit the download speed",
      "D",  0, NULL        },
    { 910, "encryption-required",  "Encrypt all peer connections",
      "er", 0, NULL        },
    { 911, "encryption-preferred", "Prefer encrypted peer connections",
      "ep", 0, NULL        },
    { 912, "encryption-tolerated", "Prefer unencrypted peer connections",
      "et", 0, NULL        },
    { 'f', "finish",               "Run a script when the torrent finishes",
      "f", 1, "<script>" },
    { 'g', "config-dir",           "Where to find configuration files",
      "g", 1, "<path>" },
    { 'i', "info",                 "Show torrent details and exit",
      "i",  0, NULL        },
    { 'm', "portmap",              "Enable portmapping via NAT-PMP or UPnP",
      "m",  0, NULL        },
    { 'M', "no-portmap",           "Disable portmapping",
      "M",  0, NULL        },
    { 'n', "new",                  "Create a new torrent",
      "n", 1, "<source>" },
    { 'p', "port",
      "Port for incoming peers (Default: " TR_DEFAULT_PORT_STR ")",
      "p", 1, "<port>" },
    { 'r', "private",              "Set the new torrent's 'private' flag",
      "r",  0, NULL        },
    { 's', "scrape",               "Scrape the torrent and exit",
      "s",  0, NULL        },
    { 't', "tos",
      "Peer socket TOS (0 to 255, default=" TR_DEFAULT_PEER_SOCKET_TOS_STR
      ")",
      "t", 1, "<tos>" },
    { 'u', "uplimit",              "Set max upload speed in KB/s",
      "u",  1, "<speed>"   },
    { 'U', "no-uplimit",           "Don't limit the upload speed",
      "U",  0, NULL        },
    { 'v', "verify",               "Verify the specified torrent",
      "v",  0, NULL        },
    { 'w', "download-dir",         "Where to save downloaded data",
      "w",  1, "<path>"    },
    {   0, NULL,                   NULL,
        NULL, 0, NULL        }
};

static const char *
getUsage( void )
{
    return "A fast and easy BitTorrent client\n"
           "\n"
           "Usage: " MY_NAME " [options] <torrent-filename>";
}

static int          parseCommandLine( int           argc,
                                      const char ** argv );

static void         sigHandler( int signal );

static char*
tr_strlratio( char * buf,
              double ratio,
              size_t buflen )
{
    if( (int)ratio == TR_RATIO_NA )
        tr_strlcpy( buf, _( "None" ), buflen );
    else if( (int)ratio == TR_RATIO_INF )
        tr_strlcpy( buf, "Inf", buflen );
    else if( ratio < 10.0 )
        tr_snprintf( buf, buflen, "%.2f", ratio );
    else if( ratio < 100.0 )
        tr_snprintf( buf, buflen, "%.1f", ratio );
    else
        tr_snprintf( buf, buflen, "%.0f", ratio );
    return buf;
}

static int
is_rfc2396_alnum( char ch )
{
    return ( '0' <= ch && ch <= '9' )
           || ( 'A' <= ch && ch <= 'Z' )
           || ( 'a' <= ch && ch <= 'z' );
}

static void
escape( char *          out,
        const uint8_t * in,
        int             in_len )                     /* rfc2396 */
{
    const uint8_t *end = in + in_len;

    while( in != end )
        if( is_rfc2396_alnum( *in ) )
            *out++ = (char) *in++;
        else
            out += tr_snprintf( out, 4, "%%%02X", (unsigned int)*in++ );

    *out = '\0';
}

static void
torrentCompletenessChanged( tr_torrent       * torrent       UNUSED,
                            tr_completeness    completeness  UNUSED,
                            void             * user_data     UNUSED )
{
    system( finishCall );
}

static int leftToScrape = 0;

static void
scrapeDoneFunc( tr_session   * session UNUSED,
                long           response_code,
                const void   * response,
                size_t         response_byte_count,
                void         * host )
{
    tr_benc top, *files;

    if( !tr_bencLoad( response, response_byte_count, &top, NULL )
      && tr_bencDictFindDict( &top, "files", &files )
      && files->val.l.count >= 2 )
    {
        int64_t   complete = -1, incomplete = -1, downloaded = -1;
        tr_benc * hash = &files->val.l.vals[1];
        tr_bencDictFindInt( hash, "complete", &complete );
        tr_bencDictFindInt( hash, "incomplete", &incomplete );
        tr_bencDictFindInt( hash, "downloaded", &downloaded );
        printf( "%4d seeders, %4d leechers, %5d downloads at %s\n",
                (int)complete, (int)incomplete, (int)downloaded,
                (char*)host );
        tr_bencFree( &top );
    }
    else
        fprintf( stderr, "Unable to parse response (http code %lu) at %s",
                 response_code,
                 (char*)host );

    --leftToScrape;

    tr_free( host );
}

static void
dumpInfo( FILE *          out,
          const tr_info * inf )
{
    int             i;
    int             prevTier = -1;
    tr_file_index_t ff;

    fprintf( out, "hash:\t" );
    for( i = 0; i < SHA_DIGEST_LENGTH; ++i )
        fprintf( out, "%02x", inf->hash[i] );
    fprintf( out, "\n" );

    fprintf( out, "name:\t%s\n", inf->name );

    for( i = 0; i < inf->trackerCount; ++i )
    {
        if( prevTier != inf->trackers[i].tier )
        {
            prevTier = inf->trackers[i].tier;
            fprintf( out, "\ntracker tier #%d:\n", ( prevTier + 1 ) );
        }
        fprintf( out, "\tannounce:\t%s\n", inf->trackers[i].announce );
    }

    fprintf( out, "size:\t%" PRIu64 " (%" PRIu64 " * %d + %" PRIu64 ")\n",
             inf->totalSize, inf->totalSize / inf->pieceSize,
             inf->pieceSize, inf->totalSize % inf->pieceSize );

    if( inf->comment && *inf->comment )
        fprintf( out, "comment:\t%s\n", inf->comment );
    if( inf->creator && *inf->creator )
        fprintf( out, "creator:\t%s\n", inf->creator );
    if( inf->isPrivate )
        fprintf( out, "private flag set\n" );

    fprintf( out, "file(s):\n" );
    for( ff = 0; ff < inf->fileCount; ++ff )
        fprintf( out, "\t%s (%" PRIu64 ")\n", inf->files[ff].name,
                 inf->files[ff].length );
}

static void
getStatusStr( const tr_stat * st,
              char *          buf,
              size_t          buflen )
{
    if( st->activity & TR_STATUS_CHECK_WAIT )
    {
        tr_snprintf( buf, buflen, "Waiting to verify local files" );
    }
    else if( st->activity & TR_STATUS_CHECK )
    {
        tr_snprintf( buf, buflen,
                     "Verifying local files (%.2f%%, %.2f%% valid)",
                     100 * st->recheckProgress,
                     100.0 * st->percentDone );
    }
    else if( st->activity & TR_STATUS_DOWNLOAD )
    {
        char ratioStr[80];
        tr_strlratio( ratioStr, st->ratio, sizeof( ratioStr ) );
        tr_snprintf(
            buf, buflen,
            "Progress: %.1f%%, dl from %d of %d peers (%.0f KB/s), "
            "ul to %d (%.0f KB/s) [%s]",
            st->percentDone * 100.0,
            st->peersSendingToUs,
            st->peersConnected,
            st->pieceDownloadSpeed,
            st->peersGettingFromUs,
            st->pieceUploadSpeed,
            ratioStr );
    }
    else if( st->activity & TR_STATUS_SEED )
    {
        char ratioStr[80];
        tr_strlratio( ratioStr, st->ratio, sizeof( ratioStr ) );
        tr_snprintf(
            buf, buflen,
            "Seeding, uploading to %d of %d peer(s), %.0f KB/s [%s]",
            st->peersGettingFromUs, st->peersConnected,
            st->pieceUploadSpeed, ratioStr );
    }
    else *buf = '\0';
}

int
main( int     argc,
      char ** argv )
{
    int           error;
    tr_session  * h;
    tr_ctor     * ctor;
    tr_torrent  * tor = NULL;

    printf( "Transmission %s - http://www.transmissionbt.com/\n",
            LONG_VERSION_STRING );

    /* user needs to pass in at least one argument */
    if( argc < 2 ) {
        tr_getopt_usage( MY_NAME, getUsage( ), options );
        return EXIT_FAILURE;
    }

    /* Get options */
    if( parseCommandLine( argc, (const char**)argv ) )
        return EXIT_FAILURE;

    /* Check the options for validity */
    if( !torrentPath )
    {
        fprintf( stderr, "No torrent specified!\n" );
        return EXIT_FAILURE;
    }
    if( peerPort < 1 || peerPort > 65535 )
    {
        fprintf( stderr, "Error: Port must between 1 and 65535; got %d\n",
                 peerPort );
        return EXIT_FAILURE;
    }
    if( peerSocketTOS < 0 || peerSocketTOS > 255 )
    {
        fprintf( stderr, "Error: value must between 0 and 255; got %d\n",
                 peerSocketTOS );
        return EXIT_FAILURE;
    }

    /* don't bind the port if we're just running the CLI
     * to get metainfo or to create a torrent */
    if( showInfo || showScrape || ( sourceFile != NULL ) )
        peerPort = -1;

    if( configdir == NULL )
        configdir = tr_getDefaultConfigDir( );

    /* if no download directory specified, use cwd instead */
    if( !downloadDir )
        downloadDir = tr_strdup( tr_getcwd( ) );

    /* Initialize libtransmission */
    h = tr_sessionInitFull(
        configdir,
        "cli",                            /* tag */
        downloadDir,                       /* where to download torrents */
        TR_DEFAULT_PEX_ENABLED,
        natTraversal,                      /* nat enabled */
        peerPort,
        encryptionMode,
        TR_DEFAULT_LAZY_BITFIELD_ENABLED,
        uploadLimit >= 0,
        uploadLimit,
        downloadLimit >= 0,
        downloadLimit,
        TR_DEFAULT_GLOBAL_PEER_LIMIT,
        verboseLevel + 1,                  /* messageLevel */
        0,                                 /* is message queueing enabled? */
        blocklistEnabled,
        peerSocketTOS,
        TR_DEFAULT_RPC_ENABLED,
        TR_DEFAULT_RPC_PORT,
        TR_DEFAULT_RPC_WHITELIST_ENABLED,
        TR_DEFAULT_RPC_WHITELIST,
        FALSE, "fnord", "potzrebie",
        TR_DEFAULT_PROXY_ENABLED,
        TR_DEFAULT_PROXY,
        TR_DEFAULT_PROXY_PORT,
        TR_DEFAULT_PROXY_TYPE,
        TR_DEFAULT_PROXY_AUTH_ENABLED,
        TR_DEFAULT_PROXY_USERNAME,
        TR_DEFAULT_PROXY_PASSWORD );

    if( sourceFile && *sourceFile ) /* creating a torrent */
    {
        int                   err;
        tr_metainfo_builder * b = tr_metaInfoBuilderCreate( h, sourceFile );
        tr_tracker_info       ti;
        ti.tier = 0;
        ti.announce = (char*) announce;
        tr_makeMetaInfo( b, torrentPath, &ti, 1, comment, isPrivate );
        while( !b->isDone )
        {
            tr_wait( 1000 );
            printf( "." );
        }

        err = b->result;
        tr_metaInfoBuilderFree( b );
        return err;
    }

    ctor = tr_ctorNew( h );
    tr_ctorSetMetainfoFromFile( ctor, torrentPath );
    tr_ctorSetPaused( ctor, TR_FORCE, showScrape );
    tr_ctorSetDownloadDir( ctor, TR_FORCE, downloadDir );

    if( showScrape )
    {
        tr_info info;

        if( !tr_torrentParse( h, ctor, &info ) )
        {
            int          i;
            const time_t start = time( NULL );
            for( i = 0; i < info.trackerCount; ++i )
            {
                if( info.trackers[i].scrape )
                {
                    const char * scrape = info.trackers[i].scrape;
                    char         escaped[SHA_DIGEST_LENGTH * 3 + 1];
                    char *       url, *host;
                    escape( escaped, info.hash, SHA_DIGEST_LENGTH );
                    url = tr_strdup_printf( "%s%cinfo_hash=%s",
                                            scrape,
                                            strchr( scrape,
                                                    '?' ) ? '&' : '?',
                                            escaped );
                    tr_httpParseURL( scrape, -1, &host, NULL, NULL );
                    ++leftToScrape;
                    tr_webRun( h, url, NULL, scrapeDoneFunc, host );
                    tr_free( url );
                }
            }

            fprintf( stderr, "scraping %d trackers:\n", leftToScrape );

            while( leftToScrape > 0 && ( ( time( NULL ) - start ) < 20 ) )
                tr_wait( 250 );
        }
        goto cleanup;
    }

    if( showInfo )
    {
        tr_info info;

        if( !tr_torrentParse( h, ctor, &info ) )
        {
            dumpInfo( stdout, &info );
            tr_metainfoFree( &info );
        }

        tr_ctorFree( ctor );
        goto cleanup;
    }

    tor = tr_torrentNew( h, ctor, &error );
    tr_ctorFree( ctor );
    if( !tor )
    {
        fprintf( stderr, "Failed opening torrent file `%s'\n", torrentPath );
        tr_sessionClose( h );
        return EXIT_FAILURE;
    }

    signal( SIGINT, sigHandler );
#ifndef WIN32
    signal( SIGHUP, sigHandler );
#endif
    tr_torrentSetCompletenessCallback( tor, torrentCompletenessChanged, NULL );
    tr_torrentStart( tor );

    if( verify )
    {
        verify = 0;
        tr_torrentVerify( tor );
    }

    for( ; ; )
    {
        char            line[LINEWIDTH];
        const tr_stat * st;

        tr_wait( 200 );

        if( gotsig )
        {
            gotsig = 0;
            printf( "\nStopping torrent...\n" );
            tr_torrentStop( tor );
        }

        if( manualUpdate )
        {
            manualUpdate = 0;
            if( !tr_torrentCanManualUpdate( tor ) )
                fprintf(
                    stderr,
                    "\nReceived SIGHUP, but can't send a manual update now\n" );
            else
            {
                fprintf( stderr,
                         "\nReceived SIGHUP: manual update scheduled\n" );
                tr_torrentManualUpdate( tor );
            }
        }

        st = tr_torrentStat( tor );
        if( st->activity & TR_STATUS_STOPPED )
            break;

        getStatusStr( st, line, sizeof( line ) );
        printf( "\r%-*s", LINEWIDTH, line );
        if( st->error )
            fprintf( stderr, "\n%s\n", st->errorString );
    }

cleanup:
    printf( "\n" );
    tr_sessionClose( h );
    return EXIT_SUCCESS;
}

/***
****
****
****
***/

static void
showUsage( void )
{
    tr_getopt_usage( MY_NAME, getUsage( ), options );
    exit( 0 );
}

static int
numarg( const char * arg )
{
    char *     end = NULL;
    const long num = strtol( arg, &end, 10 );

    if( *end )
    {
        fprintf( stderr, "Not a number: \"%s\"\n", arg );
        showUsage( );
    }
    return num;
}

static int
parseCommandLine( int           argc,
                  const char ** argv )
{
    int          c;
    const char * optarg;

    while( ( c = tr_getopt( getUsage( ), argc, argv, options, &optarg ) ) )
    {
        switch( c )
        {
            case 'a':
                announce = optarg; break;

            case 'b':
                blocklistEnabled = 1; break;

            case 'B':
                blocklistEnabled = 0; break;

            case 'c':
                comment = optarg; break;

            case 'd':
                downloadLimit = numarg( optarg ); break;

            case 'D':
                downloadLimit = -1; break;

            case 'f':
                finishCall = optarg; break;

            case 'g':
                configdir = optarg; break;

            case 'i':
                showInfo = 1; break;

            case 'm':
                natTraversal = 1; break;

            case 'M':
                natTraversal = 0; break;

            case 'n':
                sourceFile = optarg; break;

            case 'p':
                peerPort = numarg( optarg ); break;

            case 'r':
                isPrivate = 1; break;

            case 's':
                showScrape = 1; break;

            case 't':
                peerSocketTOS = numarg( optarg ); break;

            case 'u':
                uploadLimit = numarg( optarg ); break;

            case 'U':
                uploadLimit = -1; break;

            case 'v':
                verify = 1; break;

            case 'w':
                downloadDir = optarg; break;

            case 910:
                encryptionMode = TR_ENCRYPTION_REQUIRED; break;

            case 911:
                encryptionMode = TR_CLEAR_PREFERRED; break;

            case 912:
                encryptionMode = TR_ENCRYPTION_PREFERRED; break;

            case TR_OPT_UNK:
                torrentPath = optarg; break;

            default:
                return 1;
        }
    }

    return 0;
}

static void
sigHandler( int signal )
{
    switch( signal )
    {
        case SIGINT:
            gotsig = 1; break;

#ifndef WIN32
        case SIGHUP:
            manualUpdate = 1; break;

#endif
        default:
            break;
    }
}


text:
module Mirah
  module JVM
    module MethodLookup
      java_import 'mirah.lang.ast.ConstructorDefinition'

      def find_method2(mapped_type, name, mapped_params, macro_params, meta, scope=nil, &block)
        find_method(mapped_type, name, mapped_params, macro_params, meta, scope, &block)
      rescue NameError => ex
        raise ex unless ex.message.include?(name)
        if block_given?
          block.call(ex)
        end
        ex
      end

      def find_method(mapped_type, name, mapped_params, macro_params, meta, scope=nil, &block)
        if mapped_type.error?
          raise "WTF?!?"
        end

        if name == 'new' && meta # we're calling SomeClass.new
          name = "<init>"
          constructor = true
          mapped_type = mapped_type.unmeta
          meta = false
        elsif name == 'new' && !meta # we're calling some_instance.new
          constructor = false
        elsif name == '<init>' && !meta # how do we get here?
          constructor = true
        elsif name == 'initialize' && !meta && scope
          context = scope.context
          if context.kind_of?(ConstructorDefinition) || context.findAncesor(ConstructorDefinition.class)
            constructor = true
            name = '<init>'
          end
        end

        if block_given?
          if constructor
            mapped_type.add_method_listener('initialize') {block.call(find_method2(mapped_type.meta, 'new', mapped_params, macro_params, true))}
          else
            mapped_type.add_method_listener(name) {block.call(find_method2(mapped_type, name, mapped_params, macro_params, meta))}
          end
          block.call(find_method(mapped_type, name, mapped_params, macro_params, meta))
          return
        end

        begin
          unless mapped_params.any? {|p| p.nil? || p.isError}
            if constructor
              method = mapped_type.constructor(*mapped_params)
            else
              method = mapped_type.java_method(name, *mapped_params)
            end
          end
        rescue NameError => ex
          # TODO return nil instead of raising an exception if the method doesn't exist.
          raise ex unless ex.message =~ /#{Regexp.quote(mapped_type.name)}\.#{Regexp.quote(name)}|No constructor #{Regexp.quote(mapped_type.name)}/
        end

        macro = mapped_type.unmeta.macro(name, macro_params)
        if method && macro
          method = nil  # Need full lookup to determine precedence.
        elsif method.nil? && macro
          method = macro
        elsif method.nil?
          # exact args failed, do a deeper search
          log "No exact match for #{mapped_type.name}.#{name}(#{mapped_params.map(&:name).join ', '})" if mapped_params.all?

          method = find_jls(mapped_type, name, mapped_params, macro_params, meta, constructor)

          unless method
            log "Failed to locate method #{mapped_type.name}.#{name}(#{mapped_params.map(&:name).join ', '})" if mapped_params.all?
            return nil
          end
        end

        log "Found method #{method.declaring_class.name}.#{name}(#{method.argument_types.map(&:name).join ', '}) from #{mapped_type.name}"
        return method
      end

      def find_jls(mapped_type, name, mapped_params, macro_params, meta, constructor)
        interfaces = []
        by_name = if constructor
          mapped_type.unmeta.declared_constructors
        elsif meta
          mapped_type.declared_class_methods(name)
        else
          mapped_type.find_callable_methods(name)
        end
        method = find_jls2(mapped_type, name, mapped_params, meta, by_name, true)
        return method if (constructor || macro_params.nil?)
        macros = mapped_type.unmeta.find_callable_macros(name)
        if macros.size != 0
          log "Found potential macro match for #{mapped_type.name}.#{name}(#{macro_params.map(&:full_name).join ', '})"
          macro = find_jls2(mapped_type.unmeta, name, macro_params, meta, macros, false)
        end
        if macro && method
          raise "Ambiguous targets invoking #{mapped_type}.#{name}:\n#{macro} and #{method}"
        end
        macro || method
      end

      def find_jls2(mapped_type, name, mapped_params, meta, by_name, include_fields=true)
        return nil if mapped_params.any? {|p| p.nil? || p.isError}
        # filter by arity
        by_name_and_arity = by_name.select {|m| m.argument_types.size == mapped_params.size}

        phase1_methods = phase1(mapped_params, by_name_and_arity)

        if phase1_methods.size > 1
          method_list = phase1_methods.map do |m|
            "#{m.name}(#{m.parameter_types.map(&:name).join(', ')})"
          end.join("\n")
          raise "Ambiguous targets invoking #{mapped_type}.#{name}:\n#{method_list}"
        end

        phase1_methods[0] ||
          phase2(mapped_params, by_name) ||
          phase3(mapped_params, by_name) ||
          (include_fields &&
            (field_lookup(mapped_params, mapped_type, meta, name) ||
             inner_class(mapped_params, mapped_type, meta, name)))
      end

      def phase1(mapped_params, potentials)
        log "Beginning JLS phase 1 search with params (#{mapped_params.map(&:name).join ', '})"

        # cycle through methods looking for more specific matches; gather matches of equal specificity
        methods = potentials.inject([]) do |currents, potential|
          method_params = potential.argument_types
          raise "Bad arguments for method #{potential.declaring_class}.#{potential.name}" unless method_params.all?

          # exact match always wins; duplicates not possible
          if each_is_exact(mapped_params, method_params)
            return [potential]
          end

          # otherwise, check for potential match and compare to current
          # TODO: missing ambiguity check; picks last method of equal specificity
          if each_is_exact_or_subtype_or_convertible(mapped_params, method_params)
            if currents.size > 0
              if is_more_specific?(potential.argument_types, currents[0].argument_types)
                # potential is better, dump all currents
                currents = [potential]
              elsif is_more_specific?(currents[0].argument_types, potential.argument_types)
                # currents are better, try next potential
                #next
              else
                # equal specificity, append to currents
                currents << potential
              end
            else
              # no previous matches, use potential
              currents = [potential]
            end
          end

          currents
        end

        methods
      end

      def is_more_specific?(potential, current)
        each_is_exact_or_subtype_or_convertible(potential, current)
      end

      def phase2(mapped_params, potentials)
        nil
      end

      def phase3(mapped_params, potentials)
        nil
      end

      def field_lookup(mapped_params, mapped_type, meta, name)
        log("Attempting #{meta ? 'static' : 'instance'} field lookup for '#{name}' on class #{mapped_type}")
        # if we get to this point, the potentials do not match, so we ignore them

        # search for a field of the given name
        if name =~ /_set$/
          # setter
          setter = true
          name = name[0..-5]
          field = mapped_type.field_setter(name)
        else
          # getter
          setter = false

          # field accesses don't take arguments
          return if mapped_params.size > 0
          field = mapped_type.field_getter(name)
        end

        return nil unless field

        if (meta && !field.static?) ||
            (!meta && field.static?)
          field == nil
        end

        # check accessibility
        # TODO: protected field access check appropriate to current type
        if setter
          raise "cannot set final field '#{name}' on class #{mapped_type}" if field.final?
        end
        raise "cannot access field '#{name}' on class #{mapped_type}" unless field.public?

        field
      end

      def inner_class(params, type, meta, name)
        return unless params.size == 0 && meta
        log("Attempting inner class lookup for '#{name}' on #{type}")
        type.inner_class_getter(name)
      end

      def each_is_exact(incoming, target)
        incoming.each_with_index do |in_type, i|
          target_type = target[i]

          # exact match
          return false unless target_type == in_type
        end
        return true
      end

      def each_is_exact_or_subtype_or_convertible(incoming, target)
        incoming.each_with_index do |in_type, i|
          target_type = target[i]

          # exact match
          next if target_type == in_type

          unless target_type.respond_to?(:primitive?) && in_type.respond_to?(:primitive?)
            puts "Huh?"
          end
          # primitive is safely convertible
          if target_type.primitive?
            if in_type.primitive?
              next if primitive_convertible? in_type, target_type
            end
            return false
          end

          # object type is assignable
          compatible = if target_type.respond_to?(:compatible?)
            target_type.compatible? in_type
          else
            target_type.assignable_from? in_type
          end
          return false unless compatible
        end
        return true
      end

      def primitive_convertible?(in_type, target_type)
        in_type.convertible_to?(target_type)
      end
    end
  end
end


text:
require "spec_helper"

RSpec.describe Vips::Region do
  it "can create a region on an image" do
    image = Vips::Image.black(100, 100)
    region = Vips::Region.new image

    expect(region)
  end

  it "can fetch pixels from a region", version: [8, 8] do
    image = Vips::Image.black(100, 100)
    region = Vips::Region.new image
    pixel_data = region.fetch 10, 20, 30, 40

    expect(pixel_data)
    expect(pixel_data.length == 30 * 40)
  end

  it "can make regions with width and height", version: [8, 8] do
    image = Vips::Image.black(100, 100)
    region = Vips::Region.new image
    pixel_data = region.fetch 10, 20, 30, 40

    expect(pixel_data)
    expect(region.width == 30)
    expect(region.height == 40)
  end
end


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

<title>Index (Javadocs: FLib)</title>
<meta name="date" content="2014-06-11">
<link rel="stylesheet" type="text/css" href="./stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

A B C D E F G H I K L M O P Q R S T U V Y

A

area(PVector, PVector, PVector) - Static method in class flib.core.FVector

Get the area of a triangle spanned by the three given points.

B

BIAS_MAP - Static variable in class flib.core.FCalculate

blend(int, int, float) - Method in class flib.fcolor.FColor

Return a color blended between two source colors with a midpoint

blend(int, int, float, int) - Method in class flib.fcolor.FColor

Return a color blended between two source colors with a midpoint

blendArray(int, int, int) - Method in class flib.fcolor.FColor

Return an array of colors blended from two colors

boolToInt(boolean) - Static method in class flib.core.Core

return boolean value as int

brightness(int) - Static method in class flib.fcolor.FColor

bitwise brightness

BrightnessComparator - Class in flib.fcolor

BrightnessComparator() - Constructor for class flib.fcolor.BrightnessComparator

C

CM_TO_POINT - Static variable in class flib.core.FConversions

convert 1 inch to pixel (or point)

  size( 21.0*CM_TO_POINT, (int)(29.7*CM_TO_POINT)); // A4 sized

collinear(PVector, PVector, PVector) - Static method in class flib.core.FVector

Check if three points are collinear
 https://github.com/schteppe/poly-decomp.js/blob/master/src/Point.js

collinear(PVector, PVector, PVector, float) - Static method in class flib.core.FVector

Check if three points are collinear
 https://github.com/schteppe/poly-decomp.js/blob/master/src/Point.js

colors - Variable in class flib.fcolor.FPalette

compare(Integer, Integer) - Method in class flib.fcolor.BrightnessComparator

compare(Integer, Integer) - Method in class flib.fcolor.LuminanceComparator

compare(Integer, Integer) - Method in class flib.fcolor.SaturationComparator

copy(int, int, PShape) - Method in class flib.core.FDecompose

Copy the polygon from vertex to vertex.

copy(int, int) - Method in class flib.core.FDecompose

Core - Class in flib.core

Core() - Constructor for class flib.core.Core

cosec(float) - Static method in class flib.core.FCalculate

Calculate cosecants

 http://www.ssicom.org/js/x974284.htm

D

darken(int, float) - Static method in class flib.fcolor.FColor

return darkened color as int

date() - Static method in class flib.ftime.FDate

return the current date as string "yyyyMMdd"

day() - Static method in class flib.ftime.FDate

return the current day as string "dd"

decomp() - Method in class flib.core.FDecompose

Decomposes the polygon into one or more convex sub-Polygons.

desaturate(int, float) - Static method in class flib.fcolor.FColor

return desaturated color as int

desaturate(int, float, float) - Static method in class flib.fcolor.FColor

return desaturated color as int

distSq(PVector) - Method in class flib.core.FVector

distSq(PVector, PVector) - Static method in class flib.core.FVector

divisor(float) - Static method in class flib.core.FCalculate

http://nayuki.eigenstate.org/res/calculate-divisors-javascript.js

draw(int, int) - Method in class flib.fshape.FSphere

E

Ease - Class in flib.ftime

Ease() - Constructor for class flib.ftime.Ease

EMPTY_FLOAT_ARRAY - Static variable in class flib.core.FArray

EMPTY_FLOAT_OBJECT_ARRAY - Static variable in class flib.core.FArray

F

fadeIn() - Method in class flib.ftime.FFade

fadeOut() - Method in class flib.ftime.FFade

FArray - Class in flib.core

FArray() - Constructor for class flib.core.FArray

FASE - Class in flib.fcolor

FASE(PApplet) - Constructor for class flib.fcolor.FASE

Instantiate FASE

FASE(PApplet, String) - Constructor for class flib.fcolor.FASE

Instantiate FASE

FCalculate - Class in flib.core

FCalculate() - Constructor for class flib.core.FCalculate

FColor - Class in flib.fcolor

FColor() - Constructor for class flib.fcolor.FColor

FConversions - Class in flib.core

FConversions() - Constructor for class flib.core.FConversions

FDate - Class in flib.ftime

FDate() - Constructor for class flib.ftime.FDate

FDecompose - Class in flib.core

FDecompose(PShape) - Constructor for class flib.core.FDecompose

FDecompose
 TODO: support PShape with children

FDecompose() - Constructor for class flib.core.FDecompose

FFade - Class in flib.ftime

FFade(PApplet) - Constructor for class flib.ftime.FFade

FFileLoader - Class in flib.core

FFileLoader(PApplet, String) - Constructor for class flib.core.FFileLoader

Instantiate FFileLoader

FFileLoader(PApplet, String, String) - Constructor for class flib.core.FFileLoader

Instantiate FFileLoader

FFileLoader(PApplet, String, String[]) - Constructor for class flib.core.FFileLoader

Instantiate FFileLoader

FImageLoader - Class in flib.core

FImageLoader(PApplet, String) - Constructor for class flib.core.FImageLoader

Instantiate FImageLoader

findNormal(PVector, PVector, PVector, float) - Static method in class flib.core.FVector

Finds the normal at p0 - the intersection of two vectors p1 and p2.

flib.core - package flib.core

flib.fcolor - package flib.fcolor

flib.fshape - package flib.fshape

flib.ftime - package flib.ftime

FMultiTimer - Class in flib.ftime

FMultiTimer(PApplet) - Constructor for class flib.ftime.FMultiTimer

Instantiate FMultiTimer (work in progess, more so than FMultiTimer)

FMultiTimer(PApplet, float) - Constructor for class flib.ftime.FMultiTimer

Instantiate FMultiTimer (work in progess, more so than FMultiTimer)

FMultiTimer(PApplet, float[]) - Constructor for class flib.ftime.FMultiTimer

Instantiate FMultiTimer (work in progess, more so than FMultiTimer)

FPalette - Class in flib.fcolor

FPalette(PApplet, String) - Constructor for class flib.fcolor.FPalette

Instantiate FPalette

FPalette(PApplet, PImage) - Constructor for class flib.fcolor.FPalette

Instantiate FPalette

FPalette(PApplet) - Constructor for class flib.fcolor.FPalette

Instantiate FPalette

FShape - Class in flib.core

FShape() - Constructor for class flib.core.FShape

FSphere - Class in flib.fshape

FSphere(PApplet, float) - Constructor for class flib.fshape.FSphere

FSphere(PApplet, float, int, int) - Constructor for class flib.fshape.FSphere

FStopwatch - Class in flib.ftime

FStopwatch() - Constructor for class flib.ftime.FStopwatch

FStopwatch(float, boolean) - Constructor for class flib.ftime.FStopwatch

FTimer - Class in flib.ftime

FTimer() - Constructor for class flib.ftime.FTimer

Instantiate FTimer

FTimer(float) - Constructor for class flib.ftime.FTimer

Instantiate FTimer

FVector - Class in flib.core

FVector() - Constructor for class flib.core.FVector

G

getAlpha() - Method in class flib.ftime.FFade

getColor(int) - Method in class flib.fcolor.FASE

Get a color at index.

getColor(int) - Static method in class flib.fcolor.FColor

return the RGBA break down of an int/color (0 - 255) as int[4]

getColor(String) - Static method in class flib.fcolor.FColor

return int of color from a Hexidecimal color code

getColor(int) - Method in class flib.fcolor.FPalette

return selected color of the created colors

getColorF(int) - Static method in class flib.fcolor.FColor

return the RGBA break down of an int/color (0.0 - 1.0) as float[4]

getColors() - Method in class flib.fcolor.FASE

getColors() - Method in class flib.fcolor.FPalette

getColorTrans(int, float) - Method in class flib.fcolor.FPalette

return selected color of the created colors with given transprency

getCount() - Method in class flib.fcolor.FASE

getCount() - Method in class flib.fcolor.FPalette

getCutEdges(PShape) - Method in class flib.core.FDecompose

Decomposes the polygon into convex pieces.

getDecimatedVertices(List<PVector>, float, boolean) - Static method in class flib.core.FVector

breaks a line (defined as a space between points) into
  a specified number of line segments code was taken directly from toxilibs

  https://bitbucket.org/postspectacular/toxiclibs/src/9d124c80e8af/src.core/toxi/geom/LineStrip2D.java

  modified for use with Processing's native PVector

getEstimatedArcLength(List<PVector>) - Static method in class flib.core.FVector

Get estimated arc length

getExtension(String) - Static method in class flib.core.Core

return file extension from given path

getFadeMillis() - Method in class flib.ftime.FFade

getFadeSeconds() - Method in class flib.ftime.FFade

getFile(int) - Method in class flib.core.FFileLoader

getFile(int) - Method in class flib.core.FImageLoader

getFileCount() - Method in class flib.core.FFileLoader

getFileCount() - Method in class flib.core.FImageLoader

getImage(int) - Method in class flib.core.FImageLoader

getImageCount() - Method in class flib.core.FImageLoader

getIntersectionPoint(PVector, PVector, PVector, PVector, float) - Method in class flib.core.FDecompose

[getIntersectionPoint description]

getIntersectionPoint(PVector, PVector, PVector, PVector) - Method in class flib.core.FDecompose

getParallelLine(PVector[], float) - Static method in class flib.core.FVector

Calculates the vertex positions of a line parallel to the original
  line at an approximate fixed distance.

getPath() - Method in class flib.fcolor.FPalette

return the palette base image path as string

getPoints() - Method in class flib.fshape.FSphere

getTrigger() - Method in class flib.ftime.FMultiTimer

getTrigger() - Method in class flib.ftime.FTimer

getVertices(PShape) - Method in class flib.core.FDecompose

grid(int, int, PVector) - Static method in class flib.core.FVector

grid(int, int, PVector, boolean) - Static method in class flib.core.FVector

H

hour() - Static method in class flib.ftime.FDate

return the current hour as string "HH"

hue(int) - Static method in class flib.fcolor.FColor

hue

I

img - Variable in class flib.fcolor.FPalette

INCH_TO_POINT - Static variable in class flib.core.FConversions

convert 1 inch to pixel (or point)

  size( (int)(8.5*INCH_TO_POINT), 11*INCH_TO_POINT); // US Letter sized

inCirc(float) - Static method in class flib.ftime.Ease

inCubic(float) - Static method in class flib.ftime.Ease

inExpo(float) - Static method in class flib.ftime.Ease

inOutCirc(float) - Static method in class flib.ftime.Ease

inOutCubic(float) - Static method in class flib.ftime.Ease

inOutExpo(float) - Static method in class flib.ftime.Ease

inOutQuad(float) - Static method in class flib.ftime.Ease

inOutQuart(float) - Static method in class flib.ftime.Ease

inOutQuint(float) - Static method in class flib.ftime.Ease

inOutSine(float) - Static method in class flib.ftime.Ease

inQuad(float) - Static method in class flib.ftime.Ease

inQuart(float) - Static method in class flib.ftime.Ease

inQuint(float) - Static method in class flib.ftime.Ease

inSine(float) - Static method in class flib.ftime.Ease

interpolate(float, float, float) - Static method in class flib.core.FCalculate

interpolateTo(PVector, PVector, float) - Static method in class flib.core.FVector

interpolate from one PVector to another

interpolateTo(PVector, float) - Method in class flib.core.FVector

interpolate from one PVector to another

intToBool(int) - Static method in class flib.core.Core

return boolean value as int

isFadingIn() - Method in class flib.ftime.FFade

return fading in

isFadingOut() - Method in class flib.ftime.FFade

return fading out

isSimple() - Method in class flib.core.FDecompose

Checks that the line segments of this polygon do not intersect each other.

K

KeySpline(float[], float) - Static method in class flib.ftime.Ease

use bezier curve for transition easing function

KeySpline(PVector, PVector, float) - Static method in class flib.ftime.Ease

use bezier curve for transition easing function

L

lighten(int, float) - Static method in class flib.fcolor.FColor

return lightened color as int

limit(PVector, float) - Static method in class flib.core.FVector

linear(float) - Static method in class flib.ftime.Ease

load(String) - Method in class flib.fcolor.FASE

luminance(int) - Static method in class flib.fcolor.FColor

bitwise luminance
 http://processing.org/discourse/yabb2/YaBB.pl?num=1164286894

LuminanceComparator - Class in flib.fcolor

LuminanceComparator() - Constructor for class flib.fcolor.LuminanceComparator

M

max(PVector[]) - Static method in class flib.core.FVector

maxIndex(float[]) - Static method in class flib.core.FArray

method which return the index of
 the index of the largest value in the array

maxIndex(int[]) - Static method in class flib.core.FArray

maxValue(float[]) - Static method in class flib.core.FArray

finds maximum value within an array

maxValue(int[]) - Static method in class flib.core.FArray

min(PVector[]) - Static method in class flib.core.FVector

minIndex(float[]) - Static method in class flib.core.FArray

method which return the index of
 the index of the smallest value in the array

minIndex(int[]) - Static method in class flib.core.FArray

minute() - Static method in class flib.ftime.FDate

return the current minute as string "mm"

minValue(float[]) - Static method in class flib.core.FArray

finds minimum value within an array

minValue(int[]) - Static method in class flib.core.FArray

MM_TO_POINT - Static variable in class flib.core.FConversions

convert 1 millimeter to pixel (or point)

  size(210*MM_TO_POINT, 297*MM_TO_POINT); // A4 sized

month(String) - Static method in class flib.ftime.FDate

return the current month as string

month() - Static method in class flib.ftime.FDate

return the current month as string "MM"

O

outCirc(float) - Static method in class flib.ftime.Ease

outCubic(float) - Static method in class flib.ftime.Ease

outExpo(float) - Static method in class flib.ftime.Ease

outQuad(float) - Static method in class flib.ftime.Ease

outQuart(float) - Static method in class flib.ftime.Ease

outQuint(float) - Static method in class flib.ftime.Ease

outSine(float) - Static method in class flib.ftime.Ease

P

PICA_TO_POINT - Static variable in class flib.core.FConversions

POINT_TO_CM - Static variable in class flib.core.FConversions

convert 1 point (or pixel) to centimeter

POINT_TO_INCH - Static variable in class flib.core.FConversions

convert 1 point (or pixel) to inch

POINT_TO_MM - Static variable in class flib.core.FConversions

convert 1 point (or pixel) to millimeter

POINT_TO_PICA - Static variable in class flib.core.FConversions

convert 1 point (or pixel) to pica

Q

quickDecomp(PShape, ArrayList<PShape>, ArrayList<PVector>, ArrayList<PVector>, int, int, int) - Method in class flib.core.FDecompose

Quickly decompose the Polygon into convex sub-polygons.

quickDecomp() - Method in class flib.core.FDecompose

R

randomBias(float, float, float) - Static method in class flib.core.FCalculate

http://www.siafoo.net/snippet/191

randomColor() - Static method in class flib.fcolor.FColor

return random RGBA color as int

randomColor(int) - Static method in class flib.fcolor.FColor

return random RGB color as int

randomColor(int, int) - Static method in class flib.fcolor.FColor

return random RGB color within hue range as int

randomColor(int, int, float, float) - Static method in class flib.fcolor.FColor

return random RGB color within hue range with specified saturation and brightness as int

randomColors(int) - Static method in class flib.fcolor.FColor

randomGrayColor() - Static method in class flib.fcolor.FColor

return random grayscale color as int

randomGrayColor(float, float) - Static method in class flib.fcolor.FColor

return random grayscale within a percent range color as int

randomInt(float) - Static method in class flib.core.FCalculate

randomInt(float, float) - Static method in class flib.core.FCalculate

reset() - Method in class flib.ftime.FTimer

reverse(Object[]) - Static method in class flib.core.FArray

Reverse

 Reverses the order of the given array.

round(float, int) - Static method in class flib.core.FCalculate

roundMultiple(float, int) - Static method in class flib.core.FCalculate

S

saturation(int) - Static method in class flib.fcolor.FColor

saturation

SaturationComparator - Class in flib.fcolor

SaturationComparator() - Constructor for class flib.fcolor.SaturationComparator

save(int[], String, String[], String) - Method in class flib.fcolor.FASE

Exports an ASE (Adobe Swatch Echange) file

save(int[], String) - Method in class flib.fcolor.FASE

Exports an ASE (Adobe Swatch Echange) file

sec(float) - Static method in class flib.core.FCalculate

Calculate secants

 http://www.ssicom.org/js/x974780.htm

second() - Static method in class flib.ftime.FDate

return the current second as string "ss"

setAlpha(float) - Method in class flib.ftime.FFade

setCCW() - Method in class flib.core.FDecompose

Make sure that the polygon points are ordered counter-clockwise.

setCompletion(float) - Method in class flib.fshape.FSphere

setFadeMillis(int) - Method in class flib.ftime.FFade

setFadeSeconds(float) - Method in class flib.ftime.FFade

setFile(String) - Method in class flib.core.FFileLoader

setFile(String) - Method in class flib.core.FImageLoader

setFiles(String[]) - Method in class flib.core.FFileLoader

setFiles(String[]) - Method in class flib.core.FImageLoader

setFolder(String) - Method in class flib.core.FFileLoader

setFolder(String) - Method in class flib.core.FImageLoader

setFreq(float) - Method in class flib.ftime.FMultiTimer

setFreq(float[]) - Method in class flib.ftime.FMultiTimer

setFreq(float) - Method in class flib.ftime.FTimer

setLatsLongs(int, int) - Method in class flib.fshape.FSphere

setPath(String) - Method in class flib.fcolor.FPalette

setSize(float) - Method in class flib.fshape.FSphere

setSource() - Method in class flib.fcolor.FPalette

slice(PShape, PVector[][]) - Method in class flib.core.FDecompose

Slices the polygon given one or more cut edges.

slice(PShape, PVector[]) - Method in class flib.core.FDecompose

slope(float, float) - Static method in class flib.core.FCalculate

Slope

slopeAngle(PVector) - Static method in class flib.core.FCalculate

Slope to angle

slopeRatio(PVector, PVector) - Static method in class flib.core.FCalculate

Slope ratio

snap(float, float) - Static method in class flib.core.FCalculate

http://stackoverflow.com/questions/4507784/snap-to-grid-functionality-using-javascript

snap(PVector, int) - Method in class flib.core.FVector

snap(float, int) - Method in class flib.core.FVector

SNAP_GRID - Static variable in class flib.core.FVector

SNAP_ISOMETRIC - Static variable in class flib.core.FVector

SPLINE_EASE - Static variable in class flib.ftime.Ease

SPLINE_IN - Static variable in class flib.ftime.Ease

SPLINE_INOUT - Static variable in class flib.ftime.Ease

SPLINE_LINEAR - Static variable in class flib.ftime.Ease

SPLINE_OUT - Static variable in class flib.ftime.Ease

splitIntoSegments(PVector, PVector, List<PVector>, float, boolean) - Static method in class flib.core.FVector

Split into segments

start() - Method in class flib.ftime.FMultiTimer

start() - Method in class flib.ftime.FTimer

stop() - Method in class flib.ftime.FMultiTimer

stop() - Method in class flib.ftime.FTimer

stopFade() - Method in class flib.ftime.FFade

stop fade

T

time() - Static method in class flib.ftime.FDate

return the current time as string "HHmmss"

to2DArray(ArrayList<PVector>) - Static method in class flib.core.FArray

Converts an ArrayList<PVector> to float[][]

toByte(int[]) - Static method in class flib.core.FArray

Converts an array of object ints to bytes
 http://stackoverflow.com/questions/1086054/java-how-to-convert-int-to-byte

toByte(ArrayList<Integer>) - Static method in class flib.core.FArray

Converts an array of object ints to bytes

toByte(float[]) - Static method in class flib.core.FArray

Converts an array of object ints to floats
 http://stackoverflow.com/questions/1086054/java-how-to-convert-int-to-byte

toObject(float[]) - Static method in class flib.core.FArray

Converts an array of primitive floats to objects.

toPrimitive(Integer[]) - Static method in class flib.core.FArray

Converts an array of object Integers to int[]

toPrimitive(ArrayList<Integer>) - Static method in class flib.core.FArray

Converts an ArrayList to int[]

toPrimitive(int[]) - Static method in class flib.core.FArray

Float array converters

toPrimitive(Float[]) - Static method in class flib.core.FArray

Converts an array of object Floats to primitives.

toPrimitive(Float[], float) - Static method in class flib.core.FArray

Converts an array of object Floats to primitives handling null.

toRGB(float, float, float, float) - Static method in class flib.fcolor.FColor

Convert CMYK values into RGB array.

toRGB(int, int, int) - Static method in class flib.fcolor.FColor

Convert Lab values into RGB array.

U

update() - Method in class flib.ftime.FFade

update(long) - Method in class flib.ftime.FFade

V

vertices - Variable in class flib.core.FDecompose

Y

year() - Static method in class flib.ftime.FDate

return the current year as string "yyyy"

A B C D E F G H I K L M O P Q R S T U V Y

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

processing library FLib by Ken Frederick. (c) 2014


text:
.. _str: https://docs.python.org/2/library/stdtypes.html

.. _bool: https://docs.python.org/2/library/stdtypes.html

.. _ScsiDisk: ../../vim/host/ScsiDisk.rst

.. _vSphere API 5.5: ../../vim/version.rst#vimversionversion9

.. _vmodl.DynamicData: ../../vmodl/DynamicData.rst

.. _vmodl.LocalizedMethodFault: ../../vmodl/LocalizedMethodFault.rst

vim.host.DiskConfigurationResult
================================
  Disk configuration result returns success or fault of the operation on the disk.
:extends: vmodl.DynamicData_
:since: `vSphere API 5.5`_

Attributes:
    devicePath (`str`_, optional):

       The device path. See `ScsiDisk`_
    success (`bool`_, optional):

       Flag to indicate if the operation is successful
    fault (`vmodl.LocalizedMethodFault`_, optional):

       'fault' would be set if the operation was not successful


text:
package gudusoft.gsqlparser.sql2xml.model;

public class privelege_method_list
{

}


text:
#pragma once

#include "common/helpers.h"
#include "common/vk_common.h"

namespace vkb
{
class Device;
class DescriptorSetLayout;
class DescriptorPool;

/**
 * @brief A descriptor set handle allocated from a \ref DescriptorPool.
 *        Destroying the handle has no effect, as the pool manages the lifecycle of its descriptor sets.
 *
 *        Keeps track of what bindings were written to prevent a double write.
 */
class DescriptorSet
{
  public:
	/**
	 * @brief Constructs a descriptor set from buffer infos and image infos
	 *        Implicitly calls prepare()
	 * @param device A valid Vulkan device
	 * @param descriptor_set_layout The Vulkan descriptor set layout this descriptor set has
	 * @param descriptor_pool The Vulkan descriptor pool the descriptor set is allocated from
	 * @param buffer_infos The descriptors that describe buffer data
	 * @param image_infos The descriptors that describe image data
	 */
	DescriptorSet(Device &                                  device,
	              const DescriptorSetLayout &               descriptor_set_layout,
	              DescriptorPool &                          descriptor_pool,
	              const BindingMap<VkDescriptorBufferInfo> &buffer_infos = {},
	              const BindingMap<VkDescriptorImageInfo> & image_infos  = {});

	DescriptorSet(const DescriptorSet &) = delete;

	DescriptorSet(DescriptorSet &&other);

	// The descriptor set handle is managed by the pool, and will be destroyed when the pool is reset
	~DescriptorSet() = default;

	DescriptorSet &operator=(const DescriptorSet &) = delete;

	DescriptorSet &operator=(DescriptorSet &&) = delete;

	/**
	 * @brief Resets the DescriptorSet state
	 *        Optionally prepares a new set of buffer infos and/or image infos
	 * @param new_buffer_infos A map of buffer descriptors and their respective bindings
	 * @param new_image_infos A map of image descriptors and their respective bindings
	 */
	void reset(const BindingMap<VkDescriptorBufferInfo> &new_buffer_infos = {},
	           const BindingMap<VkDescriptorImageInfo> & new_image_infos  = {});

	/**
	 * @brief Updates the contents of the DescriptorSet by performing the write operations
	 * @param bindings_to_update If empty. we update all bindings. Otherwise, only write the specified bindings if they haven't already been written
	 */
	void update(const std::vector<uint32_t> &bindings_to_update = {});

	/**
	 * @brief Applies pending write operations without updating the state
	 */
	void apply_writes() const;

	const DescriptorSetLayout &get_layout() const;

	VkDescriptorSet get_handle() const;

	BindingMap<VkDescriptorBufferInfo> &get_buffer_infos();

	BindingMap<VkDescriptorImageInfo> &get_image_infos();

  protected:
	/**
	 * @brief Prepares the descriptor set to have its contents updated by loading a vector of write operations
	 *        Cannot be called twice during the lifetime of a DescriptorSet
	 */
	void prepare();

  private:
	Device &device;

	const DescriptorSetLayout &descriptor_set_layout;

	DescriptorPool &descriptor_pool;

	BindingMap<VkDescriptorBufferInfo> buffer_infos;

	BindingMap<VkDescriptorImageInfo> image_infos;

	VkDescriptorSet handle{VK_NULL_HANDLE};

	// The list of write operations for the descriptor set
	std::vector<VkWriteDescriptorSet> write_descriptor_sets;

	// The bindings of the write descriptors that have had vkUpdateDescriptorSets since the last call to update().
	// Each binding number is mapped to a hash of the binding description that it will be updated to.
	std::unordered_map<uint32_t, size_t> updated_bindings;
};
}        // namespace vkb


text:
var http = require('http'),
	fs = require('fs'),
	socketio = require('socket.io');

var server = http.createServer();

server.on('request', function(req, res) {
	res.writeHead(200, { 'Content-type': 'text/html'});
	res.end(fs.readFileSync(__dirname + '/index.html'));
});

server.listen(1333, function() {
	console.log('Listening at: http://localhost:1333');
});

Array.prototype.contains = function(k, callback) {
	var self = this;
    return (function check(i) {
        if (i >= self.length) {
            return callback(false);
        }
        if (self[i].id === k.id) {
            return callback(true);
        }
        return process.nextTick(check.bind(null, i+1));
    }(0));
};

var chatters = [];
socketio.listen(server).on('connection', function (socket) {
	socket.on('join', function (newChatter) {
		chatters.contains(newChatter, function(found) {
		    if (!found) {
		        chatters.push(newChatter);
				socket.broadcast.emit('chatter_joined',newChatter);
		    }
		    socket.broadcast.emit('chatter_already_joined', chatters);
			socket.emit('chatter_already_joined', chatters);
		});

	});

	socket.on('quit', function (chatter) {
		for (p in chatters) {
			if (chatters[p].id === chatter.id) {
				console.log('Chatter ', chatter.id, ' has quit');
				chatters.splice(p);
				socket.broadcast.emit('chatter_quit', chatter);
			}
		}
		socket.broadcast.emit('chatter_already_joined', chatters);
		socket.emit('chatter_already_joined', chatters);
	});

	socket.on('speak', function (chatter) {
		socket.broadcast.emit('chatter_said', chatter);
	});
});


text:
'use strict'
var fs = require('fs')
var path = require('path')
const fse = require('fs-extra')
const format = require('./../format')

module.exports = {
    command: 'component <agrupador> <nombre>',
    description: 'Crea un nuevo componente dentro de nuestro proyecto.',
    disabled:true,
    action: function (nombre, argument, command) {
        if(nombre && argument.length>0){
            if(!fs.existsSync(path.join(process.cwd(),'src',nombre,argument[0]+"Node"))){
                this.createDirectory(argument[0]+"Node",nombre)
                this.createFiles(argument[0]+"Node",nombre)
                console.log("Hecho!!")
            }else{
                console.log("Error: ya existe un componente con este nombre.")
            }
        }else{
            console.log("Error: faltan argumentos en el comando component <agrupador> <nombre>");
        }

    },
    createDirectory: function (name, vendor) {
        var src = path.join(process.cwd(), 'src');
        if (!fs.existsSync(path.join(src, vendor)))
            fs.mkdirSync(path.join(src, vendor));
        if (fs.existsSync(path.join(src, vendor, name)))
            return false;
        console.log("creando directorios del componente...")
        fs.mkdirSync(path.join(src, vendor, name));
        fs.mkdirSync(path.join(src, vendor, name, 'Controllers'));
        fs.mkdirSync(path.join(src, vendor, name, 'Resources'));
        fs.mkdirSync(path.join(src, vendor, name, 'Views'));
        fs.mkdirSync(path.join(src, vendor, name, 'Models'));
        fs.mkdirSync(path.join(src, vendor, name, 'i18n'));
        fs.mkdirSync(path.join(src, vendor, name, 'Commands'));
    },
    createFiles: function (name, vendor) {
        console.log("creando archivos del componente...")
        var index = fs.readFileSync(path.join(__dirname, '..', 'source', 'component.template'))
            .toString()
            .replace(/\{\{classname\}\}/g, name);

        var es6 = fs.readFileSync(path.join(__dirname, '..', 'source', 'controller.template'))
            .toString()
            .replace(/\{\{classname\}\}/g, name);

        var src = path.join(process.cwd(), 'src');
        fs.writeFileSync(path.join(src, vendor, name, 'index.js'), index);
        fs.writeFileSync(path.join(src, vendor, name, 'Controllers/DefaultController.js'), es6);

        //fs.writeFileSync(path.join(src,vendor,nodeName,'Controllers/DefaultControllerCJ.js'), commonJS);
        var data = {
            state: true,
            name: name,
            version: '1.0.0'
        }
        fs.writeFileSync(path.join(src, vendor, name, 'manifest.json'), JSON.stringify(data, null, 2))

    }
}


text:
def fixture_path(relative_path)
  main_spec_dir = File.dirname(__FILE__)
  fixture_dir   = File.join(main_spec_dir, relative_path)
end

#------------------------------------------------------------------------------
def generate(datafile, parser)
  tests = get_tests(datafile)

  if ENV['example']
    define_test(tests[ENV['example'].to_i - 1], parser, true)
  else
    tests.each do |t|
      define_test(t, parser)
    end
  end
end

#------------------------------------------------------------------------------
def get_tests(specfile)
  line_number    = 0
  start_line     = 0
  end_line       = 0
  example_number = 0
  markdown_lines = []
  html_lines     = []
  state          = 0  # 0 regular text, 1 markdown example, 2 html output
  headertext     = ''
  tests          = []
  header_re      = /#+ /
  filename       = File.basename(specfile)

  File.open(specfile) do |specf|
    specf.each_line do |line|
      line_number += 1
      if state == 0 && header_re =~ line
        headertext = line.gsub(header_re, '').strip
      end
      if line.strip == "."
        state = (state + 1) % 3
        if state == 0
          example_number += 1
          end_line = line_number
          tests << {
              markdown:   markdown_lines.join.gsub('→',"\t"),
              html:       html_lines.join,
              example:    example_number,
              start_line: start_line,
              end_line:   end_line,
              section:    headertext,
              filename:   filename}
          start_line     = 0
          markdown_lines = []
          html_lines     = []
        end
      elsif state == 1
        if start_line == 0
          start_line = line_number - 1
        end
        markdown_lines << line
      elsif state == 2
        html_lines << line
      end
    end
  end
  return tests
end

#------------------------------------------------------------------------------
def define_test(testcase, parser, debug_tokens = false)

  it "#{testcase[:filename]} #{testcase[:section]} (#{testcase[:example].to_s}/#{testcase[:start_line]}-#{testcase[:end_line]}) with markdown:\n#{testcase[:markdown]}" do
    if debug_tokens
      parser.parse(testcase[:markdown], { references: {} }).each {|token| pp token.to_json}
    end
    expect(parser.render(testcase[:markdown])).to eq testcase[:html]
  end

end


text:
//=====================================================================
//
//File:      $RCSfile: CoreUtil.java,v $
//Version:   $Revision: 1.13 $
//Modified:  $Date: 2012/06/21 02:38:52 $
//
//(c) Copyright 2004-2014 by Mentor Graphics Corp. All rights reserved.
//
//=====================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the
// License for the specific language governing permissions and limitations under
// the License.
//=====================================================================

package org.xtuml.bp.core.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;

import org.xtuml.bp.core.CorePlugin;
import org.xtuml.bp.core.Ooaofooa;
import org.xtuml.bp.core.Package_c;
import org.xtuml.bp.core.XtUMLNature;
import org.xtuml.bp.core.common.IPersistenceHierarchyMetaData;
import org.xtuml.bp.core.common.NonRootModelElement;
import org.xtuml.bp.core.common.PersistableModelComponent;
import org.xtuml.bp.core.common.PersistenceManager;

/**
 * Utility methods related to Core
 */
public class CoreUtil {
    public static boolean IsRunningHeadless = false;

    public static String getName(NonRootModelElement element) {
        String result = "";
        Class inputClass = element.getClass();
        Class[] type = new Class[0];
        Method getName = null;
        try {
            try {
                getName = inputClass.getMethod("getName", type); //$NON-NLS-1$
            } catch (NoSuchMethodException e) {
                // There is no accessor, try an explicit operation . . .
                getName = inputClass.getMethod("Get_name", type); //$NON-NLS-1$
            }
            Object[] args = new Object[0];
            result = (String) getName.invoke(element, args);
        } catch (Exception e) {

        }
        return result;
    }

    public static String getModelElementType(NonRootModelElement element) {
        IPersistenceHierarchyMetaData metaData = PersistenceManager
                .getHierarchyMetaData();
        return metaData.getComponentType(element);
    }

    /**
     * This is a delegate method for ui.canvas.GraphicsUtil#getCanvasEditorTitle
     * to remove cyclic dependencies
     */
    public static String getCanvasEditorTitle(NonRootModelElement element) {
        String title = null;
        Class graphicsUtilClass = null;
        Object graphicsUtilObj = null;
        try {
            Bundle ui_canvas = Platform
                    .getBundle("org.xtuml.bp.ui.canvas");//$NON-NLS-1$
            graphicsUtilClass = ui_canvas
                    .loadClass("org.xtuml.bp.ui.canvas.util.GraphicsUtil"); //$NON-NLS-1$
            graphicsUtilObj = graphicsUtilClass.newInstance();
        } catch (Exception cnf) {
            CorePlugin.logError("Problem accessing GraphicsUtil class ", cnf); //$NON-NLS-1$
            return title;
        }

        Class[] type;
        try {
            type = new Class[] { NonRootModelElement.class };

            Method getTitle = graphicsUtilClass.getMethod(
                    "getCanvasEditorTitle", type); //$NON-NLS-1$
            Object[] args = new Object[] { element };
            title = (String) getTitle.invoke(graphicsUtilObj, args);
        } catch (Exception e) {
            CorePlugin
                    .logError(
                            "Error invoking getCanvasEditorTitle(NRME) in GraphicsUtil  ", e); //$NON-NLS-1$
        }

        return title;
    }

    /**
     * This is a delegate method for ui.canvas.GraphicsUtil#getCanvasEditorPostTitle
     * to remove cyclic dependencies
     */
    public static String getCanvasEditorPostTitle(NonRootModelElement element, boolean checkElementToEdit) {
        String title = null;
        Class graphicsUtilClass = null;
        Object graphicsUtilObj = null;
        try {
            Bundle ui_canvas = Platform
                    .getBundle("org.xtuml.bp.ui.canvas");//$NON-NLS-1$
            graphicsUtilClass = ui_canvas
                    .loadClass("org.xtuml.bp.ui.canvas.util.GraphicsUtil"); //$NON-NLS-1$
            graphicsUtilObj = graphicsUtilClass.newInstance();
        } catch (Exception cnf) {
            CorePlugin.logError("Problem accessing GraphicsUtil class ", cnf); //$NON-NLS-1$
            return title;
        }

        Class[] type;
        try {
            type = new Class[] { NonRootModelElement.class, boolean.class };

            Method getTitle = graphicsUtilClass.getMethod(
                    "getCanvasEditorPostTitle", type); //$NON-NLS-1$
            Object[] args = new Object[] { element, checkElementToEdit };
            title = (String) getTitle.invoke(graphicsUtilObj, args);
        } catch (Exception e) {
            CorePlugin
                    .logError(
                            "Error invoking getCanvasEditorTitle(NRME) in GraphicsUtil  ", e); //$NON-NLS-1$
        }

        return title;
    }

    /**
     * A utility function that gets the canvas title and strips-off the
     * instance name returning just the diagram type.  This uses
     * getCanvasEditorPostTitle()
     *
     * @see getCanvasEditorPostTitle()
     * @return Diagram type string as defined in the canvas plugin.xml
     */
    public static String getDiagramTypeFromCanvasTitle(
			NonRootModelElement nrme, boolean checkElementToEdit) {
		String typeName = "";
		if (nrme != null) {
			String tempName = CoreUtil.getCanvasEditorPostTitle(nrme, true);
			if (tempName != null) {
				int firstColon = tempName.indexOf(':');
				if (firstColon > -1) {
					tempName = tempName.substring(firstColon+1);
				}
				typeName = tempName;
			}
		}
		return typeName.trim();
    }

    public static boolean isGraphicalRepresentable(NonRootModelElement element) {
        // we should use more accurate method to determins
        Class inputClass = element.getClass();
        Class[] type = new Class[0];
        Method get_ooa_id = null;

        try {
            get_ooa_id = inputClass.getMethod("Get_ooa_id", type); //$NON-NLS-1$
            Object[] args = new Object[0];
            Object id = get_ooa_id.invoke(element, args);
            if (id != null) {
                if (((Long) id).longValue() > 0) {
                    return true;
				}
            }
        } catch (Exception e) {
        }
        return false;
    }

    public static PersistableModelComponent getComponentOfElementInResize(NonRootModelElement element) {
        PersistableModelComponent comp = null;
        Class graphicsUtilClass = null;
        Object graphicsUtilObj = null;
        try {
            Bundle ui_canvas = Platform
                    .getBundle("org.xtuml.bp.ui.canvas");//$NON-NLS-1$
            graphicsUtilClass = ui_canvas
                    .loadClass("org.xtuml.bp.ui.canvas.util.GraphicsUtil"); //$NON-NLS-1$
            graphicsUtilObj = graphicsUtilClass.newInstance();
        } catch (Exception cnf) {
            CorePlugin.logError("Problem accessing GraphicsUtil class ", cnf); //$NON-NLS-1$
            return comp;
        }

        Class[] type;
        try {
            type = new Class[] { NonRootModelElement.class };

            Method getTitle = graphicsUtilClass.getMethod(
                    "getComponentOfElementInResize", type); //$NON-NLS-1$
            Object[] args = new Object[] { element };
            comp = (PersistableModelComponent) getTitle.invoke(graphicsUtilObj, args);
        } catch (Exception e) {
            CorePlugin
                    .logError(
                            "Error invoking getComponentOfElementInResize(NonRootModelElement) in GraphicsUtil  ", e); //$NON-NLS-1$
        }
        return comp;
    }

    public static boolean supportsPaste(Object target, String child, boolean checkCanPasteOperation) {
		String elementToPaste = child.replaceAll("_c", "").toLowerCase();
		boolean supportsPaste = hasMethod(target, "Paste" + elementToPaste, new Class[] {UUID.class}); //$NON-NLS-1$
		// the copy/cut methods use this to determine if a paste
		// operation exists, but they do not care if a Canpaste*
		// operation returns false as that is not an architectural
		// limitation
		if (supportsPaste && checkCanPasteOperation) {
			try {
				// See if there is a canPaste<ME> operation for this situation and if there is, call it and use it's
				// result to determine if the paste is allowed
				Method method = target.getClass().getMethod("Canpaste" + elementToPaste, new Class[] { }); //$NON-NLS-1$
				Object object = method.invoke(target, new Object[] {});
				supportsPaste = ((Boolean) object).booleanValue();
			} catch (Throwable err) {
				// Ignore
			}
		}
		return supportsPaste;
    }

    public static boolean supportsCopy(Object source, Object child) {
		if(source == null || child == null) return false;

		String simpleClassName = child.getClass().getSimpleName();
		String classPart = simpleClassName.substring(0, simpleClassName.length() - 2).toLowerCase();
		boolean canCopy = true;

		// Copy is allowed if there is a supporting paste for the
		// current destination, and if a canCopy* operation exists and
		// returns true
		try {
			Method method = source.getClass().getMethod("Cancopy" + classPart, new Class[] {UUID.class}); //$NON-NLS-1$
			Object object = method.invoke(source, new Object[] {((NonRootModelElement) child).Get_ooa_id()});
			canCopy = ((Boolean) object).booleanValue();
			return canCopy;
		} catch (SecurityException e) {
			// Allow this
		} catch (NoSuchMethodException e) {
			// Allow this
		} catch (IllegalArgumentException e) {
			canCopy = false;
		} catch (IllegalAccessException e) {
			canCopy = false;
		} catch (InvocationTargetException e) {
			canCopy = false;
		}
		// check for a paste operation (if we got here then
		// a paste* operation may exist but a canCopy* did
		// not
		return supportsPaste(source, child.getClass().getSimpleName(), false);
    }

	public static boolean hasMethod(Object target, String method,
			Class<?>[] args) {
		  try {
			    // execute the reflection call
		        target.getClass().getMethod(method, args);
		  } catch (NoSuchMethodException e) {
			    // if there was a no such method exception
			    // return false
			  	return false;
		  }
		  // otherwise return true
		  return true;
	}

	public static void loadWorkspace(IProgressMonitor monitor) throws CoreException {
		// this will cause initialization if necessary
		PersistenceManager.getDefaultInstance();
		// gather all system components, and load
		// the children
		IProject[] projects = getProjectsInWorkspace();
		monitor.subTask("Loading workspace...");
		for(int i = 0; i < projects.length; i++) {
			PersistableModelComponent rootComponent = PersistenceManager
					.getRootComponent(projects[i]);
			loadComponentAndChildren(monitor, rootComponent);
			if (monitor.isCanceled()) {
				// user cancelled, return
				return;
			}
		}
		monitor.done();
	}

	private static void loadComponentAndChildren(IProgressMonitor monitor,
			PersistableModelComponent component) {
		if(component == null) {
			monitor.worked(1);
			return;
		}
		if (monitor.isCanceled()) {
			return;
		}
		if (!component.isLoaded()) {
			try {
				monitor.subTask("Loading file: "
						+ component.getFile().getFullPath());
				component.load(new NullProgressMonitor());
			} catch (CoreException e) {
				CorePlugin.logError("", e);
			}
		}
		monitor.worked(1);
		// now get the children and load
		Collection<?> children = component.getChildren();
		Iterator<?> iterator = children.iterator();
		while (iterator.hasNext()) {
			PersistableModelComponent child = (PersistableModelComponent) iterator
					.next();
			loadComponentAndChildren(monitor, child);
		}
	}

	public static IProject[] getProjectsInWorkspace() throws CoreException {
		List<IProject> projectList = new ArrayList<IProject>();
		IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
			.getProjects();
		for (int i = 0; i < projects.length; i++) {
			if (projects[i].isOpen() && projects[i].exists()
					&& XtUMLNature.hasNature(projects[i]) ) {
				projectList.add(projects[i]);
			}
		}
		return projectList.toArray(new IProject[projectList.size()]);
	}

	public static int getChildrenCountOfProjects(IProject[] projects) throws CoreException {
		int count = 0;
		for(int i = 0; i < projects.length; i++) {
			if (projects[i].isOpen() && projects[i].exists()
					&& XtUMLNature.hasNature(projects[i]) ) {
				// get the models folder, and count the files under it
				// that end in the model extension
				IFolder models = projects[i].getFolder(Ooaofooa.MODELS_DIRNAME);
				if(models.exists()) {
					count += getChildrenCountOfFolder(models);
				}
			}
		}
		return count;
	}

	private static int getChildrenCountOfFolder(IFolder folder) throws CoreException {
		// get the models folder, and count the files under it
		// that end in the model extension
		int count = 0;
		IResource[] children = folder.members();
		for(int i = 0; i < children.length; i++) {
			if(children[i] instanceof IFile) {
				count++;
			} else {
				count = count + getChildrenCountOfFolder((IFolder) children[i]);
			}
		}
		return count;
	}

}


text:
'use strict';

describe('myEllipsis', function() {

  beforeEach(module('cdap-ui.filters'));

  var ellipsis;

  beforeEach(inject(function(_$filter_) {
    ellipsis = _$filter_('myEllipsis');

  }));

  it('should truncate string longer that limit to limit plus ellipsis', function() {

    var input = 'string longer than ten characters';
    var limit = 10;

    var result = ellipsis(input, limit);

    expect(result.length).toBe(limit + 1);
    expect(result).toBe(input.substr(0, limit-1) + '\u2026 ');

  });

  it('should not truncate string with length less than limit', function() {

    var input = 'short';
    var limit = 10;

    var result = ellipsis(input, limit);

    expect(result.length).toBe(input.length);
    expect(result).toEqual(input);

  });

  it('should return input when input is not type string', function() {

    var input = 12;
    expect(ellipsis(input, 10)).toEqual(input);

    input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    expect(ellipsis(input, 5)).toEqual(input);

    input = {
      1: 1,
      2: 2,
      3: 3,
      4: 4,
      5: 5
    };
    expect(ellipsis(input, 3)).toEqual(input);

  });

  it('should return null when input is null', function() {

    var input = null;
    expect(ellipsis(input, 10)).toEqual(null);

  });

});