text:
(function( jQuery ) {

var jsc = jQuery.now(),
	rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
	rselectTextarea = /^(?:select|textarea)/i,
	rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
	rnoContent = /^(?:GET|HEAD|DELETE)$/,
	rbracket = /\[\]$/,
	jsre = /\=\?(&|$)/,
	rquery = /\?/,
	rts = /([?&])_=[^&]*/,
	rurl = /^(\w+:)?\/\/([^\/?#]+)/,
	r20 = /%20/g,
	rhash = /#.*$/,

	// Keep a copy of the old load method
	_load = jQuery.fn.load;

jQuery.fn.extend({
	load: function( url, params, callback ) {
		if ( typeof url !== "string" && _load ) {
			return _load.apply( this, arguments );

		// Don't do a request if no elements are being requested
		} else if ( !this.length ) {
			return this;
		}

		var off = url.indexOf(" ");
		if ( off >= 0 ) {
			var selector = url.slice(off, url.length);
			url = url.slice(0, off);
		}

		// Default to a GET request
		var type = "GET";

		// If the second parameter was provided
		if ( params ) {
			// If it's a function
			if ( jQuery.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = null;

			// Otherwise, build a param string
			} else if ( typeof params === "object" ) {
				params = jQuery.param( params, jQuery.ajaxSettings.traditional );
				type = "POST";
			}
		}

		var self = this;

		// Request the remote document
		jQuery.ajax({
			url: url,
			type: type,
			dataType: "html",
			data: params,
			complete: function( res, status ) {
				// If successful, inject the HTML into all the matched elements
				if ( status === "success" || status === "notmodified" ) {
					// See if a selector was specified
					self.html( selector ?
						// Create a dummy div to hold the results
						jQuery("<div>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(res.responseText.replace(rscript, ""))

							// Locate the specified elements
							.find(selector) :

						// If not, just inject the full result
						res.responseText );
				}

				if ( callback ) {
					self.each( callback, [res.responseText, status, res] );
				}
			}
		});

		return this;
	},

	serialize: function() {
		return jQuery.param(this.serializeArray());
	},

	serializeArray: function() {
		return this.map(function() {
			return this.elements ? jQuery.makeArray(this.elements) : this;
		})
		.filter(function() {
			return this.name && !this.disabled &&
				(this.checked || rselectTextarea.test(this.nodeName) ||
					rinput.test(this.type));
		})
		.map(function( i, elem ) {
			var val = jQuery(this).val();

			return val == null ?
				null :
				jQuery.isArray(val) ?
					jQuery.map( val, function( val, i ) {
						return { name: elem.name, value: val };
					}) :
					{ name: elem.name, value: val };
		}).get();
	}
});

// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
	jQuery.fn[o] = function( f ) {
		return this.bind(o, f);
	};
});

jQuery.extend({
	get: function( url, data, callback, type ) {
		// shift arguments if data argument was omited
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = null;
		}

		return jQuery.ajax({
			type: "GET",
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	},

	getScript: function( url, callback ) {
		return jQuery.get(url, null, callback, "script");
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get(url, data, callback, "json");
	},

	post: function( url, data, callback, type ) {
		// shift arguments if data argument was omited
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = {};
		}

		return jQuery.ajax({
			type: "POST",
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	},

	ajaxSetup: function( settings ) {
		jQuery.extend( jQuery.ajaxSettings, settings );
	},

	ajaxSettings: {
		url: location.href,
		global: true,
		type: "GET",
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		/*
		timeout: 0,
		data: null,
		username: null,
		password: null,
		traditional: false,
		*/
		// This function can be overriden by calling jQuery.ajaxSetup
		xhr: function() {
			return new window.XMLHttpRequest();
		},
		accepts: {
			xml: "application/xml, text/xml",
			html: "text/html",
			script: "text/javascript, application/javascript",
			json: "application/json, text/javascript",
			text: "text/plain",
			_default: "*/*"
		}
	},

	ajax: function( origSettings ) {
		var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
			jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type);

		s.url = s.url.replace( rhash, "" );

		// Use original (not extended) context object if it was provided
		s.context = origSettings && origSettings.context != null ? origSettings.context : s;

		// convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Handle JSONP Parameter Callbacks
		if ( s.dataType === "jsonp" ) {
			if ( type === "GET" ) {
				if ( !jsre.test( s.url ) ) {
					s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
				}
			} else if ( !s.data || !jsre.test(s.data) ) {
				s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
			}
			s.dataType = "json";
		}

		// Build temporary JSONP function
		if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
			jsonp = s.jsonpCallback || ("jsonp" + jsc++);

			// Replace the =? sequence both in the query string and the data
			if ( s.data ) {
				s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
			}

			s.url = s.url.replace(jsre, "=" + jsonp + "$1");

			// We need to make sure
			// that a JSONP style response is executed properly
			s.dataType = "script";

			// Handle JSONP-style loading
			var customJsonp = window[ jsonp ];

			window[ jsonp ] = function( tmp ) {
				data = tmp;
				jQuery.ajax.handleSuccess( s, xhr, status, data );
				jQuery.ajax.handleComplete( s, xhr, status, data );

				if ( jQuery.isFunction( customJsonp ) ) {
					customJsonp( tmp );

				} else {
					// Garbage collect
					window[ jsonp ] = undefined;

					try {
						delete window[ jsonp ];
					} catch( jsonpError ) {}
				}

				if ( head ) {
					head.removeChild( script );
				}
			};
		}

		if ( s.dataType === "script" && s.cache === null ) {
			s.cache = false;
		}

		if ( s.cache === false && type === "GET" ) {
			var ts = jQuery.now();

			// try replacing _= if it is there
			var ret = s.url.replace(rts, "$1_=" + ts);

			// if nothing was replaced, add timestamp to the end
			s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
		}

		// If data is available, append data to url for get requests
		if ( s.data && type === "GET" ) {
			s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
		}

		// Watch for a new set of requests
		if ( s.global && jQuery.ajax.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}

		// Matches an absolute URL, and saves the domain
		var parts = rurl.exec( s.url ),
			remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);

		// If we're requesting a remote document
		// and trying to load JSON or Script with a GET
		if ( s.dataType === "script" && type === "GET" && remote ) {
			var head = document.getElementsByTagName("head")[0] || document.documentElement;
			var script = document.createElement("script");
			if ( s.scriptCharset ) {
				script.charset = s.scriptCharset;
			}
			script.src = s.url;

			// Handle Script loading
			if ( !jsonp ) {
				var done = false;

				// Attach handlers for all browsers
				script.onload = script.onreadystatechange = function() {
					if ( !done && (!this.readyState ||
							this.readyState === "loaded" || this.readyState === "complete") ) {
						done = true;
						jQuery.ajax.handleSuccess( s, xhr, status, data );
						jQuery.ajax.handleComplete( s, xhr, status, data );

						// Handle memory leak in IE
						script.onload = script.onreadystatechange = null;
						if ( head && script.parentNode ) {
							head.removeChild( script );
						}
					}
				};
			}

			// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
			// This arises when a base node is used (#2709 and #4378).
			head.insertBefore( script, head.firstChild );

			// We handle everything using the script element injection
			return undefined;
		}

		var requestDone = false;

		// Create the request object
		var xhr = s.xhr();

		if ( !xhr ) {
			return;
		}

		// Open the socket
		// Passing null username, generates a login popup on Opera (#2865)
		if ( s.username ) {
			xhr.open(type, s.url, s.async, s.username, s.password);
		} else {
			xhr.open(type, s.url, s.async);
		}

		// Need an extra try/catch for cross domain requests in Firefox 3
		try {
			// Set content-type if data specified and content-body is valid for this type
			if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) {
				xhr.setRequestHeader("Content-Type", s.contentType);
			}

			// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
			if ( s.ifModified ) {
				if ( jQuery.lastModified[s.url] ) {
					xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
				}

				if ( jQuery.ajax.etag[s.url] ) {
					xhr.setRequestHeader("If-None-Match", jQuery.ajax.etag[s.url]);
				}
			}

			// Set header so the called script knows that it's an XMLHttpRequest
			// Only send the header if it's not a remote XHR
			if ( !remote ) {
				xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
			}

			// Set the Accepts header for the server, depending on the dataType
			xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
				s.accepts[ s.dataType ] + ", */*; q=0.01" :
				s.accepts._default );
		} catch( headerError ) {}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
			// Handle the global AJAX counter
			if ( s.global && jQuery.ajax.active-- === 1 ) {
				jQuery.event.trigger( "ajaxStop" );
			}

			// close opended socket
			xhr.abort();
			return false;
		}

		if ( s.global ) {
			jQuery.ajax.triggerGlobal( s, "ajaxSend", [xhr, s] );
		}

		// Wait for a response to come back
		var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
			// The request was aborted
			if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
				// Opera doesn't call onreadystatechange before this point
				// so we simulate the call
				if ( !requestDone ) {
					jQuery.ajax.handleComplete( s, xhr, status, data );
				}

				requestDone = true;
				if ( xhr ) {
					xhr.onreadystatechange = jQuery.noop;
				}

			// The transfer is complete and the data is available, or the request timed out
			} else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
				requestDone = true;
				xhr.onreadystatechange = jQuery.noop;

				status = isTimeout === "timeout" ?
					"timeout" :
					!jQuery.ajax.httpSuccess( xhr ) ?
						"error" :
						s.ifModified && jQuery.ajax.httpNotModified( xhr, s.url ) ?
							"notmodified" :
							"success";

				var errMsg;

				if ( status === "success" ) {
					// Watch for, and catch, XML document parse errors
					try {
						// process the data (runs the xml through httpData regardless of callback)
						data = jQuery.ajax.httpData( xhr, s.dataType, s );
					} catch( parserError ) {
						status = "parsererror";
						errMsg = parserError;
					}
				}

				// Make sure that the request was successful or notmodified
				if ( status === "success" || status === "notmodified" ) {
					// JSONP handles its own success callback
					if ( !jsonp ) {
						jQuery.ajax.handleSuccess( s, xhr, status, data );
					}
				} else {
					jQuery.ajax.handleError( s, xhr, status, errMsg );
				}

				// Fire the complete handlers
				if ( !jsonp ) {
					jQuery.ajax.handleComplete( s, xhr, status, data );
				}

				if ( isTimeout === "timeout" ) {
					xhr.abort();
				}

				// Stop memory leaks
				if ( s.async ) {
					xhr = null;
				}
			}
		};

		// Override the abort handler, if we can (IE doesn't allow it, but that's OK)
		// Opera doesn't fire onreadystatechange at all on abort
		try {
			var oldAbort = xhr.abort;
			xhr.abort = function() {
				if ( xhr ) {
					oldAbort.call( xhr );
				}

				onreadystatechange( "abort" );
			};
		} catch( abortError ) {}

		// Timeout checker
		if ( s.async && s.timeout > 0 ) {
			setTimeout(function() {
				// Check to see if the request is still happening
				if ( xhr && !requestDone ) {
					onreadystatechange( "timeout" );
				}
			}, s.timeout);
		}

		// Send the data
		try {
			xhr.send( noContent || s.data == null ? null : s.data );

		} catch( sendError ) {
			jQuery.ajax.handleError( s, xhr, null, sendError );

			// Fire the complete handlers
			jQuery.ajax.handleComplete( s, xhr, status, data );
		}

		// firefox 1.5 doesn't fire statechange for sync requests
		if ( !s.async ) {
			onreadystatechange();
		}

		// return XMLHttpRequest to allow aborting the request etc.
		return xhr;
	},

	// Serialize an array of form elements or a set of
	// key/values into a query string
	param: function( a, traditional ) {
		var s = [], add = function( key, value ) {
			// If value is a function, invoke it and return its value
			value = jQuery.isFunction(value) ? value() : value;
			s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
		};

		// Set traditional to true for jQuery <= 1.3.2 behavior.
		if ( traditional === undefined ) {
			traditional = jQuery.ajaxSettings.traditional;
		}

		// If an array was passed in, assume that it is an array of form elements.
		if ( jQuery.isArray(a) || a.jquery ) {
			// Serialize the form elements
			jQuery.each( a, function() {
				add( this.name, this.value );
			});

		} else {
			// If traditional, encode the "old" way (the way 1.3.2 or older
			// did it), otherwise encode params recursively.
			for ( var prefix in a ) {
				buildParams( prefix, a[prefix], traditional, add );
			}
		}

		// Return the resulting serialization
		return s.join("&").replace(r20, "+");
	}
});

function buildParams( prefix, obj, traditional, add ) {
	if ( jQuery.isArray(obj) && obj.length ) {
		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {
				// Treat each array item as a scalar.
				add( prefix, v );

			} else {
				// If array item is non-scalar (array or object), encode its
				// numeric index to resolve deserialization ambiguity issues.
				// Note that rack (as of 1.0.0) can't currently deserialize
				// nested arrays properly, and attempting to do so may cause
				// a server error. Possible fixes are to modify rack's
				// deserialization algorithm or to provide an option or flag
				// to force array serialization to be shallow.
				buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
			}
		});

	} else if ( !traditional && obj != null && typeof obj === "object" ) {
		if ( jQuery.isEmptyObject( obj ) ) {
			add( prefix, "" );

		// Serialize object item.
		} else {
			jQuery.each( obj, function( k, v ) {
				buildParams( prefix + "[" + k + "]", v, traditional, add );
			});
		}

	} else {
		// Serialize scalar item.
		add( prefix, obj );
	}
}

jQuery.extend( jQuery.ajax, {

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {},

	handleError: function( s, xhr, status, e ) {
		// If a local callback was specified, fire it
		if ( s.error ) {
			s.error.call( s.context, xhr, status, e );
		}

		// Fire the global callback
		if ( s.global ) {
			jQuery.ajax.triggerGlobal( s, "ajaxError", [xhr, s, e] );
		}
	},

	handleSuccess: function( s, xhr, status, data ) {
		// If a local callback was specified, fire it and pass it the data
		if ( s.success ) {
			s.success.call( s.context, data, status, xhr );
		}

		// Fire the global callback
		if ( s.global ) {
			jQuery.ajax.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
		}
	},

	handleComplete: function( s, xhr, status ) {
		// Process result
		if ( s.complete ) {
			s.complete.call( s.context, xhr, status );
		}

		// The request was completed
		if ( s.global ) {
			jQuery.ajax.triggerGlobal( s, "ajaxComplete", [xhr, s] );
		}

		// Handle the global AJAX counter
		if ( s.global && jQuery.ajax.active-- === 1 ) {
			jQuery.event.trigger( "ajaxStop" );
		}
	},

	triggerGlobal: function( s, type, args ) {
		(s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
	},

	// Determines if an XMLHttpRequest was successful or not
	httpSuccess: function( xhr ) {
		try {
			// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
			return !xhr.status && location.protocol === "file:" ||
				xhr.status >= 200 && xhr.status < 300 ||
				xhr.status === 304 || xhr.status === 1223;
		} catch(e) {}

		return false;
	},

	// Determines if an XMLHttpRequest returns NotModified
	httpNotModified: function( xhr, url ) {
		var lastModified = xhr.getResponseHeader("Last-Modified"),
			etag = xhr.getResponseHeader("Etag");

		if ( lastModified ) {
			jQuery.ajax.lastModified[url] = lastModified;
		}

		if ( etag ) {
			jQuery.ajax.etag[url] = etag;
		}

		return xhr.status === 304;
	},

	httpData: function( xhr, type, s ) {
		var ct = xhr.getResponseHeader("content-type") || "",
			xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
			data = xml ? xhr.responseXML : xhr.responseText;

		if ( xml && data.documentElement.nodeName === "parsererror" ) {
			jQuery.error( "parsererror" );
		}

		// Allow a pre-filtering function to sanitize the response
		// s is checked to keep backwards compatibility
		if ( s && s.dataFilter ) {
			data = s.dataFilter( data, type );
		}

		// The filter can actually parse the response
		if ( typeof data === "string" ) {
			// Get the JavaScript object, if JSON is used.
			if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
				data = jQuery.parseJSON( data );

			// If the type is "script", eval it in global context
			} else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
				jQuery.globalEval( data );
			}
		}

		return data;
	}

});

/*
 * Create the request object; Microsoft failed to properly
 * implement the XMLHttpRequest in IE7 (can't request local files),
 * so we use the ActiveXObject when it is available
 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
 * we need a fallback.
 */
if ( window.ActiveXObject ) {
	jQuery.ajaxSettings.xhr = function() {
		if ( window.location.protocol !== "file:" ) {
			try {
				return new window.XMLHttpRequest();
			} catch(e) {}
		}

		try {
			return new window.ActiveXObject("Microsoft.XMLHTTP");
		} catch(e) {}
	};
}

// Does this browser support XHR requests?
jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();

// For backwards compatibility
jQuery.extend( jQuery.ajax );

})( jQuery );


text:
package com.vaadin.tests.components.table;

import java.io.IOException;

import org.junit.Test;

import com.vaadin.testbench.elements.TableElement;
import com.vaadin.tests.tb3.MultiBrowserTest;

public class TableScrollsOnSelectionTest extends MultiBrowserTest {

    @Test
    public void tableIsNotScrolledOnSelect() throws IOException {
        openTestURL();

        TableElement table = $(TableElement.class).first();

        scrollTable(table, 80, 79);

        table.getCell(79, 0).click();

        compareScreen("scrolled-down");
    }
}

redpajama_set_name: RedPajamaGithub


text:
using Magellan.Framework;
using NUnit.Framework;

namespace Magellan.Tests.Framework
{
    [TestFixture]
    public class DialogResultTests
    {
        [Test]
        public void ShouldAllowNullDialogName()
        {
            new DialogResult(null, null, new ViewEngineCollection());
        }

        [Test]
        public void ShouldSetViewTypeToDialog()
        {
            var result = new DialogResult("MyWindow", null, new ViewEngineCollection());
            Assert.AreEqual("Dialog", result.Options["ViewType"]);
        }

        [Test]
        public void ShouldSetModel()
        {
            var result = new DialogResult("MyWindow", "Hello", new ViewEngineCollection());
            Assert.AreEqual("Hello", result.Options["Model"]);
        }
    }
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of the RollerworksSearch package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Search\Extension\Core\ChoiceList;

use Rollerworks\Component\Search\Extension\Core\ChoiceList\Loader\ChoiceLoader;

/**
 * A choice list that loads its choices lazily.
 *
 * The choices are fetched using a {@link ChoiceLoaderInterface} instance.
 * If only {@link getChoicesForValues()} or {@link getValuesForChoices()} is
 * called, the choice list is only loaded partially for improved performance.
 *
 * Once {@link getChoices()} or {@link getValues()} is called, the list is
 * loaded fully.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
final class LazyChoiceList implements ChoiceList
{
    /**
     * @var ChoiceLoader
     */
    private $loader;

    /**
     * The callable creating string values for each choice.
     *
     * If null, choices are simply cast to strings.
     *
     * @var callable|null
     */
    private $value;

    /**
     * Optionally, a callable can be passed for generating the choice values.
     * The callable receives the choice as first and the array key as the second
     * argument.
     *
     * @param ChoiceLoader  $loader The choice loader
     * @param callable|null $value  The callable generating the choice
     *                              values
     */
    public function __construct(ChoiceLoader $loader, callable $value = null)
    {
        $this->loader = $loader;
        $this->value = $value;
    }

    public function getChoices(): array
    {
        return $this->loader->loadChoiceList($this->value)->getChoices();
    }

    public function getValues(): array
    {
        return $this->loader->loadChoiceList($this->value)->getValues();
    }

    public function getStructuredValues(): array
    {
        return $this->loader->loadChoiceList($this->value)->getStructuredValues();
    }

    public function getOriginalKeys(): array
    {
        return $this->loader->loadChoiceList($this->value)->getOriginalKeys();
    }

    public function getChoicesForValues(array $values): array
    {
        return $this->loader->loadChoicesForValues($values, $this->value);
    }

    public function getValuesForChoices(array $choices): array
    {
        return $this->loader->loadValuesForChoices($choices, $this->value);
    }

    public function isValuesConstant(): bool
    {
        return $this->loader->isValuesConstant();
    }
}


text:
namespace klib {
	class string {
		public:
			string( );
			string( const char *s );
			~string( );

			string &assign( const char *s );
			string &assign( const string &str );

			string &operator= (const string &str);
			string &operator= (const char *s );
			string &operator= (char c);

			const char *c_str( ) const;

		private:
			size_t size;
			char *buf;
	};

} // namespace klib;

#endif


text:
/**
 * @author Dmitry Batkovich <dmitry.batkovich@jetbrains.com>
 */
public class TestIndex {
}

class Some {
  public void m() {
    MethodJavaDocHelper h = new MethodJavaDocHelper();
    h.getTag();
  }
}

class Some1 {
  public void m() {
    MethodJavaDocHelper h = new MethodJavaDocHelper();
    h.getTag();
  }
}

class Some2 {
  public void m() {
    MethodJavaDocHelper h = new MethodJavaDocHelper();
    h.getTag();
  }
}

class Some3 {
  public void m() {
    MethodJavaDocHelper h = new MethodJavaDocHelper();
    h.getTag();
  }
}

class Some4 {
  public void m() {
    MethodJavaDocHelper h = new MethodJavaDocHelper();
    h.getTag();
  }
}

class Some5 {
  public void m() {
    MethodJavaDocHelper h = new MethodJavaDocHelper();
     h.getTag();
  }
}

interface PsiElement {

}

class MethodJavaDocHelper {
  public PsiElement getTag() {
    return null;
  }
}


text:
package com.koushikdutta.async;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.koushikdutta.async.callback.CompletedCallback;

public class ZipDataSink extends FilteredDataSink {
    public ZipDataSink(DataSink sink) {
        super(sink);
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ZipOutputStream zop = new ZipOutputStream(bout);

    public void putNextEntry(ZipEntry ze) throws IOException {
        zop.putNextEntry(ze);
    }

    public void closeEntry() throws IOException {
        zop.closeEntry();
    }

    protected void report(Exception e) {
        CompletedCallback closed = getClosedCallback();
        if (closed != null)
            closed.onCompleted(e);
    }

    @Override
    public void end() {
        try {
            zop.close();
        }
        catch (IOException e) {
            report(e);
            return;
        }
        setMaxBuffer(Integer.MAX_VALUE);
        write(new ByteBufferList());
        super.end();
    }

    @Override
    public ByteBufferList filter(ByteBufferList bb) {
        try {
            if (bb != null) {
                while (bb.size() > 0) {
                    ByteBuffer b = bb.remove();
                    ByteBufferList.writeOutputStream(zop, b);
                    ByteBufferList.reclaim(b);
                }
            }
            ByteBufferList ret = new ByteBufferList(bout.toByteArray());
            bout.reset();
            return ret;
        }
        catch (IOException e) {
            report(e);
            return null;
        }
        finally {
            if (bb != null)
                bb.recycle();
        }
    }
}


text:
import { predicate, Operator } from "../common/types";
import { Enumerable } from "../enumerable_";
import { wrapInIterable, wrapInThunk } from "../common/wrap";

function _cast<TResult>(source: Iterable<any>, type: Function) {
    return wrapInIterable(function* () {
        for (var item of source) {
            if (item instanceof type) {
                yield <TResult>item;
            }
            else {
                throw TypeError(`An element in the sequence cannot be cast to type '${type.name}'.`);
            }
        }
    });
}

export function cast<TResult>(source: Iterable<any>, type: Function): Iterable<TResult>;
export function cast<TResult>(type: Function): Operator<any, TResult>;
export function cast() {
    return wrapInThunk(arguments, _cast);
}

declare module '../enumerable_' {
    interface Enumerable<T> {
        cast<TResult>(type: Function): Enumerable<TResult>;
    }
}
Enumerable.prototype.cast = function <T, TResult>(this: Enumerable<T>, type: Function) {
    return new Enumerable<TResult>(_cast<TResult>(this, type));
};


text:
layout: post
comments: true
author: zq
title: It s all Text 重生
description: ~ 大妈笔记,每周不一定
categories: Log
tags: scm tools logging
---

# 难以割舍的扩展: It's all text

但是, 参考: [嫑升级 FireFox 到 56 以上](https://du.101.camp/2017-11/ff-no-upgrade/)

![11568](https://addons.cdn.mozilla.net/user-media/previews/thumbs/11/11568.png?modified=1530208138)

为了继续使用这个扩展, 禁止了升级,

...

<!--more-->

但是,从个月开始, github 宣布不在支持这种低版本的 FireFox, 几乎立即的,
在 FF 56 中, gh 各种不对劲儿了...

## 分析

因为用心使用 FireFox 十多年, 早已将 FF 的扩展组合到形成了肌肉记忆,
而升级速度地球第一的 Chrome 其扩展生态远远没有 FF 自在,
而且核心的一组扩展, 用8年也没找到合适的相似插件.

但是, github 又是另外一个强依赖环境, 也同样配置了不少习惯响应,
现在, 官方不支持这个版本的 FireFox, 而主要浏览器环境又无法脱离 FF.

只能将 github 的使用场景从 FF 中迁移到 Chrome 中,

唯一一个问题就是:

- `It's all text` 可以指定任何一个外部编辑器
    + 用快捷键召唤起来, 编辑指定的 textare 内容
    + 以免在 网页中缺少各种现代编辑器的支持.
- 必须在 Chrome 中寻求一个对等的扩展

## 搜索

- [It's All Text for Chrome? \- Super User](https://superuser.com/questions/261689/its-all-text-for-chrome)
- [firefox \- Edit any text input shown by a browser \(mostly Chrome\) with Emacs \- Super User](https://superuser.com/questions/488348/edit-any-text-input-shown-by-a-browser-mostly-chrome-with-emacs)
- [Is there a method for making Google Chrome open textareas in vim? \- Unix & Linux Stack Exchange](https://unix.stackexchange.com/questions/99466/is-there-a-method-for-making-google-chrome-open-textareas-in-vim)
- [Editing Content with a Text Editor \- MariaDB Knowledge Base](https://mariadb.com/kb/en/meta/editing-content-with-a-text-editor/)
- [Use Atom to edit in Chrome \| Hacker News](https://news.ycombinator.com/item?id=11022356)
- ["Edit with Emacs" Chrome extension](http://psung.blogspot.com/2010/01/edit-with-emacs-chrome-extension.html)
- [GhostText / It's All Text\! \- Edit text area in standalone text editor app \- Legacy \(Muon\) / Extension Requests \- Brave Community](https://community.brave.com/t/ghosttext-its-all-text-edit-text-area-in-standalone-text-editor-app/10809)
- [GhostText as a Chrome alternative to It's All Text for Firefox · Issue \#25 · GhostText/GhostText](https://github.com/GhostText/GhostText/issues/25)
- ...

果然, 有相同问题的人是大大的有...

而且当然都进行了解决:

- windows only: [Text Editor Anywhere](http://www.listary.com/text-editor-anywhere)
- 特殊编辑器支持的:
    + [Edit in Emacs](https://github.com/stsquad/emacs_chrome)
    + [TextAid \- Chrome 网上应用店](https://chrome.google.com/webstore/detail/textaid/ppoadiihggafnhokfkpphojggcdigllp) -> Vim
    + [danhper/atomic\-chrome: Edit Chrome textareas in Atom](https://github.com/danhper/atomic-chrome)
- 通用编辑器支持的:
    + [Keyboard Maestro](http://rocketink.net/2013/05/quickcursor-keyboard-maestro.html)
    + [Alfred](http://www.packal.org/workflow/edit-quickcursor-alternative)
    + [GhostText/GhostText: 👻 Use your text editor to write in your browser\. Everything you type in the editor will be instantly updated in the browser \(and vice versa\)\.](https://github.com/GhostText/GhostText)
    + ...

## 方案
> 快速尝试, 果断使用:

![gt_banner](https://raw.githubusercontent.com/GhostText/GhostText/master/promo/gt_banner.png)

效果:

![demo](https://github.com/GhostText/GhostText/raw/master/promo/demo.gif)

支持编辑器也广泛:

- [Sublime Text extension](https://sublime.wbond.net/packages/GhostText)
- [Atom package](https://github.com/GhostText/GhostText-for-Atom)
- [VS Code extension](https://marketplace.visualstudio.com/items?itemName=tokoph.ghosttext)
- [Vim script](https://github.com/falstro/ghost-text-vim)
- [Neovim plugin](https://github.com/raghur/vim-ghost)
- [Emacs package](https://melpa.org/#/atomic-chrome)
- ...

同时也兼容主要浏览器:

- [Chrome extension](https://chrome.google.com/webstore/detail/ghosttext/godiecgffnchndlihlpaajjcplehddca)
- [Firefox add\-on](https://addons.mozilla.org/en-US/firefox/addon/ghosttext/)
- [opera](https://addons.opera.com/en/extensions/details/download-chrome-extension-9/)

使用和 `It's all text` 有点不同:

- 不是通过快捷键
- 而是先进入对应 TextArea
- 然后点击扩展图标:
    + 启动一个 websocket 服务
    + 端口是 `:4001`
    + 并自动打开有对应扩展呼应的编辑器
- 到编辑器中自然编辑:
    + 后台自动同步编辑内容到网页中
- 以上

> 综上当前浏览器使用状态变成:

- FireFox 56 作为主浏览器, 进行主要的浏览和信息管理
- Chrome 进行翻越和 gmail
- Safari 作为调试器, 配合进行各种了 web app 前端检验环境, 以及云盘等需要口令安全记忆的网站

### ps:

    Package Control Messages
    ========================

    GhostText
    ---------

    GhostText for Sublime Text
    ==========================

    We put a lot of effort to bring you GhostText, an updated experience to write in the browser with Sublime Text.

    Don't forget to install the Chrome extension:
    https://chrome.google.com/webstore/detail/ghosttext/godiecgffnchndlihlpaajjcplehddca

    Or the Firefox add-on:
    https://addons.mozilla.org/de/firefox/addon/ghosttext-for-firefox/

    Usage
    -----

    In Chrome or Firefox, when you're in a page with a text field (<textarea>, content editable element, code mirror or ACE editor), click the GhostText button in the upper-right corner to open up Sublime Text. Everything you type in the editor will be instantly updated in the browser (and vice versa).

    To close the link, either close the tab in Sublime Text or click on the GhostText button again.

    For more specific instructions, read this: https://github.com/Cacodaimon/GhostText-for-SublimeText/blob/master/README.md

## 是也乎

- 181127 嗯哼到了...
- 181001 第N次尝试
- 171122 起念


text:
FOUNDATION_EXPORT double Pods_MmineUITestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_MmineUITestsVersionString[];


text:
/* eslint-disable no-console */
/**
 * Logging level that Excalibur will tag
 */
export enum LogLevel {
  Debug,
  Info,
  Warn,
  Error,
  Fatal
}

/**
 * Static singleton that represents the logging facility for Excalibur.
 * Excalibur comes built-in with a [[ConsoleAppender]] and [[ScreenAppender]].
 * Derive from [[Appender]] to create your own logging appenders.
 */
export class Logger {
  private static _INSTANCE: Logger = null;
  private _appenders: Appender[] = [];

  constructor() {
    if (Logger._INSTANCE) {
      throw new Error('Logger is a singleton');
    }
    Logger._INSTANCE = this;
    // Default console appender
    Logger._INSTANCE.addAppender(new ConsoleAppender());
    return Logger._INSTANCE;
  }

  /**
   * Gets or sets the default logging level. Excalibur will only log
   * messages if equal to or above this level. Default: [[LogLevel.Info]]
   */
  public defaultLevel: LogLevel = LogLevel.Info;

  /**
   * Gets the current static instance of Logger
   */
  public static getInstance(): Logger {
    if (Logger._INSTANCE == null) {
      Logger._INSTANCE = new Logger();
    }
    return Logger._INSTANCE;
  }

  /**
   * Adds a new [[Appender]] to the list of appenders to write to
   */
  public addAppender(appender: Appender): void {
    this._appenders.push(appender);
  }

  /**
   * Clears all appenders from the logger
   */
  public clearAppenders(): void {
    this._appenders.length = 0;
  }

  /**
   * Logs a message at a given LogLevel
   * @param level  The LogLevel`to log the message at
   * @param args   An array of arguments to write to an appender
   */
  private _log(level: LogLevel, args: any[]): void {
    if (level == null) {
      level = this.defaultLevel;
    }

    const len = this._appenders.length;

    for (let i = 0; i < len; i++) {
      if (level >= this.defaultLevel) {
        this._appenders[i].log(level, args);
      }
    }
  }

  /**
   * Writes a log message at the [[LogLevel.Debug]] level
   * @param args  Accepts any number of arguments
   */
  public debug(...args: any[]): void {
    this._log(LogLevel.Debug, args);
  }

  /**
   * Writes a log message at the [[LogLevel.Info]] level
   * @param args  Accepts any number of arguments
   */
  public info(...args: any[]): void {
    this._log(LogLevel.Info, args);
  }

  /**
   * Writes a log message at the [[LogLevel.Warn]] level
   * @param args  Accepts any number of arguments
   */
  public warn(...args: any[]): void {
    this._log(LogLevel.Warn, args);
  }

  /**
   * Writes a log message at the [[LogLevel.Error]] level
   * @param args  Accepts any number of arguments
   */
  public error(...args: any[]): void {
    this._log(LogLevel.Error, args);
  }

  /**
   * Writes a log message at the [[LogLevel.Fatal]] level
   * @param args  Accepts any number of arguments
   */
  public fatal(...args: any[]): void {
    this._log(LogLevel.Fatal, args);
  }
}

/**
 * Contract for any log appender (such as console/screen)
 */
export interface Appender {
  /**
   * Logs a message at the given [[LogLevel]]
   * @param level  Level to log at
   * @param args   Arguments to log
   */
  log(level: LogLevel, args: any[]): void;
}

/**
 * Console appender for browsers (i.e. `console.log`)
 */
export class ConsoleAppender implements Appender {
  /**
   * Logs a message at the given [[LogLevel]]
   * @param level  Level to log at
   * @param args   Arguments to log
   */
  public log(level: LogLevel, args: any[]): void {
    // Check for console support
    if (!console && !console.log && console.warn && console.error) {
      // todo maybe do something better than nothing
      return;
    }

    // Create a new console args array
    const consoleArgs: any[] = [];
    consoleArgs.unshift.apply(consoleArgs, args);
    consoleArgs.unshift('[' + LogLevel[level] + '] : ');

    if (level < LogLevel.Warn) {
      // Call .log for Debug/Info
      if (console.log.apply) {
        // this is required on some older browsers that don't support apply on console.log :(
        console.log.apply(console, consoleArgs);
      } else {
        console.log(consoleArgs.join(' '));
      }
    } else if (level < LogLevel.Error) {
      // Call .warn for Warn
      if (console.warn.apply) {
        console.warn.apply(console, consoleArgs);
      } else {
        console.warn(consoleArgs.join(' '));
      }
    } else {
      // Call .error for Error/Fatal
      if (console.error.apply) {
        console.error.apply(console, consoleArgs);
      } else {
        console.error(consoleArgs.join(' '));
      }
    }
  }
}

/**
 * On-screen (canvas) appender
 */
export class ScreenAppender implements Appender {
  // @todo Clean this up

  private _messages: string[] = [];
  private _canvas: HTMLCanvasElement;
  private _ctx: CanvasRenderingContext2D;

  /**
   * @param width   Width of the screen appender in pixels
   * @param height  Height of the screen appender in pixels
   */
  constructor(width?: number, height?: number) {
    this._canvas = <HTMLCanvasElement>document.createElement('canvas');
    this._canvas.width = width || window.innerWidth;
    this._canvas.height = height || window.innerHeight;
    this._canvas.style.position = 'absolute';
    // eslint-disable-next-line
    this._ctx = <CanvasRenderingContext2D>this._canvas.getContext('2d'); // eslint-disable-line
    document.body.appendChild(this._canvas);
  }

  /**
   * Logs a message at the given [[LogLevel]]
   * @param level  Level to log at
   * @param args   Arguments to log
   */
  public log(level: LogLevel, args: any[]): void {
    const message = args.join(',');

    this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);

    this._messages.unshift('[' + LogLevel[level] + '] : ' + message);

    let pos = 10;
    let opacity = 1.0;
    for (let i = 0; i < this._messages.length; i++) {
      this._ctx.fillStyle = 'rgba(255,255,255,' + opacity.toFixed(2) + ')';
      this._ctx.fillText(this._messages[i], 200, pos);
      pos += 10;
      opacity = opacity > 0 ? opacity - 0.05 : 0;
    }
  }
}


text:
from config.api1_1_config import *
from modules.logger import Log
from on_http_api1_1 import ConfigApi as Config
from on_http_api1_1 import NodesApi as Nodes
from on_http_api1_1 import rest
from datetime import datetime
from proboscis.asserts import assert_equal
from proboscis.asserts import assert_false
from proboscis.asserts import assert_raises
from proboscis.asserts import assert_not_equal
from proboscis.asserts import assert_true
from proboscis import SkipTest
from proboscis import test
from json import dumps, loads

LOG = Log(__name__)

@test(groups=['config.tests'])
class ConfigTests(object):
    def __init__(self):
        self.__client = config.api_client

    @test(groups=['config.tests', 'check-config'])
    def check_server_config(self):
        """Testing GET:/config to get server configuration"""
        Config().config_get()
        rsp = self.__client.last_response
        assert_equal(200, rsp.status, message=rsp.reason)

    @test(groups=['patch-config'], depends_on_groups=['check-config'])
    def patch_server_config(self):
        """Testing PATCH:/config to patch a specific configuration item"""
        test_pwd = {"PWD": "/this/is/a/test/for/patch_config"}
        LOG.info("Patch PWD with a test path")
        Config().config_patch(body=test_pwd)
        server_config = loads(self.__client.last_response.data)
        assert_equal(server_config.get('PWD'),'/this/is/a/test/for/patch_config', 'Oops patch config failed')
        LOG.info("Doing a check config with test PWD")
        Config().config_get()
        rsp = self.__client.last_response
        assert_equal(200, rsp.status, message=rsp.reason)
        LOG.info("Restoring PWD config after patch test")
        Config().config_patch(body = {"PWD": "/var/renasar/on-http"})
        rsp = self.__client.last_response
        assert_equal(200, rsp.status, message=rsp.reason)


text:
/**
 * @Version : 6.0.3 Sat Nov 29 15:51:16 BRST 2014
 * @Author  : WebNMS Agent Toolkit Java Edition
 */

// Any changes made to this file will be lost, if regenerated.
// User code should be added within user tags for code merging support, if regenerated.

// Package Name (Dont Delete this comment)
package com.ufrgs.gerencia.agent;

// SNMP API Imports
import com.adventnet.snmp.snmp2.SnmpAPI;
import com.adventnet.snmp.snmp2.SnmpVar;
import com.adventnet.snmp.snmp2.SnmpVarBind;
import com.adventnet.snmp.snmp2.SnmpString;
import com.adventnet.snmp.snmp2.SnmpInt;

// SNMP Agent API Imports
import com.adventnet.snmp.snmp2.agent.AgentNode;
import com.adventnet.snmp.snmp2.agent.AgentSnmpException;
import com.adventnet.snmp.snmp2.agent.AgentUtil;
import com.adventnet.snmp.snmp2.agent.SimpleRequestHandler;
import com.adventnet.snmp.snmp2.agent.VarBindRequestEvent;
import com.adventnet.snmp.snmp2.agent.VarBindAndFailure;

// Agent Utility API Imports
import com.adventnet.utils.agent.utils;
import  com.adventnet.utils.agent.ScalarModelListener;
import com.adventnet.utilities.common.AgentException;

// Java Imports
import java.util.Hashtable;
import java.util.Vector;

/**
 * Handles all requests under
 * condominium group
 */

public class CondominiumRequestHandler extends SimpleRequestHandler{

	final static int CMNAME = 1;
	final static int CMADDRESS = 2;
	final static int CMMANAGER = 3;
	final static int CMUPEOPLE = 4;

	private final static int[]condominiumOidRep = {1,3,6,1,4,1,12619,1,2};

	/**
	 * To get OID array of this Scalar Group
	* @return OID array of this Scalar Group
	*/
	public static int[] getCondominiumOidRep(){
		return condominiumOidRep;
	}

	// This is generated to preserve the old API
	public int[] getOidRep(){
		return getCondominiumOidRep();
	}
	public CondominioAgent agentName;

	/**
	* Used for retreiving Sub-Ids of the Attributes in this Scalar Group
	* @return array of Sub-Ids of the Attributes in this Scalar group
	*/
	protected int[] getSubidList(){
		int[] subidList = {1,2,3,4};
		return subidList;
	}

	CondominiumInstrument instrument = null;

	public void setCondominiumInstrument(CondominiumInstrument instrument){
		this.instrument = instrument;
		this.addInstrumentHandler(instrument);
	}

	public CondominiumRequestHandler(CondominioAgent agentRef){
		agentName = agentRef;
	}

	private Hashtable objectHash;
	private Hashtable objectTypeHash;

	/**
	* Used for retreiving Sub-Ids of the Attributes in this Scalar Group
 	* @return Hashtable having AttributeName(String) - SubId(Integer) pairs
	*/
	public Hashtable getObjectHash(){
		if(objectHash == null){
			objectHash = new Hashtable();
			objectHash.put("CMNAME",new Integer(1));
			objectHash.put("CMADDRESS",new Integer(2));
			objectHash.put("CMMANAGER",new Integer(3));
			objectHash.put("CMUPEOPLE",new Integer(4));
		}
		return objectHash;
	}

	/**
	* Used for retreiving Syntax-Types of the Attributes in this Scalar Group
	* @return Hashtable having AttributeName(String) - Syntax Type(Integer) pairs
	*/
	public Hashtable getObjectTypeHash(){
		if(objectTypeHash == null){
			objectTypeHash = new Hashtable();
			objectTypeHash.put("CMNAME",new Integer(4));
			objectTypeHash.put("CMADDRESS",new Integer(4));
			objectTypeHash.put("CMMANAGER",new Integer(4));
			objectTypeHash.put("CMUPEOPLE",new Integer(2));
		}
		return objectTypeHash;
	}

	/**
	* This method is used for processing the incoming GET Requests
	* @param listOfVarbinds List of SnmpVarbinds for which GET Request is to be performed
	* @param listOfNodes List of AgentNodes for which GET Request is to be performed
	* @param pe VarbindRequestEvent
	*/
	protected void processGetRequest(Vector listOfVarbinds,
					 Vector listOfNodes,
					 VarBindRequestEvent pe) {
		SnmpVarBind varb = null;
		AgentNode node = null;
		Vector failedList = new Vector();
		Vector listOfColumns = new Vector();
		int nodeSize = listOfNodes.size();

		for(int i=0;i<nodeSize;i++){
			try{
				node = (AgentNode)listOfNodes.elementAt(i);
				varb =(SnmpVarBind) listOfVarbinds.elementAt(i);
				if(node == null){
					AgentUtil.throwNoSuchInstance(pe.getVersion());
				}
				int[] oid = (int[] )varb.getObjectID().toValue();
				if(oid.length != condominiumOidRep.length + 2){
					AgentUtil.throwNoSuchInstance(pe.getVersion());
				}

				int[] inst = AgentUtil.getInstance(oid,condominiumOidRep.length);
				if(inst[1] != 0){
					AgentUtil.throwNoSuchInstance(pe.getVersion());
				}
				listOfColumns.addElement(new Integer(node.getSubId()));
			}catch(Exception exp){
				if(exp instanceof AgentException){
					AgentException ae = (AgentException )exp;
					AgentSnmpException ase = AgentUtil.convertToAgentSnmpException(pe.getVersion(),ae);
					failedList.addElement(new VarBindAndFailure(ase,i));
				}
				else if(exp instanceof AgentSnmpException){
					failedList.addElement(new VarBindAndFailure((AgentSnmpException )exp,i));
				}
				else{
					failedList.addElement(new VarBindAndFailure(
							new AgentSnmpException("Exception occurred: ", SnmpAPI.SNMP_ERR_GENERR) ,i));
				}
				utils.handleError(exp);
				listOfColumns.addElement(new Integer(-1));
			}
		} // end of for loop
		if(listOfColumns.size() > 0) {
			getValuesFromInstrument(pe,listOfVarbinds,listOfColumns,failedList);
		}
		if(!pe.isRollback()){
			pe.setFailedList(failedList);
		}
	}

	/**
	* This method is used for processing the incoming SET Requests
	* @param listOfVarbinds List of SnmpVarbinds for which SET Request is to be performed
	* @param listOfNodes List of Agent Nodes for which SET Request is to be performed
	* @param pe VarbindRequest Event
	*/
	protected void processSetRequest(Vector listOfVarbinds,
					 Vector listOfNodes,
					 VarBindRequestEvent pe) {
		SnmpVarBind varb = null;
		AgentNode node = null;
		Vector failedList = new Vector();
		Hashtable toSendHash = new Hashtable();
		Vector indexList = new Vector();
		Hashtable indexHash = new Hashtable();
		Vector trapVector = new Vector();

		int nodeSize = listOfNodes.size();

		for(int i=0;i<nodeSize;i++){
			try{
				node = (AgentNode)listOfNodes.elementAt(i);
				varb =(SnmpVarBind) listOfVarbinds.elementAt(i);
				if(node == null){
					AgentUtil.throwNoCreation(pe.getVersion());
				}
				int[] oid = (int[] )varb.getObjectID().toValue();
				if(oid.length != condominiumOidRep.length + 2){
					AgentUtil.throwNoCreation(pe.getVersion());
				}

				int[] inst = AgentUtil.getInstance(oid,condominiumOidRep.length);
				if(inst[1] != 0){
					AgentUtil.throwNoCreation(pe.getVersion());
				}
				indexHash.put(new Integer(node.getSubId()),new Integer(i));
				SnmpVar var =  varb.getVariable();
				switch(node.getSubId()){
					case CMNAME:
						AgentUtil.throwNotWritable(pe.getVersion());

						break;

					case CMADDRESS:
						AgentUtil.throwNotWritable(pe.getVersion());

						break;

					case CMMANAGER:
						// Check for the proper instance
						if(!(var instanceof SnmpString )){
							AgentUtil.throwWrongType(pe.getVersion());
						}
						String cmManagerStr = (String )var.getVarObject();
						toSendHash.put(new Integer(CMMANAGER),cmManagerStr);

						indexList.removeElement(new Integer(CMMANAGER));
						indexList.addElement(new Integer(CMMANAGER));
						break;

					case CMUPEOPLE:
						AgentUtil.throwNotWritable(pe.getVersion());

						break;

					default:
						AgentUtil.throwNoSuchInstance(pe.getVersion());
				}
			}catch(Exception exp){
				if(exp instanceof AgentException){
					AgentException ae = (AgentException )exp;
					AgentSnmpException ase = AgentUtil.convertToAgentSnmpException(pe.getVersion(),ae);
					failedList.addElement(new VarBindAndFailure(ase,i));
				}
				else if(exp instanceof AgentSnmpException){
					failedList.addElement(new VarBindAndFailure((AgentSnmpException )exp,i));
				}
				else{
					failedList.addElement(new VarBindAndFailure(
							new AgentSnmpException("Exception occurred: ", SnmpAPI.SNMP_ERR_GENERR) ,i));
				}
				utils.handleError(exp);
				break;
			}
		}

		if(toSendHash.size() > 0){
			try{
				instrumentHandler.setAttributes(toSendHash,indexList);
			}catch(Exception exp){
				Integer temp = instrumentHandler.getFailedSubId();
				temp = (Integer)indexHash.get(temp);
				if(exp instanceof AgentException){
					AgentException ae = (AgentException )exp;
					AgentSnmpException ase = AgentUtil.convertToAgentSnmpException(pe.getVersion(),ae);
					failedList.addElement(new VarBindAndFailure(ase,temp.intValue()));
				}
				else{
					failedList.addElement(new VarBindAndFailure(
							new AgentSnmpException("Exception occurred: ", SnmpAPI.SNMP_ERR_GENERR) ,temp.intValue()));
				}
				pe.setFailedList(failedList);
				return;
			}
		}
		pe.setFailedList(failedList);
	}

	/**
	* This method will be used for processing the Incoming GETNEXT Requests
	* @param listOfVarbinds List of SnmpVarbinds for which GETNEXT Request is to be performed
	* @param listOfNodes List of AgentNodes for which GETNEXT Request is to be performed
	* @param pe VarbindRequest Event
	*/
	protected void processGetNextRequest(Vector listOfVarbinds,
					 Vector listOfNodes,
					 VarBindRequestEvent pe) {
		SnmpVarBind varb = null;
		AgentNode node = null;
		Vector failedList = new Vector();
		Vector listOfColumns = new Vector();
		//Vector varbVector = new Vector();
		int columnID;

		int nodeSize = listOfNodes.size();

		for(int i=0;i<nodeSize;i++){
			try{
				node = (AgentNode)listOfNodes.elementAt(i);
				varb =(SnmpVarBind) listOfVarbinds.elementAt(i);
				if(node == null){
					AgentUtil.throwNoNextObject();
				}
				int[] oid = (int[] )varb.getObjectID().toValue();
				columnID=node.getSubId();
				if(oid.length >= condominiumOidRep.length + 2){
					AgentUtil.throwNoNextObject();
				}
				node = node.getNearestLeafCell(oid);
				listOfColumns.addElement(new Integer(node.getSubId()));
			}catch(Exception exp){
				if(exp instanceof AgentException){
					AgentException ae = (AgentException )exp;
					AgentSnmpException ase = AgentUtil.convertToAgentSnmpException(pe.getVersion(),ae);
					failedList.addElement(new VarBindAndFailure(ase,i));
				}
				else if(exp instanceof AgentSnmpException){
					failedList.addElement(new VarBindAndFailure((AgentSnmpException )exp,i));
				}
				utils.handleError(exp);
				listOfColumns.addElement(new Integer(-1));
			}
		} // end of for loop
		if(listOfColumns.size() > 0) {
			getValuesFromInstrument(pe,listOfVarbinds,listOfColumns,failedList);
		}
		pe.setFailedList(failedList);
	}

	/**
	* This method is used for getting the attribute values from Instrument file,while processing GET/GETNEXT requests
	* @param pe VarbindRequest Event
	* @param varbVector List of varbinds for which value is to be retreived
	* @return List of Objects for which GETNEXT is failed
	*/
	public void getValuesFromInstrument(VarBindRequestEvent pe, Vector varbVector,Vector columns,Vector failedList) {
		Hashtable valuesHash = new Hashtable();
		int size = columns.size();
		try{
			valuesHash = instrumentHandler.getAttributes(columns.elements());
		}catch(Exception exp) {
			// Exceptions occured during the getAttributes(Enumeration) call will be handled inside that method itself.
			// For missing values in 'valuesHash' , appropriate Snmp Error message will be propagated from inside the 'for loop' below.
		}
		SnmpVarBind varb=null;
		int columnID=0;

		for(int j=0; j< size; j++){
			try{
				Integer key = (Integer)columns.elementAt(j);
				if(key.equals(new Integer(-1))) {
					continue;
				}
				if( ! valuesHash.containsKey(key)) {
					AgentUtil.throwNoSuchInstance(pe.getVersion());
				}
				columnID = key.intValue();
				varb=(SnmpVarBind)varbVector.elementAt(j);
				Object toReturn  = null;

				switch(columnID){
					case CMNAME:
						toReturn = valuesHash.get(new Integer(CMNAME));
						if(toReturn == null){
							AgentUtil.throwNoSuchInstance(pe.getVersion());
						}
						// Generating for other TC
						SnmpString var0 = new SnmpString((String )toReturn);
						varb.setVariable(var0);
						break;

					case CMADDRESS:
						toReturn = valuesHash.get(new Integer(CMADDRESS));
						if(toReturn == null){
							AgentUtil.throwNoSuchInstance(pe.getVersion());
						}
						// Generating for other TC
						SnmpString var1 = new SnmpString((String )toReturn);
						varb.setVariable(var1);
						break;

					case CMMANAGER:
						toReturn = valuesHash.get(new Integer(CMMANAGER));
						if(toReturn == null){
							AgentUtil.throwNoSuchInstance(pe.getVersion());
						}
						// Generating for other TC
						SnmpString var2 = new SnmpString((String )toReturn);
						varb.setVariable(var2);
						break;

					case CMUPEOPLE:
						toReturn = valuesHash.get(new Integer(CMUPEOPLE));
						if(toReturn == null){
							AgentUtil.throwNoSuchInstance(pe.getVersion());
						}
						SnmpInt var3 = new SnmpInt(((Integer )toReturn).intValue());
						varb.setVariable(var3);
						break;

					default:
						AgentUtil.throwNoSuchInstance(pe.getVersion());
				} //end of switch
			}catch(Exception exp){
				if(exp instanceof AgentException){
					AgentException ae = (AgentException )exp;
					AgentSnmpException ase = AgentUtil.convertToAgentSnmpException(pe.getVersion(),ae);
					failedList.addElement(new VarBindAndFailure(ase,j));
				}
				else if(exp instanceof AgentSnmpException){
					failedList.addElement(new VarBindAndFailure((AgentSnmpException )exp,j));
				}
				else{
					failedList.addElement(new VarBindAndFailure(
							new AgentSnmpException("Exception occurred: ", SnmpAPI.SNMP_ERR_GENERR) ,j));
				}
				utils.handleError(exp);
			}
			varb.setObjectID(AgentUtil.getScalarSnmpOID(condominiumOidRep, columnID));
		}
	}

}


text:
import CellTags from './components/CellTags';
import SelectList from './components/SelectList';
import Cell from './components/Cell';
import CellInput from './components/CellInput';
import CellGroup from './components/CellGroup';
import CellDatePicker from './components/CellDatePicker';
import CellListProvider, { CellListItem } from './components/CellListProvider';
import CellSheet from './components/CellSheet';
import ActionSheet, { ActionItem } from './components/ActionSheet';
import DatePicker from './components/DatePicker';
import CellSlider from './components/CellSlider';
import CellSwitch from './components/CellSwitch';
import Icon from './lib/Icon';

module.exports = {
  CellTags,
  SelectList,
  ActionSheet,
  ActionItem,
  DatePicker,
  CellInput,
  Cell,
  CellGroup,
  CellListProvider,
  CellListItem,
  CellDatePicker,
  CellSheet,
  CellSlider,
  CellSwitch,
  Icon
}


text:
/* ###
 * IP: GHIDRA
 *
 * 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 ghidra.app.util.bin.format.macho.dyld;

import java.io.IOException;

import ghidra.app.util.bin.*;
import ghidra.app.util.importer.MessageLog;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.Program;
import ghidra.program.model.util.CodeUnitInsertionException;
import ghidra.util.exception.DuplicateNameException;
import ghidra.util.task.TaskMonitor;

/**
 * Represents a objc_opt_t structure, which resides in the libobjc DYLIB within a DYLD cache
 *
 * @see dyld/include/objc-shared-cache.h
 */
@SuppressWarnings("unused")
public class LibObjcOptimization implements StructConverter {

	/**
	 * The name of the section that contains the objc_opt_t_structure
	 */
	public final static String SECTION_NAME = "__objc_opt_ro";

	private int version;
	private int flags;
	private int selopt_offset;
	private int headeropt_ro_offset;
	private int clsopt_offset;
	private int protocolopt1_offset;
	private int headeropt_rw_offset;
	private int protocolopt2_offset;
	private int largeSharedCachesClassOffset;
	private int largeSharedCachesProtocolOffset;
	private long relativeMethodSelectorBaseAddressOffset;

	private long objcOptAddr;

	/**
	 * Create a new {@link LibObjcOptimization}.
	 *
	 * @param program The {@link Program}
	 * @param objcOptRoSectionAddr The start address of the __objc_opt_ro section
	 * @throws IOException if there was an IO-related problem parsing the structure
	 */
	public LibObjcOptimization(Program program, Address objcOptRoSectionAddr) throws IOException {
		try (ByteProvider provider =
			new MemoryByteProvider(program.getMemory(), objcOptRoSectionAddr)) {
			BinaryReader reader = new BinaryReader(provider, !program.getLanguage().isBigEndian());

			version = reader.readNextInt();
			if (version <= 14) {
				selopt_offset = reader.readNextInt();
				headeropt_ro_offset = reader.readNextInt();
				clsopt_offset = reader.readNextInt();
				if (version >= 13) {
					protocolopt1_offset = reader.readNextInt();
				}
			}
			else {
				flags = reader.readNextInt();
				selopt_offset = reader.readNextInt();
				headeropt_ro_offset = reader.readNextInt();
				clsopt_offset = reader.readNextInt();
				protocolopt1_offset = reader.readNextInt();
				headeropt_rw_offset = reader.readNextInt();
				protocolopt2_offset = reader.readNextInt();
				if (version >= 16) {
					largeSharedCachesClassOffset = reader.readNextInt();
					largeSharedCachesProtocolOffset = reader.readNextInt();
					relativeMethodSelectorBaseAddressOffset = reader.readNextLong();
				}
			}
		}

		objcOptAddr = objcOptRoSectionAddr.getOffset();
	}

	/**
	 * Gets the address of the objc_opt_t structure
	 *
	 * @return The address of the objc_opt_t structure
	 */
	public long getAddr() {
		return objcOptAddr;
	}

	/**
	 * Gets the relative method selector base address offset.  This will be 0 if the version is less
	 * than 16.
	 *
	 * @return The relative method selector base address offset
	 */
	public long getRelativeSelectorBaseAddressOffset() {
		return relativeMethodSelectorBaseAddressOffset;
	}

	/**
	 * Marks up up this structure in memory
	 *
	 * @param program The {@link Program}
	 * @param space The {@link AddressSpace}
	 * @param log The log
	 * @param monitor A cancelable task monitor
	 */
	public void markup(Program program, AddressSpace space, MessageLog log, TaskMonitor monitor) {
		Address addr = space.getAddress(getAddr());
		try {
			DataUtilities.createData(program, addr, toDataType(), -1, false,
				DataUtilities.ClearDataMode.CHECK_FOR_SPACE);
		}
		catch (CodeUnitInsertionException | DuplicateNameException | IOException e) {
			log.appendMsg(LibObjcOptimization.class.getSimpleName(),
				"Failed to markup objc_opt_t.");
		}
	}

	@Override
	public DataType toDataType() throws DuplicateNameException, IOException {
		StructureDataType struct = new StructureDataType("objc_opt_t", 0);
		if (version <= 12) {
			struct.add(DWORD, "version", "");
			struct.add(DWORD, "selopt_offset", "");
			struct.add(DWORD, "headeropt_offset", "");
			struct.add(DWORD, "clsopt_offset", "");
		}
		else if (version >= 13 && version <= 14) {
			struct.add(DWORD, "version", "");
			struct.add(DWORD, "selopt_offset", "");
			struct.add(DWORD, "headeropt_offset", "");
			struct.add(DWORD, "clsopt_offset", "");
			struct.add(DWORD, "protocolopt_offset", "");
		}
		else if (version == 15) {
			struct.add(DWORD, "version", "");
			struct.add(DWORD, "flags", "");
			struct.add(DWORD, "selopt_offset", "");
			struct.add(DWORD, "headeropt_ro_offset", "");
			struct.add(DWORD, "clsopt_offset", "");
			struct.add(DWORD, "unused_protocolopt_offset", "");
			struct.add(DWORD, "headeropt_rw_offset", "");
			struct.add(DWORD, "protocolopt_offset", "");
		}
		else { // version >= 16
			struct.add(DWORD, "version", "");
			struct.add(DWORD, "flags", "");
			struct.add(DWORD, "selopt_offset", "");
			struct.add(DWORD, "headeropt_ro_offset", "");
			struct.add(DWORD, "unused_clsopt_offset", "");
			struct.add(DWORD, "unused_protocolopt_offset", "");
			struct.add(DWORD, "headeropt_rw_offset", "");
			struct.add(DWORD, "unused_protocolopt2_offset", "");
			struct.add(DWORD, "largeSharedCachesClassOffset", "");
			struct.add(DWORD, "largeSharedCachesProtocolOffset", "");
			struct.add(QWORD, "relativeMethodSelectorBaseAddressOffset", "");

		}
		return struct;
	}
}


text:
<?xml version="1.0" encoding="Windows-1252" ?>
<Node nodeName="NotepadPlus">
    <Node nodeName="LexerStyles">
        <Node nodeName="LexerType" name="name">
            <Node nodeName="WordsStyle" name="name"/>
        </Node>
    </Node>
    <Node nodeName="GlobalStyles">
        <Node nodeName="WidgetStyle" name="name" />
    </Node>
</Node>


text:
package loon.action.map.battle;

public class BattleTransition {

	protected BattleState from;
	protected BattleState to;

	protected BattleCondition condition;

	public BattleTransition(BattleState from, BattleCondition condition, BattleState to) {
		this.from = from;
		this.condition = condition;
		this.to = to;
	}

}


text:
import { EntitySchema } from "../../../../../src"
import { Post } from "../model/Post"

export const PostEntity = new EntitySchema<Post>({
    name: "post",
    columns: {
        id: {
            type: Number,
            primary: true,
        },
        title: {
            type: String,
        },
        text: {
            type: String,
        },
    },
    relations: {
        categories: {
            type: "many-to-many",
            target: "category", // CategoryEntity
            joinTable: true,
        },
    },
})


text:
package com.parting_soul.baidumap.support.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.baidu.tts.client.SpeechError;
import com.baidu.tts.client.SpeechSynthesizer;
import com.baidu.tts.client.SpeechSynthesizerListener;
import com.baidu.tts.client.TtsMode;
import com.parting_soul.baidumap.R;
import com.parting_soul.baidumap.support.utils.io.IOUtils;

/**
 * Created by parting_soul on 17-5-8.
 * 语音合成工类
 */

public class TTSUtils implements SpeechSynthesizerListener {
    public static final String TAG = TTSUtils.class.getSimpleName();

    private SpeechSynthesizer mSpeechSynthesizer;
    private Context context;

    private String mTTSFilePath;

    /**
     * 存放tts语音文件的文件夹名
     */
    private static final String BAIDU_TTS__DIR_NAME = "baidumap_baiduTTS";
    private static final String BAIDU_TTS_ENGLISH_DIR_NAME = "english";

    private static final String SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female.dat";
    private static final String SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male.dat";
    private static final String TEXT_MODEL_NAME = "bd_etts_text.dat";
    private static final String ENGLISH_SPEECH_FEMALE_MODEL_NAME = "bd_etts_speech_female_en.dat";
    private static final String ENGLISH_SPEECH_MALE_MODEL_NAME = "bd_etts_speech_male_en.dat";
    private static final String ENGLISH_TEXT_MODEL_NAME = "bd_etts_text_en.dat";

    public TTSUtils(Context context) {
        this.context = context;
        initialEnv();
        initialTts();
    }

    /**
     * c初始化TTS语言参数
     */
    private void initialTts() {
        mSpeechSynthesizer = SpeechSynthesizer.getInstance();
        //设置app上下文参数
        mSpeechSynthesizer.setContext(context);
        //设置tts监听器,回调合成和播放进度以及错误信息
        mSpeechSynthesizer.setSpeechSynthesizerListener(this);
        // 文本模型文件路径 (离线引擎使用)
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_TEXT_MODEL_FILE, mTTSFilePath + "/"
                + TEXT_MODEL_NAME);
        // 声学模型文件路径 (离线引擎使用)
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_TTS_SPEECH_MODEL_FILE, mTTSFilePath + "/"
                + SPEECH_FEMALE_MODEL_NAME);
        // 语音开发者平台上注册应用得到的App ID (离线授权)
        mSpeechSynthesizer.setAppId(context.getResources().getString(R.string.app_id));
        mSpeechSynthesizer.setApiKey(context.getResources().getString(R.string.api_key), context.getResources().getString(R.string.secret_key));

        // 发音人(在线引擎),可用参数为0,1,2,3。。。(服务器端会动态增加,各值含义参考文档,以文档说明为准。0--普通女声,1--普通男声,2--特别男声,3--情感男声。。。)
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_SPEAKER, "0");
        // 设置Mix模式的合成策略(在线和离线混合)
        mSpeechSynthesizer.setParam(SpeechSynthesizer.PARAM_MIX_MODE, SpeechSynthesizer.MIX_MODE_DEFAULT);

        // 初始化tts
        mSpeechSynthesizer.initTts(TtsMode.MIX);

        //加载离线模型文件
        int result = mSpeechSynthesizer.loadModel(mTTSFilePath + "/" + SPEECH_FEMALE_MODEL_NAME, mTTSFilePath + "/" + TEXT_MODEL_NAME);

        Log.i(TAG, TAG + " initialTts result = " + result);
    }

    /**
     * 初始化tts语音引擎,把assets中的离线文件拷贝到手机指定位置
     */
    private void initialEnv() {
        mTTSFilePath = getApplicateionDataFilePath(context);
        //将assert中的离线文件放入手机内部对应位置
        IOUtils.copyFromAssetsToPhone(context, false, SPEECH_FEMALE_MODEL_NAME, mTTSFilePath + "/" + SPEECH_FEMALE_MODEL_NAME);
        IOUtils.copyFromAssetsToPhone(context, false, SPEECH_MALE_MODEL_NAME, mTTSFilePath + "/" + SPEECH_MALE_MODEL_NAME);
        IOUtils.copyFromAssetsToPhone(context, false, TEXT_MODEL_NAME, mTTSFilePath + "/" + TEXT_MODEL_NAME);
        IOUtils.copyFromAssetsToPhone(context, false, BAIDU_TTS_ENGLISH_DIR_NAME + "/" + ENGLISH_SPEECH_FEMALE_MODEL_NAME, mTTSFilePath + "/"
                + ENGLISH_SPEECH_FEMALE_MODEL_NAME);
        IOUtils.copyFromAssetsToPhone(context, false, BAIDU_TTS_ENGLISH_DIR_NAME + "/" + ENGLISH_SPEECH_MALE_MODEL_NAME, mTTSFilePath + "/"
                + ENGLISH_SPEECH_MALE_MODEL_NAME);
        IOUtils.copyFromAssetsToPhone(context, false, BAIDU_TTS_ENGLISH_DIR_NAME + "/" + ENGLISH_TEXT_MODEL_NAME, mTTSFilePath + "/"
                + ENGLISH_TEXT_MODEL_NAME);
    }

    /**
     * 如果sdcard挂载,则在sdcard中创建存放tts文件的文件夹,若sdcard没有被挂载则再内部存储中创建文件夹
     *
     * @param context
     * @return
     */
    private String getApplicateionDataFilePath(Context context) {
        String path = null;
        if (IOUtils.isSDCardIsMounted()) {
            path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + BAIDU_TTS__DIR_NAME;
            IOUtils.createFileWithPath(path);
        }
        if (path == null) {
            path = context.getFilesDir().getAbsolutePath() + "/" + BAIDU_TTS__DIR_NAME;
            IOUtils.createFileWithPath(path);
        }
        return path;
    }

    /**
     * 暂停tts当前的任务,可以用resume来恢复
     */
    public void pause() {
        this.mSpeechSynthesizer.pause();
    }

    /**
     * 恢复暂停时tts的任务,如果未暂停,此操作无任何影响
     */
    public void resume() {
        this.mSpeechSynthesizer.resume();
    }

    /**
     * 停止tts的所有任务,也会清空所有的排队任务
     */
    public void stop() {
        this.mSpeechSynthesizer.stop();
    }

    /**
     * 释放tts资源,如果有未完成的任务,会先停止所有的任务,后释放资源
     */
    public void destroy() {
        this.mSpeechSynthesizer.stop();
    }

    /**
     * 读出msg内容
     *
     * @param msg
     */
    public void speak(String msg) {
        mSpeechSynthesizer.speak(msg);
    }

    @Override
    public void onSynthesizeStart(String s) {

    }

    @Override
    public void onSynthesizeDataArrived(String s, byte[] bytes, int i) {

    }

    @Override
    public void onSynthesizeFinish(String s) {

    }

    @Override
    public void onSpeechStart(String s) {

    }

    @Override
    public void onSpeechProgressChanged(String s, int i) {

    }

    @Override
    public void onSpeechFinish(String s) {

    }

    @Override
    public void onError(String s, SpeechError speechError) {

    }
}


text:
class EntityParentHandlerSystem : public EntitySystem
{
public:
	EntityParentHandlerSystem();
	virtual void processEntities( const vector<Entity*>& p_entities ) final;

};


text:
package org.apache.hadoop.hbase;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import junit.framework.Assert;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.master.HMaster;
import org.apache.hadoop.hbase.protobuf.RequestConverter;
import org.apache.hadoop.hbase.master.ServerManager;
import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.HRegionServer;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.JVMClusterUtil;
import org.apache.hadoop.hbase.zookeeper.ZKAssign;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.apache.zookeeper.KeeperException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * Test the draining servers feature.
 *
 * This is typically an integration test: a unit test would be to check that the
 * master does no assign regions to a regionserver marked as drained.
 *
 * @see HBASE-4298
 */
@Category(MediumTests.class)
public class TestDrainingServer {
  private static final Log LOG = LogFactory.getLog(TestDrainingServer.class);
  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
  private static final int NB_SLAVES = 5;
  private static final int COUNT_OF_REGIONS = NB_SLAVES * 2;

  /**
   * Spin up a cluster with a bunch of regions on it.
   */
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    TEST_UTIL.startMiniCluster(NB_SLAVES);
    TEST_UTIL.getHBaseCluster().waitForActiveAndReadyMaster();
    TEST_UTIL.getConfiguration().setBoolean("hbase.master.enabletable.roundrobin", true);

    final List<String> families = new ArrayList<String>(1);
    families.add("family");
    TEST_UTIL.createRandomTable("table", families, 1, 0, 0, COUNT_OF_REGIONS, 0);

    // Ensure a stable env
    TEST_UTIL.getHBaseAdmin().setBalancerRunning(false, false);

    boolean ready = false;
    while (!ready){
      waitForAllRegionsOnline();

      // Assert that every regionserver has some regions on it.
      int i = 0;
      ready = true;
      while (i < NB_SLAVES && ready){
        HRegionServer hrs = TEST_UTIL.getMiniHBaseCluster().getRegionServer(i);
        if (ProtobufUtil.getOnlineRegions(hrs).isEmpty()){
          ready = false;
        }
        i++;
      }

      if (!ready){
        TEST_UTIL.getHBaseAdmin().setBalancerRunning(true, true);
        Assert.assertTrue("Can't start a balance!", TEST_UTIL.getHBaseAdmin().balancer());
        TEST_UTIL.getHBaseAdmin().setBalancerRunning(false, false);
        Thread.sleep(100);
      }
    }
  }

  private static HRegionServer setDrainingServer(final HRegionServer hrs)
  throws KeeperException {
    LOG.info("Making " + hrs.getServerName() + " the draining server; " +
      "it has " + hrs.getNumberOfOnlineRegions() + " online regions");
    ZooKeeperWatcher zkw = hrs.getZooKeeper();
    String hrsDrainingZnode =
      ZKUtil.joinZNode(zkw.drainingZNode, hrs.getServerName().toString());
    ZKUtil.createWithParents(zkw, hrsDrainingZnode);
    return hrs;
  }

  private static HRegionServer unsetDrainingServer(final HRegionServer hrs)
  throws KeeperException {
    ZooKeeperWatcher zkw = hrs.getZooKeeper();
    String hrsDrainingZnode =
      ZKUtil.joinZNode(zkw.drainingZNode, hrs.getServerName().toString());
    ZKUtil.deleteNode(zkw, hrsDrainingZnode);
    return hrs;
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    TEST_UTIL.shutdownMiniCluster();
  }

  /**
   * Test adding server to draining servers and then move regions off it.
   * Make sure that no regions are moved back to the draining server.
   * @throws IOException
   * @throws KeeperException
   */
  @Test  // (timeout=30000)
  public void testDrainingServerOffloading()
  throws Exception {
    // I need master in the below.
    HMaster master = TEST_UTIL.getMiniHBaseCluster().getMaster();
    HRegionInfo hriToMoveBack = null;
    // Set first server as draining server.
    HRegionServer drainingServer =
      setDrainingServer(TEST_UTIL.getMiniHBaseCluster().getRegionServer(0));
    try {
      final int regionsOnDrainingServer =
        drainingServer.getNumberOfOnlineRegions();
      Assert.assertTrue(regionsOnDrainingServer > 0);
      List<HRegionInfo> hris = ProtobufUtil.getOnlineRegions(drainingServer);
      for (HRegionInfo hri : hris) {
        // Pass null and AssignmentManager will chose a random server BUT it
        // should exclude draining servers.
        master.moveRegion(null,
          RequestConverter.buildMoveRegionRequest(hri.getEncodedNameAsBytes(), null));
        // Save off region to move back.
        hriToMoveBack = hri;
      }
      // Wait for regions to come back on line again.
      waitForAllRegionsOnline();
      Assert.assertEquals(0, drainingServer.getNumberOfOnlineRegions());
    } finally {
      unsetDrainingServer(drainingServer);
    }
    // Now we've unset the draining server, we should be able to move a region
    // to what was the draining server.
    master.moveRegion(null,
      RequestConverter.buildMoveRegionRequest(hriToMoveBack.getEncodedNameAsBytes(),
      Bytes.toBytes(drainingServer.getServerName().toString())));
    // Wait for regions to come back on line again.
    waitForAllRegionsOnline();
    Assert.assertEquals(1, drainingServer.getNumberOfOnlineRegions());
  }

  /**
   * Test that draining servers are ignored even after killing regionserver(s).
   * Verify that the draining server is not given any of the dead servers regions.
   * @throws KeeperException
   * @throws IOException
   */
  @Test  (timeout=30000)
  public void testDrainingServerWithAbort() throws KeeperException, Exception {
    HMaster master = TEST_UTIL.getHBaseCluster().getMaster();

    waitForAllRegionsOnline();

    final long regionCount = TEST_UTIL.getMiniHBaseCluster().countServedRegions();

    // Let's get a copy of the regions today.
    Collection<HRegion> regions = new ArrayList<HRegion>();
    for (int i = 0; i < NB_SLAVES; i++) {
      HRegionServer hrs = TEST_UTIL.getMiniHBaseCluster().getRegionServer(i);
      regions.addAll( hrs.getCopyOfOnlineRegionsSortedBySize().values() );
    }

      // Choose the draining server
    HRegionServer drainingServer = TEST_UTIL.getMiniHBaseCluster().getRegionServer(0);
    final int regionsOnDrainingServer = drainingServer.getNumberOfOnlineRegions();
    Assert.assertTrue(regionsOnDrainingServer > 0);

    ServerManager sm = master.getServerManager();

    Collection<HRegion> regionsBefore = drainingServer.
      getCopyOfOnlineRegionsSortedBySize().values();
    LOG.info("Regions of drained server are: "+ regionsBefore );

    try {
      // Add first server to draining servers up in zk.
      setDrainingServer(drainingServer);

      //wait for the master to receive and manage the event
      while  (sm.createDestinationServersList().contains(drainingServer.getServerName())) {
        Thread.sleep(1);
      }

      LOG.info("The available servers are: "+ sm.createDestinationServersList());

      Assert.assertEquals("Nothing should have happened here.", regionsOnDrainingServer,
        drainingServer.getNumberOfOnlineRegions());
      Assert.assertFalse("We should not have regions in transition here. List is: " +
          master.getAssignmentManager().getRegionStates().getRegionsInTransition(),
          master.getAssignmentManager().getRegionStates().isRegionsInTransition());

      // Kill a few regionservers.
      for (int aborted = 0; aborted <= 2; aborted++) {
        HRegionServer hrs = TEST_UTIL.getMiniHBaseCluster().getRegionServer(aborted + 1);
        hrs.abort("Aborting");
      }

      // Wait for regions to come back online again.
      waitForAllRegionsOnline();

      Collection<HRegion> regionsAfter =
          drainingServer.getCopyOfOnlineRegionsSortedBySize().values();
      LOG.info("Regions of drained server are: " + regionsAfter);

      Assert.assertEquals("Test conditions are not met: regions were" +
        " created/deleted during the test. ",
        regionCount, TEST_UTIL.getMiniHBaseCluster().countServedRegions());

      // Assert the draining server still has the same regions.
      StringBuilder result = new StringBuilder();
      for (HRegion r: regionsAfter){
        if (!regionsBefore.contains(r)){
          result.append(r).append(" was added after the drain");
          if (regions.contains(r)){
            result.append("(existing region");
          } else {
            result.append("(new region)");
          }
          result.append("; ");
        }
      }
      for (HRegion r: regionsBefore){
        if (!regionsAfter.contains(r)){
          result.append(r).append(" was removed after the drain; ");
        }
      }
      Assert.assertTrue("Errors are: "+ result.toString(), result.length()==0);

    } finally {
      unsetDrainingServer(drainingServer);
    }
  }

  private static void waitForAllRegionsOnline() throws Exception {
    // Wait for regions to come back on line again.

    boolean done = false;
    while (!done) {
      Thread.sleep(1);

      // Nothing in ZK RIT for a start
      ZKAssign.blockUntilNoRIT(TEST_UTIL.getZooKeeperWatcher());

      // Then we want all the regions to be marked as available...
      if (!isAllRegionsOnline()) continue;

      // And without any work in progress on the master side
      if (TEST_UTIL.getMiniHBaseCluster().getMaster().
          getAssignmentManager().getRegionStates().isRegionsInTransition()) continue;

      // nor on the region server side
      done = true;
      for (JVMClusterUtil.RegionServerThread rs :
          TEST_UTIL.getMiniHBaseCluster().getLiveRegionServerThreads()) {
        if (!rs.getRegionServer().getRegionsInTransitionInRS().isEmpty()) {
          done = false;
        }
      }
    }
  }

  private static boolean isAllRegionsOnline() {
    return TEST_UTIL.getMiniHBaseCluster().countServedRegions() ==
        (COUNT_OF_REGIONS + 2 /*catalog regions*/);
  }

}


text:
package cmd

import (
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/nemosupremo/vault-gatekeeper/scheduler"

	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

const defaultVaultAddr = "http://localhost:8200"
const defaultGatekeeperAddr = "http://localhost:9201"
const defaultPolicyPath = "secret/data/gatekeeper"
const defaultVaultKvVer = "2"

var Version = "dev"

func init() {
	viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
	viper.AutomaticEnv()

	viper.SetDefault("log-level", "info")

	rootCmd.PersistentFlags().String("log-level", viper.GetString("log-level"), "Logging level.")

	viper.BindPFlag("log-level", rootCmd.PersistentFlags().Lookup("log-level"))
}

func bindViperFlags(cmd *cobra.Command, options []scheduler.Args) {
	for _, option := range options {
		viper.BindPFlag(option.Name, cmd.PersistentFlags().Lookup(option.Name))
	}
}

var rootCmd = &cobra.Command{
	Use:              "gatekeeper [command]",
	Short:            "",
	PersistentPreRun: Setup,
}

var RootCmd = rootCmd

func Setup(cmd *cobra.Command, args []string) {
	if l, err := logrus.ParseLevel(viper.GetString("log-level")); err == nil {
		logrus.SetLevel(l)
	} else {
		logrus.SetLevel(logrus.InfoLevel)
	}

	logrus.SetFormatter(&logrus.TextFormatter{TimestampFormat: time.RFC3339, FullTimestamp: true})
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}


text:
SecureRandom prng = new SecureRandom();
int randomData = 0;

// BAD: Using a constant value as a seed for a random number generator means all numbers it generates are predictable.
prng.setSeed(12345L);
randomData = prng.next(32);

// BAD: System.currentTimeMillis() returns the system time which is predictable.
prng.setSeed(System.currentTimeMillis());
randomData = prng.next(32);

// GOOD: SecureRandom implementations seed themselves securely by default.
prng = new SecureRandom();
randomData = prng.next(32);


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

<title>DatastoreServiceFactory (Google App Engine API for Java)</title>
<meta name="date" content="2016-07-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.appengine.api.datastore

Class DatastoreServiceFactory

java.lang.Object

com.google.appengine.api.datastore.DatastoreServiceFactory

public final class DatastoreServiceFactory
extends java.lang.Object

Creates DatastoreService implementations.

Constructor Summary

Constructors

Constructor and Description

DatastoreServiceFactory()

Deprecated.

Exposed by accident, do not instantiate.

Method Summary

All Methods Static Methods Concrete Methods Deprecated Methods

Modifier and Type
Method and Description

static AsyncDatastoreService
getAsyncDatastoreService()

Creates an AsyncDatastoreService using the default config (
 DatastoreServiceConfig.Builder.withDefaults()).

static AsyncDatastoreService
getAsyncDatastoreService(DatastoreServiceConfig config)

Creates an AsyncDatastoreService using the provided config.

static DatastoreService
getDatastoreService()

Creates a DatastoreService using the default config (
 DatastoreServiceConfig.Builder.withDefaults()).

static DatastoreService
getDatastoreService(DatastoreConfig oldConfig)

Deprecated.

Use getDatastoreService(DatastoreServiceConfig) instead.

static DatastoreService
getDatastoreService(DatastoreServiceConfig config)

Creates a DatastoreService using the provided config.

static DatastoreConfig
getDefaultDatastoreConfig()

Deprecated.

Use DatastoreServiceConfig.Builder.withDefaults() instead.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DatastoreServiceFactory

@Deprecated
public DatastoreServiceFactory()

Deprecated. Exposed by accident, do not instantiate.

Method Detail

getDatastoreService

public static DatastoreService getDatastoreService(DatastoreServiceConfig config)

Creates a DatastoreService using the provided config.

getAsyncDatastoreService

public static AsyncDatastoreService getAsyncDatastoreService(DatastoreServiceConfig config)

Creates an AsyncDatastoreService using the provided config. The async datastore service
 does not support implicit transaction management policy
 ImplicitTransactionManagementPolicy.AUTO.

Throws:

java.lang.IllegalArgumentException - If the provided DatastoreServiceConfig has an implicit
         transaction management policy of ImplicitTransactionManagementPolicy.AUTO.

getDatastoreService

public static DatastoreService getDatastoreService()

Creates a DatastoreService using the default config (
 DatastoreServiceConfig.Builder.withDefaults()).

getAsyncDatastoreService

public static AsyncDatastoreService getAsyncDatastoreService()

Creates an AsyncDatastoreService using the default config (
 DatastoreServiceConfig.Builder.withDefaults()).

getDatastoreService

@Deprecated
public static DatastoreService getDatastoreService(DatastoreConfig oldConfig)

Deprecated. Use getDatastoreService(DatastoreServiceConfig) instead.

Creates a DatastoreService using the provided config.

getDefaultDatastoreConfig

@Deprecated
public static DatastoreConfig getDefaultDatastoreConfig()

Deprecated. Use DatastoreServiceConfig.Builder.withDefaults() instead.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Java is a registered trademark of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.apache.pdfbox.debugger.ui;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import java.awt.Component;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Khyrul Bashar
 *
 * A Customized class that helps to open and save file. It uses JFileChooser to operate.
 */
public class FileOpenSaveDialog
{
    private static final JFileChooser fileChooser = new JFileChooser()
    {
        @Override
        public void approveSelection()
        {
            File selectedFile = getSelectedFile();
            if (selectedFile.exists() && getDialogType() == JFileChooser.SAVE_DIALOG)
            {
                int result = JOptionPane.showConfirmDialog(this,
                    "Do you want to overwrite?",
                    "File already exists",
                    JOptionPane.YES_NO_OPTION);
                if (result != JOptionPane.YES_OPTION)
                {
                    cancelSelection();
                    return;
                }
            }
            super.approveSelection();
        }
    };
    private final Component mainUI;

    /**
     * Constructor.
     * @param parentUI the main UI (JFrame) on top of which File open/save dialog should open.
     * @param fileFilter file Filter, null is allowed when no filter is applicable.
     */
    public FileOpenSaveDialog(Component parentUI, FileFilter fileFilter)
    {
        mainUI = parentUI;
        fileChooser.resetChoosableFileFilters();
        fileChooser.setFileFilter(fileFilter);
    }

    /**
     * Saves data into a file after the user is prompted to choose the destination.
     *
     * @param bytes byte array to be saved in a file.
     * @param extension file extension.
     * @return true if the file is saved successfully or false if failed.
     * @throws IOException if there is an error in creation of the file.
     */
    public boolean saveFile(byte[] bytes, String extension) throws IOException
    {
        int result = fileChooser.showSaveDialog(mainUI);
        if (result == JFileChooser.APPROVE_OPTION)
        {
            String filename = fileChooser.getSelectedFile().getAbsolutePath();
            if (extension != null && !filename.endsWith(extension))
            {
                filename += "." + extension;
            }

            try (FileOutputStream outputStream = new FileOutputStream(filename))
            {
                outputStream.write(bytes);
            }
            return true;
        }
        return false;
    }

    /**
     * open a file prompting user to select the file.
     * @return the file opened.
     * @throws IOException if there is error in opening the file.
     */
    public File openFile() throws IOException
    {
        int result = fileChooser.showOpenDialog(mainUI);
        if (result == JFileChooser.APPROVE_OPTION)
        {
            return fileChooser.getSelectedFile();
        }
        return null;
    }
}


text:
package br.org.tutty.posdiff.visual_interface;

import br.org.tutty.posdiff.database.Database;
import br.org.tutty.posdiff.database.DatabaseManager;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;

/**
 * Created by drferreira on 16/06/15.
 */
public class BottomPanel extends JPanel implements View, ActionListener {
    private static String COMPARE_BUTTON_LABEL = "Compare";

    private CompareButton compareButton = new CompareButton(COMPARE_BUTTON_LABEL);
    private Window window;

    public BottomPanel(Window window) {
        this.window = window;
    }

    @Override
    public void mount() {
        this.add(compareButton);
        compareButton.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String nameLeft = window.leftPanel.databaseNameLeft.getText();
        String urlLeft = window.leftPanel.urlDataBaseLeft.getText();
        String portLeft = window.leftPanel.portLeft.getText();
        String passwordLeft = new String(window.leftPanel.passwordLeft.getPassword());
        String userLeft = new String(window.leftPanel.usernameLeft.getText());

        Database leftDatabase = new Database(nameLeft, urlLeft,portLeft,passwordLeft, userLeft);

        String nameRight = window.rightPanel.databaseNameRight.getText();
        String urlRight = window.rightPanel.urlDataBaseRight.getText();
        String portRight = window.rightPanel.portRight.getText();
        String passwordRight = new String(window.rightPanel.passwordRight.getPassword());
        String userRight = new String(window.rightPanel.usernameRight.getText());

        Database rightDatabase = new Database(nameRight, urlRight,portRight,passwordRight, userRight);

        try{
            DatabaseManager databaseManager = new DatabaseManager();
            BufferedReader result = databaseManager.compare(leftDatabase, rightDatabase);
            WindowResult windowResult = new WindowResult(result);
            windowResult.mount();

        }catch (Exception exception){
            exception.printStackTrace();
        }
    }
}


text:
package org.skywalking.apm.agent.core.context.trace;

import java.util.LinkedList;
import java.util.List;
import org.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.skywalking.apm.agent.core.context.ids.DistributedTraceId;
import org.skywalking.apm.agent.core.context.ids.DistributedTraceIds;
import org.skywalking.apm.agent.core.context.ids.GlobalIdGenerator;
import org.skywalking.apm.agent.core.context.ids.ID;
import org.skywalking.apm.agent.core.context.ids.NewDistributedTraceId;
import org.skywalking.apm.network.proto.TraceSegmentObject;
import org.skywalking.apm.network.proto.UpstreamSegment;

/**
 * {@link TraceSegment} is a segment or fragment of the distributed trace. {@see https://github.com/opentracing/specification/blob/master/specification.md#the-opentracing-data-model}
 * A {@link TraceSegment} means the segment, which exists in current {@link Thread}. And the distributed trace is formed
 * by multi {@link TraceSegment}s, because the distributed trace crosses multi-processes, multi-threads.

 *
 * @author wusheng
 */
public class TraceSegment {
    /**
     * The id of this trace segment. Every segment has its unique-global-id.
     */
    private ID traceSegmentId;

    /**
     * The refs of parent trace segments, except the primary one. For most RPC call, {@link #refs} contains only one
     * element, but if this segment is a start span of batch process, the segment faces multi parents, at this moment,
     * we use this {@link #refs} to link them.
     */
    private List<TraceSegmentRef> refs;

    /**
     * The spans belong to this trace segment. They all have finished. All active spans are hold and controlled by
     * "skywalking-api" module.
     */
    private List<AbstractTracingSpan> spans;

    /**
     * The relatedGlobalTraces represent a set of all related trace. Most time it contains only one
     * element, because only one parent {@link TraceSegment} exists, but, in batch scenario, the num becomes greater
     * than 1, also meaning multi-parents {@link TraceSegment}.
 The difference between
     * relatedGlobalTraces and {@link #refs} is: {@link #refs} targets this {@link TraceSegment}'s direct
     * parent,
 and
 relatedGlobalTraces targets this {@link TraceSegment}'s related call chain, a
     * call chain contains multi {@link TraceSegment}s, only using {@link #refs} is not enough for analysis and ui.
     */
    private DistributedTraceIds relatedGlobalTraces;

    private boolean ignore = false;

    private boolean isSizeLimited = false;

    /**
     * Create a default/empty trace segment, with current time as start time, and generate a new segment id.
     */
    public TraceSegment() {
        this.traceSegmentId = GlobalIdGenerator.generate();
        this.spans = new LinkedList<AbstractTracingSpan>();
        this.relatedGlobalTraces = new DistributedTraceIds();
        this.relatedGlobalTraces.append(new NewDistributedTraceId());
    }

    /**
     * Establish the link between this segment and its parents.
     *
     * @param refSegment {@link TraceSegmentRef}
     */
    public void ref(TraceSegmentRef refSegment) {
        if (refs == null) {
            refs = new LinkedList<TraceSegmentRef>();
        }
        if (!refs.contains(refSegment)) {
            refs.add(refSegment);
        }
    }

    /**
     * Establish the line between this segment and all relative global trace ids.
     */
    public void relatedGlobalTraces(DistributedTraceId distributedTraceId) {
        relatedGlobalTraces.append(distributedTraceId);
    }

    /**
     * After {@link AbstractSpan} is finished, as be controller by "skywalking-api" module, notify the {@link
     * TraceSegment} to archive it.
     *
     * @param finishedSpan
     */
    public void archive(AbstractTracingSpan finishedSpan) {
        spans.add(finishedSpan);
    }

    /**
     * Finish this {@link TraceSegment}.
 return this, for chaining
     */
    public TraceSegment finish(boolean isSizeLimited) {
        this.isSizeLimited = isSizeLimited;
        return this;
    }

    public ID getTraceSegmentId() {
        return traceSegmentId;
    }

    public int getApplicationId() {
        return RemoteDownstreamConfig.Agent.APPLICATION_ID;
    }

    public boolean hasRef() {
        return !(refs == null || refs.size() == 0);
    }

    public List<TraceSegmentRef> getRefs() {
        return refs;
    }

    public List<DistributedTraceId> getRelatedGlobalTraces() {
        return relatedGlobalTraces.getRelatedGlobalTraces();
    }

    public boolean isSingleSpanSegment() {
        return this.spans != null && this.spans.size() == 1;
    }

    public boolean isIgnore() {
        return ignore;
    }

    public void setIgnore(boolean ignore) {
        this.ignore = ignore;
    }

    /**
     * This is a high CPU cost method, only called when sending to collector or test cases.
     *
     * @return the segment as GRPC service parameter
     */
    public UpstreamSegment transform() {
        UpstreamSegment.Builder upstreamBuilder = UpstreamSegment.newBuilder();
        for (DistributedTraceId distributedTraceId : getRelatedGlobalTraces()) {
            upstreamBuilder = upstreamBuilder.addGlobalTraceIds(distributedTraceId.toUniqueId());
        }
        TraceSegmentObject.Builder traceSegmentBuilder = TraceSegmentObject.newBuilder();
        /**
         * Trace Segment
         */
        traceSegmentBuilder.setTraceSegmentId(this.traceSegmentId.transform());
        // TraceSegmentReference
        if (this.refs != null) {
            for (TraceSegmentRef ref : this.refs) {
                traceSegmentBuilder.addRefs(ref.transform());
            }
        }
        // SpanObject
        for (AbstractTracingSpan span : this.spans) {
            traceSegmentBuilder.addSpans(span.transform());
        }
        traceSegmentBuilder.setApplicationId(RemoteDownstreamConfig.Agent.APPLICATION_ID);
        traceSegmentBuilder.setApplicationInstanceId(RemoteDownstreamConfig.Agent.APPLICATION_INSTANCE_ID);
        traceSegmentBuilder.setIsSizeLimited(this.isSizeLimited);

        upstreamBuilder.setSegment(traceSegmentBuilder.build().toByteString());
        return upstreamBuilder.build();
    }

    @Override
    public String toString() {
        return "TraceSegment{" +
            "traceSegmentId='" + traceSegmentId + '\'' +
            ", refs=" + refs +
            ", spans=" + spans +
            ", relatedGlobalTraces=" + relatedGlobalTraces +
            '}';
    }

    public int getApplicationInstanceId() {
        return RemoteDownstreamConfig.Agent.APPLICATION_INSTANCE_ID;
    }
}


text:
<?php

namespace Egulias\EmailValidator\Warning;

class NoDNSMXRecord extends Warning
{
    const CODE = 6;

    public function __construct()
    {
        $this->message = 'No MX DSN record was found for this email';
        $this->rfcNumber = 5321;
    }
}


text:
title: "Goatee"
excerpt: "PaperFaces portrait of @danimal drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-danimal-twitter-lg.jpg
  thumb: paperfaces-danimal-twitter-150.jpg
tags: [portrait, illustration, Paper by 53]
---

PaperFaces portrait of project donator [@danimal](http://twitter.com/danimal).

{% include boilerplate/paperfaces.html %}