text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GameFramework
{
    public interface Graphics
    {
        #region Fields
        /// <summary>
        /// Returns screen width.
        /// </summary>
        int Width { get; }

        /// <summary>
        /// Returns screen width divided by two (usefull for positioning purposes).
        /// </summary>
        int HalfWidth { get; }

        /// <summary>
        /// Returns screen height.
        /// </summary>
        int Height { get; }

        /// <summary>
        /// Returns screen height divided by two (usefull for positioning purposes).
        /// </summary>
        int HalfHeight { get; }
        #endregion
        #region Methods
        /// <summary>
        /// Creates an object of Image class from file.
        /// </summary>
        /// <param name="filename">Path to image file from Contents directory.</param>
        /// <returns>An object of Image class.</returns>
        Image NewImage(String filename);

        /// <summary>
        /// Loads font from file.
        /// </summary>
        /// <param name="filename">Path to font file from Contents directory.</param>
        /// <returns>An object of SpriteFont class.</returns>
        SpriteFont NewFont(String filename);

        /// <summary>
        /// Draws image passed as parameter on the screen.
        /// </summary>
        /// <param name="image">An image object to draw on the screen.</param>
        void DrawImage(Image image);

        /// <summary>
        /// Draws image passed as parameter on the screen at specified location (from upper left screen corner).
        /// </summary>
        /// <param name="image">An image object to draw on the screen.</param>
        /// <param name="x">X-position relative from the left of the screen.</param>
        /// <param name="y">Y-position relative from the top of the screen.</param>
        void DrawImage(Image image, int x, int y);

        /// <summary>
        /// Draws image passed as parameter on the screen at specified location (from upper left screen corner) and
        /// specified image width and height. Usefull while drawing part of an image (i.e. from spritesheet).
        /// </summary>
        /// <param name="image">An image object to draw on the screen.</param>
        /// <param name="x">X-position relative from the left of the screen.</param>
        /// <param name="y">Y-position relative from the top of the screen.</param>
        /// <param name="width">Image width.</param>
        /// <param name="height">Image height.</param>
        void DrawImage(Image image, int x, int y, int width, int height);

        /// <summary>
        /// Draws image passed as parameter on the screen at specified location (from upper left screen corner) and
        /// specified background color (or transparency).
        /// </summary>
        /// <param name="image">An image object to draw on the screen.</param>
        /// <param name="x">X-position relative from the left of the screen.</param>
        /// <param name="y">Y-position relative from the top of the screen.</param>
        /// <param name="color">Background color.</param>
        void DrawImage(Image image, int x, int y, Color color);

        /// <summary>
        /// Draws image passed as parameter on the screen at specified location (from upper left screen corner) and
        /// specified image width and height. Usefull while drawing scaled image. While not respecting image ratio
        /// it will be stretched.
        /// </summary>
        /// <param name="image">An image object to draw on the screen.</param>
        /// <param name="x">X-position relative from the left of the screen.</param>
        /// <param name="y">Y-position relative from the top of the screen.</param>
        /// <param name="scaledWidth">Target image width.</param>
        /// <param name="scaledHeight">Target image height.</param>
        void DrawScaledImage(Image image, int x, int y, int scaledWidth, int scaledHeight);

        /// <summary>
        /// Draws text at specified location (from upper left screen corner) and specified color.
        /// </summary>
        /// <param name="font">Font which will be used for drawing text.</param>
        /// <param name="text">Text string to draw.</param>
        /// <param name="x">X-position relative from the left of the screen.</param>
        /// <param name="y">Y-position relative from the top of the screen.</param>
        /// <param name="color">Text color (or transparency).</param>
        void DrawString(SpriteFont font, String text, int x, int y, Color color);

        /// <summary>
        /// Draws scaled text at specified location (from upper left screen corner) and specified color.
        /// </summary>
        /// <param name="font">Font which will be used for drawing text.</param>
        /// <param name="text">Text string to draw.</param>
        /// <param name="x">X-position relative from the left of the screen.</param>
        /// <param name="y">Y-position relative from the top of the screen.</param>
        /// <param name="scale">Font scale.</param>
        /// <param name="color">Text color (or transparency).</param>
        void DrawString(SpriteFont font, String text, int x, int y, float scale, Color color);

        /// <summary>
        /// Fills screen with specified color.
        /// </summary>
        /// <param name="color">Color to fill screen.</param>
        void Clear(Color color);

        /// <summary>
        /// Release resources.
        /// </summary>
        void Dispose();
        #endregion
    }
}


text:
<?php

namespace Ipunkt\LaravelJsonApi\Contracts\RequestHandlers;

use Illuminate\Database\Eloquent\Model;
use Ipunkt\LaravelJsonApi\Contracts\RelatedRepository;

interface HandlesRelationshipItemDeleteRequest extends ApiRequestHandler
{
    /**
     * relationship item request
     *
     * @param Model|mixed $resourceModel
     * @param string|int $relatedId
     * @param RelatedRepository $repository
     * @return void
     */
    public function relatedItemDelete($resourceModel, $relatedId, RelatedRepository $repository);
}

redpajama_set_name: RedPajamaGithub


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

namespace SCSharp
{
	[Flags]
	public enum ElementFlags
	{
		Unknown00000001   = 0x00000001,
		Unknown00000002   = 0x00000002,
		Unknown00000004   = 0x00000004,
		Visible           = 0x00000008,
		RespondToMouse    = 0x00000010,
		Unknown00000020   = 0x00000020,
		CancelButton      = 0x00000040,
		NoSoundOnMouseOvr = 0x00000080,
		Unknown00000100   = 0x00000100,
		HasHotkey         = 0x00000200,
		FontSmallest      = 0x00000400,
		FontSmaller       = 0x00000800,
		Unknown00001000   = 0x00001000,
		Transparent       = 0x00002000,
		FontLargest       = 0x00004000,
		Unused00008000    = 0x00008000,
		FontLarger       = 0x00010000,
		Unused00020000    = 0x00020000,
		Translucent       = 0x00040000,
		DefaultButton     = 0x00080000,
		BringToFront      = 0x00100000,
		CenterTextHoriz   = 0x00200000,
		RightAlignText    = 0x00400000,
		CenterTextVert    = 0x00800000,
		Unused01000000    = 0x01000000,
		BottomAlignText   = 0x02000000,
		NoClickSound      = 0x04000000,
		Unused08000000    = 0x08000000,
		Unused10000000    = 0x10000000,
		Unused20000000    = 0x20000000,
		Unused40000000    = 0x40000000
	}

	public enum ElementType
	{
		DialogBox = 0,
		DefaultButton = 1,
		Button = 2,
		OptionButton = 3,
		CheckBox = 4,
		Image = 5,
		Slider = 6,
		TextBox = 8,
		LabelLeftAlign = 9,
		LabelCenterAlign = 10,
		LabelRightAlign = 11,
		ListBox = 12,
		ComboBox = 13,
		ButtonWithoutBorder = 14,

		UserElement = 128
	}

	public class BinElement
	{
		public ushort x1;
		public ushort y1;
		public ushort x2;
		public ushort y2;

		public ushort width;
		public ushort height;

		public byte hotkey;
		public string text;
		public uint text_offset;

		public ElementFlags flags;
		public ElementType type;

		public object resolvedData;

		public BinElement (byte[] buf, int position, uint stream_length)
		{
			x1 = Util.ReadWord (buf, position + 4);
			y1 = Util.ReadWord (buf, position + 6);
			x2 = Util.ReadWord (buf, position + 8);
			y2 = Util.ReadWord (buf, position + 10);
			width = Util.ReadWord (buf, position + 12);
			height = Util.ReadWord (buf, position + 14);
			text_offset = Util.ReadDWord (buf, position + 20);

			flags = (ElementFlags)Util.ReadDWord (buf, position + 24);
			type = (ElementType)buf[position + 34];

			if (text_offset < stream_length) {
				uint text_length = 0;
				while (buf[text_offset + text_length] != 0) text_length ++;

				text = Encoding.ASCII.GetString (buf, (int)text_offset, (int)text_length);

				if ((flags & ElementFlags.HasHotkey) == ElementFlags.HasHotkey) {
					hotkey = Encoding.ASCII.GetBytes (new char[] {text[0]})[0];
					text = text.Substring (1);
				}
			}
			else
				text = "";
		}

		public void DumpFlags ()
		{
			Console.Write ("Flags: ");
			foreach (ElementFlags f in Enum.GetValues (typeof (ElementFlags)))
				if ((flags & f) == f) {
					Console.Write (f);
					Console.Write (" ");
				}
			Console.WriteLine ();
		}

		public override string ToString ()
		{
			return String.Format ("{0} ({1})", type, text);
		}

		public string Text {
			get { return text; }
			set {
				text = value;
				resolvedData = null;
			}
		}
	}

	public class Bin : MpqResource {
		Stream stream;
		List<BinElement> elements;

		public Bin ()
		{
			elements = new List<BinElement> ();
		}

		public void ReadFromStream (Stream stream)
		{
			this.stream = stream;
			ReadElements ();
		}

		void ReadElements ()
		{
			int position;

			byte[] buf = new byte[stream.Length];

			stream.Read (buf, 0, (int)stream.Length);

			position = 0;
			do {
				BinElement element = new BinElement (buf, position, (uint)stream.Length);

				elements.Add (element);

				position += 86;
			} while (position < ((BinElement)elements[0]).text_offset);
		}

		BinElement[] arr;
		public BinElement[] Elements {
			get {
				if (arr == null)
					arr = elements.ToArray();
				return arr;
			}
		}
	}
}


text:
@interface PlistUtils (Private)

+ (id) readObjectFromPlist:(NSString *)path;
+ (void) writeObject:(id)obj toPlist:(NSString *)path;

@end

@implementation PlistUtils

+ (NSDictionary *) readDictionaryFromPlist:(NSString *)path
{
    return (NSDictionary *) [self readObjectFromPlist:path];
}

+ (void) writeDictionary:(NSDictionary *)dictionary toPlist:(NSString *)path
{
    [self writeObject:dictionary toPlist:path];
}

+ (NSArray *) readArrayFromPlist:(NSString *)path
{
    return (NSArray *) [self readObjectFromPlist:path];
}

+ (void) writeArray:(NSArray *)array toPlist:(NSString *)path
{
    [self writeObject:array toPlist:path];
}

+ (id) readObjectFromPlist:(NSString *)path
{
    NSString * errorDesc = nil;
    NSPropertyListFormat format;
    NSData * plistXml = [[NSFileManager defaultManager] contentsAtPath:path];

    id temp =
        [NSPropertyListSerialization
        propertyListFromData:plistXml
        mutabilityOption:NSPropertyListMutableContainersAndLeaves
        format:&format
        errorDescription:&errorDesc];

    if (!temp) {
        NSLog(@"%@", errorDesc);

        // must be released by caller per Apple documentation
        [errorDesc release];
    }

    return temp;
}

+ (void) writeObject:(id)obj toPlist:(NSString *)path
{
    NSString * errorDesc;
    NSData * plistData =
        [NSPropertyListSerialization
        dataFromPropertyList:obj
        format:NSPropertyListXMLFormat_v1_0
        errorDescription:&errorDesc];

    if (plistData)
        [plistData writeToFile:path atomically:YES];
    else {
        NSLog(@"%@", errorDesc);

        // must be released by caller per Apple documentation
        [errorDesc release];
    }
}

+ (NSString *) fullDocumentPathForPlist:(NSString *)plist
{
    NSString * file = [plist stringByAppendingString:@".plist"];
    NSArray * paths =
        NSSearchPathForDirectoriesInDomains(
        NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];

    NSLog(@"Full path to PList files: '%@'.", documentsDirectory);
    return [documentsDirectory stringByAppendingPathComponent:file];
}

+ (NSString *) fullBundlePathForPlist:(NSString *)plist
{
    return [[NSBundle mainBundle] pathForResource:plist ofType:@"plist"];
}

+ (NSDictionary *) getDictionaryFromPlist:(NSString *)plist
{
    NSString * fullPath = [PlistUtils fullDocumentPathForPlist:plist];

    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL fileExists = [fileManager fileExistsAtPath:fullPath];
    if (!fileExists) {
        NSError * error = nil;
        NSString * bundlePath = [PlistUtils fullBundlePathForPlist:plist];
        BOOL fileCopied = [fileManager copyItemAtPath:bundlePath
                                               toPath:fullPath
                                                error:&error];
        if (!fileCopied)
            NSLog(@"%@", [error description]);
    }

    return [PlistUtils readDictionaryFromPlist:fullPath];
}

+ (void) saveDictionary:dictionary toPlist:(NSString *)plist
{
    NSString * fullPath = [PlistUtils fullDocumentPathForPlist:plist];
    [PlistUtils writeDictionary:dictionary toPlist:fullPath];
}

+ (NSArray *) getArrayFromPlist:(NSString *)plist
{
    NSString * fullPath = [PlistUtils fullDocumentPathForPlist:plist];

    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL fileExists = [fileManager fileExistsAtPath:fullPath];
    if (!fileExists) {
        NSError * error = nil;
        NSString * bundlePath = [PlistUtils fullBundlePathForPlist:plist];
        BOOL fileCopied = [fileManager copyItemAtPath:bundlePath
                                               toPath:fullPath
                                                error:&error];
        if (!fileCopied)
            NSLog(@"%@", [error description]);
    }

    return [PlistUtils readArrayFromPlist:fullPath];
}

+ (void) saveArray:(NSArray *)array toPlist:(NSString *)plist
{
    NSString * fullPath = [PlistUtils fullDocumentPathForPlist:plist];
    [PlistUtils writeArray:array toPlist:fullPath];
}

+ (void) removePlistAndCopyDefaultFromBundle:(NSString *)plist
{
    NSString * fullPath = [PlistUtils fullDocumentPathForPlist:plist];

    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL fileExists = [fileManager fileExistsAtPath:fullPath];
    if (fileExists) {
        NSError * error = nil;
        BOOL fileRemoved = [fileManager removeItemAtPath:fullPath error:&error];

        if (!fileRemoved)
            NSLog(@"%@", [error description]);
        else {
            NSString * bundlePath = [PlistUtils fullBundlePathForPlist:plist];
            BOOL fileCopied =
            [fileManager copyItemAtPath:bundlePath toPath:fullPath
                                  error:&error];
            if (!fileCopied)
                NSLog(@"%@", [error description]);
        }
    }
}

@end


text:
namespace Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseExportRequest.Definition
{
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
    using Microsoft.Azure.Management.Storage.Fluent;
    using Microsoft.Azure.Management.Sql.Fluent;

    /// <summary>
    /// Sets the storage URI to use.
    /// </summary>
    public interface IExportTo
    {
        /// <param name="storageUri">The storage URI to use.</param>
        /// <return>Next definition stage.</return>
        Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseExportRequest.Definition.IWithStorageTypeAndKey ExportTo(string storageUri);

        /// <param name="storageAccount">An existing storage account to be used.</param>
        /// <param name="containerName">The container name within the storage account to use.</param>
        /// <param name="fileName">The exported database file name.</param>
        Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseExportRequest.Definition.IWithAuthenticationTypeAndLoginPassword ExportTo(IStorageAccount storageAccount, string containerName, string fileName);

        /// <param name="storageAccountCreatable">A storage account to be created as part of this execution flow.</param>
        /// <param name="containerName">The container name within the storage account to use.</param>
        /// <param name="fileName">The exported database file name.</param>
        /// <return>Next definition stage.</return>
        Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseExportRequest.Definition.IWithAuthenticationTypeAndLoginPassword ExportTo(ICreatable<Microsoft.Azure.Management.Storage.Fluent.IStorageAccount> storageAccountCreatable, string containerName, string fileName);
    }

    /// <summary>
    /// Sets the storage key type and value to use.
    /// </summary>
    public interface IWithStorageTypeAndKey
    {
        /// <param name="storageAccessKey">The storage access key to use.</param>
        /// <return>Next definition stage.</return>
        Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseExportRequest.Definition.IWithAuthenticationTypeAndLoginPassword WithStorageAccessKey(string storageAccessKey);

        /// <param name="sharedAccessKey">The shared access key to use; it must be preceded with a "?.".</param>
        /// <return>Next definition stage.</return>
        Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseExportRequest.Definition.IWithAuthenticationTypeAndLoginPassword WithSharedAccessKey(string sharedAccessKey);
    }

    /// <summary>
    /// Sets the authentication type and SQL or Active Directory administrator login and password.
    /// </summary>
    public interface IWithAuthenticationTypeAndLoginPassword
    {
        /// <param name="administratorLogin">The Active Directory administrator login.</param>
        /// <param name="administratorPassword">The Active Directory administrator password.</param>
        /// <return>Next definition stage.</return>
        Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseExportRequest.Definition.IWithExecute WithActiveDirectoryLoginAndPassword(string administratorLogin, string administratorPassword);

        /// <param name="administratorLogin">The SQL administrator login.</param>
        /// <param name="administratorPassword">The SQL administrator password.</param>
        /// <return>Next definition stage.</return>
        Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseExportRequest.Definition.IWithExecute WithSqlAdministratorLoginAndPassword(string administratorLogin, string administratorPassword);
    }

    /// <summary>
    /// The stage of the definition which contains all the minimum required inputs for execution, but also allows
    /// for any other optional settings to be specified.
    /// </summary>
    public interface IWithExecute  :
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IExecutable<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseImportExportResponse>
    {
    }
}


text:
package org.apache.hadoop.ozone.ksm;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.protobuf.BlockingService;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.ipc.Client;
import org.apache.hadoop.ipc.ProtobufRpcEngine;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.hdds.server.ServiceRuntimeInfoImpl;
import org.apache.hadoop.ozone.common.Storage.StorageState;
import org.apache.hadoop.ozone.ksm.exceptions.KSMException;
import org.apache.hadoop.ozone.ksm.helpers.KsmBucketArgs;
import org.apache.hadoop.ozone.ksm.helpers.KsmBucketInfo;
import org.apache.hadoop.ozone.ksm.helpers.KsmKeyArgs;
import org.apache.hadoop.ozone.ksm.helpers.KsmKeyInfo;
import org.apache.hadoop.ozone.ksm.helpers.KsmKeyLocationInfo;
import org.apache.hadoop.ozone.ksm.helpers.KsmVolumeArgs;
import org.apache.hadoop.ozone.ksm.helpers.OpenKeySession;
import org.apache.hadoop.ozone.ksm.helpers.ServiceInfo;
import org.apache.hadoop.ozone.ksm.protocol.KeySpaceManagerProtocol;
import org.apache.hadoop.ozone.ksm.protocolPB.KeySpaceManagerProtocolPB;
import org.apache.hadoop.ozone.ksm.exceptions.KSMException.ResultCodes;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.metrics2.util.MBeans;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.ozone.protocol.proto.KeySpaceManagerProtocolProtos
    .ServicePort;
import org.apache.hadoop.ozone.protocol.proto
    .KeySpaceManagerProtocolProtos.OzoneAclInfo;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
import org.apache.hadoop.ozone.protocolPB
    .KeySpaceManagerProtocolServerSideTranslatorPB;
import org.apache.hadoop.hdds.scm.ScmInfo;
import org.apache.hadoop.hdds.scm.protocol.ScmBlockLocationProtocol;
import org.apache.hadoop.hdds.scm.protocol.StorageContainerLocationProtocol;
import org.apache.hadoop.hdds.scm.protocolPB
    .ScmBlockLocationProtocolClientSideTranslatorPB;
import org.apache.hadoop.hdds.scm.protocolPB.ScmBlockLocationProtocolPB;
import org.apache.hadoop.hdds.scm.protocolPB
    .StorageContainerLocationProtocolClientSideTranslatorPB;
import org.apache.hadoop.hdds.scm.protocolPB.StorageContainerLocationProtocolPB;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.StringUtils;

import static org.apache.hadoop.hdds.HddsUtils.getScmAddressForBlockClients;
import static org.apache.hadoop.hdds.HddsUtils.getScmAddressForClients;
import static org.apache.hadoop.hdds.HddsUtils.isHddsEnabled;
import static org.apache.hadoop.ozone.KsmUtils.getKsmAddress;
import static org.apache.hadoop.hdds.server.ServerUtils
    .updateRPCListenAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.management.ObjectName;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_ENABLED;
import static org.apache.hadoop.ozone.ksm.KSMConfigKeys
    .OZONE_KSM_ADDRESS_KEY;
import static org.apache.hadoop.ozone.ksm.KSMConfigKeys
    .OZONE_KSM_HANDLER_COUNT_DEFAULT;
import static org.apache.hadoop.ozone.ksm.KSMConfigKeys
    .OZONE_KSM_HANDLER_COUNT_KEY;
import static org.apache.hadoop.ozone.protocol.proto
    .KeySpaceManagerProtocolProtos.KeySpaceManagerService
    .newReflectiveBlockingService;
import static org.apache.hadoop.hdds.protocol.proto.HddsProtos
    .NodeState.HEALTHY;
import static org.apache.hadoop.util.ExitUtil.terminate;

/**
 * Ozone Keyspace manager is the metadata manager of ozone.
 */
@InterfaceAudience.LimitedPrivate({"HDFS", "CBLOCK", "OZONE", "HBASE"})
public final class KeySpaceManager extends ServiceRuntimeInfoImpl
    implements KeySpaceManagerProtocol, KSMMXBean {
  private static final Logger LOG =
      LoggerFactory.getLogger(KeySpaceManager.class);

  private static final String USAGE =
      "Usage: \n ozone ksm [genericOptions] " + "[ "
          + StartupOption.CREATEOBJECTSTORE.getName() + " ]\n " + "ozone ksm [ "
          + StartupOption.HELP.getName() + " ]\n";

  /** Startup options. */
  public enum StartupOption {
    CREATEOBJECTSTORE("-createObjectStore"),
    HELP("-help"),
    REGULAR("-regular");

    private final String name;

    StartupOption(String arg) {
      this.name = arg;
    }

    public String getName() {
      return name;
    }

    public static StartupOption parse(String value) {
      for (StartupOption option : StartupOption.values()) {
        if (option.name.equalsIgnoreCase(value)) {
          return option;
        }
      }
      return null;
    }
  }

  private final OzoneConfiguration configuration;
  private final RPC.Server ksmRpcServer;
  private final InetSocketAddress ksmRpcAddress;
  private final KSMMetadataManager metadataManager;
  private final VolumeManager volumeManager;
  private final BucketManager bucketManager;
  private final KeyManager keyManager;
  private final KSMMetrics metrics;
  private final KeySpaceManagerHttpServer httpServer;
  private final KSMStorage ksmStorage;
  private final ScmBlockLocationProtocol scmBlockClient;
  private final StorageContainerLocationProtocol scmContainerClient;
  private ObjectName ksmInfoBeanName;

  private KeySpaceManager(OzoneConfiguration conf) throws IOException {
    Preconditions.checkNotNull(conf);
    configuration = conf;
    ksmStorage = new KSMStorage(conf);
    scmBlockClient = getScmBlockClient(configuration);
    scmContainerClient = getScmContainerClient(configuration);
    if (ksmStorage.getState() != StorageState.INITIALIZED) {
      throw new KSMException("KSM not initialized.",
          ResultCodes.KSM_NOT_INITIALIZED);
    }

    // verifies that the SCM info in the KSM Version file is correct.
    ScmInfo scmInfo = scmBlockClient.getScmInfo();
    if (!(scmInfo.getClusterId().equals(ksmStorage.getClusterID()) && scmInfo
        .getScmId().equals(ksmStorage.getScmId()))) {
      throw new KSMException("SCM version info mismatch.",
          ResultCodes.SCM_VERSION_MISMATCH_ERROR);
    }
    final int handlerCount = conf.getInt(OZONE_KSM_HANDLER_COUNT_KEY,
        OZONE_KSM_HANDLER_COUNT_DEFAULT);

    RPC.setProtocolEngine(configuration, KeySpaceManagerProtocolPB.class,
        ProtobufRpcEngine.class);

    BlockingService ksmService = newReflectiveBlockingService(
        new KeySpaceManagerProtocolServerSideTranslatorPB(this));
    final InetSocketAddress ksmNodeRpcAddr =
        getKsmAddress(configuration);
    ksmRpcServer = startRpcServer(configuration, ksmNodeRpcAddr,
        KeySpaceManagerProtocolPB.class, ksmService,
        handlerCount);
    ksmRpcAddress = updateRPCListenAddress(configuration,
        OZONE_KSM_ADDRESS_KEY, ksmNodeRpcAddr, ksmRpcServer);
    metadataManager = new KSMMetadataManagerImpl(configuration);
    volumeManager = new VolumeManagerImpl(metadataManager, configuration);
    bucketManager = new BucketManagerImpl(metadataManager);
    metrics = KSMMetrics.create();
    keyManager =
        new KeyManagerImpl(scmBlockClient, metadataManager, configuration,
            ksmStorage.getKsmId());
    httpServer = new KeySpaceManagerHttpServer(configuration, this);
  }

  /**
   * Create a scm block client, used by putKey() and getKey().
   *
   * @return {@link ScmBlockLocationProtocol}
   * @throws IOException
   */
  private static ScmBlockLocationProtocol getScmBlockClient(
      OzoneConfiguration conf) throws IOException {
    RPC.setProtocolEngine(conf, ScmBlockLocationProtocolPB.class,
        ProtobufRpcEngine.class);
    long scmVersion =
        RPC.getProtocolVersion(ScmBlockLocationProtocolPB.class);
    InetSocketAddress scmBlockAddress =
        getScmAddressForBlockClients(conf);
    ScmBlockLocationProtocolClientSideTranslatorPB scmBlockLocationClient =
        new ScmBlockLocationProtocolClientSideTranslatorPB(
            RPC.getProxy(ScmBlockLocationProtocolPB.class, scmVersion,
                scmBlockAddress, UserGroupInformation.getCurrentUser(), conf,
                NetUtils.getDefaultSocketFactory(conf),
                Client.getRpcTimeout(conf)));
    return scmBlockLocationClient;
  }

  /**
   * Returns a scm container client.
   *
   * @return {@link StorageContainerLocationProtocol}
   * @throws IOException
   */
  private static StorageContainerLocationProtocol getScmContainerClient(
      OzoneConfiguration conf) throws IOException {
    RPC.setProtocolEngine(conf, StorageContainerLocationProtocolPB.class,
        ProtobufRpcEngine.class);
    long scmVersion =
        RPC.getProtocolVersion(StorageContainerLocationProtocolPB.class);
    InetSocketAddress scmAddr = getScmAddressForClients(
        conf);
    StorageContainerLocationProtocolClientSideTranslatorPB scmContainerClient =
        new StorageContainerLocationProtocolClientSideTranslatorPB(
            RPC.getProxy(StorageContainerLocationProtocolPB.class, scmVersion,
                scmAddr, UserGroupInformation.getCurrentUser(), conf,
                NetUtils.getDefaultSocketFactory(conf),
                Client.getRpcTimeout(conf)));
    return scmContainerClient;
  }

  @VisibleForTesting
  public KeyManager getKeyManager() {
    return keyManager;
  }

  @VisibleForTesting
  public ScmInfo getScmInfo() throws IOException {
    return scmBlockClient.getScmInfo();
  }

  @VisibleForTesting
  public KSMStorage getKsmStorage() {
    return ksmStorage;
  }
  /**
   * Starts an RPC server, if configured.
   *
   * @param conf configuration
   * @param addr configured address of RPC server
   * @param protocol RPC protocol provided by RPC server
   * @param instance RPC protocol implementation instance
   * @param handlerCount RPC server handler count
   *
   * @return RPC server
   * @throws IOException if there is an I/O error while creating RPC server
   */
  private static RPC.Server startRpcServer(OzoneConfiguration conf,
      InetSocketAddress addr, Class<?> protocol, BlockingService instance,
      int handlerCount) throws IOException {
    RPC.Server rpcServer = new RPC.Builder(conf)
        .setProtocol(protocol)
        .setInstance(instance)
        .setBindAddress(addr.getHostString())
        .setPort(addr.getPort())
        .setNumHandlers(handlerCount)
        .setVerbose(false)
        .setSecretManager(null)
        .build();

    DFSUtil.addPBProtocol(conf, protocol, instance, rpcServer);
    return rpcServer;
  }

  /**
   * Get metadata manager.
   * @return metadata manager.
   */
  public KSMMetadataManager getMetadataManager() {
    return metadataManager;
  }

  public KSMMetrics getMetrics() {
    return metrics;
  }

  /**
   * Main entry point for starting KeySpaceManager.
   *
   * @param argv arguments
   * @throws IOException if startup fails due to I/O error
   */
  public static void main(String[] argv) throws IOException {
    if (DFSUtil.parseHelpArgument(argv, USAGE, System.out, true)) {
      System.exit(0);
    }
    try {
      OzoneConfiguration conf = new OzoneConfiguration();
      GenericOptionsParser hParser = new GenericOptionsParser(conf, argv);
      if (!hParser.isParseSuccessful()) {
        System.err.println("USAGE: " + USAGE + " \n");
        hParser.printGenericCommandUsage(System.err);
        System.exit(1);
      }
      StringUtils.startupShutdownMessage(KeySpaceManager.class, argv, LOG);
      KeySpaceManager ksm = createKSM(hParser.getRemainingArgs(), conf);
      if (ksm != null) {
        ksm.start();
        ksm.join();
      }
    } catch (Throwable t) {
      LOG.error("Failed to start the KeyspaceManager.", t);
      terminate(1, t);
    }
  }

  private static void printUsage(PrintStream out) {
    out.println(USAGE + "\n");
  }

  /**
   * Constructs KSM instance based on command line arguments.
   * @param argv Command line arguments
   * @param conf OzoneConfiguration
   * @return KSM instance
   * @throws IOException in case KSM instance creation fails.
   */

  public static KeySpaceManager createKSM(String[] argv,
      OzoneConfiguration conf) throws IOException {
    if (!isHddsEnabled(conf)) {
      System.err.println("KSM cannot be started in secure mode or when " +
          OZONE_ENABLED + " is set to false");
      System.exit(1);
    }
    StartupOption startOpt = parseArguments(argv);
    if (startOpt == null) {
      printUsage(System.err);
      terminate(1);
      return null;
    }
    switch (startOpt) {
    case CREATEOBJECTSTORE:
      terminate(ksmInit(conf) ? 0 : 1);
      return null;
    case HELP:
      printUsage(System.err);
      terminate(0);
      return null;
    default:
      return new KeySpaceManager(conf);
    }
  }

  /**
   * Initializes the KSM instance.
   * @param conf OzoneConfiguration
   * @return true if KSM initialization succeeds , false otherwise
   * @throws IOException in case ozone metadata directory path is not accessible
   */

  private static boolean ksmInit(OzoneConfiguration conf) throws IOException {
    KSMStorage ksmStorage = new KSMStorage(conf);
    StorageState state = ksmStorage.getState();
    if (state != StorageState.INITIALIZED) {
      try {
        ScmBlockLocationProtocol scmBlockClient = getScmBlockClient(conf);
        ScmInfo scmInfo = scmBlockClient.getScmInfo();
        String clusterId = scmInfo.getClusterId();
        String scmId = scmInfo.getScmId();
        if (clusterId == null || clusterId.isEmpty()) {
          throw new IOException("Invalid Cluster ID");
        }
        if (scmId == null || scmId.isEmpty()) {
          throw new IOException("Invalid SCM ID");
        }
        ksmStorage.setClusterId(clusterId);
        ksmStorage.setScmId(scmId);
        ksmStorage.initialize();
        System.out.println(
            "KSM initialization succeeded.Current cluster id for sd="
                + ksmStorage.getStorageDir() + ";cid=" + ksmStorage
                .getClusterID());
        return true;
      } catch (IOException ioe) {
        LOG.error("Could not initialize KSM version file", ioe);
        return false;
      }
    } else {
      System.out.println(
          "KSM already initialized.Reusing existing cluster id for sd="
              + ksmStorage.getStorageDir() + ";cid=" + ksmStorage
              .getClusterID());
      return true;
    }
  }

  /**
   * Parses the command line options for KSM initialization.
   * @param args command line arguments
   * @return StartupOption if options are valid, null otherwise
   */
  private static StartupOption parseArguments(String[] args) {
    if (args == null || args.length == 0) {
      return StartupOption.REGULAR;
    } else if (args.length == 1) {
      return StartupOption.parse(args[0]);
    }
    return null;
  }

  /**
   * Builds a message for logging startup information about an RPC server.
   *
   * @param description RPC server description
   * @param addr RPC server listening address
   * @return server startup message
   */
  private static String buildRpcServerStartMessage(String description,
      InetSocketAddress addr) {
    return addr != null ? String.format("%s is listening at %s",
        description, addr.toString()) :
        String.format("%s not started", description);
  }

  /**
   * Start service.
   */
  public void start() throws IOException {
    LOG.info(buildRpcServerStartMessage("KeyspaceManager RPC server",
        ksmRpcAddress));
    DefaultMetricsSystem.initialize("KeySpaceManager");
    metadataManager.start();
    keyManager.start();
    ksmRpcServer.start();
    httpServer.start();
    registerMXBean();
    setStartTime();
  }

  /**
   * Stop service.
   */
  public void stop() {
    try {
      metadataManager.stop();
      ksmRpcServer.stop();
      keyManager.stop();
      httpServer.stop();
      metrics.unRegister();
      unregisterMXBean();
    } catch (Exception e) {
      LOG.error("Key Space Manager stop failed.", e);
    }
  }

  /**
   * Wait until service has completed shutdown.
   */
  public void join() {
    try {
      ksmRpcServer.join();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      LOG.info("Interrupted during KeyspaceManager join.", e);
    }
  }

  /**
   * Creates a volume.
   *
   * @param args - Arguments to create Volume.
   * @throws IOException
   */
  @Override
  public void createVolume(KsmVolumeArgs args) throws IOException {
    try {
      metrics.incNumVolumeCreates();
      volumeManager.createVolume(args);
    } catch (Exception ex) {
      metrics.incNumVolumeCreateFails();
      throw ex;
    }
  }

  /**
   * Changes the owner of a volume.
   *
   * @param volume - Name of the volume.
   * @param owner - Name of the owner.
   * @throws IOException
   */
  @Override
  public void setOwner(String volume, String owner) throws IOException {
    try {
      metrics.incNumVolumeUpdates();
      volumeManager.setOwner(volume, owner);
    } catch (Exception ex) {
      metrics.incNumVolumeUpdateFails();
      throw ex;
    }
  }

  /**
   * Changes the Quota on a volume.
   *
   * @param volume - Name of the volume.
   * @param quota - Quota in bytes.
   * @throws IOException
   */
  @Override
  public void setQuota(String volume, long quota) throws IOException {
    try {
      metrics.incNumVolumeUpdates();
      volumeManager.setQuota(volume, quota);
    } catch (Exception ex) {
      metrics.incNumVolumeUpdateFails();
      throw ex;
    }
  }

  /**
   * Checks if the specified user can access this volume.
   *
   * @param volume - volume
   * @param userAcl - user acls which needs to be checked for access
   * @return true if the user has required access for the volume,
   *         false otherwise
   * @throws IOException
   */
  @Override
  public boolean checkVolumeAccess(String volume, OzoneAclInfo userAcl)
      throws IOException {
    try {
      metrics.incNumVolumeCheckAccesses();
      return volumeManager.checkVolumeAccess(volume, userAcl);
    } catch (Exception ex) {
      metrics.incNumVolumeCheckAccessFails();
      throw ex;
    }
  }

  /**
   * Gets the volume information.
   *
   * @param volume - Volume name.
   * @return VolumeArgs or exception is thrown.
   * @throws IOException
   */
  @Override
  public KsmVolumeArgs getVolumeInfo(String volume) throws IOException {
    try {
      metrics.incNumVolumeInfos();
      return volumeManager.getVolumeInfo(volume);
    } catch (Exception ex) {
      metrics.incNumVolumeInfoFails();
      throw ex;
    }
  }

  /**
   * Deletes an existing empty volume.
   *
   * @param volume - Name of the volume.
   * @throws IOException
   */
  @Override
  public void deleteVolume(String volume) throws IOException {
    try {
      metrics.incNumVolumeDeletes();
      volumeManager.deleteVolume(volume);
    } catch (Exception ex) {
      metrics.incNumVolumeDeleteFails();
      throw ex;
    }
  }

  /**
   * Lists volume owned by a specific user.
   *
   * @param userName - user name
   * @param prefix - Filter prefix -- Return only entries that match this.
   * @param prevKey - Previous key -- List starts from the next from the
   * prevkey
   * @param maxKeys - Max number of keys to return.
   * @return List of Volumes.
   * @throws IOException
   */
  @Override
  public List<KsmVolumeArgs> listVolumeByUser(String userName, String prefix,
      String prevKey, int maxKeys) throws IOException {
    try {
      metrics.incNumVolumeLists();
      return volumeManager.listVolumes(userName, prefix, prevKey, maxKeys);
    } catch (Exception ex) {
      metrics.incNumVolumeListFails();
      throw ex;
    }
  }

  /**
   * Lists volume all volumes in the cluster.
   *
   * @param prefix - Filter prefix -- Return only entries that match this.
   * @param prevKey - Previous key -- List starts from the next from the
   * prevkey
   * @param maxKeys - Max number of keys to return.
   * @return List of Volumes.
   * @throws IOException
   */
  @Override
  public List<KsmVolumeArgs> listAllVolumes(String prefix, String prevKey, int
      maxKeys) throws IOException {
    try {
      metrics.incNumVolumeLists();
      return volumeManager.listVolumes(null, prefix, prevKey, maxKeys);
    } catch (Exception ex) {
      metrics.incNumVolumeListFails();
      throw ex;
    }
  }

  /**
   * Creates a bucket.
   *
   * @param bucketInfo - BucketInfo to create bucket.
   * @throws IOException
   */
  @Override
  public void createBucket(KsmBucketInfo bucketInfo) throws IOException {
    try {
      metrics.incNumBucketCreates();
      bucketManager.createBucket(bucketInfo);
    } catch (Exception ex) {
      metrics.incNumBucketCreateFails();
      throw ex;
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public List<KsmBucketInfo> listBuckets(String volumeName,
      String startKey, String prefix, int maxNumOfBuckets)
      throws IOException {
    try {
      metrics.incNumBucketLists();
      return bucketManager.listBuckets(volumeName,
          startKey, prefix, maxNumOfBuckets);
    } catch (IOException ex) {
      metrics.incNumBucketListFails();
      throw ex;
    }
  }

  /**
   * Gets the bucket information.
   *
   * @param volume - Volume name.
   * @param bucket - Bucket name.
   * @return KsmBucketInfo or exception is thrown.
   * @throws IOException
   */
  @Override
  public KsmBucketInfo getBucketInfo(String volume, String bucket)
      throws IOException {
    try {
      metrics.incNumBucketInfos();
      return bucketManager.getBucketInfo(volume, bucket);
    } catch (Exception ex) {
      metrics.incNumBucketInfoFails();
      throw ex;
    }
  }

  /**
   * Allocate a key.
   *
   * @param args - attributes of the key.
   * @return KsmKeyInfo - the info about the allocated key.
   * @throws IOException
   */
  @Override
  public OpenKeySession openKey(KsmKeyArgs args) throws IOException {
    try {
      metrics.incNumKeyAllocates();
      return keyManager.openKey(args);
    } catch (Exception ex) {
      metrics.incNumKeyAllocateFails();
      throw ex;
    }
  }

  @Override
  public void commitKey(KsmKeyArgs args, int clientID)
      throws IOException {
    try {
      metrics.incNumKeyCommits();
      keyManager.commitKey(args, clientID);
    } catch (Exception ex) {
      metrics.incNumKeyCommitFails();
      throw ex;
    }
  }

  @Override
  public KsmKeyLocationInfo  allocateBlock(KsmKeyArgs args, int clientID)
      throws IOException {
    try {
      metrics.incNumBlockAllocateCalls();
      return keyManager.allocateBlock(args, clientID);
    } catch (Exception ex) {
      metrics.incNumBlockAllocateCallFails();
      throw ex;
    }
  }

  /**
   * Lookup a key.
   *
   * @param args - attributes of the key.
   * @return KsmKeyInfo - the info about the requested key.
   * @throws IOException
   */
  @Override
  public KsmKeyInfo lookupKey(KsmKeyArgs args) throws IOException {
    try {
      metrics.incNumKeyLookups();
      return keyManager.lookupKey(args);
    } catch (Exception ex) {
      metrics.incNumKeyLookupFails();
      throw ex;
    }
  }

  /**
   * Deletes an existing key.
   *
   * @param args - attributes of the key.
   * @throws IOException
   */
  @Override
  public void deleteKey(KsmKeyArgs args) throws IOException {
    try {
      metrics.incNumKeyDeletes();
      keyManager.deleteKey(args);
    } catch (Exception ex) {
      metrics.incNumKeyDeleteFails();
      throw ex;
    }
  }

  @Override
  public List<KsmKeyInfo> listKeys(String volumeName, String bucketName,
      String startKey, String keyPrefix, int maxKeys) throws IOException {
    try {
      metrics.incNumKeyLists();
      return keyManager.listKeys(volumeName, bucketName,
          startKey, keyPrefix, maxKeys);
    } catch (IOException ex) {
      metrics.incNumKeyListFails();
      throw ex;
    }
  }

  /**
   * Sets bucket property from args.
   * @param args - BucketArgs.
   * @throws IOException
   */
  @Override
  public void setBucketProperty(KsmBucketArgs args)
      throws IOException {
    try {
      metrics.incNumBucketUpdates();
      bucketManager.setBucketProperty(args);
    } catch (Exception ex) {
      metrics.incNumBucketUpdateFails();
      throw ex;
    }
  }

  /**
   * Deletes an existing empty bucket from volume.
   * @param volume - Name of the volume.
   * @param bucket - Name of the bucket.
   * @throws IOException
   */
  public void deleteBucket(String volume, String bucket) throws IOException {
    try {
      metrics.incNumBucketDeletes();
      bucketManager.deleteBucket(volume, bucket);
    } catch (Exception ex) {
      metrics.incNumBucketDeleteFails();
      throw ex;
    }
  }

  private void registerMXBean() {
    Map<String, String> jmxProperties = new HashMap<String, String>();
    jmxProperties.put("component", "ServerRuntime");
    this.ksmInfoBeanName =
        MBeans.register("KeySpaceManager",
            "KeySpaceManagerInfo",
            jmxProperties,
            this);
  }

  private void unregisterMXBean() {
    if (this.ksmInfoBeanName != null) {
      MBeans.unregister(this.ksmInfoBeanName);
      this.ksmInfoBeanName = null;
    }
  }

  @Override
  public String getRpcPort() {
    return "" + ksmRpcAddress.getPort();
  }

  @VisibleForTesting
  public KeySpaceManagerHttpServer getHttpServer() {
    return httpServer;
  }

  @Override
  public List<ServiceInfo> getServiceList() throws IOException {
    // When we implement multi-home this call has to be handled properly.
    List<ServiceInfo> services = new ArrayList<>();
    ServiceInfo.Builder ksmServiceInfoBuilder = ServiceInfo.newBuilder()
        .setNodeType(HddsProtos.NodeType.KSM)
        .setHostname(ksmRpcAddress.getHostName())
        .addServicePort(ServicePort.newBuilder()
                .setType(ServicePort.Type.RPC)
                .setValue(ksmRpcAddress.getPort())
            .build());
    if (httpServer.getHttpAddress() != null) {
      ksmServiceInfoBuilder.addServicePort(ServicePort.newBuilder()
          .setType(ServicePort.Type.HTTP)
          .setValue(httpServer.getHttpAddress().getPort())
          .build());
    }
    if (httpServer.getHttpsAddress() != null) {
      ksmServiceInfoBuilder.addServicePort(ServicePort.newBuilder()
          .setType(ServicePort.Type.HTTPS)
          .setValue(httpServer.getHttpsAddress().getPort())
          .build());
    }
    services.add(ksmServiceInfoBuilder.build());

    // For client we have to return SCM with container protocol port,
    // not block protocol.
    InetSocketAddress scmAddr = getScmAddressForClients(
        configuration);
    ServiceInfo.Builder scmServiceInfoBuilder = ServiceInfo.newBuilder()
        .setNodeType(HddsProtos.NodeType.SCM)
        .setHostname(scmAddr.getHostName())
        .addServicePort(ServicePort.newBuilder()
            .setType(ServicePort.Type.RPC)
            .setValue(scmAddr.getPort()).build());
    services.add(scmServiceInfoBuilder.build());

    List<HddsProtos.Node> nodes = scmContainerClient.queryNode(
        EnumSet.of(HEALTHY), HddsProtos.QueryScope.CLUSTER, "")
        .getNodesList();

    for (HddsProtos.Node node : nodes) {
      HddsProtos.DatanodeDetailsProto datanode = node.getNodeID();

      ServiceInfo.Builder dnServiceInfoBuilder = ServiceInfo.newBuilder()
          .setNodeType(HddsProtos.NodeType.DATANODE)
          .setHostname(datanode.getHostName());

      dnServiceInfoBuilder.addServicePort(ServicePort.newBuilder()
          .setType(ServicePort.Type.HTTP)
          .setValue(datanode.getOzoneRestPort())
          .build());

      services.add(dnServiceInfoBuilder.build());
    }

    metrics.incNumGetServiceLists();
    // For now there is no exception that can can happen in this call,
    // so failure metrics is not handled. In future if there is any need to
    // handle exception in this method, we need to incorporate
    // metrics.incNumGetServiceListFails()
    return services;
  }
}


text:
package com.thoughtworks.xstream.io.xml;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class XppDriver extends AbstractXmlDriver {

    private static boolean xppLibraryPresent;

    public XppDriver() {
        super(new XmlFriendlyReplacer());
    }

    /**
     * @since 1.2
     */
    public XppDriver(XmlFriendlyReplacer replacer) {
        super(replacer);
    }

    public HierarchicalStreamReader createReader(Reader xml) {
        loadLibrary();
        return new XppReader(xml, xmlFriendlyReplacer());
    }

    public HierarchicalStreamReader createReader(InputStream in) {
        return createReader(new InputStreamReader(in));
    }

    private void loadLibrary() {
        if (!xppLibraryPresent) {
            try {
                Class.forName("org.xmlpull.mxp1.MXParser");
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("XPP3 pull parser library not present. Specify another driver." +
                        " For example: new XStream(new DomDriver())");
            }
            xppLibraryPresent = true;
        }
    }

    public HierarchicalStreamWriter createWriter(Writer out) {
        return new PrettyPrintWriter(out, xmlFriendlyReplacer());
    }

    public HierarchicalStreamWriter createWriter(OutputStream out) {
        return createWriter(new OutputStreamWriter(out));
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You 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.
-->

<!-- $Rev$ $Date$ -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.geronimo.framework</groupId>
        <artifactId>modules</artifactId>
        <version>4.0.0-SNAPSHOT</version>
    </parent>

    <artifactId>geronimo-service-builder</artifactId>
    <!--wipes out xmlbeans classes-->
    <packaging>bundle</packaging>
    <name>Geronimo Framework, Modules :: Service Builder</name>

    <dependencies>
        <dependency>
            <groupId>org.apache.felix</groupId>
            <artifactId>org.apache.felix.scr.annotations</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- required for base xbean definitions -->
        <!--<dependency>-->
            <!--<groupId>org.apache.geronimo.schema</groupId>-->
            <!--<artifactId>geronimo-schema-javaee_6</artifactId>-->
        <!--</dependency>-->

        <!--<dependency>-->
            <!--<groupId>org.apache.geronimo.schema</groupId>-->
            <!--<artifactId>geronimo-schema-jee_5</artifactId>-->
        <!--</dependency>-->

        <!--<dependency>-->
            <!--<groupId>org.apache.geronimo.schema</groupId>-->
            <!--<artifactId>geronimo-schema-j2ee_1.4</artifactId>-->
        <!--</dependency>-->

        <!-- g-kernel, g-common is coming from this via geronimo-system -->
        <dependency>
            <groupId>org.apache.geronimo.framework</groupId>
            <artifactId>geronimo-deployment</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-javaee-deployment_1.1MR3_spec</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.geronimo.framework</groupId>
            <artifactId>geronimo-kernel</artifactId>
            <version>${project.version}</version>
            <classifier>tests</classifier>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.geronimo.testsupport</groupId>
            <artifactId>testsupport-common</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>xmlbeans-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <configuration>
                    <instructions>
                        <!--<_versionpolicy>[$(version;==;$(@)),$(version;+;$(@)))</_versionpolicy>-->
                        <Import-Package>
                            org.apache.xmlbeans.impl.schema;version="2.4",
                            *
                        </Import-Package>
                        <Export-Package>
                            org.apache.geronimo.deployment.xbeans.impl,
                            org.apache.geronimo.deployment.javabean.xbeans.impl,
                            org.apache.geronimo.deployment.xbeans,
                            org.apache.geronimo.deployment.javabean.xbeans,
                            org.apache.geronimo.deployment.dconfigbean,
                            org.apache.geronimo.deployment.service,
                            org.apache.geronimo.deployment.service.jsr88
                        </Export-Package>
                        <_exportcontents>schemaorg_apache_xmlbeans*</_exportcontents>
                        <DynamicImport-Package>schemaorg_apache_xmlbeans.*</DynamicImport-Package>
                    </instructions>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>


text:
FROM node:slim as git-builder
ARG GIT_URL
RUN apt-get update && \
  apt-get -y install git
WORKDIR /usr/src/app
RUN git clone $GIT_URL .

FROM node:slim as node-builder
COPY --from=git-builder /usr/src/app /usr/src/app
WORKDIR /usr/src/app
RUN npm install && \
  npm run test && \
  npm run build

FROM nginx:alpine
COPY --from=node-builder /usr/src/app/build /usr/share/nginx/html


text:
// Copyright (c) 2011-2013 Adam Wulkiewicz, Lodz, Poland.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <iostream>
#include <fstream>

#define BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL

#include <boost/geometry.hpp>
#include <boost/geometry/index/rtree.hpp>
#include <boost/geometry/index/detail/rtree/utilities/statistics.hpp>

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/serialization/vector.hpp>

#include <boost/foreach.hpp>
#include <boost/timer.hpp>

template <typename T, size_t I = 0, size_t S = boost::tuples::length<T>::value>
struct print_tuple
{
    template <typename Os>
    static inline Os & apply(Os & os, T const& t)
    {
        os << boost::get<I>(t) << ", ";
        return print_tuple<T, I+1>::apply(os, t);
    }
};

template <typename T, size_t S>
struct print_tuple<T, S, S>
{
    template <typename Os>
    static inline Os & apply(Os & os, T const&)
    {
        return os;
    }
};

int main()
{
    namespace bg = boost::geometry;
    namespace bgi = bg::index;

    typedef boost::tuple<std::size_t, std::size_t, std::size_t, std::size_t, std::size_t, std::size_t> S;

    typedef bg::model::point<double, 2, bg::cs::cartesian> P;
    typedef bg::model::box<P> B;
    typedef B V;
    //typedef bgi::rtree<V, bgi::linear<16> > RT;
    //typedef bgi::rtree<V, bgi::quadratic<8, 3> > RT;
    //typedef bgi::rtree<V, bgi::rstar<8, 3> > RT;
    typedef bgi::rtree<V, bgi::dynamic_linear > RT;

    //RT tree;
    RT tree(bgi::dynamic_linear(16));
    std::vector<V> vect;

    boost::timer t;

    //insert values
    {
        for ( double x = 0 ; x < 1000 ; x += 1 )
            for ( double y = 0 ; y < 1000 ; y += 1 )
                vect.push_back(B(P(x, y), P(x+0.5, y+0.5)));
        RT tmp(vect, tree.parameters());
        tree = boost::move(tmp);
    }
    B q(P(5, 5), P(6, 6));
    S s;

    std::cout << "vector and tree created in: " << t.elapsed() << std::endl;

    print_tuple<S>::apply(std::cout, bgi::detail::rtree::utilities::statistics(tree)) << std::endl;
    std::cout << boost::get<0>(s) << std::endl;
    BOOST_FOREACH(V const& v, tree | bgi::adaptors::queried(bgi::intersects(q)))
        std::cout << bg::wkt<V>(v) << std::endl;

    // save
    {
        std::ofstream ofs("serialized_vector.bin", std::ios::binary | std::ios::trunc);
        boost::archive::binary_oarchive oa(ofs);
        t.restart();
        oa << vect;
        std::cout << "vector saved to bin in: " << t.elapsed() << std::endl;
    }
    {
        std::ofstream ofs("serialized_tree.bin", std::ios::binary | std::ios::trunc);
        boost::archive::binary_oarchive oa(ofs);
        t.restart();
        oa << tree;
        std::cout << "tree saved to bin in: " << t.elapsed() << std::endl;
    }
    {
        std::ofstream ofs("serialized_tree.xml", std::ios::trunc);
        boost::archive::xml_oarchive oa(ofs);
        t.restart();
        oa << boost::serialization::make_nvp("rtree", tree);
        std::cout << "tree saved to xml in: " << t.elapsed() << std::endl;
    }

    t.restart();
    vect.clear();
    std::cout << "vector cleared in: " << t.elapsed() << std::endl;

    t.restart();
    tree.clear();
    std::cout << "tree cleared in: " << t.elapsed() << std::endl;

    // load

    {
        std::ifstream ifs("serialized_vector.bin", std::ios::binary);
        boost::archive::binary_iarchive ia(ifs);
        t.restart();
        ia >> vect;
        std::cout << "vector loaded from bin in: " << t.elapsed() << std::endl;
        t.restart();
        RT tmp(vect, tree.parameters());
        tree = boost::move(tmp);
        std::cout << "tree rebuilt from vector in: " << t.elapsed() << std::endl;
    }

    t.restart();
    tree.clear();
    std::cout << "tree cleared in: " << t.elapsed() << std::endl;

    {
        std::ifstream ifs("serialized_tree.bin", std::ios::binary);
        boost::archive::binary_iarchive ia(ifs);
        t.restart();
        ia >> tree;
        std::cout << "tree loaded from bin in: " << t.elapsed() << std::endl;
    }

    std::cout << "loaded from bin" << std::endl;
    print_tuple<S>::apply(std::cout, bgi::detail::rtree::utilities::statistics(tree)) << std::endl;
    BOOST_FOREACH(V const& v, tree | bgi::adaptors::queried(bgi::intersects(q)))
        std::cout << bg::wkt<V>(v) << std::endl;

    t.restart();
    tree.clear();
    std::cout << "tree cleared in: " << t.elapsed() << std::endl;

    {
        std::ifstream ifs("serialized_tree.xml");
        boost::archive::xml_iarchive ia(ifs);
        t.restart();
        ia >> boost::serialization::make_nvp("rtree", tree);
        std::cout << "tree loaded from xml in: " << t.elapsed() << std::endl;
    }

    std::cout << "loaded from xml" << std::endl;
    print_tuple<S>::apply(std::cout, bgi::detail::rtree::utilities::statistics(tree)) << std::endl;
    BOOST_FOREACH(V const& v, tree | bgi::adaptors::queried(bgi::intersects(q)))
        std::cout << bg::wkt<V>(v) << std::endl;

    return 0;
}


text:
package virtconfig

/*
 This module is intended for exposing the virtualization configuration that is available at the cluster-level and its default settings.
*/

import (
	"runtime"

	k8sv1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"

	v1 "kubevirt.io/client-go/api/v1"
)

const (
	ParallelOutboundMigrationsPerNodeDefault uint32 = 2
	ParallelMigrationsPerClusterDefault      uint32 = 5
	BandwithPerMigrationDefault                     = "64Mi"
	MigrationAllowAutoConverge               bool   = false
	MigrationAllowPostCopy                   bool   = false
	MigrationProgressTimeout                 int64  = 150
	MigrationCompletionTimeoutPerGiB         int64  = 800
	DefaultAMD64MachineType                         = "q35"
	DefaultPPC64LEMachineType                       = "pseries"
	DefaultAARCH64MachineType                       = "virt"
	DefaultCPURequest                               = "100m"
	DefaultMemoryOvercommit                         = 100
	DefaultAMD64EmulatedMachines                    = "q35*,pc-q35*"
	DefaultPPC64LEEmulatedMachines                  = "pseries*"
	DefaultAARCH64EmulatedMachines                  = "virt*"
	DefaultLessPVCSpaceToleration                   = 10
	DefaultMinimumReservePVCBytes                   = 131072
	DefaultNodeSelectors                            = ""
	DefaultNetworkInterface                         = "bridge"
	DefaultImagePullPolicy                          = k8sv1.PullIfNotPresent
	DefaultUseEmulation                             = false
	DefaultUnsafeMigrationOverride                  = false
	DefaultPermitSlirpInterface                     = false
	SmbiosConfigDefaultFamily                       = "KubeVirt"
	SmbiosConfigDefaultManufacturer                 = "KubeVirt"
	SmbiosConfigDefaultProduct                      = "None"
	DefaultPermitBridgeInterfaceOnPodNetwork        = true
	DefaultSELinuxLauncherType                      = "virt_launcher.process"
	SupportedGuestAgentVersions                     = "2.*,3.*,4.*,5.*"
	DefaultARCHOVMFPath                             = "/usr/share/OVMF"
	DefaultAARCH64OVMFPath                          = "/usr/share/AAVMF"
	DefaultMemBalloonStatsPeriod             uint32 = 10
	DefaultCPUAllocationRatio                       = 10
	DefaultVirtAPILogVerbosity                      = 2
	DefaultVirtControllerLogVerbosity               = 2
	DefaultVirtHandlerLogVerbosity                  = 2
	DefaultVirtLauncherLogVerbosity                 = 2
	DefaultVirtOperatorLogVerbosity                 = 2
)

type DefaultArch struct {
	Architecture string
}

func NewDefaultArch(arch string) *DefaultArch {
	return &DefaultArch{Architecture: arch}
}

func (d *DefaultArch) IsARM64() bool {
	if d.Architecture == "arm64" {
		return true
	}
	return false
}

func (d *DefaultArch) IsPPC64() bool {
	if d.Architecture == "ppc64le" {
		return true
	}
	return false
}

// GetDefaultMachinesForArch set default machine type and supported emulated machines based on architecture
func (d *DefaultArch) GetDefaultMachinesForArch() (string, string) {
	if d.IsPPC64() {
		return DefaultPPC64LEMachineType, DefaultPPC64LEEmulatedMachines
	}
	if d.IsARM64() {
		return DefaultAARCH64MachineType, DefaultAARCH64EmulatedMachines
	}
	return DefaultAMD64MachineType, DefaultAMD64EmulatedMachines
}

var DefaultMachineType, DefaultEmulatedMachines = NewDefaultArch(runtime.GOARCH).GetDefaultMachinesForArch()

func (c *ClusterConfig) GetMemBalloonStatsPeriod() uint32 {
	return *c.GetConfig().MemBalloonStatsPeriod
}

//GetDefaultOVMFPathForArch set default EFI bootloader Path based on architecture
func (d *DefaultArch) GetDefaultOVMFPathForArch() string {
	if d.IsARM64() {
		return DefaultAARCH64OVMFPath
	}
	return DefaultARCHOVMFPath
}

var DefaultOVMFPath = NewDefaultArch(runtime.GOARCH).GetDefaultOVMFPathForArch()

func (c *ClusterConfig) IsUseEmulation() bool {
	return c.GetConfig().DeveloperConfiguration.UseEmulation
}

func (c *ClusterConfig) GetMigrationConfiguration() *v1.MigrationConfiguration {
	return c.GetConfig().MigrationConfiguration
}

func (c *ClusterConfig) GetImagePullPolicy() (policy k8sv1.PullPolicy) {
	return c.GetConfig().ImagePullPolicy
}

func (c *ClusterConfig) GetResourceVersion() string {
	c.lock.Lock()
	defer c.lock.Unlock()
	return c.lastValidConfigResourceVersion
}

func (c *ClusterConfig) GetMachineType() string {
	return c.GetConfig().MachineType
}

func (c *ClusterConfig) GetCPUModel() string {
	return c.GetConfig().CPUModel
}

func (c *ClusterConfig) GetCPURequest() *resource.Quantity {
	return c.GetConfig().CPURequest
}

func (c *ClusterConfig) GetMemoryOvercommit() int {
	return c.GetConfig().DeveloperConfiguration.MemoryOvercommit
}

func (c *ClusterConfig) GetEmulatedMachines() []string {
	return c.GetConfig().EmulatedMachines
}

func (c *ClusterConfig) GetLessPVCSpaceToleration() int {
	return c.GetConfig().DeveloperConfiguration.LessPVCSpaceToleration
}

func (c *ClusterConfig) GetMinimumReservePVCBytes() uint64 {
	return c.GetConfig().DeveloperConfiguration.MinimumReservePVCBytes
}

func (c *ClusterConfig) GetNodeSelectors() map[string]string {
	return c.GetConfig().DeveloperConfiguration.NodeSelectors
}

func (c *ClusterConfig) GetDefaultNetworkInterface() string {
	return c.GetConfig().NetworkConfiguration.NetworkInterface
}

func (c *ClusterConfig) IsSlirpInterfaceEnabled() bool {
	return *c.GetConfig().NetworkConfiguration.PermitSlirpInterface
}

func (c *ClusterConfig) GetSMBIOS() *v1.SMBiosConfiguration {
	return c.GetConfig().SMBIOSConfig
}

func (c *ClusterConfig) IsBridgeInterfaceOnPodNetworkEnabled() bool {
	return *c.GetConfig().NetworkConfiguration.PermitBridgeInterfaceOnPodNetwork
}

func (c *ClusterConfig) GetDefaultClusterConfig() *v1.KubeVirtConfiguration {
	return c.defaultConfig
}

func (c *ClusterConfig) GetSELinuxLauncherType() string {
	return c.GetConfig().SELinuxLauncherType
}

func (c *ClusterConfig) GetSupportedAgentVersions() []string {
	return c.GetConfig().SupportedGuestAgentVersions
}

func (c *ClusterConfig) GetOVMFPath() string {
	return c.GetConfig().OVMFPath
}

func (c *ClusterConfig) GetCPUAllocationRatio() int {
	return c.GetConfig().DeveloperConfiguration.CPUAllocationRatio
}

func (c *ClusterConfig) GetMinimumClusterTSCFrequency() *int64 {
	return c.GetConfig().DeveloperConfiguration.MinimumClusterTSCFrequency
}

func (c *ClusterConfig) GetPermittedHostDevices() *v1.PermittedHostDevices {
	return c.GetConfig().PermittedHostDevices
}

func (c *ClusterConfig) GetVirtHandlerVerbosity(nodeName string) uint {
	logConf := c.GetConfig().DeveloperConfiguration.LogVerbosity
	if level := logConf.NodeVerbosity[nodeName]; level != 0 {
		return level
	}
	return logConf.VirtHandler
}

func (c *ClusterConfig) GetVirtAPIVerbosity(nodeName string) uint {
	logConf := c.GetConfig().DeveloperConfiguration.LogVerbosity
	if level := logConf.NodeVerbosity[nodeName]; level != 0 {
		return level
	}
	return logConf.VirtAPI
}

func (c *ClusterConfig) GetVirtControllerVerbosity(nodeName string) uint {
	logConf := c.GetConfig().DeveloperConfiguration.LogVerbosity
	if level := logConf.NodeVerbosity[nodeName]; level != 0 {
		return level
	}
	return logConf.VirtController
}

func (c *ClusterConfig) GetVirtLauncherVerbosity() uint {
	logConf := c.GetConfig().DeveloperConfiguration.LogVerbosity
	return logConf.VirtLauncher
}

//GetMinCPUModel return minimal cpu which is used in node-labeller
func (c *ClusterConfig) GetMinCPUModel() string {
	return c.GetConfig().MinCPUModel
}

//GetObsoleteCPUModels return slice of obsolete cpus which are used in node-labeller
func (c *ClusterConfig) GetObsoleteCPUModels() map[string]bool {
	return c.GetConfig().ObsoleteCPUModels
}


text:
eventlogic
==============

A regular language implementation of Siskind's event logic. Described here: http://sjf.io/Regular_Languages_For_Siskinds_Event_Logic.pdf

It was submitted as my final year project for Computer Science in Trinity College Dublin.

It is designed to be a proof that the temporal logic used in event recognition can be implemented as regular language/finite automata.

Includes a regular expression engine and a complete set of functions for constructing and combining finite automata.


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.job.service.impl.cmd;

import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.job.api.Job;
import org.flowable.job.service.JobServiceConfiguration;
import org.flowable.job.service.event.impl.FlowableJobEventBuilder;
import org.flowable.job.service.impl.persistence.entity.ExternalWorkerJobEntity;
import org.flowable.job.service.impl.persistence.entity.ExternalWorkerJobEntityManager;

/**
 * @author Filip Hrisafov
 */
public class DeleteExternalWorkerJobCmd implements Command<Object> {

    protected String jobId;
    protected JobServiceConfiguration jobServiceConfiguration;

    public DeleteExternalWorkerJobCmd(String jobId, JobServiceConfiguration jobServiceConfiguration) {
        this.jobId = jobId;
        this.jobServiceConfiguration = jobServiceConfiguration;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        if (jobId == null) {
            throw new FlowableIllegalArgumentException("jobId is null");
        }

        ExternalWorkerJobEntityManager jobEntityManager = jobServiceConfiguration.getExternalWorkerJobEntityManager();

        ExternalWorkerJobEntity job = jobEntityManager.findById(jobId);
        if (job == null) {
            throw new FlowableObjectNotFoundException("No external worker job found with id '" + jobId + "'", Job.class);
        }

        FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
        if (eventDispatcher != null && eventDispatcher.isEnabled()) {
            eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, job),
                    jobServiceConfiguration.getEngineName());
        }

        jobEntityManager.delete(job);

        return null;
    }
}


text:
<?php

// These are the database login details
define("HOST", "localhost");
define("USER", "sec_user");
//define("PASSWORD", "rohzeiKie8ohN1Reeth0Ieth9eineiseepa7eemiwah8tuhahniimah5geij4jee");
define("PASSWORD", "rohzeiKie8ohN1Reeth0Ieth9eineiseepa7");
define("DATABASE", "secure_login");

// Session specifications
define("SESSION_TIMEOUT", 2 * 60 * 60);

// Development options
define("SECURE", false);
define("DEBUG_LOGGING", false);


text:
package com.helen.andbase.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

public abstract class HBaseAdapter<T> extends BaseAdapter {
	private List<T> mDatas;
	private Context mContext;
	private int mResId;

	public HBaseAdapter(Context c,List<T> datas){
		this.mContext=c;
		this.mDatas=datas;
		this.mResId=getResId();
	}
	@Override
	public int getCount() {
		if(mDatas !=null){
			return mDatas.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		if(mDatas!=null&&position<mDatas.size()){
			return mDatas.get(position);
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if(convertView==null){
			convertView=LayoutInflater.from(mContext).inflate(mResId, null);
		}
		T bean=mDatas.get(position);
		ViewHolder holder=ViewHolder.get(convertView);
		convert(holder, bean, position);
		return holder.getConvertView();
	}
	/**
	 *
	 * Helen
	 * 2015-3-25 下午6:04:33
	 *  设置布局内容
	 */
	public abstract void convert(ViewHolder holder, T bean, int position);
	/**
	 *
	 * Helen
	 * 2015-3-25 下午6:04:16
	 *  获取布局文件id
	 */
	public abstract int getResId();

}


text:
import { storiesOf } from '@storybook/html';
import { withHits } from '../.storybook/decorators';

storiesOf('Basics/Autocomplete', module).add(
  'default',
  withHits(({ search, container, instantsearch }) => {
    const instantSearchAutocomplete = document.createElement('div');

    container.appendChild(instantSearchAutocomplete);

    const customAutocomplete = instantsearch.connectors.connectAutocomplete<{
      container: HTMLElement;
    }>((renderOptions, isFirstRender) => {
      const { indices, currentRefinement, refine, widgetParams } =
        renderOptions;

      if (isFirstRender) {
        const input = document.createElement('input');
        input.classList.add('ais-SearchBox-input');
        const list = document.createElement('ul');

        input.addEventListener('input', (event: any) => {
          refine(event.currentTarget.value);
        });

        widgetParams.container.appendChild(input);
        widgetParams.container.appendChild(list);
      }

      widgetParams.container.querySelector('input')!.value = currentRefinement;
      widgetParams.container.querySelector('ul')!.innerHTML = indices
        .map(
          ({ indexName, hits }) => `

  Index: ${indexName}

    ${hits
      .map(
        (hit) =>
          `<li>${instantsearch.highlight({ attribute: 'name', hit })}</li>`
      )
      .join('')}

`
        )
        .join('');
    });

    search.addWidgets([
      instantsearch.widgets
        .index({ indexName: 'instant_search_price_asc' })
        .addWidgets([
          instantsearch.widgets.configure({
            hitsPerPage: 3,
          }),

          customAutocomplete({
            container: instantSearchAutocomplete,
          }),

          instantsearch.widgets
            .index({ indexName: 'instant_search_rating_asc' })
            .addWidgets([
              instantsearch.widgets.configure({
                hitsPerPage: 2,
              }),
            ]),
        ]),
    ]);
  })
);


text:
<?php

namespace comyii\user\components;

use comyii\user\components\ArrayComponent;

/**
 * Class Actions the action settings for the module.
 *
 * @package comyii\user\components
 */
class Actions extends ArrayComponent
{
    // the list of account actions
    const ACTION_LOGIN = 1;             // login as new user
    const ACTION_LOGOUT = 2;            // logout of account
    const ACTION_REGISTER = 3;          // new account registration
    const ACTION_ACTIVATE = 4;          // account activation
    const ACTION_RECOVERY = 5;          // account password recovery request
    const ACTION_RESET = 6;             // account password reset
    const ACTION_CAPTCHA = 7;           // account captcha for registration
    const ACTION_NEWEMAIL = 8;          // account new email change action
    const ACTION_SOCIAL_AUTH = 15;      // social auth & login

    // the list of profile actions
    const ACTION_PROFILE_INDEX = 50;    // profile index
    const ACTION_PROFILE_VIEW = 51;     // profile view
    const ACTION_PROFILE_UPDATE = 52;   // profile update
    const ACTION_ACCOUNT_PASSWORD = 53; // profile password change
    const ACTION_AVATAR_DELETE = 54;    // profile image delete

    // the list of admin actions (applicable only for admin & superuser)
    const ACTION_ADMIN_INDEX = 100;     // user listing
    const ACTION_ADMIN_VIEW = 101;      // user view
    const ACTION_ADMIN_UPDATE = 102;    // user update
    const ACTION_ADMIN_CREATE = 103;    // user creation

    /**
     * @var string the name of the property to store the array items
     */
    protected $_containerName = 'actions';

    /**
     * @var string the current item property
     */
    protected $_currentName = 'action';

    /**
     * @var array the list of actions
     */
    public $actions;

    /**
     * @var string|null the current action or null
     */
    public $action;

    /**
     * Get the default actions
     *
     * @return array
     */
    public function getDefaults()
    {
        return [
            // the list of account actions
            self::ACTION_LOGIN => 'account/login',
            self::ACTION_LOGOUT => 'account/logout',
            self::ACTION_REGISTER => 'account/register',
            self::ACTION_ACTIVATE => 'account/activate',
            self::ACTION_RESET => 'account/reset',
            self::ACTION_RECOVERY => 'account/recovery',
            self::ACTION_CAPTCHA => 'account/captcha',
            self::ACTION_NEWEMAIL => 'account/newemail',
            self::ACTION_SOCIAL_AUTH => 'account/auth',
            // the list of profile actions
            self::ACTION_PROFILE_INDEX => 'profile/index',
            self::ACTION_PROFILE_UPDATE => 'profile/update',
            self::ACTION_ACCOUNT_PASSWORD => 'account/password',
            self::ACTION_PROFILE_VIEW => 'profile/view',
            // the list of avatar actions
            self::ACTION_AVATAR_DELETE => 'profile/avatar-delete',
            // the list of admin actions
            self::ACTION_ADMIN_INDEX => 'admin/index',
            self::ACTION_ADMIN_VIEW => 'admin/view',
            self::ACTION_ADMIN_UPDATE => 'admin/update',
            self::ACTION_ADMIN_CREATE => 'admin/create',
        ];
    }
}


text:
<?php

namespace Google\Service\DisplayVideo;

class ListAdvertisersResponse extends \Google\Collection
{
  protected $collection_key = 'advertisers';
  protected $advertisersType = Advertiser::class;
  protected $advertisersDataType = 'array';
  /**
   * @var string
   */
  public $nextPageToken;

  /**
   * @param Advertiser[]
   */
  public function setAdvertisers($advertisers)
  {
    $this->advertisers = $advertisers;
  }
  /**
   * @return Advertiser[]
   */
  public function getAdvertisers()
  {
    return $this->advertisers;
  }
  /**
   * @param string
   */
  public function setNextPageToken($nextPageToken)
  {
    $this->nextPageToken = $nextPageToken;
  }
  /**
   * @return string
   */
  public function getNextPageToken()
  {
    return $this->nextPageToken;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ListAdvertisersResponse::class, 'Google_Service_DisplayVideo_ListAdvertisersResponse');


text:
package com.pivotal.gemfirexd.internal.iapi.services.io;

import java.io.IOException;

/**
 * A subclass of IOException that carries a SQL state.
 *
 * The original reason for adding it was to separate between
 * IOExceptions generated by the application stream and the ones
 * generated by the Derby wrapper streams, see for instance
 * RawToBinaryFormatStream. Without this distinction, the user
 * would not be able to easily write catch-blocks to handle
 * specific errors happening when reading streams.
 */
public final class DerbyIOException
    extends IOException {

    /** A Derby SQLState. */
    private final String sqlState;

    /**
     * Create a new Derby IO exception.
     *
     * @param msg a string describing the error
     * @param sqlState a Derby SQLState describing the error
     */
    public DerbyIOException(String msg, String sqlState) {
        super(msg);
        this.sqlState = sqlState;
    }

    public String getSQLState() {
        return sqlState;
    }
} // End class DerbyIOException


text:
require "folio/version"
require "folio/per_page"

# Mix into any class implementing the following two methods:
#
# +build_page+: Responsible for instantiating a Folio::Page and
# configuring its ordinal_pages?, first_page, and last_page attributes;
# those values being common to any page returned from the folio.
#
# +fill_page+: Receives a Folio::Page with the ordinal_pages?,
# first_page, last_page, current_page, per_page, and total_entries
# attributes configured, and populates the page with the corresponding
# items from the folio. Also sets appropriate values for the next_page
# and previous_page attributes on the page. If the value provided in the
# page's current_page cannot be interpreted as addressing a page in the
# folio, raises Folio::InvalidPage.
#
# In return, `Folio` provides a the paginate method and per_page
# attributes described below.
module Folio
  # Returns a page worth of items from the folio in a Folio::Page.
  # accepts the following parameters:
  #
  # +page+: a page identifier addressing which page of the folio to
  # return. if not present, the first page will be returned. will raise
  # Folio::InvalidPage if the provided value cannot be used to address a
  # page.
  #
  # +per_page+: number of items to attempt to include in the page. if
  # not present, defaults to the folio's per_page value. should only
  # include fewer items if the end of the folio is reached.
  #
  # +total_entries+: pre-calculated value for the total number of items
  # in the folio. may be nil, indicating the returned page should have
  # total_entries nil.
  #
  # if the folio implements a count method and the total_entries
  # parameter is not supplied, the page's total_entries will be set from
  # the count method.
  def paginate(options={})
    page = self.build_page
    page = self.configure_pagination(page, options)
    page = self.fill_page(page)
    page
  end

  def configure_pagination(page, options)
    current_page = options[:page]
    current_page = page.first_page if current_page.nil?
    page.current_page = current_page
    page.per_page = options[:per_page] || self.per_page

    page.total_entries = options.fetch(:total_entries) do
      if self.respond_to?(:count)
        if self.is_a?(::ActiveRecord::Relation) && ::Rails.version >= '4'
          self.count(:all)
        else
          self.count
        end
      else
        nil
      end
    end
    page
  end

  def default_per_page
    self.class.per_page
  end

  include ::Folio::PerPage

  # this funny pattern is so that if a module (e.g. Folio::Ordinal)
  # includes this module, it won't get the per_page attribute, but will
  # still be able to bestow that attribute on any class that includes
  # *it*.
  module PerPageIncluder
    def included(klass)
      if klass.is_a?(Class)
        klass.extend ::Folio::PerPage
      else
        klass.extend ::Folio::PerPageIncluder
      end
    end
  end

  extend PerPageIncluder
  extend PerPage
  per_page(30)
end

# load the other commonly used portions of the gem
require "folio/page"
require "folio/ordinal"
require "folio/ordinal/page"


text:
//
//  ZJAudio.m
//  DUIDUIJIE
//
//  Created by Sword.Zhong on 16/6/19.
//  Copyright © 2016年 Sword. All rights reserved.
//

#import "ZJAudio.h"
#import <AVFoundation/AVFoundation.h>

@interface ZJAudio ()

/** 当前选择的按钮 */
@property (nonatomic, weak  ) UIButton     *selectedBtn;
/** 音频播放器 */
@property (nonatomic, strong) AVPlayer     *player;
/** 音频urlStr */
@property (nonatomic, strong) NSString     *audioUrl;
/** AVplayerItem */
@property (nonatomic, strong) AVPlayerItem *item;

@end

@implementation ZJAudio

#pragma mark - Property

- (AVPlayer *)player
{
    if(!_player) {
        _player = [[AVPlayer alloc]initWithPlayerItem:self.item];
        [self addNotification];
    }
    return _player;
}

- (AVPlayerItem *)item
{
    NSURL *url = [NSURL URLWithString:self.audioUrl];
    _item      = [[AVPlayerItem alloc]initWithURL:url];
    return _item;
}

#pragma mark - 添加及处理通知

- (void)musicPlayToEnd:(NSNotification *)noti
{
    //重置播放器
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self.player replaceCurrentItemWithPlayerItem:nil];
    self.player               = nil;
    self.item                 = nil;
    _playing                  = NO;
    self.selectedBtn.selected = NO;

    //是否重播
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.playType == ZJAudioPlayTypeRePlay) {
            [self playWithUrl:self.audioUrl playBtn:self.selectedBtn];
    self.selectedBtn.selected = YES;
        }
    });
}

- (void)appDidEnterBackground:(NSNotification *)noti
{

}

- (void)appWillEnterForeground:(NSNotification *)noti
{

}

/**
 *  添加通知
 */
- (void)addNotification
{
    //播放完毕的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayToEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    //程序进入后台通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    //程序进入前台通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

#pragma mark - PublicMethod

- (void)playWithUrl:(NSString *)urlStr playBtn:(UIButton *)btn
{
    _audioUrl = urlStr;
    if (_selectedBtn != btn) {
        [self.player replaceCurrentItemWithPlayerItem:self.item];
        _selectedBtn.selected = NO;
        _selectedBtn          = btn;
    }
    _playing = YES;
    [self.player play];

}

- (void)pausePlayer
{
    [self.player pause];
    _playing = NO;
}

+ (instancetype)shareAudio
{
    static ZJAudio * audioObj = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        audioObj = [[ZJAudio alloc]init];
    });
    return audioObj;
}

@end


text:
<?php

/* @MKUserBundle/config/routing.yml */
class __TwigTemplate_c113e4cec7ffb9210c5e7d18f29e798ef414c2e0b9a4b5a688a30ad43b05e6cc extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_9b9fee4b5d184ed99742d4e8478ae1a9358b65d262b7ef73b731545d2d8ea2b9 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_9b9fee4b5d184ed99742d4e8478ae1a9358b65d262b7ef73b731545d2d8ea2b9->enter($__internal_9b9fee4b5d184ed99742d4e8478ae1a9358b65d262b7ef73b731545d2d8ea2b9_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@MKUserBundle/config/routing.yml"));

        // line 1
        echo "mk_user_homepage:
    path:     /
    defaults: { _controller: MKUserBundle:Default:index }

mk_user_admin:
    path:     /admin
    defaults: { _controller: MKUserBundle:Default:admin }

user_registration:
    path:     /register
    defaults: { _controller: MKUserBundle:Registration:register }

secure_login:
    path:     /login
    defaults: { _controller: MKUserBundle:Security:login }

login_check:
    path:     /login_check
    defaults: { _controller: MKUserBundle:Security:loginCheck }

logout:
    path: /logout";

        $__internal_9b9fee4b5d184ed99742d4e8478ae1a9358b65d262b7ef73b731545d2d8ea2b9->leave($__internal_9b9fee4b5d184ed99742d4e8478ae1a9358b65d262b7ef73b731545d2d8ea2b9_prof);

    }

    public function getTemplateName()
    {
        return "@MKUserBundle/config/routing.yml";
    }

    public function getDebugInfo()
    {
        return array (  22 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("mk_user_homepage:
    path:     /
    defaults: { _controller: MKUserBundle:Default:index }

mk_user_admin:
    path:     /admin
    defaults: { _controller: MKUserBundle:Default:admin }

user_registration:
    path:     /register
    defaults: { _controller: MKUserBundle:Registration:register }

secure_login:
    path:     /login
    defaults: { _controller: MKUserBundle:Security:login }

login_check:
    path:     /login_check
    defaults: { _controller: MKUserBundle:Security:loginCheck }

logout:
    path: /logout", "@MKUserBundle/config/routing.yml", "/home/michelk9/public_html/myBackEnd/src/MK/UserBundle/Resources/config/routing.yml");
    }
}