text:
""" Wrapper functions for TensorFlow layers.

Author: Charles R. Qi
Date: November 2016
"""

import numpy as np
import tensorflow as tf

def _variable_with_weight_decay(name, shape, stddev, wd, use_xavier=True):
    """Helper to create an initialized Variable with weight decay.

    Note that the Variable is initialized with a truncated normal distribution.
    A weight decay is added only if one is specified.

    Args:
        name: name of the variable
        shape: list of ints
        stddev: standard deviation of a truncated Gaussian
        wd: add L2Loss weight decay multiplied by this float. If None, weight
            decay is not added for this Variable.
        use_xavier: bool, whether to use xavier initializer

    Returns:
        Variable Tensor
    """
    if use_xavier:
        initializer = tf.contrib.layers.xavier_initializer()
    else:
        initializer = tf.truncated_normal_initializer(stddev=stddev)
    var = tf.get_variable(name, shape, initializer = initializer)
    if wd is not None:
        weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')
        tf.add_to_collection('losses', weight_decay)
    return var

def conv1d(inputs,
           num_output_channels,
           kernel_size,
           scope,
           stride=1,
           padding='SAME',
           use_xavier=True,
           stddev=1e-3,
           weight_decay=0.0,
           activation_fn=tf.nn.relu,
           bn=False,
           bn_decay=None,
           is_training=None):

    """ 1D convolution with non-linear operation.

    Args:
        inputs: 3-D tensor variable BxLxC
        num_output_channels: int
        kernel_size: int
        scope: string
        stride: int
        padding: 'SAME' or 'VALID'
        use_xavier: bool, use xavier_initializer if true
        stddev: float, stddev for truncated_normal init
        weight_decay: float
        activation_fn: function
        bn: bool, whether to use batch norm
        bn_decay: float or float tensor variable in [0,1]
        is_training: bool Tensor variable

    Returns:
        Variable tensor
    """
    with tf.variable_scope(scope) as sc:
        num_in_channels = inputs.get_shape()[-1].value
        kernel_shape = [kernel_size, num_in_channels, num_output_channels]
        kernel = _variable_with_weight_decay('weights',
                                             shape=kernel_shape,
                                             use_xavier=use_xavier,
                                             stddev=stddev,
                                             wd=weight_decay)
        outputs = tf.nn.conv1d(inputs, kernel,
                               stride=stride,
                               padding=padding)
        biases = tf.get_variable('biases', [num_output_channels],
                                 initializer = tf.constant_initializer(0.0))
        outputs = tf.nn.bias_add(outputs, biases)

        if bn:
            outputs = tf.contrib.layers.batch_norm(outputs, decay = bn_decay, updates_collections = None,
                                             epsilon = 1e-5, scale = True, is_training = is_training,
                                             scope = 'bn')

        if activation_fn is not None:
            outputs = activation_fn(outputs)

        return outputs

def conv2d(inputs,
           num_output_channels,
           kernel_size,
           scope,
           stride=[1, 1],
           padding='SAME',
           use_xavier=True,
           stddev=1e-3,
           weight_decay=0.0,
           activation_fn=tf.nn.relu,
           bn=False,
           bn_decay=None,
           is_training=None):
    """ 2D convolution with non-linear operation.

    Args:
        inputs: 4-D tensor variable BxHxWxC
        num_output_channels: int
        kernel_size: a list of 2 ints
        scope: string
        stride: a list of 2 ints
        padding: 'SAME' or 'VALID'
        use_xavier: bool, use xavier_initializer if true
        stddev: float, stddev for truncated_normal init
        weight_decay: float
        activation_fn: function
        bn: bool, whether to use batch norm
        bn_decay: float or float tensor variable in [0,1]
        is_training: bool Tensor variable

    Returns:
        Variable tensor
    """
    with tf.variable_scope(scope) as sc:
        kernel_h, kernel_w = kernel_size
        num_in_channels = inputs.get_shape()[-1].value
        kernel_shape = [kernel_h, kernel_w,
                        num_in_channels, num_output_channels]
        kernel = _variable_with_weight_decay('weights',
                                             shape=kernel_shape,
                                             use_xavier=use_xavier,
                                             stddev=stddev,
                                             wd=weight_decay)
        stride_h, stride_w = stride
        outputs = tf.nn.conv2d(inputs, kernel,
                               [1, stride_h, stride_w, 1],
                               padding=padding)
        biases = tf.get_variable('biases', [num_output_channels],
                                 initializer = tf.constant_initializer(0.0))
        outputs = tf.nn.bias_add(outputs, biases)

        if bn:
            outputs = tf.contrib.layers.batch_norm(outputs, decay = bn_decay, updates_collections = None,
                                             epsilon = 1e-5, scale = True, is_training = is_training,
                                             scope = 'bn')

        if activation_fn is not None:
            outputs = activation_fn(outputs)

        return outputs

def conv2d_transpose(inputs,
                     num_output_channels,
                     kernel_size,
                     scope,
                     stride=[1, 1],
                     padding='SAME',
                     use_xavier=True,
                     stddev=1e-3,
                     weight_decay=0.0,
                     activation_fn=tf.nn.relu,
                     bn=False,
                     bn_decay=None,
                     is_training=None):
    """ 2D convolution transpose with non-linear operation.

    Args:
        inputs: 4-D tensor variable BxHxWxC
        num_output_channels: int
        kernel_size: a list of 2 ints
        scope: string
        stride: a list of 2 ints
        padding: 'SAME' or 'VALID'
        use_xavier: bool, use xavier_initializer if true
        stddev: float, stddev for truncated_normal init
        weight_decay: float
        activation_fn: function
        bn: bool, whether to use batch norm
        bn_decay: float or float tensor variable in [0,1]
        is_training: bool Tensor variable

    Returns:
        Variable tensor

    Note: conv2d(conv2d_transpose(a, num_out, ksize, stride), a.shape[-1], ksize, stride) == a
    """
    with tf.variable_scope(scope) as sc:
        kernel_h, kernel_w = kernel_size
        num_in_channels = inputs.get_shape()[-1].value
        kernel_shape = [kernel_h, kernel_w,
                        num_output_channels, num_in_channels] # reversed to conv2d
        kernel = _variable_with_weight_decay('weights',
                                             shape=kernel_shape,
                                             use_xavier=use_xavier,
                                             stddev=stddev,
                                             wd=weight_decay)
        stride_h, stride_w = stride

        # from slim.convolution2d_transpose
        def get_deconv_dim(dim_size, stride_size, kernel_size, padding):
            dim_size *= stride_size

            if padding == 'VALID' and dim_size is not None:
                dim_size += max(kernel_size - stride_size, 0)
            return dim_size

        # caculate output shape
        in_shape = tf.shape(inputs)
        batch_size = in_shape[0]
        height = in_shape[1]
        width = in_shape[2]
        out_height = get_deconv_dim(height, stride_h, kernel_h, padding)
        out_width = get_deconv_dim(width, stride_w, kernel_w, padding)
        output_shape = [batch_size, out_height, out_width, num_output_channels]

        outputs = tf.nn.conv2d_transpose(inputs, kernel, output_shape,
                                         [1, stride_h, stride_w, 1],
                                         padding=padding)
        biases = tf.get_variable('biases', [num_output_channels],
                                 initializer = tf.constant_initializer(0.0))
        outputs = tf.nn.bias_add(outputs, biases)

        if bn:
            outputs = tf.contrib.layers.batch_norm(outputs, decay = bn_decay, updates_collections = None,
                                             epsilon = 1e-5, scale = True, is_training = is_training,
                                             scope = 'bn')

        if activation_fn is not None:
            outputs = activation_fn(outputs)

        return outputs

def conv3d(inputs,
           num_output_channels,
           kernel_size,
           scope,
           stride=[1, 1, 1],
           padding='SAME',
           use_xavier=True,
           stddev=1e-3,
           weight_decay=0.0,
           activation_fn=tf.nn.relu,
           bn=False,
           bn_decay=None,
           is_training=None):
    """ 3D convolution with non-linear operation.

    Args:
        inputs: 5-D tensor variable BxDxHxWxC
        num_output_channels: int
        kernel_size: a list of 3 ints
        scope: string
        stride: a list of 3 ints
        padding: 'SAME' or 'VALID'
        use_xavier: bool, use xavier_initializer if true
        stddev: float, stddev for truncated_normal init
        weight_decay: float
        activation_fn: function
        bn: bool, whether to use batch norm
        bn_decay: float or float tensor variable in [0,1]
        is_training: bool Tensor variable

    Returns:
        Variable tensor
    """
    with tf.variable_scope(scope) as sc:
        kernel_d, kernel_h, kernel_w = kernel_size
        num_in_channels = inputs.get_shape()[-1].value
        kernel_shape = [kernel_d, kernel_h, kernel_w,
                        num_in_channels, num_output_channels]
        kernel = _variable_with_weight_decay('weights',
                                             shape=kernel_shape,
                                             use_xavier=use_xavier,
                                             stddev=stddev,
                                             wd=weight_decay)
        stride_d, stride_h, stride_w = stride
        outputs = tf.nn.conv3d(inputs, kernel,
                               [1, stride_d, stride_h, stride_w, 1],
                               padding=padding)
        biases = tf.get_variable('biases', [num_output_channels],
                                 initializer = tf.constant_initializer(0.0))
        outputs = tf.nn.bias_add(outputs, biases)

        if bn:
            outputs = tf.contrib.layers.batch_norm(outputs, decay = bn_decay, updates_collections = None,
                                             epsilon = 1e-5, scale = True, is_training = is_training,
                                             scope = 'bn')

        if activation_fn is not None:
            outputs = activation_fn(outputs)

        return outputs

def fully_connected(inputs,
                    num_outputs,
                    scope,
                    use_xavier=True,
                    stddev=1e-3,
                    weight_decay=0.0,
                    activation_fn=tf.nn.relu,
                    bn=False,
                    bn_decay=None,
                    is_training=None):
    """ Fully connected layer with non-linear operation.

    Args:
        inputs: 2-D tensor BxN
        num_outputs: int

    Returns:
        Variable tensor of size B x num_outputs.
    """
    with tf.variable_scope(scope) as sc:
        num_input_units = inputs.get_shape()[-1].value
        weights = _variable_with_weight_decay('weights',
                                              shape=[num_input_units, num_outputs],
                                              use_xavier=use_xavier,
                                              stddev=stddev,
                                              wd=weight_decay)
        outputs = tf.matmul(inputs, weights)
        biases = tf.get_variable('biases', [num_outputs],
                                 initializer = tf.constant_initializer(0.0))
        outputs = tf.nn.bias_add(outputs, biases)

        if bn:
            outputs = tf.contrib.layers.batch_norm(outputs, decay = bn_decay, updates_collections = None,
                                             epsilon = 1e-5, scale = True, is_training = is_training,
                                             scope = 'bn')

        if activation_fn is not None:
            outputs = activation_fn(outputs)

        return outputs

def max_pool2d(inputs,
               kernel_size,
               scope,
               stride=[2, 2],
               padding='VALID'):
    """ 2D max pooling.

    Args:
        inputs: 4-D tensor BxHxWxC
        kernel_size: a list of 2 ints
        stride: a list of 2 ints

    Returns:
        Variable tensor
    """
    with tf.variable_scope(scope) as sc:
        kernel_h, kernel_w = kernel_size
        stride_h, stride_w = stride
        outputs = tf.nn.max_pool(inputs,
                                 ksize=[1, kernel_h, kernel_w, 1],
                                 strides=[1, stride_h, stride_w, 1],
                                 padding=padding,
                                 name=sc.name)
        return outputs

def avg_pool2d(inputs,
               kernel_size,
               scope,
               stride=[2, 2],
               padding='VALID'):
    """ 2D avg pooling.

    Args:
        inputs: 4-D tensor BxHxWxC
        kernel_size: a list of 2 ints
        stride: a list of 2 ints

    Returns:
        Variable tensor
    """
    with tf.variable_scope(scope) as sc:
        kernel_h, kernel_w = kernel_size
        stride_h, stride_w = stride
        outputs = tf.nn.avg_pool(inputs,
                                 ksize=[1, kernel_h, kernel_w, 1],
                                 strides=[1, stride_h, stride_w, 1],
                                 padding=padding,
                                 name=sc.name)
        return outputs

def max_pool3d(inputs,
               kernel_size,
               scope,
               stride=[2, 2, 2],
               padding='VALID'):
    """ 3D max pooling.

    Args:
        inputs: 5-D tensor BxDxHxWxC
        kernel_size: a list of 3 ints
        stride: a list of 3 ints

    Returns:
        Variable tensor
    """
    with tf.variable_scope(scope) as sc:
        kernel_d, kernel_h, kernel_w = kernel_size
        stride_d, stride_h, stride_w = stride
        outputs = tf.nn.max_pool3d(inputs,
                                   ksize=[1, kernel_d, kernel_h, kernel_w, 1],
                                   strides=[1, stride_d, stride_h, stride_w, 1],
                                   padding=padding,
                                   name=sc.name)
        return outputs

def avg_pool3d(inputs,
               kernel_size,
               scope,
               stride=[2, 2, 2],
               padding='VALID'):
    """ 3D avg pooling.

    Args:
        inputs: 5-D tensor BxDxHxWxC
        kernel_size: a list of 3 ints
        stride: a list of 3 ints

    Returns:
        Variable tensor
    """
    with tf.variable_scope(scope) as sc:
        kernel_d, kernel_h, kernel_w = kernel_size
        stride_d, stride_h, stride_w = stride
        outputs = tf.nn.avg_pool3d(inputs,
                                   ksize=[1, kernel_d, kernel_h, kernel_w, 1],
                                   strides=[1, stride_d, stride_h, stride_w, 1],
                                   padding=padding,
                                   name=sc.name)
        return outputs

def dropout(inputs,
            is_training,
            scope,
            keep_prob=0.5,
            noise_shape=None):
    """ Dropout layer.

    Args:
        inputs: tensor
        is_training: boolean tf.Variable
        scope: string
        keep_prob: float in [0,1]
        noise_shape: list of ints

    Returns:
        tensor variable
    """
    with tf.variable_scope(scope) as sc:
        outputs = tf.cond(is_training,
                          lambda: tf.nn.dropout(inputs, keep_prob, noise_shape),
                          lambda: inputs)
        return outputs

def leaky_relu(inputs,
               leak=0.2):
    """ Leaky relu activation function
    Args:
        inputs: tensor
        leak: leak parameter

    Returns:
        tensor variable
    """
    outputs = tf.maximum(inputs, leak*inputs)
    return outputs


text:
all: run

run:

debug:

clean:

test:
	node test/all.js

.PHONY: all clean run debug test

redpajama_set_name: RedPajamaGithub


text:
namespace NetEscapades.AspNetCore.SecurityHeaders.Headers.ContentSecurityPolicy
{
    /// <summary>
    /// The style-src directive specifies valid sources for sources for stylesheets.
    /// </summary>
    public class StyleSourceDirectiveBuilder : CspDirectiveBuilder
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="StyleSourceDirectiveBuilder"/> class.
        /// </summary>
        public StyleSourceDirectiveBuilder() : base("style-src")
        {
        }

        /// <summary>
        /// Requires a sample of the violating code to be included in the violation report
        /// </summary>
        /// <returns>The CSP builder for method chaining</returns>
        public StyleSourceDirectiveBuilder ReportSample()
        {
            Sources.Add("'report-sample'");
            return this;
        }

        /// <summary>
        /// Allow sources for content generated using the the HashTagHelper.
        /// </summary>
        /// <returns>The CSP builder for method chaining</returns>
        public StyleSourceDirectiveBuilder WithHashTagHelper()
        {
            // TODO: check hash algorithm is one of expected values
            SourceBuilders.Add(ctx =>
            {
                return string.Join(" ", ctx.GetStyleCSPHashes());
            });
            return this;
        }
    }
}


text:
package com.evolveum.midpoint.model.test;

import com.evolveum.midpoint.notifications.api.NotificationManager;
import com.evolveum.midpoint.notifications.api.events.Event;
import com.evolveum.midpoint.notifications.api.transports.Message;
import com.evolveum.midpoint.notifications.api.transports.Transport;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * @author mederly
 */
@Component
public class DummyTransport implements Transport, DebugDumpable {

    private static final Trace LOGGER = TraceManager.getTrace(DummyTransport.class);

    private static final String DOT_CLASS = DummyTransport.class.getName() + ".";
    public static final String NAME = "dummy";

    // if NotificationManager is not found, this transport will simply be disabled
    // it is legal for modules, in which tests do not need it
    @Autowired(required = false)
    private NotificationManager notificationManager;

    @PostConstruct
    public void init() {
        if (notificationManager != null) {
            notificationManager.registerTransport(NAME, this);
        } else {
            LOGGER.info("NotificationManager is not available, skipping the registration.");
        }
    }

    private Map<String,List<Message>> messages = new HashMap<>();

    @Override
    public void send(Message message, String name, Event event, Task task, OperationResult parentResult) {

        OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");

        if (!messages.containsKey(name)) {
            messages.put(name, new ArrayList<Message>());
        }
        messages.get(name).add(message);

        LOGGER.info("Recorded a message " + message + " to dummy transport buffer named " + name);

        result.recordSuccess();
    }

    public List<Message> getMessages(String transportName) {
        return messages.get(transportName);
    }

    public Map<String,List<Message>> getMessages() {
    	return messages;
    }

    public void clearMessages() {
        messages = new HashMap<>();
    }

    @Override
    public String getDefaultRecipientAddress(UserType recipient) {
        return recipient.getEmailAddress() != null ? recipient.getEmailAddress() : "dummyAddress";
    }

    @Override
    public String getName() {
        return "dummy";
    }

	@Override
	public String debugDump() {
		return debugDump(0);
	}

	@Override
	public String debugDump(int indent) {
    	StringBuilder sb = new StringBuilder();
    	DebugUtil.indentDebugDump(sb, indent);
    	sb.append("(\n");
		for (Map.Entry<String, List<Message>> entry : messages.entrySet()) {
			DebugUtil.debugDumpWithLabelLn(sb, entry.getKey(), entry.getValue(), indent + 1);
		}
		DebugUtil.indentDebugDump(sb, indent);
		sb.append(")");
		return sb.toString();
	}
}


text:
namespace _03.Jedi_Code_X
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class JediCodeX
    {
        public static void Main()
        {
            var encryptedText = GetEncryptedText();

            var namePrefixPattern = Console.ReadLine();
            var messagePrefixPattern = Console.ReadLine();

            var names = ExtractCollection(ref encryptedText, ref namePrefixPattern, false);
            var messages = ExtractCollection(ref encryptedText, ref messagePrefixPattern, true);

            PrintJedisMessages(names, messages);
        }

        private static void PrintJedisMessages(List<string> names, List<string> messages)
        {
            var indexesOfMessage = Console.ReadLine().Split().Select(int.Parse).ToArray();
            var jedis = new StringBuilder();

            for (int i = 0; i < names.Count; i++)
            {
                if (i < indexesOfMessage.Length && indexesOfMessage[i] > 0 && indexesOfMessage[i] <= messages.Count)
                {
                    jedis.Append($"{names[i]} - {messages[indexesOfMessage[i] - 1]}{Environment.NewLine}");
                }
                else
                {
                    break;
                }
            }

            Console.Write(jedis);
        }

        private static List<string> ExtractCollection(ref string encryptedText, ref string prefixPattern, bool canHaveDigits)
        {
            var collection = new List<string>();
            var indexOfPattern = encryptedText.IndexOf(prefixPattern);

            while (indexOfPattern >= 0)
            {
                var startIndexOfMatch = indexOfPattern + prefixPattern.Length;

                if (startIndexOfMatch >= encryptedText.Length - prefixPattern.Length)
                {
                    break;
                }

                if (char.IsLetter(encryptedText[startIndexOfMatch + prefixPattern.Length]) ||
                    canHaveDigits && char.IsDigit(encryptedText[startIndexOfMatch + prefixPattern.Length]))
                {
                    indexOfPattern = encryptedText.IndexOf(prefixPattern, indexOfPattern + 1);
                    continue;
                }

                var match = encryptedText.Substring(startIndexOfMatch, prefixPattern.Length);

                if (IsValid(match, canHaveDigits))
                {
                    collection.Add(match);
                }

                indexOfPattern = encryptedText.IndexOf(prefixPattern, indexOfPattern + 1);
            }

            return collection;
        }

        private static bool IsValid(string match, bool canHaveDigits)
        {
            for (int i = 0; i < match.Length; i++)
            {
                if (!char.IsLetter(match[i]))
                {
                    if (canHaveDigits && char.IsDigit(match[i]))
                    {
                        continue;
                    }

                    return false;
                }
            }

            return true;
        }

        private static string GetEncryptedText()
        {
            var numberOfLines = int.Parse(Console.ReadLine());
            var input = new StringBuilder();

            while (numberOfLines > 0)
            {
                input.Append(Console.ReadLine());
                numberOfLines--;
            }

            return input.ToString();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using DigitalPlatform.Text;

namespace DigitalPlatform.CirculationClient
{
    /// <summary>
    /// 馆藏点对话框
    /// </summary>
    public partial class LocationItemDialog : Form
    {
        /// <summary>
        /// 是否为创建模式
        /// </summary>
        public bool CreateMode = false; // 是否为创建模式?==true为创建模式;==false为修改模式

        /// <summary>
        /// 图书馆代码列表字符串。提供给 combobox 使用
        /// </summary>
        public string LibraryCodeList
        {
            get
            {
                StringBuilder text = new StringBuilder();
                foreach (string s in this.comboBox_libraryCode.Items)
                {
                    if (text.Length > 0)
                        text.Append(",");
                    text.Append(s);
                }
                return text.ToString();
            }
            set
            {
                List<string> values = StringUtil.SplitList(value);
                this.comboBox_libraryCode.Items.Clear();
                foreach (string s in values)
                {
                    this.comboBox_libraryCode.Items.Add(s);
                }
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public LocationItemDialog()
        {
            InitializeComponent();
        }

        private void LocationItemDialog_Load(object sender, EventArgs e)
        {
            // 如果只有一项列表事项,而当前为空白,则自动设置好这一项
            if (this.CreateMode == true
                && string.IsNullOrEmpty(this.comboBox_libraryCode.Text) == true
                && this.comboBox_libraryCode.Items.Count > 0)
                this.comboBox_libraryCode.Text = (string)this.comboBox_libraryCode.Items[0];
        }

        private void button_OK_Click(object sender, EventArgs e)
        {
            if (this.textBox_location.Text == "")
            {
                // 允许馆藏地点为空,但是要确认一下

                DialogResult msgResult = MessageBox.Show(this,
                    "确实要把馆藏地点名称设置为空?",
                    "LocationItemDialog",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button2);
                if (msgResult == DialogResult.No)
                    return;
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void button_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// 馆代码
        /// </summary>
        public string LibraryCode
        {
            get
            {
                return this.comboBox_libraryCode.Text;
            }
            set
            {
                this.comboBox_libraryCode.Text = value;
            }
        }

        /// <summary>
        /// 馆藏点字符串
        /// </summary>
        public string LocationString
        {
            get
            {
                return this.textBox_location.Text;
            }
            set
            {
                this.textBox_location.Text = value;
            }
        }

        /// <summary>
        /// 是否允许外借
        /// </summary>
        public bool CanBorrow
        {
            get
            {
                return this.checkBox_canBorrow.Checked;
            }
            set
            {
                this.checkBox_canBorrow.Checked = value;
            }
        }

        /// <summary>
        /// 册条码号可为空
        /// </summary>
        public bool ItemBarcodeNullable
        {
            get
            {
                return this.checkBox_itemBarcodeNullable.Checked;
            }
            set
            {
                this.checkBox_itemBarcodeNullable.Checked = value;
            }
        }
    }
}


text:
package SVCInterface;
import java.util.Map;

/**
 * Common SVC customize handler interface
 * Used to IOC the user defined SVC handler logic module into Http Service handing for "SVC" request
 */
public interface ISvcHandler {
    public String getRequest(String funcName,Map<String,String> params,ISvcHelper serviceHelper);
    public String postRequest(String funcName,Map<String,String> params,String jsonBody,ISvcHelper serviceHelper);
}


text:
package io.cdap.plugin.zuora.objects;

import com.google.gson.annotations.SerializedName;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.plugin.zuora.restobjects.annotations.ObjectDefinition;
import io.cdap.plugin.zuora.restobjects.annotations.ObjectFieldDefinition;
import io.cdap.plugin.zuora.restobjects.objects.BaseObject;

import javax.annotation.Nullable;

/**
* Object name: SubscribeRequest (SubscribeRequest).
* Related objects:
**/
@SuppressWarnings("unused")
@ObjectDefinition(
  Name = "SubscribeRequest",
  ObjectType = ObjectDefinition.ObjectDefinitionType.NESTED
)
public class SubscribeRequest extends BaseObject {
  /**
  * Name: PaymentMethod (PaymentMethod), Type: SubscribeRequestPaymentMethodItem.
  * Options (custom, update, select): false, false, false
  **/
  @Nullable
  @SerializedName("paymentMethod")
  @ObjectFieldDefinition(FieldType = Schema.Type.STRING)
  private String paymentMethod;

  /**
  * Name: PreviewOptions (PreviewOptions), Type: SubscribeRequestPreviewOptionsItem.
  * Options (custom, update, select): false, false, false
  **/
  @Nullable
  @SerializedName("previewOptions")
  @ObjectFieldDefinition(FieldType = Schema.Type.STRING)
  private String previewOptions;

  /**
  * Name: SubscribeOptions (SubscribeOptions), Type: SubscribeRequestSubscribeOptionsItem.
  * Options (custom, update, select): false, false, false
  **/
  @Nullable
  @SerializedName("subscribeOptions")
  @ObjectFieldDefinition(FieldType = Schema.Type.STRING)
  private String subscribeOptions;

  /**
  * Name: SubscriptionData (SubscriptionData), Type: SubscribeRequestSubscriptionDataItem.
  * Options (custom, update, select): false, false, false
  **/
  @Nullable
  @SerializedName("subscriptionData")
  @ObjectFieldDefinition(FieldType = Schema.Type.STRING)
  private String subscriptionData;

  @Override
  public void addFields() {
    addCustomField("paymentMethod", paymentMethod, String.class);
    addCustomField("previewOptions", previewOptions, String.class);
    addCustomField("subscribeOptions", subscribeOptions, String.class);
    addCustomField("subscriptionData", subscriptionData, String.class);
  }
}


text:
<?php

namespace stp\spsr\type;

use stp\spsr\BaseType;

/**
 * @property string $Login
 * @property string $ICN
 * @property string|null $InvoiceNumber
 * @property string|null $GCInvoiceNumber
 * @property string|null $BarCode
 */
class InvoiceInfoType extends BaseType
{

}


text:
package net.liftweb
package mongodb

import json._

import scala.util.matching.Regex
import java.util.{Date, UUID}
import java.util.regex.Pattern

import org.bson.types.ObjectId

object BsonDSL extends JsonDSL {
  implicit def objectid2jvalue(oid: ObjectId): JValue = Meta.objectIdAsJValue(oid)
  implicit def pattern2jvalue(p: Pattern): JValue = Meta.patternAsJValue(p)
  implicit def regex2jvalue(r: Regex): JValue = Meta.patternAsJValue(r.pattern)
  implicit def uuid2jvalue(u: UUID): JValue = Meta.uuidAsJValue(u)
  implicit def date2jvalue(d: Date)(implicit formats: Formats): JValue = Meta.dateAsJValue(d, formats)
}


text:
if(NOT CMAKE_VERSION VERSION_LESS 3.9)
  get_property(isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
elseif(CMAKE_CONFIGURATION_TYPES)
  # CMAKE_CONFIGURATION_TYPES is set by project() call for multi-config generators
  set(isMultiConfig True)
else()
  set(isMultiConfig False)
endif()

if(isMultiConfig)
  set(CMAKE_CONFIGURATION_TYPES
    "Coverage;Debug;MinSizeRel;Release;RelWithDebInfo"
    CACHE STRING "Configurations for Multi-Config CMake Generator" FORCE)
else()
  if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Build Type" FORCE)
  endif()
  set_property(CACHE CMAKE_BUILD_TYPE
    PROPERTY
      STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo" "Coverage")
endif()


text:
import React from "react";
import { mocked, Mocked } from "jest-mock";
import { render, screen, act } from "@testing-library/react";
import { PendingEventOrdering } from "matrix-js-sdk/src/client";
import { Room } from "matrix-js-sdk/src/models/room";
import { RoomStateEvent } from "matrix-js-sdk/src/models/room-state";
import { RoomType } from "matrix-js-sdk/src/@types/event";

import type { MatrixClient } from "matrix-js-sdk/src/client";
import type { RoomMember } from "matrix-js-sdk/src/models/room-member";
import { stubClient, wrapInMatrixClientContext, mkRoomMember } from "../../../test-utils";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
import DMRoomMap from "../../../../src/utils/DMRoomMap";
import SettingsStore from "../../../../src/settings/SettingsStore";
import _RoomPreviewCard from "../../../../src/components/views/rooms/RoomPreviewCard";

const RoomPreviewCard = wrapInMatrixClientContext(_RoomPreviewCard);

describe("RoomPreviewCard", () => {
    let client: Mocked<MatrixClient>;
    let room: Room;
    let alice: RoomMember;
    let enabledFeatures: string[];

    beforeEach(() => {
        stubClient();
        client = mocked(MatrixClientPeg.get());
        client.getUserId.mockReturnValue("@alice:example.org");
        DMRoomMap.makeShared();

        room = new Room("!1:example.org", client, "@alice:example.org", {
            pendingEventOrdering: PendingEventOrdering.Detached,
        });
        alice = mkRoomMember(room.roomId, "@alice:example.org");
        jest.spyOn(room, "getMember").mockImplementation(userId => userId === alice.userId ? alice : null);

        client.getRoom.mockImplementation(roomId => roomId === room.roomId ? room : null);
        client.getRooms.mockReturnValue([room]);
        client.reEmitter.reEmit(room, [RoomStateEvent.Events]);

        enabledFeatures = [];
        jest.spyOn(SettingsStore, "getValue").mockImplementation(settingName =>
            enabledFeatures.includes(settingName) ? true : undefined,
        );
    });

    afterEach(() => {
        client.reEmitter.stopReEmitting(room, [RoomStateEvent.Events]);
        jest.restoreAllMocks();
    });

    const renderPreview = async (): Promise<void> => {
        render(
            <RoomPreviewCard
                room={room}
                onJoinButtonClicked={() => { }}
                onRejectButtonClicked={() => { }}
            />,
        );
        await act(() => Promise.resolve()); // Allow effects to settle
    };

    it("shows a beta pill on Jitsi video room invites", async () => {
        jest.spyOn(room, "getType").mockReturnValue(RoomType.ElementVideo);
        jest.spyOn(room, "getMyMembership").mockReturnValue("invite");
        enabledFeatures = ["feature_video_rooms"];

        await renderPreview();
        screen.getByRole("button", { name: /beta/i });
    });

    it("shows a beta pill on Element video room invites", async () => {
        jest.spyOn(room, "getType").mockReturnValue(RoomType.UnstableCall);
        jest.spyOn(room, "getMyMembership").mockReturnValue("invite");
        enabledFeatures = ["feature_video_rooms", "feature_element_call_video_rooms"];

        await renderPreview();
        screen.getByRole("button", { name: /beta/i });
    });

    it("doesn't show a beta pill on normal invites", async () => {
        jest.spyOn(room, "getMyMembership").mockReturnValue("invite");

        await renderPreview();
        expect(screen.queryByRole("button", { name: /beta/i })).toBeNull();
    });

    it("shows instructions on Jitsi video rooms invites if video rooms are disabled", async () => {
        jest.spyOn(room, "getType").mockReturnValue(RoomType.ElementVideo);
        jest.spyOn(room, "getMyMembership").mockReturnValue("invite");

        await renderPreview();
        screen.getByText(/enable video rooms in labs/i);
    });

    it("shows instructions on Element video rooms invites if video rooms are disabled", async () => {
        jest.spyOn(room, "getType").mockReturnValue(RoomType.UnstableCall);
        jest.spyOn(room, "getMyMembership").mockReturnValue("invite");
        enabledFeatures = ["feature_element_call_video_rooms"];

        await renderPreview();
        screen.getByText(/enable video rooms in labs/i);
    });
});


text:
from pyro.util import ignore_jit_warnings

from .messenger import Messenger

class BroadcastMessenger(Messenger):
    """
    Automatically broadcasts the batch shape of the stochastic function
    at a sample site when inside a single or nested plate context.
    The existing `batch_shape` must be broadcastable with the size
    of the :class:`~pyro.plate` contexts installed in the
    `cond_indep_stack`.

    Notice how `model_automatic_broadcast` below automates expanding of
    distribution batch shapes. This makes it easy to modularize a
    Pyro model as the sub-components are agnostic of the wrapping
    :class:`~pyro.plate` contexts.

    >>> def model_broadcast_by_hand():
    ...     with IndepMessenger("batch", 100, dim=-2):
    ...         with IndepMessenger("components", 3, dim=-1):
    ...             sample = pyro.sample("sample", dist.Bernoulli(torch.ones(3) * 0.5)
    ...                                                .expand_by(100))
    ...             assert sample.shape == torch.Size((100, 3))
    ...     return sample

    >>> @poutine.broadcast
    ... def model_automatic_broadcast():
    ...     with IndepMessenger("batch", 100, dim=-2):
    ...         with IndepMessenger("components", 3, dim=-1):
    ...             sample = pyro.sample("sample", dist.Bernoulli(torch.tensor(0.5)))
    ...             assert sample.shape == torch.Size((100, 3))
    ...     return sample
    """

    @staticmethod
    @ignore_jit_warnings(["Converting a tensor to a Python boolean"])
    def _pyro_sample(msg):
        """
        :param msg: current message at a trace site.
        """
        if msg["done"] or msg["type"] != "sample":
            return

        dist = msg["fn"]
        actual_batch_shape = getattr(dist, "batch_shape", None)
        if actual_batch_shape is not None:
            target_batch_shape = [
                None if size == 1 else size for size in actual_batch_shape
            ]
            for f in msg["cond_indep_stack"]:
                if f.dim is None or f.size == -1:
                    continue
                assert f.dim < 0
                target_batch_shape = [None] * (
                    -f.dim - len(target_batch_shape)
                ) + target_batch_shape
                if (
                    target_batch_shape[f.dim] is not None
                    and target_batch_shape[f.dim] != f.size
                ):
                    raise ValueError(
                        "Shape mismatch inside plate('{}') at site {} dim {}, {} vs {}".format(
                            f.name,
                            msg["name"],
                            f.dim,
                            f.size,
                            target_batch_shape[f.dim],
                        )
                    )
                target_batch_shape[f.dim] = f.size
            # Starting from the right, if expected size is None at an index,
            # set it to the actual size if it exists, else 1.
            for i in range(-len(target_batch_shape) + 1, 1):
                if target_batch_shape[i] is None:
                    target_batch_shape[i] = (
                        actual_batch_shape[i] if len(actual_batch_shape) >= -i else 1
                    )
            msg["fn"] = dist.expand(target_batch_shape)
            if msg["fn"].has_rsample != dist.has_rsample:
                msg["fn"].has_rsample = dist.has_rsample  # copy custom attribute


text:
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- GENERAL INFORMATION -->
    <groupId>es.bsc.mobile</groupId>
    <artifactId>compssmobile-maven-plugin</artifactId>
    <version>1.0</version>
    <packaging>maven-plugin</packaging>

    <parent>
        <groupId>es.bsc.mobile</groupId>
        <artifactId>programming-model</artifactId>
        <version>1.0</version>
        <relativePath>..</relativePath>
    </parent>

    <!-- PROJECT INFORMATION -->
    <name>Maven Plugin For COMPSs-Mobile</name>
    <description>Maven Plugin to instrument Android applications to use COMPSs-Mobile</description>
    <url>http://www.bsc.es</url>

    <inceptionYear>2014</inceptionYear>
    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
        </license>
    </licenses>

    <organization>
        <name>BSC</name>
        <url>http://www.bsc.es</url>
    </organization>

    <!-- PROPERTIES -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!-- DEPENDENCIES -->
    <dependencies>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
            <version>3.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-utils</artifactId>
            <version>3.0.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>es.bsc.mobile</groupId>
            <artifactId>parallelizer</artifactId>
            <version>1.0</version>
        </dependency>
    </dependencies>

    <!--BUILD-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <goalPrefix>compssmobile-maven-plugin</goalPrefix>
                    <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
                </configuration>
                <executions>
                    <execution>
                        <id>mojo-descriptor</id>
                        <goals>
                            <goal>descriptor</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>help-goal</id>
                        <goals>
                            <goal>helpmojo</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <!--PROFILES-->
    <profiles>
        <profile>
            <id>run-its</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-invoker-plugin</artifactId>
                        <version>1.7</version>
                        <configuration>
                            <debug>true</debug>
                            <cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>
                            <pomIncludes>
                                <pomInclude>*/pom.xml</pomInclude>
                            </pomIncludes>
                            <postBuildHookScript>verify</postBuildHookScript>
                            <localRepositoryPath>${project.build.directory}/local-repo</localRepositoryPath>
                            <settingsFile>src/it/settings.xml</settingsFile>
                            <goals>
                                <goal>clean</goal>
                                <goal>test-compile</goal>
                            </goals>
                        </configuration>
                        <executions>
                            <execution>
                                <id>integration-test</id>
                                <goals>
                                    <goal>install</goal>
                                    <goal>integration-test</goal>
                                    <goal>verify</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>

            </build>
        </profile>
    </profiles>
</project>


text:
@implementation UIScrollView (ScrollViewListener)

- (void)svl_setScrollViewListnerWithBlock:(void(^)(UIScrollView *scrollView, CGFloat distanceToTop, CGFloat distanceToBottom))block{

    ScrollViewListener *listener = [[ScrollViewListener alloc] initWithScrollView:self];
    [listener addListener:block];

    objc_setAssociatedObject(self, @selector(svl_scrollViewListener), listener, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (ScrollViewListener *)svl_scrollViewListener{
    return objc_getAssociatedObject(self, @selector(svl_scrollViewListener));
}

@end


text:
package org.kie.workbench.common.screens.projecteditor.client.wizard;

import org.guvnor.common.services.project.model.Build;
import org.guvnor.common.services.project.model.POM;
import org.guvnor.common.services.project.model.Plugin;

/**
 * The Project Name is used to generate the folder name and hence is only checked to be a valid file name.
 * The ArtifactID is initially set to the project name, subsequently validated against the maven regex,
 * and preserved as is in the pom.xml file. However, as it is used to construct the default workspace and
 * hence package names, it is sanitized in the ProjectService.newProject() method.
 */
public class POMBuilder {

    private static final String KIE_MAVEN_PLUGIN_GROUP_ID = "org.kie";
    private static final String KIE_MAVEN_PLUGIN_ARTIFACT_ID = "kie-maven-plugin";

    private final POM pom;

    public POMBuilder() {
        this( new POM() );
    }

    public POMBuilder( final POM pom ) {
        this.pom = pom;
        setDefaultPackaging( pom );
        setDefaultVersion( pom );
    }

    private void setDefaultVersion( POM pom ) {
        if ( pom.getGav().getVersion() == null ) {
            this.pom.getGav().setVersion( "1.0" );
        }
    }

    private void setDefaultPackaging( POM pom ) {
        if ( pom.getPackaging() == null ) {
            this.pom.setPackaging( "kjar" );
        }
    }

    public POMBuilder setProjectName( final String projectName ) {
        pom.setName( projectName );
        if ( projectName != null ) {
            pom.getGav().setArtifactId( sanitizeProjectName( projectName ) );
        }
        return this;
    }

    public POMBuilder setGroupId( final String groupId ) {
        pom.getGav().setGroupId( groupId );
        return this;
    }

    public POMBuilder setVersion( final String version ) {
        pom.getGav().setVersion( version );
        return this;
    }

    public POMBuilder setPackaging( final String packaging ) {
        pom.setPackaging( packaging );
        return this;
    }

    public POMBuilder addKieBuildPlugin( final String kieVersion ) {
        if ( pom.getBuild() == null ) {
            pom.setBuild( new Build() );
        }

        pom.getBuild().getPlugins().add( getKieMavenPlugin( kieVersion ) );
        return this;
    }

    public POM build() {
        return pom;
    }

    /**
     * The projectName has been validated as a FileSystem folder name, which may not be consistent with Maven ArtifactID
     * naming restrictions (see org.apache.maven.model.validation.DefaultModelValidator.java::ID_REGEX). Therefore we'd
     * best sanitize the projectName
     */
    private String sanitizeProjectName( final String projectName ) {
        //Only [A-Za-z0-9_\-.] are valid so strip everything else out
        return projectName != null ? projectName.replaceAll( "[^A-Za-z0-9_\\-.]", "" ) : projectName;
    }

    private Plugin getKieMavenPlugin( final String kieVersion ) {
        final Plugin plugin = new Plugin();
        plugin.setGroupId( KIE_MAVEN_PLUGIN_GROUP_ID );
        plugin.setArtifactId( KIE_MAVEN_PLUGIN_ARTIFACT_ID );
        plugin.setVersion( kieVersion );
        plugin.setExtensions( true );
        return plugin;
    }

}


text:
@interface PDAddressCell()
{
    UIView *back;
    UILabel *address;

    NSMutableArray *list;

}
@end

@implementation PDAddressCell

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        //
        CGFloat h = [PDAddressCell cellHeightWithData:nil];

        back = [[UIView alloc] initWithFrame:CGRectMake(kCellLeftGap, kCellLeftGap, kAppWidth-2*kCellLeftGap, h-kCellLeftGap)];
        [self addSubview:back];
        back.layer.borderWidth = 0.5f;
        back.layer.borderColor = [[UIColor colorWithHexString:@"#e6e6e6"] CGColor];

        address = [[UILabel alloc] initWithFrame:CGRectMake(kCellLeftGap, 0, back.width - 2*kCellLeftGap-20, back.height)];
        [back addSubview:address];
        address.numberOfLines = 2;
        address.font = [UIFont systemFontOfSize:15];
        address.textColor = [UIColor colorWithHexString:@"#333333"];

        UIButton *deletebutton=[[UIButton alloc] initWithFrame:CGRectMake(address.right, (back.height-20)/2, 20, 20)];
        [deletebutton setBackgroundImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
        [deletebutton setBackgroundImage:[UIImage imageNamed:@"delete2"] forState:UIControlStateHighlighted];
        [back addSubview:deletebutton];
        [deletebutton handleControlEvents:UIControlEventTouchUpInside actionBlock:^(id sender) {
            if (self.delegate&&[self.delegate respondsToSelector:@selector(pdBaseTableViewCellDelegate:deleteAddressWithData:)]) {
                [self.delegate pdBaseTableViewCellDelegate:self deleteAddressWithData:self.data];
            }
        }];
    }
    return self;
}

-(void)configData:(id)data{

    PDModelAddress *addressData = data;

    address.text = addressData.address;

    [address sizeToFit];
    address.top = (back.height - address.height)/2;
     //[self showDebugRect];
}

+(CGFloat )cellHeightWithData:(id)data{

    return 50+kCellLeftGap;
}

@end


text:
using System;
using Cairo;
using ZWCloud.DWriteCairo.Internal;

namespace ZWCloud.DWriteCairo
{
    /// <summary>
    /// Helper for use DirectWrite with Cairo
    /// </summary>
    public static class DWriteCairo
    {
        private static DWriteFactory factory;
        private static DWriteFactory Factory
        {
            get
            {
                if(factory == null)
                {
                    factory = DWriteFactory.Create();
                }
                return factory;
            }
        }

        private static DirectWriteCairoTextRenderer render;
        private static DirectWriteCairoTextRenderer Render
        {
            get
            {
                if (render == null)
                {
                    render = DirectWriteCairoTextRenderer.Create();
                }
                return render;
            }
        }

        /// <summary>
        /// Create a text format object used for text layout.
        /// </summary>
        /// <param name="fontFamilyName">Name of the font family</param>
        /// <param name="fontWeight">Font weight</param>
        /// <param name="fontStyle">Font style</param>
        /// <param name="fontStretch">Font stretch</param>
        /// <param name="fontSize">Logical size of the font in DIP units. A DIP ("device-independent pixel") equals 1/96 inch.</param>
        /// <param name="localeName">Locale name(optional)</param>
        /// TODO understand the meaning of Locale name
        /// <returns> newly created text format object </returns>
        public static TextFormat CreateTextFormat(
            string fontFamilyName,
            FontWeight fontWeight, FontStyle fontStyle, FontStretch fontStretch,
            float fontSize,
            string localeName = "en-us")
        {
            var ptr = Factory.CreateTextFormat(fontFamilyName, IntPtr.Zero,
                fontWeight,
                fontStyle, fontStretch, fontSize,
                localeName);
            var dWriteTextFormat = new TextFormat(ptr);
            return dWriteTextFormat;
        }

        /// <summary>
        /// CreateTextLayout takes a string, format, and associated constraints
        /// and produces an object representing the fully analyzed
        /// and formatted result.
        /// </summary>
        /// <param name="text">The text to layout.</param>
        /// <param name="textFormat">The format to apply to the string.</param>
        /// <param name="maxWidth">Width of the layout box.</param>
        /// <param name="maxHeight">Height of the layout box.</param>
        /// <returns>
        /// The resultant object.
        /// </returns>
        public static TextLayout CreateTextLayout(string text, TextFormat textFormat, int maxWidth, int maxHeight)
        {
            var ptr = Factory.CreateTextLayout(text,
            text.Length, textFormat.Handle, maxWidth, maxHeight);
            var dWriteTextLayout = new TextLayout(ptr);
            return dWriteTextLayout;
        }

        /// <summary>
        /// Show the layout
        /// </summary>
        /// <param name="context">a Cairo context</param>
        /// <param name="textLayout">the layout to show</param>
        public static Path RenderLayoutToCairoPath(Cairo.Context context, TextLayout textLayout)
        {
            return textLayout.RenderToCairoPath(context, Render, textLayout);
        }
    }
}


text:
package projects

import (
	"context"
	"testing"

	"go.chromium.org/luci/config/validation"

	. "github.com/smartystreets/goconvey/convey"
	. "go.chromium.org/luci/common/testing/assertions"
)

func TestConfig(t *testing.T) {
	t.Parallel()

	Convey("validate", t, func() {
		c := &validation.Context{Context: context.Background()}

		Convey("invalid", func() {
			Convey("project", func() {
				cfg := &Config{}
				cfg.Validate(c)
				errs := c.Finalize().(*validation.Error).Errors
				So(errs, ShouldContainErr, "project is required")
			})

			Convey("revision", func() {
				cfg := &Config{
					Revision: "revision",
				}
				cfg.Validate(c)
				errs := c.Finalize().(*validation.Error).Errors
				So(errs, ShouldContainErr, "revision must not be specified")
			})
		})

		Convey("valid", func() {
			cfg := &Config{
				Project: "project",
			}
			cfg.Validate(c)
			So(c.Finalize(), ShouldBeNil)
		})
	})
}


text:
#include <linux/module.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <linux/key.h>
#include <linux/crypto.h>
#include <net/sock.h>
#include <net/af_rxrpc.h>
#include <keys/rxrpc-type.h>
#include <keys/user-type.h>
#include "ar-internal.h"

static int rxrpc_instantiate(struct key *, const void *, size_t);
static int rxrpc_instantiate_s(struct key *, const void *, size_t);
static void rxrpc_destroy(struct key *);
static void rxrpc_destroy_s(struct key *);
static void rxrpc_describe(const struct key *, struct seq_file *);

/*
 * rxrpc defined keys take an arbitrary string as the description and an
 * arbitrary blob of data as the payload
 */
struct key_type key_type_rxrpc = {
	.name		= "rxrpc",
	.instantiate	= rxrpc_instantiate,
	.match		= user_match,
	.destroy	= rxrpc_destroy,
	.describe	= rxrpc_describe,
};

EXPORT_SYMBOL(key_type_rxrpc);

/*
 * rxrpc server defined keys take "<serviceId>:<securityIndex>" as the
 * description and an 8-byte decryption key as the payload
 */
struct key_type key_type_rxrpc_s = {
	.name		= "rxrpc_s",
	.instantiate	= rxrpc_instantiate_s,
	.match		= user_match,
	.destroy	= rxrpc_destroy_s,
	.describe	= rxrpc_describe,
};

/*
 * instantiate an rxrpc defined key
 * data should be of the form:
 *	OFFSET	LEN	CONTENT
 *	0	4	key interface version number
 *	4	2	security index (type)
 *	6	2	ticket length
 *	8	4	key expiry time (time_t)
 *	12	4	kvno
 *	16	8	session key
 *	24	[len]	ticket
 *
 * if no data is provided, then a no-security key is made
 */
static int rxrpc_instantiate(struct key *key, const void *data, size_t datalen)
{
	const struct rxkad_key *tsec;
	struct rxrpc_key_payload *upayload;
	size_t plen;
	u32 kver;
	int ret;

	_enter("{%x},,%zu", key_serial(key), datalen);

	/* handle a no-security key */
	if (!data && datalen == 0)
		return 0;

	/* get the key interface version number */
	ret = -EINVAL;
	if (datalen <= 4 || !data)
		goto error;
	memcpy(&kver, data, sizeof(kver));
	data += sizeof(kver);
	datalen -= sizeof(kver);

	_debug("KEY I/F VERSION: %u", kver);

	ret = -EKEYREJECTED;
	if (kver != 1)
		goto error;

	/* deal with a version 1 key */
	ret = -EINVAL;
	if (datalen < sizeof(*tsec))
		goto error;

	tsec = data;
	if (datalen != sizeof(*tsec) + tsec->ticket_len)
		goto error;

	_debug("SCIX: %u", tsec->security_index);
	_debug("TLEN: %u", tsec->ticket_len);
	_debug("EXPY: %x", tsec->expiry);
	_debug("KVNO: %u", tsec->kvno);
	_debug("SKEY: %02x%02x%02x%02x%02x%02x%02x%02x",
	       tsec->session_key[0], tsec->session_key[1],
	       tsec->session_key[2], tsec->session_key[3],
	       tsec->session_key[4], tsec->session_key[5],
	       tsec->session_key[6], tsec->session_key[7]);
	if (tsec->ticket_len >= 8)
		_debug("TCKT: %02x%02x%02x%02x%02x%02x%02x%02x",
		       tsec->ticket[0], tsec->ticket[1],
		       tsec->ticket[2], tsec->ticket[3],
		       tsec->ticket[4], tsec->ticket[5],
		       tsec->ticket[6], tsec->ticket[7]);

	ret = -EPROTONOSUPPORT;
	if (tsec->security_index != 2)
		goto error;

	key->type_data.x[0] = tsec->security_index;

	plen = sizeof(*upayload) + tsec->ticket_len;
	ret = key_payload_reserve(key, plen);
	if (ret < 0)
		goto error;

	ret = -ENOMEM;
	upayload = kmalloc(plen, GFP_KERNEL);
	if (!upayload)
		goto error;

	/* attach the data */
	memcpy(&upayload->k, tsec, sizeof(*tsec));
	memcpy(&upayload->k.ticket, (void *)tsec + sizeof(*tsec),
	       tsec->ticket_len);
	key->payload.data = upayload;
	key->expiry = tsec->expiry;
	ret = 0;

error:
	return ret;
}

/*
 * instantiate a server secret key
 * data should be a pointer to the 8-byte secret key
 */
static int rxrpc_instantiate_s(struct key *key, const void *data,
			       size_t datalen)
{
	struct crypto_blkcipher *ci;

	_enter("{%x},,%zu", key_serial(key), datalen);

	if (datalen != 8)
		return -EINVAL;

	memcpy(&key->type_data, data, 8);

	ci = crypto_alloc_blkcipher("pcbc(des)", 0, CRYPTO_ALG_ASYNC);
	if (IS_ERR(ci)) {
		_leave(" = %ld", PTR_ERR(ci));
		return PTR_ERR(ci);
	}

	if (crypto_blkcipher_setkey(ci, data, 8) < 0)
		BUG();

	key->payload.data = ci;
	_leave(" = 0");
	return 0;
}

/*
 * dispose of the data dangling from the corpse of a rxrpc key
 */
static void rxrpc_destroy(struct key *key)
{
	kfree(key->payload.data);
}

/*
 * dispose of the data dangling from the corpse of a rxrpc key
 */
static void rxrpc_destroy_s(struct key *key)
{
	if (key->payload.data) {
		crypto_free_blkcipher(key->payload.data);
		key->payload.data = NULL;
	}
}

/*
 * describe the rxrpc key
 */
static void rxrpc_describe(const struct key *key, struct seq_file *m)
{
	seq_puts(m, key->description);
}

/*
 * grab the security key for a socket
 */
int rxrpc_request_key(struct rxrpc_sock *rx, char __user *optval, int optlen)
{
	struct key *key;
	char *description;

	_enter("");

	if (optlen <= 0 || optlen > PAGE_SIZE - 1)
		return -EINVAL;

	description = kmalloc(optlen + 1, GFP_KERNEL);
	if (!description)
		return -ENOMEM;

	if (copy_from_user(description, optval, optlen)) {
		kfree(description);
		return -EFAULT;
	}
	description[optlen] = 0;

	key = request_key(&key_type_rxrpc, description, NULL);
	if (IS_ERR(key)) {
		kfree(description);
		_leave(" = %ld", PTR_ERR(key));
		return PTR_ERR(key);
	}

	rx->key = key;
	kfree(description);
	_leave(" = 0 [key %x]", key->serial);
	return 0;
}

/*
 * grab the security keyring for a server socket
 */
int rxrpc_server_keyring(struct rxrpc_sock *rx, char __user *optval,
			 int optlen)
{
	struct key *key;
	char *description;

	_enter("");

	if (optlen <= 0 || optlen > PAGE_SIZE - 1)
		return -EINVAL;

	description = kmalloc(optlen + 1, GFP_KERNEL);
	if (!description)
		return -ENOMEM;

	if (copy_from_user(description, optval, optlen)) {
		kfree(description);
		return -EFAULT;
	}
	description[optlen] = 0;

	key = request_key(&key_type_keyring, description, NULL);
	if (IS_ERR(key)) {
		kfree(description);
		_leave(" = %ld", PTR_ERR(key));
		return PTR_ERR(key);
	}

	rx->securities = key;
	kfree(description);
	_leave(" = 0 [key %x]", key->serial);
	return 0;
}

/*
 * generate a server data key
 */
int rxrpc_get_server_data_key(struct rxrpc_connection *conn,
			      const void *session_key,
			      time_t expiry,
			      u32 kvno)
{
	struct key *key;
	int ret;

	struct {
		u32 kver;
		struct rxkad_key tsec;
	} data;

	_enter("");

	key = key_alloc(&key_type_rxrpc, "x", 0, 0, current, 0,
			KEY_ALLOC_NOT_IN_QUOTA);
	if (IS_ERR(key)) {
		_leave(" = -ENOMEM [alloc %ld]", PTR_ERR(key));
		return -ENOMEM;
	}

	_debug("key %d", key_serial(key));

	data.kver = 1;
	data.tsec.security_index = 2;
	data.tsec.ticket_len = 0;
	data.tsec.expiry = expiry;
	data.tsec.kvno = 0;

	memcpy(&data.tsec.session_key, session_key,
	       sizeof(data.tsec.session_key));

	ret = key_instantiate_and_link(key, &data, sizeof(data), NULL, NULL);
	if (ret < 0)
		goto error;

	conn->key = key;
	_leave(" = 0 [%d]", key_serial(key));
	return 0;

error:
	key_revoke(key);
	key_put(key);
	_leave(" = -ENOMEM [ins %d]", ret);
	return -ENOMEM;
}

EXPORT_SYMBOL(rxrpc_get_server_data_key);


text:
ifneq ($(MAKECMDGOALS),clean)
-include ../../Makeconfig
endif

# Setting the source, object and dependency files
SRC = $(wildcard ./*.cpp)
DEP = $(SRC:.cpp=.d)
OBJ = $(SRC:.cpp=.o)
BIN = $(SRC:.cpp=)

# General rules
default: all
all: $(BIN)
essential: VCaVCa AliasingTest

# Build rules
VCaVCa: VCaVCa.o
	@$(CXX) $(CXXFLAGS) -o $@ $< $(LIBRARIES)
VCaVCb: VCaVCb.o
	@$(CXX) $(CXXFLAGS) -o $@ $< $(LIBRARIES)
VCbVCa: VCbVCa.o
	@$(CXX) $(CXXFLAGS) -o $@ $< $(LIBRARIES)
VCbVCb: VCbVCb.o
	@$(CXX) $(CXXFLAGS) -o $@ $< $(LIBRARIES)

AliasingTest: AliasingTest.o
	@$(CXX) $(CXXFLAGS) -o $@ $< $(LIBRARIES)

# Cleanup
clean:
	@$(RM) $(DEP) $(OBJ) $(BIN)

# Makefile includes
ifneq ($(MAKECMDGOALS),clean)
-include $(DEP)
endif

# Makefile generation
%.d: %.cpp
	@$(CXX) -MM -MP -MT "$*.o $*.d" -MF $@ $(CXXFLAGS) $<

# Setting the independent commands
.PHONY: default all essential clean


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DarkNotes.JniInterface;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using Microsoft.Win32;
using DarkNotes.CoreClassProxies;
using System.Threading;

namespace DarkNotes
{
	/// <summary>
	/// Main wrapper for the low-level JNI functionality.
	/// </summary>
	internal class JniWrapper : IDisposable
	{
		private readonly string _vmDll;
		private readonly IntPtr _envP;
		private readonly IntPtr _vmP;
		private readonly JavaVM _vm;
		private readonly JniEnv _env;
		private IntPtr _vmDllModule;
		private readonly bool _vmReuse;
		private readonly ThreadLocal<IntPtr> _currentThreadEnv;
		private const int _jniVersion = 0x00010006;

		private unsafe delegate int CreateJavaVM(IntPtr* pvm, IntPtr* penv, IntPtr args);
		private unsafe delegate int GetCreatedJavaVMs(IntPtr* pvm, int bufferLength, out int numVms);
		private delegate int GetDefaultJavaVMInitArgs(ref JavaVMInitArgs args);

		[DllImport("kernel32.dll", EntryPoint = "LoadLibraryW")]
		private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPWStr)] string name);

		[DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
		private static extern bool FreeLibrary(IntPtr hModule);

		[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
		private static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string name);

		/// <summary>
		/// Create the Java VM and wrap it.
		/// </summary>
		/// <param name="jvmDllPath">(Optional) Path to jvm.dll where we'll load the JNI library. If not provided we'll try to infer its location from the Java install path.</param>
		/// <param name="attemptVmReuse">
		/// This is an annoying workaround to a fundamental JNI problem: you can't host a JVM within the process again once you've hosted it once
		/// (ever, even if you destroy the first one). So if this flag is <c>true</c>, we'll attempt to find an existing JVM in the process and use that
		/// if available, and we won't destroy the JVM on dispose so subsequent constructions of this object will succeed.
		/// The downside of reuse of course is that if we're reusing it then we won't be able to construct it with fresh arguments.
		/// </param>
		internal JniWrapper(string jvmDllPath, bool attemptVmReuse, IEnumerable<JavaOption> options)
		{
			_currentThreadEnv = new ThreadLocal<IntPtr>(() =>
				{
					IntPtr ret;
					unsafe
					{
						if (_vm.GetDelegate<GetEnv>()(_vmP, (IntPtr)(&ret), _jniVersion) == -2)
						{
							_vm.GetDelegate<AttachCurrentThread>()(_vmP, (IntPtr)(&ret), IntPtr.Zero);
						}
						return ret;
					}
				});
			if (String.IsNullOrEmpty(jvmDllPath))
			{
				string javaHome = GetJavaInstallationPath();
				_vmDll = Path.Combine(javaHome, "bin", "server", "jvm.dll");
			}
			else
			{
				_vmDll = jvmDllPath;
			}
			if (!File.Exists(_vmDll))
			{
				throw new InvalidOperationException("Couldn't find the runtime library for Java at: " + _vmDll);
			}
			IntPtr envP;
			IntPtr vmP;
			_vmDllModule = LoadLibrary(_vmDll);
			if (_vmDllModule == IntPtr.Zero)
			{
				throw new Win32Exception();
			}
			if (attemptVmReuse)
			{
				_vmReuse = true;
				int numVms;
				unsafe
				{
					ThrowOnBadResult(GetDelegateFromJni<GetCreatedJavaVMs>("JNI_GetCreatedJavaVMs")(&vmP, 1, out numVms), "GetCreatedJavaVMs");
					if (numVms >= 1)
					{
						_vmP = vmP;
						_vm = (JavaVM)Marshal.PtrToStructure(vmP, typeof(JavaVM));
						ThrowOnBadResult(_vm.GetDelegate<AttachCurrentThread>()(_vmP, (IntPtr)(&envP), IntPtr.Zero), "AttachCurrentThread");
						_envP = envP;
						_env = (JniEnv)Marshal.PtrToStructure(envP, typeof(JniEnv));
						return;
					}
				}
			}
			JavaVMInitArgs vmArgs = new JavaVMInitArgs();
			GetDelegateFromJni<GetDefaultJavaVMInitArgs>("JNI_GetDefaultJavaVMInitArgs")(ref vmArgs);
			vmArgs.Version = _jniVersion;
			vmArgs._nOptions = options.Count();
			vmArgs._options = Marshal.AllocHGlobal(vmArgs._nOptions * Marshal.SizeOf(typeof(JavaVMOption)));
			IntPtr vmArgsP = Marshal.AllocHGlobal(Marshal.SizeOf(vmArgs));
			try
			{
				int optionsLocation = 0;
				foreach (JavaOption currentOption in options)
				{
					Marshal.StructureToPtr(currentOption.ActualOption, vmArgs._options + optionsLocation * Marshal.SizeOf(typeof(JavaVMOption)), false);
					optionsLocation++;
				}
				Marshal.StructureToPtr(vmArgs, vmArgsP, false);
				unsafe
				{
					ThrowOnBadResult(GetDelegateFromJni<CreateJavaVM>("JNI_CreateJavaVM")(&vmP, &envP, vmArgsP), "CreateJavaVM");
					_vm = (JavaVM)Marshal.PtrToStructure(vmP, typeof(JavaVM));
					_env = (JniEnv)Marshal.PtrToStructure(envP, typeof(JniEnv));
					_envP = envP;
					_vmP = vmP;
				}
			}
			finally
			{
				Marshal.DestroyStructure(vmArgsP, typeof(JavaVMInitArgs));
				Marshal.FreeHGlobal(vmArgsP);
				Marshal.FreeHGlobal(vmArgs._options);
			}
		}

		private static void ThrowOnBadResult(int ret, string operationName)
		{
			if (ret != 0)
			{
				throw new InvalidOperationException(operationName + " failed - return value obtained: " + ret);
			}
		}

		private T GetDelegateFromJni<T>(string procName)
			where T: class
		{
			return Marshal.GetDelegateForFunctionPointer(GetProcAddress(_vmDllModule, procName), typeof(T)) as T;
		}

		private static string GetJavaInstallationPath()
		{
			string environmentPath = Environment.GetEnvironmentVariable("JAVA_HOME");
			if (!string.IsNullOrEmpty(environmentPath))
			{
				return environmentPath;
			}

			using (RegistryKey javaKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\JavaSoft\Java Runtime Environment"))
			{
				if (javaKey == null)
				{
					throw new InvalidOperationException("Couldn't find Java installed on the machine");
				}
				string currentVersion = javaKey.GetValue("CurrentVersion").ToString();
				using (RegistryKey key = javaKey.OpenSubKey(currentVersion))
				{
					return key.GetValue("JavaHome").ToString();
				}
			}
		}

		public IntPtr GetStaticFieldId(IntPtr classP, string fieldName, string fieldSignature)
		{
			return SafeJniCall(_env.GetDelegate<GetStaticFieldID>().Invoke, classP, fieldName, fieldSignature);
		}

		public IntPtr FindClass(string className)
		{
			return SafeJniCall(_env.GetDelegate<FindClass>().Invoke, className);
		}

		public long GetVersion()
		{
			return SafeJniCall(_env.GetDelegate<GetVersion>().Invoke);
		}

		public IntPtr FromReflectedField(IntPtr reflectedField)
		{
			return SafeJniCall(_env.GetDelegate<FromReflectedField>().Invoke, reflectedField);
		}

		public IntPtr FromReflectedMethod(IntPtr reflectedMethod)
		{
			return SafeJniCall( _env.GetDelegate<FromReflectedMethod>().Invoke, reflectedMethod);
		}

		public IntPtr GetStaticObjectField(IntPtr classP, IntPtr fieldId)
		{
			return SafeJniCall(_env.GetDelegate<GetStaticObjectField>().Invoke, classP, fieldId);
		}

		public IntPtr GetObjectField(IntPtr obj, IntPtr fieldId)
		{
			return SafeJniCall(_env.GetDelegate<GetObjectField>().Invoke, obj, fieldId);
		}

		public IntPtr GetMethodID(IntPtr classP, string name, string sig)
		{
			return SafeJniCall(_env.GetDelegate<GetMethodID>().Invoke, classP, name, sig);
		}

		public IntPtr GetStaticMethodID(IntPtr classP, string name, string sig)
		{
			return SafeJniCall(_env.GetDelegate<GetStaticMethodID>().Invoke, classP, name, sig);
		}

		public byte CallByteMethod(IntPtr obj, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallByteMethodA>().Invoke, obj, methodId, args);
		}

		public short CallShortMethod(IntPtr obj, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallShortMethodA>().Invoke, obj, methodId, args);
		}

		public int CallIntMethod(IntPtr obj, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallIntMethodA>().Invoke, obj, methodId, args);
		}

		public long CallLongMethod(IntPtr obj, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallLongMethodA>().Invoke, obj, methodId, args);
		}

		public char CallCharMethod(IntPtr obj, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallCharMethodA>().Invoke, obj, methodId, args);
		}

		public float CallFloatMethod(IntPtr obj, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallFloatMethodA>().Invoke, obj, methodId, args);
		}

		public double CallDoubleMethod(IntPtr obj, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallDoubleMethodA>().Invoke, obj, methodId, args);
		}

		public bool CallBooleanMethod(IntPtr obj, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallBooleanMethodA>().Invoke, obj, methodId, args);
		}

		public IntPtr CallObjectMethod(IntPtr obj, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallObjectMethodA>().Invoke, obj, methodId, args);
		}

		public void CallVoidMethod(IntPtr obj, IntPtr methodId, params JValue[] args)
		{
			SafeJniCallA(_env.GetDelegate<CallVoidMethodA>().Invoke, obj, methodId, args);
		}

		public IntPtr NewObject(IntPtr classP, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<NewObjectA>().Invoke, classP, methodId, args);
		}

		public IntPtr NewStringUTF(string utf)
		{
			return SafeJniCall(_env.GetDelegate<NewStringUTF>().Invoke, utf);
		}

		public IntPtr NewString(string s)
		{
			byte[] bytes = Encoding.Unicode.GetBytes(s);
			unsafe
			{
				fixed (byte* buf = bytes)
				{
					// The NewString len parameter expects the length of an array of 2-byte characters, which
					// is half the length of an array of bytes.
					return SafeJniCall(_env.GetDelegate<NewString>().Invoke, new IntPtr(buf), bytes.Length / 2);
				}
			}
		}

		public byte CallStaticByteMethod(IntPtr classP, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallStaticByteMethodA>().Invoke, classP, methodId, args);
		}

		public short CallStaticShortMethod(IntPtr classP, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallStaticShortMethodA>().Invoke, classP, methodId, args);
		}

		public int CallStaticIntMethod(IntPtr classP, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallStaticIntMethodA>().Invoke, classP, methodId, args);
		}

		public long CallStaticLongMethod(IntPtr classP, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallStaticLongMethodA>().Invoke, classP, methodId, args);
		}

		public char CallStaticCharMethod(IntPtr classP, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallStaticCharMethodA>().Invoke, classP, methodId, args);
		}

		public float CallStaticFloatMethod(IntPtr classP, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallStaticFloatMethodA>().Invoke, classP, methodId, args);
		}

		public double CallStaticDoubleMethod(IntPtr classP, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallStaticDoubleMethodA>().Invoke, classP, methodId, args);
		}

		public bool CallStaticBooleanMethod(IntPtr classP, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallStaticBooleanMethodA>().Invoke, classP, methodId, args);
		}

		public void CallStaticVoidMethod(IntPtr classP, IntPtr methodId, params JValue[] args)
		{
			SafeJniCallA(_env.GetDelegate<CallStaticVoidMethodA>().Invoke, classP, methodId, args);
		}

		public IntPtr CallStaticObjectMethod(IntPtr classP, IntPtr methodId, params JValue[] args)
		{
			return SafeJniCall(_env.GetDelegate<CallStaticObjectMethodA>().Invoke, classP, methodId, args);
		}

		public IntPtr GetObjectClass(IntPtr obj)
		{
			return SafeJniCall( _env.GetDelegate<GetObjectClass>().Invoke, obj);
		}

		public string GetString(IntPtr stringPointer)
		{
			IntPtr stringChars = SafeJniCall(_env.GetDelegate<GetStringChars>().Invoke, stringPointer, IntPtr.Zero);
			try
			{
				return Marshal.PtrToStringUni(stringChars);
			}
			finally
			{
				SafeJniCallA(_env.GetDelegate<ReleaseStringChars>().Invoke, stringPointer, stringChars);
			}
		}

		private T[] GetPrimitiveArray<T>(IntPtr arrayPtr, Action<IntPtr, IntPtr, int, int, T[]> func)
		{
			int length = SafeJniCall(_env.GetDelegate<GetArrayLength>().Invoke, arrayPtr);
			T[] ret = new T[length];
			SafeJniCallA(func, arrayPtr, 0, length, ret);
			return ret;
		}

		public int GetArrayLength(IntPtr arrayPtr)
		{
			return SafeJniCall(_env.GetDelegate<GetArrayLength>().Invoke, arrayPtr);
		}

		public bool[] GetBooleanArray(IntPtr arrayPtr)
		{
			return GetPrimitiveArray<byte>(arrayPtr, _env.GetDelegate<GetBooleanArrayRegion>().Invoke).Select(b => b != 0).ToArray();
		}

		public byte[] GetByteArray(IntPtr arrayPtr)
		{
			return GetPrimitiveArray<byte>(arrayPtr, _env.GetDelegate<GetByteArrayRegion>().Invoke);
		}

		public char[] GetCharArray(IntPtr arrayPtr)
		{
			return GetPrimitiveArray<ushort>(arrayPtr, _env.GetDelegate<GetCharArrayRegion>().Invoke).Select(s => (char)s).ToArray();
		}

		public short[] GetShortArray(IntPtr arrayPtr)
		{
			return GetPrimitiveArray<short>(arrayPtr, _env.GetDelegate<GetShortArrayRegion>().Invoke);
		}

		public int[] GetIntArray(IntPtr arrayPtr)
		{
			return GetPrimitiveArray<int>(arrayPtr, _env.GetDelegate<GetIntArrayRegion>().Invoke);
		}

		public long[] GetLongArray(IntPtr arrayPtr)
		{
			return GetPrimitiveArray<long>(arrayPtr, _env.GetDelegate<GetLongArrayRegion>().Invoke);
		}

		public float[] GetFloatArray(IntPtr arrayPtr)
		{
			return GetPrimitiveArray<float>(arrayPtr, _env.GetDelegate<GetFloatArrayRegion>().Invoke);
		}

		public double[] GetDoubleArray(IntPtr arrayPtr)
		{
			return GetPrimitiveArray<double>(arrayPtr, _env.GetDelegate<GetDoubleArrayRegion>().Invoke);
		}

		public IntPtr[] GetArray(IntPtr arrayPtr)
		{
			int length = SafeJniCall(_env.GetDelegate<GetArrayLength>().Invoke, arrayPtr);
			IntPtr[] ret = new IntPtr[length];
			for (int i = 0; i < length; i++)
			{
				ret[i] = SafeJniCall(_env.GetDelegate<GetObjectArrayElement>().Invoke, arrayPtr, i);
			}
			return ret;
		}

		public IntPtr NewBooleanArray(bool[] elements)
		{
			IntPtr ret = SafeJniCall(_env.GetDelegate<NewBooleanArray>().Invoke, elements.Length);
			SafeJniCallA(_env.GetDelegate<SetBooleanArrayRegion>().Invoke, ret, 0, elements.Length, elements.Select(b => b ? (byte)1 : (byte)0).ToArray());
			return ret;
		}

		public IntPtr NewByteArray(byte[] elements)
		{
			IntPtr ret = SafeJniCall(_env.GetDelegate<NewByteArray>().Invoke, elements.Length);
			SafeJniCallA(_env.GetDelegate<SetByteArrayRegion>().Invoke, ret, 0, elements.Length, elements);
			return ret;
		}

		public IntPtr NewCharArray(char[] elements)
		{
			IntPtr ret = SafeJniCall(_env.GetDelegate<NewCharArray>().Invoke, elements.Length);
			SafeJniCallA(_env.GetDelegate<SetCharArrayRegion>().Invoke, ret, 0, elements.Length, elements.Select(c => (ushort)c).ToArray());
			return ret;
		}

		public IntPtr NewShortArray(short[] elements)
		{
			IntPtr ret = SafeJniCall(_env.GetDelegate<NewShortArray>().Invoke, elements.Length);
			SafeJniCallA(_env.GetDelegate<SetShortArrayRegion>().Invoke, ret, 0, elements.Length, elements);
			return ret;
		}

		public IntPtr NewIntArray(int[] elements)
		{
			IntPtr ret = SafeJniCall(_env.GetDelegate<NewIntArray>().Invoke, elements.Length);
			SafeJniCallA(_env.GetDelegate<SetIntArrayRegion>().Invoke, ret, 0, elements.Length, elements);
			return ret;
		}

		public IntPtr NewLongArray(long[] elements)
		{
			IntPtr ret = SafeJniCall(_env.GetDelegate<NewLongArray>().Invoke, elements.Length);
			SafeJniCallA(_env.GetDelegate<SetLongArrayRegion>().Invoke, ret, 0, elements.Length, elements);
			return ret;
		}

		public IntPtr NewFloatArray(float[] elements)
		{
			IntPtr ret = SafeJniCall(_env.GetDelegate<NewFloatArray>().Invoke, elements.Length);
			SafeJniCallA(_env.GetDelegate<SetFloatArrayRegion>().Invoke, ret, 0, elements.Length, elements);
			return ret;
		}

		public IntPtr NewDoubleArray(double[] elements)
		{
			IntPtr ret = SafeJniCall(_env.GetDelegate<NewDoubleArray>().Invoke, elements.Length);
			SafeJniCallA(_env.GetDelegate<SetDoubleArrayRegion>().Invoke, ret, 0, elements.Length, elements);
			return ret;
		}

		public IntPtr NewArray(IntPtr classP, IntPtr[] elements)
		{
			IntPtr ret = SafeJniCall(_env.GetDelegate<NewObjectArray>().Invoke, elements.Length, classP, IntPtr.Zero);
			for (int i = 0; i < elements.Length; i++)
			{
				SafeJniCallA(_env.GetDelegate<SetObjectArrayElement>().Invoke, ret, i, elements[i]);
			}
			return ret;
		}

		private A SafeJniCall<A>(Func<IntPtr, A> func)
		{
			return SafeJniCall(() => func(_currentThreadEnv.Value));
		}

		private B SafeJniCall<A, B>(Func<IntPtr, A, B> func, A arg1)
		{
			return SafeJniCall(() => func(_currentThreadEnv.Value, arg1));
		}

		private C SafeJniCall<A, B, C>(Func<IntPtr, A, B, C> func, A arg1, B arg2)
		{
			return SafeJniCall(() => func(_currentThreadEnv.Value, arg1, arg2));
		}

		private D SafeJniCall<A, B, C, D>(Func<IntPtr, A, B, C, D> func, A arg1, B arg2, C arg3)
		{
			return SafeJniCall(() => func(_currentThreadEnv.Value, arg1, arg2, arg3));
		}

		private void SafeJniCallA(Action<IntPtr> func)
		{
			SafeJniCall<object>(() => { func(_currentThreadEnv.Value); return null; });
		}

		private void SafeJniCallA<A>(Action<IntPtr, A> func, A arg1)
		{
			SafeJniCall<object>(() => { func(_currentThreadEnv.Value, arg1); return null; });
		}

		private void SafeJniCallA<A, B>(Action<IntPtr, A, B> func, A arg1, B arg2)
		{
			SafeJniCall<object>(() => { func(_currentThreadEnv.Value, arg1, arg2); return null; });
		}

		private void SafeJniCallA<A, B, C>(Action<IntPtr, A, B, C> func, A arg1, B arg2, C arg3)
		{
			SafeJniCall<object>(() => { func(_currentThreadEnv.Value, arg1, arg2, arg3); return null; });
		}

		private void SafeJniCallA<A, B, C, D>(Action<IntPtr, A, B, C, D> func, A arg1, B arg2, C arg3, D arg4)
		{
			SafeJniCall<object>(() => { func(_currentThreadEnv.Value, arg1, arg2, arg3, arg4); return null; });
		}

		private T SafeJniCall<T>(Func<T> func)
		{
			_env.GetDelegate<ExceptionClear>()(_currentThreadEnv.Value);
			T ret = func();
			if (_env.GetDelegate<ExceptionCheck>()(_currentThreadEnv.Value))
			{
				IntPtr exception = _env.GetDelegate<ExceptionOccurred>()(_currentThreadEnv.Value);
				_env.GetDelegate<ExceptionClear>()(_currentThreadEnv.Value);
				string exceptionType = GetExceptionType(exception);
				JThrowableClass throwableClass = new JThrowableClass(this);
				string exceptionMessage = throwableClass.GetMessage(exception);
				exceptionMessage = AppendCause(exceptionMessage, exception, throwableClass);
				throw new JavaException(exceptionType + (String.IsNullOrEmpty(exceptionMessage) ? "" : ": " + exceptionMessage),
					javaStackTrace: throwableClass.GetStackTrace(exception));
			}
			return ret;
		}

		private string GetExceptionType(IntPtr exception)
		{
			IntPtr exceptionTypePtr = new JObjectClass(this).GetClass(exception);
			return new JClassClass(this).GetName(exceptionTypePtr);
		}

		private string AppendCause(string exceptionMessage, IntPtr exception, JThrowableClass throwableClass)
		{
			IntPtr cause = throwableClass.GetCause(exception);
			if (cause == IntPtr.Zero)
			{
				return exceptionMessage;
			}
			else
			{
				string causeType = GetExceptionType(cause);
				string causeMessage = throwableClass.GetMessage(exception);
				if (causeMessage != null)
				{
					exceptionMessage = (exceptionMessage ?? "") + ". Caused by: " + causeType + ": " + causeMessage;
				}
				return AppendCause(exceptionMessage, cause, throwableClass);
			}
		}

		public void DetachThread()
		{
			_vm.GetDelegate<DetachCurrentThread>()(_vmP);
			_currentThreadEnv.Value = IntPtr.Zero;
		}

		public void Dispose()
		{
			if (_vmDllModule != IntPtr.Zero && !_vmReuse)
			{
				int ret = _vm.GetDelegate<DestroyJavaVM>()(_vmP);
				if (ret != 0)
				{
					throw new InvalidOperationException("JavaVM destruction failed - return value obtained: " + ret);
				}
				if (!FreeLibrary(_vmDllModule))
				{
					throw new Win32Exception();
				}
				_vmDllModule = IntPtr.Zero;
			}
		}
	}
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <wchar.h>
#include "a.h"
typedef unsigned long long UINT64;
typedef unsigned int       UINTN;
typedef char               CHAR8;
typedef long long          INT64;

char    cs[10] = "a张";
wchar_t wb[20] = L"0123456789abcdef";
wchar_t ws[20] = L"a张";
wchar_t ws2[20] = L"b涛";

static wchar_t mHexStr[] = { L'0', L'1', L'2', L'3', L'4', L'5', L'6', L'7',
                            L'8', L'9', L'A', L'B', L'C', L'D', L'E', L'F' };

wchar_t *
AsciiToUnicode (
  CHAR8   *Ascii,
  UINTN   *StrLen
  )
/*++

Routine Description:
  Convert the passed in Ascii string to Unicode.
  Optionally return the length of the strings.

Arguments:
  Ascii   - Ascii string to convert
  StrLen  - Length of string

Returns:
  Pointer to malloc'ed Unicode version of Ascii

--*/
{
  UINTN   Index;
  wchar_t  *Unicode;

  //
  // Allocate a buffer for unicode string
  //
  for (Index = 0; Ascii[Index] != '\0'; Index++)
    ;
  Unicode = malloc ((Index + 1) * sizeof (wchar_t));
  if (Unicode == NULL) {
    return NULL;
  }

  for (Index = 0; Ascii[Index] != '\0'; Index++) {
    Unicode[Index] = (wchar_t) Ascii[Index];
  }

  Unicode[Index] = '\0';

  if (StrLen != NULL) {
    *StrLen = Index;
  }

  return Unicode;
}

UINT64
DivU64x32 (
  UINT64   Dividend,
  UINTN    Divisor,
  UINTN   *Remainder
  )
/*++

Routine Description:

  This routine allows a 64 bit value to be divided with a 32 bit value returns
  64bit result and the Remainder.

Arguments:

  Dividend  - dividend
  Divisor   - divisor
  Remainder - buffer for remainder

Returns:

  Dividend  / Divisor
  Remainder = Dividend mod Divisor

--*/
{
  if (Remainder != NULL) {
    *Remainder = Dividend % Divisor;
  }

  return Dividend / Divisor;
}

UINT64
RShiftU64 (
  UINT64   Operand,
  UINTN    Count
  )
/*++

Routine Description:

  This routine allows a 64 bit value to be right shifted by 32 bits and returns the
  shifted value.
  Count is valid up 63. (Only Bits 0-5 is valid for Count)

Arguments:

  Operand - Value to be shifted
  Count   - Number of times to shift right.

Returns:

  Value shifted right identified by the Count.

--*/
{
  return Operand >> Count;
}

UINTN
EfiValueToHexStr (
  wchar_t  *Buffer,
  UINT64      Value,
  UINTN       Flags,
  UINTN       Width
  )
/*++

Routine Description:

  VSPrint worker function that prints a Value as a hex number in Buffer

Arguments:

  Buffer - Location to place ascii hex string of Value.

  Value  - Hex value to convert to a string in Buffer.

  Flags  - Flags to use in printing Hex string, see file header for details.

  Width  - Width of hex value.

Returns:

  Number of characters printed.

--*/
{
  wchar_t  TempBuffer[CHARACTER_NUMBER_FOR_VALUE];
  wchar_t  *TempStr;
  wchar_t  Prefix;
  wchar_t  *BufferPtr;
  UINTN   Count;
  UINTN   Index;

  TempStr   = TempBuffer;
  BufferPtr = Buffer;

  //
  // Count starts at one since we will null terminate. Each iteration of the
  // loop picks off one nibble. Oh yea TempStr ends up backwards
  //
  Count = 0;

  if (Width > CHARACTER_NUMBER_FOR_VALUE - 1) {
    Width = CHARACTER_NUMBER_FOR_VALUE - 1;
  }

  do {
    Index = ((UINTN)Value & 0xf);
    *(TempStr++) = mHexStr[Index];
    Value = RShiftU64 (Value, 4);
    Count++;
  } while (Value != 0);

  if (Flags & PREFIX_ZERO) {
    Prefix = '0';
  } else {
    Prefix = ' ';
  }

  Index = Count;
  if (!(Flags & LEFT_JUSTIFY)) {
    for (; Index < Width; Index++) {
      *(TempStr++) = Prefix;
    }
  }

  //
  // Reverse temp string into Buffer.
  //
  if (Width > 0 && (UINTN) (TempStr - TempBuffer) > Width) {
    TempStr = TempBuffer + Width;
  }
  Index = 0;
  while (TempStr != TempBuffer) {
    *(BufferPtr++) = *(--TempStr);
    Index++;
  }

  *BufferPtr = 0;
  return Index;
}

UINTN
EfiValueToString (
  wchar_t  *Buffer,
  INT64       Value,
  UINTN       Flags,
  UINTN       Width
  )
/*++

Routine Description:

  VSPrint worker function that prints a Value as a decimal number in Buffer

Arguments:

  Buffer - Location to place ascii decimal number string of Value.

  Value  - Decimal value to convert to a string in Buffer.

  Flags  - Flags to use in printing decimal string, see file header for details.

  Width  - Width of hex value.

Returns:

  Number of characters printed.

--*/
{
  wchar_t    TempBuffer[CHARACTER_NUMBER_FOR_VALUE];
  wchar_t    *TempStr;
  wchar_t    *BufferPtr;
  UINTN     Count;
  UINTN     ValueCharNum;
  UINTN     Remainder;
  wchar_t    Prefix;
  UINTN     Index;
  int   ValueIsNegative;

  TempStr         = TempBuffer;
  BufferPtr       = Buffer;
  Count           = 0;
  ValueCharNum    = 0;
  ValueIsNegative = FALSE;

  if (Width > CHARACTER_NUMBER_FOR_VALUE - 1) {
    Width = CHARACTER_NUMBER_FOR_VALUE - 1;
  }

  if (Value < 0) {
    Value           = -Value;
    ValueIsNegative = TRUE;
  }

  do {
    Value = (long long)DivU64x32 ((UINT64)Value, 10, &Remainder);
    *(TempStr++) = (wchar_t)(Remainder + '0');
    ValueCharNum++;
    Count++;
    if ((Flags & COMMA_TYPE) == COMMA_TYPE) {
      if (ValueCharNum % 3 == 0 && Value != 0) {
        *(TempStr++) = ',';
        Count++;
      }
    }
  } while (Value != 0);

  if (ValueIsNegative) {
    *(TempStr++)    = '-';
    Count++;
  }

  if ((Flags & PREFIX_ZERO) && !ValueIsNegative) {
    Prefix = '0';
  } else {
    Prefix = ' ';
  }

  Index = Count;
  if (!(Flags & LEFT_JUSTIFY)) {
    for (; Index < Width; Index++) {
      *(TempStr++) = Prefix;
    }
  }

  //
  // Reverse temp string into Buffer.
  //
  if (Width > 0 && (UINTN) (TempStr - TempBuffer) > Width) {
    TempStr = TempBuffer + Width;
  }
  Index = 0;
  while (TempStr != TempBuffer) {
    *(BufferPtr++) = *(--TempStr);
    Index++;
  }

  *BufferPtr = 0;
  return Index;
}

static
wchar_t *
GetFlagsAndWidth (
  wchar_t      *Format,
  UINTN       *Flags,
  UINTN       *Width,
  va_list *Marker
  )
/*++

Routine Description:

  VSPrint worker function that parses flag and width information from the
  Format string and returns the next index into the Format string that needs
  to be parsed. See file headed for details of Flag and Width.

Arguments:

  Format - Current location in the VSPrint format string.

  Flags  - Returns flags

  Width  - Returns width of element

  Marker - Vararg list that may be paritally consumed and returned.

Returns:

  Pointer indexed into the Format string for all the information parsed
  by this routine.

--*/
{
  UINTN   Count;
  int Done;

  *Flags  = 0;
  *Width  = 0;
  for (Done = FALSE; !Done;) {
    Format++;

    switch (*Format) {

    case '-':
      *Flags |= LEFT_JUSTIFY;
      break;

    case '+':
      *Flags |= PREFIX_SIGN;
      break;

    case ' ':
      *Flags |= PREFIX_BLANK;
      break;

    case ',':
      *Flags |= COMMA_TYPE;
      break;

    case 'L':
    case 'l':
      *Flags |= LONG_TYPE;
      break;

    case '*':
      *Width = va_arg (*Marker, UINTN);
      break;

    case '0':
      *Flags |= PREFIX_ZERO;

    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
      Count = 0;
      do {
        Count = (Count * 10) +*Format - '0';
        Format++;
      } while ((*Format >= '0') && (*Format <= '9'));
      Format--;
      *Width = Count;
      break;

    default:
      Done = TRUE;
    }
  }

  return Format;
}

/*
  %[flags][width]type

  flags:
    '-' - Left justify
    '+' - Prefix a sign
    ' ' - Prefix a blank
    ',' - Place commas in numberss
    '0' - Prefix for width with zeros
    'l' - unsigned long long
    'L' - unsigned long long

  width:
    '*' - Get width from a unsigned int argumnet from the argument list
    Decimal number that represents width of print

  type:
    'X' - argument is a unsigned int hex number, prefix '0'
    'x' - argument is a hex number
    'd' - argument is a decimal number
    'a' - argument is an ascii string
    'S','s' - argument is an Unicode string
    'g' - argument is a pointer to an EFI_GUID
    't' - argument is a pointer to an EFI_TIME structure
    'c' - argument is an ascii character
    'r' - argument is EFI_STATUS
    '%' - Print a %

*/

int _vswprintf(wchar_t *StartOfBuffer, size_t BufferSize, const wchar_t *FormatString, va_list Marker)
{
  wchar_t    TempBuffer[CHARACTER_NUMBER_FOR_VALUE];
  wchar_t    *Buffer;
  unsigned char     *AsciiStr;
  wchar_t    *UnicodeStr;
  wchar_t    *Format;
  UINTN     Index;
  UINTN     Flags;
  UINTN     Width;
  UINTN     Count;
  UINTN     NumberOfCharacters;
  UINTN     BufferLeft;
  UINT64    Value;

  //
  // Process the format string. Stop if Buffer is over run.
  //

  Buffer              = StartOfBuffer;
  Format              = (wchar_t *) FormatString;
  NumberOfCharacters  = BufferSize / sizeof (wchar_t);
  BufferLeft          = BufferSize;
  for (Index = 0; (*Format != '\0') && (Index < NumberOfCharacters - 1); Format++) {
    if (*Format != '%') {
      if ((*Format == '\n') && (Index < NumberOfCharacters - 2)) {
        //
        // If carage return add line feed
        //
        Buffer[Index++] = '\r';
        BufferLeft -= sizeof (wchar_t);
      }

      Buffer[Index++] = *Format;
      BufferLeft -= sizeof (wchar_t);
    } else {

      //
      // Now it's time to parse what follows after %
      //
      Format = GetFlagsAndWidth (Format, &Flags, &Width, &Marker);
      switch (*Format) {
      case 'X':
        Flags |= PREFIX_ZERO;
        Width = sizeof (UINT64) * 2;

      //
      // break skiped on purpose
      //
      case 'x':
        if ((Flags & LONG_TYPE) == LONG_TYPE) {
          Value = va_arg (Marker, UINT64);
        } else {
          Value = va_arg (Marker, UINTN);
        }

        EfiValueToHexStr (TempBuffer, Value, Flags, Width);
        UnicodeStr = TempBuffer;

        for (; (*UnicodeStr != '\0') && (Index < NumberOfCharacters - 1); UnicodeStr++) {
          Buffer[Index++] = *UnicodeStr;
        }
        break;

      case 'd':
        if ((Flags & LONG_TYPE) == LONG_TYPE) {
          Value = va_arg (Marker, UINT64);
        } else {
          Value = (UINTN) va_arg (Marker, UINTN);
        }

        EfiValueToString (TempBuffer, Value, Flags, Width);
        UnicodeStr = TempBuffer;

        for (; (*UnicodeStr != '\0') && (Index < NumberOfCharacters - 1); UnicodeStr++) {
          Buffer[Index++] = *UnicodeStr;
        }
        break;

      case 's':
      case 'S':
        UnicodeStr = (wchar_t *) va_arg (Marker, wchar_t *);
        if (UnicodeStr == NULL) {
          UnicodeStr = L"<null string>";
        }

        for (Count = 0; (*UnicodeStr != '\0') && (Index < NumberOfCharacters - 1); UnicodeStr++, Count++) {
          Buffer[Index++] = *UnicodeStr;
        }
        //
        // Add padding if needed
        //
        for (; (Count < Width) && (Index < NumberOfCharacters - 1); Count++) {
          Buffer[Index++] = ' ';
        }

        break;

      case 'a':
        AsciiStr = (unsigned char *) va_arg (Marker, unsigned char *);
        if (AsciiStr == NULL) {
          AsciiStr = "<null string>";
        }

        for (Count = 0; (*AsciiStr != '\0') && (Index < NumberOfCharacters - 1); AsciiStr++, Count++) {
          Buffer[Index++] = (wchar_t) * AsciiStr;
        }
        //
        // Add padding if needed
        //
        for (; (Count < Width) && (Index < NumberOfCharacters - 1); Count++) {
          Buffer[Index++] = ' ';
        }
        break;

      case 'c':
        Buffer[Index++] = (wchar_t) va_arg (Marker, UINTN);
        break;

      case '%':
        Buffer[Index++] = *Format;
        break;

      default:
        //
        // if the type is unknown print it to the screen
        //
        Buffer[Index++] = *Format;
      }

      BufferLeft = BufferSize - Index * sizeof (wchar_t);
    }
  }

  Buffer[Index++] = '\0';

  return &Buffer[Index] - StartOfBuffer;
}

int _swprintf(wchar_t * Buffer, size_t BufferSize, const wchar_t *Format, ...)
{
  UINTN Return;
  va_list Marker;

  va_start (Marker, Format);
  Return = _vswprintf(Buffer, BufferSize, Format, Marker);
  va_end (Marker);

  return Return;
}

int main()
{
  printf("strlen(cs) = %d\n",strlen(cs));
  _swprintf(wb,12, L"%S1%S",ws,ws2);

  printf("cs[0] = 0x%x\n",cs[0]);
  printf("cs[1] = 0x%x\n",cs[1]);
  printf("cs[2] = 0x%x\n",cs[2]);
  printf("cs[3] = 0x%x\n",cs[3]);

  printf("wb[0] = 0x%x\n",wb[0]);
  printf("wb[1] = 0x%x\n",wb[1]);
  printf("wb[2] = 0x%x\n",wb[2]);
  printf("wb[3] = 0x%x\n",wb[3]);
  printf("wb[4] = 0x%x\n",wb[4]);
  printf("wb[5] = 0x%x\n",wb[5]);
  printf("wb[6] = 0x%x\n",wb[6]);
  printf("wb[7] = 0x%x\n",wb[7]);
  return 0;
}