text:
import jsonschema
import six

from daisy.common import exception
from daisy.common import utils
from daisy import i18n

_ = i18n._

class Schema(object):

    def __init__(self, name, properties=None, links=None, required=None,
                 definitions=None):
        self.name = name
        if properties is None:
            properties = {}
        self.properties = properties
        self.links = links
        self.required = required
        self.definitions = definitions

    def validate(self, obj):
        try:
            jsonschema.validate(obj, self.raw())
        except jsonschema.ValidationError as e:
            raise exception.InvalidObject(schema=self.name,
                                          reason=utils.exception_to_str(e))

    def filter(self, obj):
        filtered = {}
        for key, value in six.iteritems(obj):
            if self._filter_func(self.properties, key):
                filtered[key] = value
        return filtered

    @staticmethod
    def _filter_func(properties, key):
        return key in properties

    def merge_properties(self, properties):
        # Ensure custom props aren't attempting to override base props
        original_keys = set(self.properties.keys())
        new_keys = set(properties.keys())
        intersecting_keys = original_keys.intersection(new_keys)
        conflicting_keys = [k for k in intersecting_keys
                            if self.properties[k] != properties[k]]
        if conflicting_keys:
            props = ', '.join(conflicting_keys)
            reason = _("custom properties (%(props)s) conflict "
                       "with base properties")
            raise exception.SchemaLoadError(reason=reason % {'props': props})

        self.properties.update(properties)

    def raw(self):
        raw = {
            'name': self.name,
            'properties': self.properties,
            'additionalProperties': False,
        }
        if self.definitions:
            raw['definitions'] = self.definitions
        if self.required:
            raw['required'] = self.required
        if self.links:
            raw['links'] = self.links
        return raw

    def minimal(self):
        minimal = {
            'name': self.name,
            'properties': self.properties
        }
        if self.definitions:
            minimal['definitions'] = self.definitions
        if self.required:
            minimal['required'] = self.required
        return minimal

class PermissiveSchema(Schema):
    @staticmethod
    def _filter_func(properties, key):
        return True

    def raw(self):
        raw = super(PermissiveSchema, self).raw()
        raw['additionalProperties'] = {'type': 'string'}
        return raw

    def minimal(self):
        minimal = super(PermissiveSchema, self).raw()
        return minimal

class CollectionSchema(object):

    def __init__(self, name, item_schema):
        self.name = name
        self.item_schema = item_schema

    def raw(self):
        definitions = None
        if self.item_schema.definitions:
            definitions = self.item_schema.definitions
            self.item_schema.definitions = None
        raw = {
            'name': self.name,
            'properties': {
                self.name: {
                    'type': 'array',
                    'items': self.item_schema.raw(),
                },
                'first': {'type': 'string'},
                'next': {'type': 'string'},
                'schema': {'type': 'string'},
            },
            'links': [
                {'rel': 'first', 'href': '{first}'},
                {'rel': 'next', 'href': '{next}'},
                {'rel': 'describedby', 'href': '{schema}'},
            ],
        }
        if definitions:
            raw['definitions'] = definitions
            self.item_schema.definitions = definitions

        return raw

    def minimal(self):
        definitions = None
        if self.item_schema.definitions:
            definitions = self.item_schema.definitions
            self.item_schema.definitions = None
        minimal = {
            'name': self.name,
            'properties': {
                self.name: {
                    'type': 'array',
                    'items': self.item_schema.minimal(),
                },
                'schema': {'type': 'string'},
            },
            'links': [
                {'rel': 'describedby', 'href': '{schema}'},
            ],
        }
        if definitions:
            minimal['definitions'] = definitions
            self.item_schema.definitions = definitions

        return minimal

class DictCollectionSchema(Schema):
    def __init__(self, name, item_schema):
        self.name = name
        self.item_schema = item_schema

    def raw(self):
        definitions = None
        if self.item_schema.definitions:
            definitions = self.item_schema.definitions
            self.item_schema.definitions = None
        raw = {
            'name': self.name,
            'properties': {
                self.name: {
                    'type': 'object',
                    'additionalProperties': self.item_schema.raw(),
                },
                'first': {'type': 'string'},
                'next': {'type': 'string'},
                'schema': {'type': 'string'},
            },
            'links': [
                {'rel': 'first', 'href': '{first}'},
                {'rel': 'next', 'href': '{next}'},
                {'rel': 'describedby', 'href': '{schema}'},
            ],
        }
        if definitions:
            raw['definitions'] = definitions
            self.item_schema.definitions = definitions

        return raw

    def minimal(self):
        definitions = None
        if self.item_schema.definitions:
            definitions = self.item_schema.definitions
            self.item_schema.definitions = None
        minimal = {
            'name': self.name,
            'properties': {
                self.name: {
                    'type': 'object',
                    'additionalProperties': self.item_schema.minimal(),
                },
                'schema': {'type': 'string'},
            },
            'links': [
                {'rel': 'describedby', 'href': '{schema}'},
            ],
        }
        if definitions:
            minimal['definitions'] = definitions
            self.item_schema.definitions = definitions

        return minimal


text:
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
             xmlns:b="urn:import:org.gwtbootstrap3.client.ui"
             xmlns:g="urn:import:com.google.gwt.user.client.ui">

    <ui:with field="i18n" type="org.ext.uberfire.social.activities.client.resources.i18n.Constants"/>

    <g:HTMLPanel>
        <g:HTMLPanel>
            <b:Heading ui:field="title" size="H4"/>
        </g:HTMLPanel>
        <b:Heading size="H3" text="{i18n.Following}">
            <b:Badge ui:field="followingBadge"/>
        </b:Heading>
        <b:ListGroup ui:field="allfollowing"/>
        <b:Heading size="H3" text="{i18n.Followers}">
            <b:Badge ui:field="followersBadge"/>
        </b:Heading>
        <b:ListGroup ui:field="allfollowers"/>
        <b:Heading size="H3" text="{i18n.AllUsers}">
            <b:Badge ui:field="allusersBadge"/>
        </b:Heading>
        <b:ListGroup ui:field="allusers"/>
    </g:HTMLPanel>
</ui:UiBinder>

redpajama_set_name: RedPajamaGithub


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

namespace LegendaryClient.Logic.Riot.Platform
{
    [Serializable]
    [SerializedName("com.riotgames.platform.game.StartChampSelectDTO")]
    public class StartChampSelectDTO
    {
        [SerializedName("invalidPlayers")]
        public List<object> InvalidPlayers { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;

namespace CExtensions.EFModelGenerator.Providers
{
    public class SqlDataProvider : AbstractProvider
    {
        #region queries

        private const string TABLE_SQL = @"SELECT t.name as TABLE_NAME
                                              FROM sys.tables AS t
                                              INNER JOIN sys.schemas AS s
                                              ON t.[schema_id] = s.[schema_id]
                                              WHERE s.name = N'{0}';";

        private const String COLUMN_SQL = @"SELECT
                                            TABLE_NAME as TableName,
                                            COLUMN_NAME as ColumnName,
                                            DATA_TYPE as DataType,
                                            NUMERIC_SCALE as DataScale,
                                            IS_NULLABLE as IsNullable,
                                            CAST(ISNULL(CHARACTER_MAXIMUM_LENGTH, 0) AS INT) as MaxLength,
                                            CAST(ISNULL(NUMERIC_PRECISION, 0) AS INT) AS [Precision]
                                            FROM INFORMATION_SCHEMA.COLUMNS
                                            WHERE TABLE_SCHEMA='{0}'
                                            AND TABLE_NAME = '{1}'
                                            ";

        private const String PK_SQL = @"SELECT Tab.TABLE_NAME, Col.COLUMN_NAME from
                                        INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
                                        INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
                                    WHERE
                                        Col.Constraint_Name = Tab.Constraint_Name
                                        AND Col.Table_Name = Tab.Table_Name
                                        AND Constraint_Type = 'PRIMARY KEY'
                                    ";

        private const String FK_SQL = @"
                                    SELECT
                                       OBJECT_NAME(f.parent_object_id) as TABLE_NAME,
                                       COL_NAME(fc.parent_object_id,fc.parent_column_id) as COLUMN_NAME,
                                       OBJECT_NAME(f.referenced_object_id) as R_TABLE_NAME
                                    FROM
                                       sys.foreign_keys AS f
                                    INNER JOIN
                                       sys.foreign_key_columns AS fc
                                          ON f.OBJECT_ID = fc.constraint_object_id
                                    INNER JOIN
                                       sys.tables t
                                          ON t.OBJECT_ID = fc.referenced_object_id
                                    ";

        #endregion

        public SqlDataProvider(String connString, string schema)
        {
            ConnectionString = connString;
            Schema = schema;
        }

        public String ConnectionString { get; private set; }

        public String Schema { get; private set; }

        public override IList<string> ListTableNames()
        {
            SqlConnection dbcon = new SqlConnection(ConnectionString);

            List<String> result = new List<string>();

            try
            {
                dbcon.Open();

                var formatQuery = string.Format(TABLE_SQL, Schema);

                using (var TableCmd = new SqlCommand(formatQuery, dbcon))
                {
                    using (var rdr = TableCmd.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            result.Add(rdr["TABLE_NAME"].ToString());
                        }
                    }
                }
            }
            finally
            {
                dbcon.Close();
            }

            return result;
        }

        public override IList<ColumnMetadata> ListColumnsFor(string tableName)
        {
            SqlConnection dbcon = new SqlConnection(ConnectionString);

            List<ColumnMetadata> result = new List<ColumnMetadata>();

            try
            {
                dbcon.Open();

                String formatedColumnCommand = String.Format(COLUMN_SQL, Schema, tableName);

                using (var ColumnCmd = new SqlCommand(formatedColumnCommand, dbcon))
                {
                    using (var colRdr = ColumnCmd.ExecuteReader())
                    {
                        while (colRdr.Read())
                        {
                            var col = new ColumnMetadata()
                            {
                                Name = colRdr["ColumnName"].ToString(),
                                DBType = colRdr["DataType"].ToString(),
                                DBDataScale = colRdr["DataScale"].ToString(),
                                IsNullable = "YES".Equals(colRdr["IsNullable"].ToString()),
                                MaxLength = Int32.Parse(colRdr["MaxLength"]?.ToString()),
                                Precision = Int32.Parse(colRdr["Precision"]?.ToString())
                            };

                            result.Add(col);
                        }
                    }
                }
            }
            finally
            {
                dbcon.Close();
            }

            return result;
        }

        public override IList<Tuple<string,string>> ListAllPrimaryKeys()
        {
            SqlConnection dbcon = new SqlConnection(ConnectionString);

            List<Tuple<string, string>> result = new List<Tuple<string, string>>();

            try
            {
                dbcon.Open();

                using (var PkCmd = new SqlCommand(PK_SQL, dbcon))
                {
                    using (var PkReader = PkCmd.ExecuteReader())
                    {
                        while (PkReader.Read())
                        {
                            var myStruct = Tuple.Create<string, string>(PkReader["TABLE_NAME"].ToString(), PkReader["COLUMN_NAME"].ToString());

                            result.Add(myStruct);
                        }
                    }
                }
            }
            finally
            {
                dbcon.Close();
            }

            return result;
        }

        public override IList<Tuple<string, string, string>> ListAllForeignKeys()
        {
            SqlConnection dbcon = new SqlConnection(ConnectionString);

            IList<Tuple<string, string, string>> result = new List<Tuple<string, string, string>>();
            try
            {
                dbcon.Open();

                using (var FKCmd = new SqlCommand(FK_SQL, dbcon))
                {
                    using (var FkReader = FKCmd.ExecuteReader())
                    {
                        while (FkReader.Read())
                        {
                            var fk = Tuple.Create<string, string, string>(
                                 FkReader["TABLE_NAME"].ToString(),
                                 FkReader["COLUMN_NAME"].ToString(),
                                 FkReader["R_TABLE_NAME"].ToString()
                            );

                            result.Add(fk);
                        }
                    }
                }
            }
            finally
            {
                dbcon.Close();
            }

            return result;
        }
    }
}


text:
package ru.job4j;

/**
 * Class SearchSubstring.
 *
 *@author Alexander Vezgin
 *@version 1.0
 *@since 22.11.2016
 */
public class SearchSubstring {

	/**
	* This method returned true if string contains substring and false if not.
	*@param origin is a original string
	*@param sub is a substring
	*@return true if string contains substring and false if not
	*/
	public boolean contains(String origin, String sub) {
		/**
		 * Here the original string is converted to a character array.
		 */
		char[] origChar = origin.toCharArray();

		/**
		 * Here the substring is converted to a character array.
		 */
		char[] subChar = sub.toCharArray();

		for (int i = 0; i <= origChar.length - subChar.length; i++) {
			for (int j = 0; j < subChar.length; j++) {
				if (subChar[j] != origChar[i + j]) {
					break;
				}
				if (j == subChar.length - 1) {
					return true;
				}
			}
		}

		return false;
	}
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GetLoginStatus : MonoBehaviour {
    private NetworkManager _networkManager;
    private Text _text;

    // Use this for initialization
	void Start () {
	    _networkManager = GameObject.FindObjectOfType<NetworkManager>();
	    _text = gameObject.GetComponent<Text>();
	}

	// Update is called once per frame
	void Update () {
	    _text.text = _networkManager.CurrentLoginText;
	}
}


text:
require 'net/http'
require 'uri'
require 'json'

require 'lights/bridge'
require 'lights/exception'
require 'lights/datastore'
require 'lights/groupstate'
require 'lights/loggerconfig'

class Lights

  attr_reader :bulbs, :username
  def initialize(ip,username=nil)
    @ip = ip
    @username = username
    @http = Net::HTTP.new(ip,80)
    @bulbs = []
    @groups = []
    @bridges = []
    @logger = Logger.new(STDERR)
    @logger.level = LoggerConfig::LIGHTS_LEVEL
  end

  def discover_hubs
    http = Net::HTTP.new("discovery.meethue.com",443)
    http.use_ssl = true
    request = Net::HTTP::Get.new( "/" )
    response = http.request request

    case response.code.to_i
    when 200
      result = JSON.parse( response.body )
      result.each { |b| @bridges << Bridge.new(b) }
    else
      @logger.fatal "Could not discover bridge. HTTP error #{response.code}"
      @logger.fatal "Response: #{response.body}"
      raise "Unknown error"
    end
    @bridges
  end

  def register
    data = { "devicetype"=>"lights" }
    response = @http.post "/api", data.to_json
    result = JSON.parse(response.body).first
    if result.has_key? "error"
      process_error result
    elsif result["success"]
      @username = result["success"]["username"]
    end
    result
  end

  # backwards compatibility
  alias_method :register_username, :register

  def request_config
    get "config"
  end

  def add_bulb(id,bulb_data)
    @bulbs << Bulb.new( id, bulb_data )
  end

  def search_new
    post "lights"
  end

  def request_bulb_list
    get "lights"
  end

  def request_new_bulb_list
    get "lights/new"
  end

  def request_new_sensor_list
    get "sensors/new"
  end

  def request_bulb_info( id )
    response = get "lights/#{id}"
    Bulb.new(id,response)
  end

  def request_group_info( id )
    response = get "groups/#{id}"
    Group.new(id,response)
  end

  def request_sensor_info( id )
    response = get "sensors/#{id}"
    Sensor.new(id,response)
  end

  def request_sensor_list
    get "sensors"
  end

  def request_group_list
    get "groups"
  end

  def request_schedule_list
    get "schedules"
  end

  def request_scene_list
    get "scenes"
  end

  def request_config
    get "config"
  end

  def request_rules
    get "rules"
  end

  def request_schedules
    get "schedules"
  end

  def request_datastore
    get ""
  end

  def set_bulb_state( id, state )
    put "lights/#{id}/state", state
  end

  def set_group_state( id, state )
    put "groups/#{id}/action", state
  end

  def create_group( group )
    post "groups", group
  end

  def create_scene( scene )
    post "scenes/#{scene.id}", scene
  end

  def delete_scene( id )
    delete "scenes/#{id}"
  end

  def delete_group( id )
    delete "groups/#{id}"
  end

  def edit_bulb( bulb )
    put "lights/#{bulb.id}", bulb
  end

  def edit_group( group )
    put "groups/#{group.id}", group
  end

  def delete_user( username )
    delete "config/whitelist/#{username}"
  end

private
  def process_error(result)
    type = result["error"]["type"]
    case type
    when 1
      raise UsernameException
    when 3
      raise ResourceUnavailableException, result["error"]["description"]
    when 6
      raise ParameterUnavailableException, result["error"]["description"]
    when 101
      raise BridgeConnectException
    when 403
      raise SceneLockedException, result["error"]["description"]
    else
      raise "Unknown Error: #{result["error"]["description"]}"
    end
  end

  def get( path )
    @logger.debug "==> GET: #{path}"
    raise UsernameException unless @username
    request = Net::HTTP::Get.new( "/api/#{@username}/#{path}" )
    response = @http.request request
    result = JSON.parse( response.body )
    @logger.debug "<== #{response.code}"
    @logger.debug response.body
    if result.first.kind_of?(Hash) && result.first.has_key?("error")
      process_error result.first
    end
    result
  end

  def put( path, data={} )
    @logger.debug "==> PUT: #{path}"
    raise UsernameException unless @username
    @logger.debug data.to_json
    response = @http.put( "/api/#{@username}/#{path}", data.to_json )
    result = JSON.parse( response.body )
    @logger.debug "<== #{response.code}"
    @logger.debug response.body
    if result.first.kind_of?(Hash) && result.first.has_key?("error")
      process_error result.first
    end
    result
  end

  def post( path, data={} )
    @logger.debug "==> POST: #{path}"
    raise UsernameException unless @username
    @logger.debug data.to_json
    response = @http.post( "/api/#{@username}/#{path}", data.to_json )
    result = JSON.parse( response.body )
    @logger.debug "<== #{response.code}"
    @logger.debug response.body
    if result.first.kind_of?(Hash) && result.first.has_key?("error")
      process_error result.first
    end
    result
  end

  def delete( path )
    @logger.debug "==> DELETE: #{path}"
    raise UsernameException unless @username
    request = Net::HTTP::Delete.new( "/api/#{@username}/#{path}" )
    response = @http.request request
    result = JSON.parse( response.body )
    @logger.debug "<== #{response.code}"
    @logger.debug response.body
    if result.first.kind_of?(Hash) && result.first.has_key?("error")
      process_error result.first
    end
    result
  end

end


text:
.class public interface abstract Lcom/android/server/notification/NotificationSignalExtractor;
.super Ljava/lang/Object;
.source "NotificationSignalExtractor.java"

# virtual methods
.method public abstract initialize(Landroid/content/Context;)V
.end method

.method public abstract process(Lcom/android/server/notification/NotificationRecord;)Lcom/android/server/notification/RankingReconsideration;
.end method

.method public abstract setConfig(Lcom/android/server/notification/RankingConfig;)V
.end method


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Flora 32:662. 1849

#### Original name
null

### Remarks
null


text:
#include "sasl-internal.h"

#include "engine/engine-internal.h"

static const char ANONYMOUS[] = "ANONYMOUS";
static const char EXTERNAL[] = "EXTERNAL";
static const char PLAIN[] = "PLAIN";

bool pni_init_server(pn_transport_t* transport)
{
  return true;
}

bool pni_init_client(pn_transport_t* transport)
{
  return true;
}

void pni_sasl_impl_free(pn_transport_t *transport)
{
  free(transport->sasl->impl_context);
}

// Client handles ANONYMOUS or PLAIN mechanisms if offered
bool pni_process_mechanisms(pn_transport_t *transport, const char *mechs)
{
  // Check whether offered EXTERNAL, PLAIN or ANONYMOUS
  // Look for "EXTERNAL" in mechs
  const char *found = strstr(mechs, EXTERNAL);
  // Make sure that string is separated and terminated and allowed
  if (found && (found==mechs || found[-1]==' ') && (found[8]==0 || found[8]==' ') &&
      pni_included_mech(transport->sasl->included_mechanisms, pn_bytes(8, found))) {
    transport->sasl->selected_mechanism = pn_strdup(EXTERNAL);
    if (transport->sasl->username) {
      size_t size = strlen(transport->sasl->username);
      char *iresp = (char *) malloc(size);
      if (!iresp) return false;

      transport->sasl->impl_context = iresp;

      memmove(iresp, transport->sasl->username, size);
      transport->sasl->bytes_out.start = iresp;
      transport->sasl->bytes_out.size =  size;
    } else {
      static const char empty[] = "";
      transport->sasl->bytes_out.start = empty;
      transport->sasl->bytes_out.size =  0;
    }
    return true;
  }

  // Look for "PLAIN" in mechs
  found = strstr(mechs, PLAIN);
  // Make sure that string is separated and terminated, allowed
  // and we have a username and password and connection is encrypted or we allow insecure
  if (found && (found==mechs || found[-1]==' ') && (found[5]==0 || found[5]==' ') &&
      pni_included_mech(transport->sasl->included_mechanisms, pn_bytes(5, found)) &&
      (transport->sasl->external_ssf > 0 || transport->sasl->allow_insecure_mechs) &&
      transport->sasl->username && transport->sasl->password) {
    transport->sasl->selected_mechanism = pn_strdup(PLAIN);
    size_t usize = strlen(transport->sasl->username);
    size_t psize = strlen(transport->sasl->password);
    size_t size = 2*usize + psize + 2;
    char *iresp = (char *) malloc(size);
    if (!iresp) return false;

    transport->sasl->impl_context = iresp;

    memmove(iresp, transport->sasl->username, usize);
    iresp[usize] = 0;
    memmove(iresp + usize + 1, transport->sasl->username, usize);
    iresp[2*usize + 1] = 0;
    memmove(iresp + 2*usize + 2, transport->sasl->password, psize);
    transport->sasl->bytes_out.start = iresp;
    transport->sasl->bytes_out.size =  size;

    // Zero out password and dealloc
    free(memset(transport->sasl->password, 0, psize));
    transport->sasl->password = NULL;

    return true;
  }

  // Look for "ANONYMOUS" in mechs
  found = strstr(mechs, ANONYMOUS);
  // Make sure that string is separated and terminated and allowed
  if (found && (found==mechs || found[-1]==' ') && (found[9]==0 || found[9]==' ') &&
      pni_included_mech(transport->sasl->included_mechanisms, pn_bytes(9, found))) {
    transport->sasl->selected_mechanism = pn_strdup(ANONYMOUS);
    if (transport->sasl->username) {
      size_t size = strlen(transport->sasl->username);
      char *iresp = (char *) malloc(size);
      if (!iresp) return false;

      transport->sasl->impl_context = iresp;

      memmove(iresp, transport->sasl->username, size);
      transport->sasl->bytes_out.start = iresp;
      transport->sasl->bytes_out.size =  size;
    } else {
      static const char anon[] = "anonymous";
      transport->sasl->bytes_out.start = anon;
      transport->sasl->bytes_out.size =  sizeof anon-1;
    }
    return true;
  }
  return false;
}

// Server will offer only ANONYMOUS and EXTERNAL if appropriate
int pni_sasl_impl_list_mechs(pn_transport_t *transport, char **mechlist)
{
  // If we have an external authid then we can offer EXTERNAL
  if (transport->sasl && transport->sasl->external_auth) {
    *mechlist = pn_strdup("EXTERNAL ANONYMOUS");
    return 2;
  } else {
    *mechlist = pn_strdup("ANONYMOUS");
    return 1;
  }
}

void pni_process_init(pn_transport_t *transport, const char *mechanism, const pn_bytes_t *recv)
{
  // Check that mechanism is ANONYMOUS and it is allowed
  if (strcmp(mechanism, ANONYMOUS)==0 &&
      pni_included_mech(transport->sasl->included_mechanisms, pn_bytes(sizeof(ANONYMOUS)-1, ANONYMOUS))) {
    transport->sasl->username = "anonymous";
    transport->sasl->outcome = PN_SASL_OK;
    transport->authenticated = true;
    pni_sasl_set_desired_state(transport, SASL_POSTED_OUTCOME);
  } else if (strcmp(mechanism, EXTERNAL)==0 &&
      transport->sasl->external_auth &&
      pni_included_mech(transport->sasl->included_mechanisms, pn_bytes(sizeof(EXTERNAL)-1, EXTERNAL))) {
    transport->sasl->username = transport->sasl->external_auth;
    transport->sasl->outcome = PN_SASL_OK;
    transport->authenticated = true;
    pni_sasl_set_desired_state(transport, SASL_POSTED_OUTCOME);
  } else {
    transport->sasl->outcome = PN_SASL_AUTH;
    pni_sasl_set_desired_state(transport, SASL_POSTED_OUTCOME);
  }
}

/* The default implementation neither sends nor receives challenges or responses */
void pni_process_challenge(pn_transport_t *transport, const pn_bytes_t *recv)
{
}

void pni_process_response(pn_transport_t *transport, const pn_bytes_t *recv)
{
}

bool pni_sasl_impl_can_encrypt(pn_transport_t *transport)
{
  return false;
}

ssize_t pni_sasl_impl_max_encrypt_size(pn_transport_t *transport)
{
  return 0;
}

ssize_t pni_sasl_impl_encode(pn_transport_t *transport, pn_bytes_t in, pn_bytes_t *out)
{
  return 0;
}

ssize_t pni_sasl_impl_decode(pn_transport_t *transport, pn_bytes_t in, pn_bytes_t *out)
{
  return 0;
}

bool pn_sasl_extended(void)
{
  return false;
}


text:
package org.apache.geode.internal.admin.remote;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.logging.log4j.Logger;

import org.apache.geode.DataSerializer;
import org.apache.geode.cache.ExpirationAction;
import org.apache.geode.cache.Region;
import org.apache.geode.distributed.internal.ClusterDistributionManager;
import org.apache.geode.internal.logging.LogService;

/**
 * A message that is sent to a particular distribution manager to let it know that the sender is an
 * administation console that just connected.
 */
public class DestroyEntryMessage extends RegionAdminMessage {

  private static final Logger logger = LogService.getLogger();

  private Object key;
  private ExpirationAction action;

  public static DestroyEntryMessage create(Object key, ExpirationAction action) {
    DestroyEntryMessage m = new DestroyEntryMessage();
    m.action = action;
    m.key = key;
    return m;
  }

  @Override
  public void process(ClusterDistributionManager dm) {
    Region r = getRegion(dm.getSystem());
    if (r != null) {
      try {
        if (action == ExpirationAction.LOCAL_DESTROY) {
          r.localDestroy(key);
        } else if (action == ExpirationAction.DESTROY) {
          r.destroy(key);
        } else if (action == ExpirationAction.INVALIDATE) {
          r.invalidate(key);
        } else if (action == ExpirationAction.LOCAL_INVALIDATE) {
          r.localInvalidate(key);
        }
      } catch (Exception e) {
        logger.warn("Failed attempt to destroy or invalidate entry {} {} from console at {}",
            new Object[] {r.getFullPath(), key, this.getSender()});
      }
    }
  }

  public int getDSFID() {
    return DESTROY_ENTRY_MESSAGE;
  }

  @Override
  public void toData(DataOutput out) throws IOException {
    super.toData(out);
    DataSerializer.writeObject(this.action, out);
    DataSerializer.writeObject(this.key, out);
  }

  @Override
  public void fromData(DataInput in) throws IOException, ClassNotFoundException {
    super.fromData(in);
    this.action = (ExpirationAction) DataSerializer.readObject(in);
    this.key = DataSerializer.readObject(in);
  }

  @Override
  public String toString() {
    return String.format("DestroyEntryMessage from %s",
        this.getSender());
  }
}


text:
#ifndef CURVE25519_REF10_H
#define CURVE25519_REF10_H

#include <stddef.h>
#include <stdint.h>

#define fe crypto_core_curve25519_ref10_fe
typedef int32_t fe[10];

/*
 fe means field element.
 Here the field is \Z/(2^255-19).
 An element t, entries t[0]...t[9], represents the integer
 t[0]+2^26 t[1]+2^51 t[2]+2^77 t[3]+2^102 t[4]+...+2^230 t[9].
 Bounds on each t[i] vary depending on context.
 */

#define fe_frombytes crypto_core_curve25519_ref10_fe_frombytes
#define fe_tobytes crypto_core_curve25519_ref10_fe_tobytes
#define fe_copy crypto_core_curve25519_ref10_fe_copy
#define fe_isnonzero crypto_core_curve25519_ref10_fe_isnonzero
#define fe_isnegative crypto_core_curve25519_ref10_fe_isnegative
#define fe_0 crypto_core_curve25519_ref10_fe_0
#define fe_1 crypto_core_curve25519_ref10_fe_1
#define fe_cmov crypto_core_curve25519_ref10_fe_cmov
#define fe_add crypto_core_curve25519_ref10_fe_add
#define fe_sub crypto_core_curve25519_ref10_fe_sub
#define fe_neg crypto_core_curve25519_ref10_fe_neg
#define fe_mul crypto_core_curve25519_ref10_fe_mul
#define fe_sq crypto_core_curve25519_ref10_fe_sq
#define fe_sq2 crypto_core_curve25519_ref10_fe_sq2
#define fe_invert crypto_core_curve25519_ref10_fe_invert
#define fe_pow22523 crypto_core_curve25519_ref10_fe_pow22523

extern void fe_frombytes(fe,const unsigned char *);
extern void fe_tobytes(unsigned char *,const fe);

extern void fe_copy(fe,const fe);
extern int fe_isnonzero(const fe);
extern int fe_isnegative(const fe);
extern void fe_0(fe);
extern void fe_1(fe);
extern void fe_cmov(fe,const fe,unsigned int);
extern void fe_add(fe,const fe,const fe);
extern void fe_sub(fe,const fe,const fe);
extern void fe_neg(fe,const fe);
extern void fe_mul(fe,const fe,const fe);
extern void fe_sq(fe,const fe);
extern void fe_sq2(fe,const fe);
extern void fe_invert(fe,const fe);
extern void fe_pow22523(fe,const fe);

/*
 ge means group element.
 *
 Here the group is the set of pairs (x,y) of field elements (see fe.h)
 satisfying -x^2 + y^2 = 1 + d x^2y^2
 where d = -121665/121666.
 *
 Representations:
 ge_p2 (projective): (X:Y:Z) satisfying x=X/Z, y=Y/Z
 ge_p3 (extended): (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT
 ge_p1p1 (completed): ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T
 ge_precomp (Duif): (y+x,y-x,2dxy)
 */

#define ge_p2 crypto_core_curve25519_ref10_ge_p2
typedef struct {
    fe X;
    fe Y;
    fe Z;
} ge_p2;

#define ge_p3 crypto_core_curve25519_ref10_ge_p3
typedef struct {
    fe X;
    fe Y;
    fe Z;
    fe T;
} ge_p3;

#define ge_p1p1 crypto_core_curve25519_ref10_ge_p1p1
typedef struct {
    fe X;
    fe Y;
    fe Z;
    fe T;
} ge_p1p1;

#define ge_precomp crypto_core_curve25519_ref10_ge_precomp
typedef struct {
    fe yplusx;
    fe yminusx;
    fe xy2d;
} ge_precomp;

#define ge_cached crypto_core_curve25519_ref10_ge_cached
typedef struct {
    fe YplusX;
    fe YminusX;
    fe Z;
    fe T2d;
} ge_cached;

#define ge_frombytes_negate_vartime crypto_core_curve25519_ref10_ge_frombytes_negate_vartime
#define ge_tobytes crypto_core_curve25519_ref10_ge_tobytes
#define ge_p3_tobytes crypto_core_curve25519_ref10_ge_p3_tobytes

#define ge_p2_0 crypto_core_curve25519_ref10_ge_p2_0
#define ge_p3_0 crypto_core_curve25519_ref10_ge_p3_0
#define ge_precomp_0 crypto_core_curve25519_ref10_ge_precomp_0
#define ge_p3_to_p2 crypto_core_curve25519_ref10_ge_p3_to_p2
#define ge_p3_to_cached crypto_core_curve25519_ref10_ge_p3_to_cached
#define ge_p1p1_to_p2 crypto_core_curve25519_ref10_ge_p1p1_to_p2
#define ge_p1p1_to_p3 crypto_core_curve25519_ref10_ge_p1p1_to_p3
#define ge_p2_dbl crypto_core_curve25519_ref10_ge_p2_dbl
#define ge_p3_dbl crypto_core_curve25519_ref10_ge_p3_dbl

#define ge_madd crypto_core_curve25519_ref10_ge_madd
#define ge_msub crypto_core_curve25519_ref10_ge_msub
#define ge_add crypto_core_curve25519_ref10_ge_add
#define ge_sub crypto_core_curve25519_ref10_ge_sub
#define ge_scalarmult_base crypto_core_curve25519_ref10_ge_scalarmult_base
#define ge_double_scalarmult_vartime crypto_core_curve25519_ref10_ge_double_scalarmult_vartime
#define ge_scalarmult_vartime crypto_core_curve25519_ref10_ge_scalarmult_vartime

extern void ge_tobytes(unsigned char *,const ge_p2 *);
extern void ge_p3_tobytes(unsigned char *,const ge_p3 *);
extern int ge_frombytes_negate_vartime(ge_p3 *,const unsigned char *);

extern void ge_p2_0(ge_p2 *);
extern void ge_p3_0(ge_p3 *);
extern void ge_precomp_0(ge_precomp *);
extern void ge_p3_to_p2(ge_p2 *,const ge_p3 *);
extern void ge_p3_to_cached(ge_cached *,const ge_p3 *);
extern void ge_p1p1_to_p2(ge_p2 *,const ge_p1p1 *);
extern void ge_p1p1_to_p3(ge_p3 *,const ge_p1p1 *);
extern void ge_p2_dbl(ge_p1p1 *,const ge_p2 *);
extern void ge_p3_dbl(ge_p1p1 *,const ge_p3 *);

extern void ge_madd(ge_p1p1 *,const ge_p3 *,const ge_precomp *);
extern void ge_msub(ge_p1p1 *,const ge_p3 *,const ge_precomp *);
extern void ge_add(ge_p1p1 *,const ge_p3 *,const ge_cached *);
extern void ge_sub(ge_p1p1 *,const ge_p3 *,const ge_cached *);
extern void ge_scalarmult_base(ge_p3 *,const unsigned char *);
extern void ge_double_scalarmult_vartime(ge_p2 *,const unsigned char *,const ge_p3 *,const unsigned char *);
extern void ge_scalarmult_vartime(ge_p3 *,const unsigned char *,const ge_p3 *);

/*
 The set of scalars is \Z/l
 where l = 2^252 + 27742317777372353535851937790883648493.
 */

#define sc_reduce crypto_core_curve25519_ref10_sc_reduce
#define sc_muladd crypto_core_curve25519_ref10_sc_muladd

extern void sc_reduce(unsigned char *);
extern void sc_muladd(unsigned char *,const unsigned char *,const unsigned char *,const unsigned char *);

#endif


text:
    This example shows how to render a Kml layer with Googlemap control for Asp.Net MVC.

    Change the configuration above to see how it affects the map.


text:
title: "Embed a Tabbed Dashboard into an existing page"
id: "embed_tabbed"
index: 7
--

Create the HTML markup for rendering the dashboard.
~~~
<!doctype html>

    <title>RazorFlow Embedded Example</title>
    <link rel="stylesheet" href="razorflow_js/css/razorflow.min.css"/>

Embedded Dashboard

~~~

### To embed a Tabbed Dashboard into a web page follow these steps:

1. Create a `TabbedDashboard` object.
2. Use `setTabbedDashboardTitle` to set the tabbed dashboard title.
3. Use `addDashboardTab` to add individual dashboards to the tabbed dashboard object.
4. Use `active` on a dashboard to set the active dashboard.
5. You can also use the `title` option to override the dashboard title.
5. Use the `embedTo` method to render the tabbed dashboard as embedded.

Here's an example javascript snippet of embedding a tabbed dashboard into a webpage.
~~~
var tdb = new TabbedDashboard();
tdb.setTabbedDashboardTitle("Tabbed Dashboard");

// Dashboard 1
var db1 = new Dashboard();
db1.setDashboardTitle('Table In Razorfow');

var c1 = new TableComponent();
c1.setDimensions(12, 6);
c1.setCaption('List of items in stock');
c1.addColumn('ProductID', 'Product ID');
c1.addColumn('ProductName', 'Product Name');
c1.addColumn('CategoryName', 'Category');
c1.addColumn('UnitPrice', 'Price', {
    dataType: "number",
    numberPrefix: "$",
    numberForceDecimals: true,
    numberDecimalPoints: 2
});
c1.addColumn('UnitsInStock', 'Stock', {
    dataType: "number"
});
c1.addColumn('Discontinued', 'Discontinued?');
c1.lock();
db1.addComponent(c1);

$.ajax({
    url: '/static/fixtures/products.json',
    type: 'GET',
    success: function(products) {
        if (_.isString(products)) {
            products = JSON.parse(products);
        }
        for(var i=-1; ++i<products.length;) {
            c1.addRow(products[i], {});
        }
        c1.unlock();
    }
});

// Dashboard 2
var db2 = new Dashboard('db2');

db2.setDashboardTitle('KPI Types Supported in RazorFlow');

var c2 = new KPIComponent();
c2.setDimensions(4, 2);
c2.setCaption('Average Monthly Sales');
c2.setValue(513.22, {
    numberPrefix: '$'
});
db2.addComponent(c2);

var c3 = new KPIComponent();
c3.setDimensions(4, 2);
c3.setCaption('Average Monthly Units');
c3.setValue(22);
c3.setSparkValues(['Jan', "Feb", 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
                    [12.31, 10.34, 10.26, 9, 8.21, 13.41, 14.43, 23.31, 13.41, 11.4, 28.34, 29.21]);
db2.addComponent(c3);

tdb.addDashboardTab(db1);
tdb.addDashboardTab(db2);

tdb.embedTo('dashboard_target');
~~~


text:
Red October
===========

Red October is a software-based
[two-man rule](https://en.wikipedia.org/wiki/Two-man_rule) style
encryption and decryption server.

## Building

[![Build Status](https://travis-ci.org/cloudflare/redoctober.png?branch=master)](https://travis-ci.org/cloudflare/redoctober) [![Build Status](https://drone.io/github.com/cloudflare/redoctober/status.png)](https://drone.io/github.com/cloudflare/redoctober/latest)

This project requires [Go 1.1](http://golang.org/doc/install#download)
or later to compile. Verify your go version by running `go version`:

    $ go version
    go version go1.1

As with any Go program you do need to set the
[GOPATH enviroment variable](http://golang.org/doc/code.html#GOPATH)
accordingly. With Go set up you can download and compile sources:

    $ go get github.com/cloudflare/redoctober

And run the tests:

    $ go test github.com/cloudflare/redoctober...

## Running

Red October is a TLS server. It requires a local file to hold the key
vault an internet address and a certificate keypair.

First you need to acquire a TLS certificate. The simplest (and least
secure) way is to skip the
[Certificate Authority](https://en.wikipedia.org/wiki/Certificate_authority#Issuing_a_certificate)
verification and generate a self-signed TLS certificate. Read this
[detailed guide](http://www.akadia.com/services/ssh_test_certificate.html)
or, alternatively, follow this unsecure commands:

    $ mkdir cert
    $ chmod 700 cert
    ## Generate private key with password "password"
    $ openssl genrsa -aes128 -passout pass:password -out cert/server.pem 2048
    ## Remove password from private key
    $ openssl rsa -passin pass:password -in cert/server.pem -out cert/server.pem
    ## Generate CSR (make sure the common name CN field matches your server
    ## address. It's set to "localhost" here.)
    $ openssl req -new -key cert/server.pem -out cert/server.csr -subj '/C=US/ST=California/L=Everywhere/CN=localhost'
    ## Sign the CSR and create certificate
    $ openssl x509 -req -days 365 -in cert/server.csr -signkey cert/server.pem -out cert/server.crt
    ## Clean up
    $ rm cert/server.csr
    $ chmod 600 cert/*

You're ready to run the server:

    $ ./bin/redoctober -addr=localhost:8080 \
                       -vaultpath=diskrecord.json \
                       -cert=certs/server.crt \
                       -key=certs/server.pem \
                       -static=$GOPATH/src/github.com/cloudflare/redoctober/index.html

## Quick start: example webapp

At this point Red October should be serving an example webapp. Access it using your browser:

  - [`https://localhost:8080/index`](https://localhost:8080/index)

## Using the API

The server exposes several JSON API endpoints. JSON of the prescribed
format is POSTed and JSON is returned.

 - `/create`: Create the first admin account.
 - `/delegate`: Delegate a password to Red October
 - `/modify`: Modify permissions
 - `/encrypt`: Encrypt
 - `/decrypt`: Decrypt
 - `/summary`: Display summary of the delegates
 - `/password`: Change password
 - `/index`: Optionally, the server can host a static HTML file.

### Create

Create is the necessary first call to a new vault. It creates an
admin account.

Example query:

    $ curl --cacert cert/server.crt https://localhost:8080/create \
            -d '{"Name":"Alice","Password":"Lewis"}'
    {"Status":"ok"}

### Delegate

Delegate allows a user to delegate their decryption password to the
server for a fixed period of time and for a fixed number of
decryptions.  If the user's account is not created, it creates it.
Any new delegation overrides the previous delegation.

Example query:

    $ curl --cacert cert/server.crt https://localhost:8080/delegate \
           -d '{"Name":"Bill","Password":"Lizard","Time":"2h34m","Uses":3}'
    {"Status":"ok"}
    $ curl --cacert cert/server.crt https://localhost:8080/delegate \
           -d '{"Name":"Cat","Password":"Cheshire","Time":"2h34m","Uses":3}'
    {"Status":"ok"}
    $ curl --cacert cert/server.crt https://localhost:8080/delegate \
           -d '{"Name":"Dodo","Password":"Dodgson","Time":"2h34m","Uses":3}'
    {"Status":"ok"}

### Summary

Summary provides a list of the users with keys on the system, and a
list of users who have currently delegated their key to the
server. Only Admins are allowed to call summary.

Example query:

    $ curl --cacert cert/server.crt https://localhost:8080/summary  \
            -d '{"Name":"Alice","Password":"Lewis"}'
    {"Status":"ok",
     "Live":{
      "Bill":{"Admin":false,
              "Type":"RSA",
              "Expiry":"2013-11-26T08:42:29.65501032-08:00",
              "Uses":3},
      "Cat":{"Admin":false,
             "Type":"RSA",
             "Expiry":"2013-11-26T08:42:42.016311595-08:00",
             "Uses":3},
      "Dodo":{"Admin":false,
              "Type":"RSA",
              "Expiry":"2013-11-26T08:43:06.651429104-08:00",
              "Uses":3}
     },
     "All":{
      "Alice":{"Admin":true, "Type":"RSA"},
      "Bill":{"Admin":false, "Type":"RSA"},
      "Cat":{"Admin":false, "Type":"RSA"},
      "Dodo":{"Admin":false, "Type":"RSA"}
     }
    }

### Encrypt

Encrypt allows an admin to encrypt a piece of data. A list of valid
users is provided and a minimum number of delegated users required to
decrypt. The returned data can be decrypted as long as "Minimum"
number users from the set of "Owners" have delegated their keys to the
server.

Example query:

    $ echo "Why is a raven like a writing desk?"|python -c "print raw_input().encode('base64')"
    V2h5IGlzIGEgcmF2ZW4gbGlrZSBhIHdyaXRpbmcgZGVzaz8=

    $ curl --cacert cert/server.crt https://localhost:8080/encrypt  \
            -d '{"Name":"Alice","Password":"Lewis","Minimum":2, "Owners":["Alice","Bill","Cat","Dodo"],"Data":"V2h5IGlzIGEgcmF2ZW4gbGlrZSBhIHdyaXRpbmcgZGVzaz8="}'
    {"Status":"ok","Response":"eyJWZXJzaW9uIj...NSSllzPSJ9"}

The data expansion is not tied to the size of the input.

### Decrypt

Decrypt allows an admin to decrypt a piece of data. As long as
"Minimum" number users from the set of "Owners" have delegated their
keys to the server, the clear data will be returned.

Example query:

    $ curl --cacert cert/server.crt https://localhost:8080/decrypt  \
            -d {"Name":"Alice","Password":"Lewis","Data":"eyJWZXJzaW9uIj...NSSllzPSJ9"}
    {"Status":"ok","Response":"V2h5IGlzIGEgcmF2ZW4gbGlrZSBhIHdyaXRpbmcgZGVzaz8="}

If there aren't enough keys delegated you'll see:

    {"Status":"Need more delegated keys"}

### Password

Password allows a user to change their password.  This password change
does not require the previously encrypted files to be re-encrypted.

Example Input JSON format:

    $ curl --cacert cert/server.crt https://localhost:8080/password \
           -d '{"Name":"Bill","Password":"Lizard", "NewPassword": "theLizard"}'
    {"Status":"ok"}

### Modify

Modify allows an admin user to change information about a given user.
There are 3 commands:

 - `revoke`: revokes the admin status of a user
 - `admin`: grants admin status to a user
 - `delete`: removes the account of a user

Example input JSON format:

    $ curl --cacert cert/server.crt https://localhost:8080/modify \
           -d '{"Name":"Alice","Password":"Lewis","ToModify":"Bill","Command":"admin"}'
    {"Status":"ok"}

### Web interface

You can build a web interface to manage the Red October service using
the `-static` flag and providing a path to the HTML file you want to
serve.

The index.html file in this repo provides a basic example for using
all of the service's features, including encrypting and decrypting
data. Data sent to the server *needs to be base64 encoded*. The
example uses JavaScript's `btoa` and `atob` functions for string
conversion. For dealing with files directly, using the
[HTML5 File API](https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsDataURL)
would be a good option.


text:
package io.permazen.cli.cmd;

import com.google.common.base.Preconditions;

import io.permazen.SessionMode;
import io.permazen.cli.CliSession;
import io.permazen.cli.ParamParser;
import io.permazen.parse.FieldTypeParser;
import io.permazen.parse.ObjIdParser;
import io.permazen.parse.ObjTypeParser;
import io.permazen.parse.ParseSession;
import io.permazen.parse.Parser;
import io.permazen.parse.expr.ExprParser;
import io.permazen.parse.expr.Node;
import io.permazen.util.ParseContext;

import java.util.EnumSet;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Support superclass for CLI {@link Command} implementations.
 *
 * @see Command
 */
public abstract class AbstractCommand implements Command {

    protected final Logger log = LoggerFactory.getLogger(this.getClass());
    protected final String name;
    protected final ParamParser paramParser;

// Constructors

    /**
     * Constructor.
     *
     * @param spec {@link ParamParser} spec string, possibly containing custom type names (see {@link #getParser getParser()})
     */
    protected AbstractCommand(String spec) {
        Preconditions.checkArgument(spec != null, "null spec");
        final Matcher matcher = Pattern.compile("([^\\s]+)(\\s+(.*))?").matcher(spec);
        if (!matcher.matches())
            throw new IllegalArgumentException("invalid command specification `" + spec + "'");
        this.name = matcher.group(1);
        final String paramSpec = matcher.group(3);
        this.paramParser = new ParamParser(paramSpec != null ? paramSpec : "") {
            @Override
            protected Parser<?> getParser(String typeName) {
                try {
                    return super.getParser(typeName);
                } catch (IllegalArgumentException e) {
                    return AbstractCommand.this.getParser(typeName);
                }
            }
        };
    }

// Command stuff

    @Override
    public String getName() {
        return this.name;
    }

    /**
     * {@inheritDoc}
     *
     *

     * The implementation in {@link AbstractCommand} delegates to {@link ParamParser#getUsage ParamParser.getUsage()}.
     *
     * @return command usage string
     */
    @Override
    public String getUsage() {
        return this.paramParser.getUsage(this.name);
    }

    /**
     * Get summarized help (typically a single line).
     *
     * @return one line command summary
     */
    @Override
    public abstract String getHelpSummary();

    /**
     * {@inheritDoc}
     *
     *

     * The implementation in {@link AbstractCommand} delegates to {@link #getHelpSummary getHelpSummary()}.
     *
     * @return detailed command description
     */
    @Override
    public String getHelpDetail() {
        return this.getHelpSummary();
    }

    /**
     * {@inheritDoc}
     *
     *

     * The implementation in {@link AbstractCommand} returns an {@link EnumSet} containing
     * {@link SessionMode#CORE_API} and {@link SessionMode#PERMAZEN}.
     *
     * @return set of supported {@link SessionMode}s
     */
    @Override
    public EnumSet<SessionMode> getSessionModes() {
        return EnumSet.<SessionMode>of(SessionMode.CORE_API, SessionMode.PERMAZEN);
    }

    /**
     * {@inheritDoc}
     *
     *

     * The implementation in {@link AbstractCommand} parses the parameters and delegates to {@link #getAction getAction()}
     * with the result.
     *
     * @param session CLI session
     * @param ctx input to parse
     * @param complete false if parse is "for real", true if only for tab completion calculation
     * @return action to perform for the parsed command
     * @throws io.permazen.parse.ParseException if parse fails, or if {@code complete} is true and there are valid completions
     * @throws io.permazen.parse.ParseException if parameters are invalid
     * @throws IllegalArgumentException if {@code session} is not a {@link CliSession}
     */
    @Override
    public CliSession.Action parse(ParseSession session, ParseContext ctx, boolean complete) {
        Preconditions.checkArgument(session instanceof CliSession, "session is not a CliSession");
        return this.getAction((CliSession)session, ctx, complete, this.paramParser.parse(session, ctx, complete));
    }

    /**
     * Process command line parameters and return action.
     *
     * @param session CLI session
     * @param ctx input to parse
     * @param complete false if parse is "for real", true if only for tab completion calculation
     * @param params parsed parameters indexed by name
     * @return action to perform for the parsed command
     * @throws io.permazen.parse.ParseException if parse fails, or if {@code complete} is true and there are valid completions
     * @throws io.permazen.parse.ParseException if parameters are invalid
     */
    protected abstract CliSession.Action getAction(CliSession session,
      ParseContext ctx, boolean complete, Map<String, Object> params);

    /**
     * Convert parameter spec type name into a {@link Parser}. Used for custom type names not supported by {@link ParamParser}.
     *
     *

     * The implementation in {@link AbstractCommand} supports all {@link io.permazen.core.FieldType}s registered with the
     * database, plus:
     *

     *
{@code type} for an object type name (returns {@link Integer})

     *
{@code objid} for an object ID of the form {@code 64e8f29755302fe1} (returns {@link io.permazen.core.ObjId})

     *
{@code expr} for an arbitrary Java expression

     *

     *
     * @param typeName parameter type name
     * @return parser for parameters of the specified type
     */
    protected Parser<?> getParser(String typeName) {
        Preconditions.checkArgument(typeName != null, "null typeName");
        if (typeName.equals("type"))
            return new ObjTypeParser();
        if (typeName.equals("objid"))
            return new ObjIdParser();
        if (typeName.equals("expr"))
            return new ExprParser();
        return FieldTypeParser.getFieldTypeParser(typeName);
    }

    /**
     * Evaluate an {@code "expr"} parameter, expecting the specified type.
     *
     * @param session CLI session
     * @param node parsed parameter
     * @param name parameter name
     * @param type expected type
     * @param <T> expected result type
     * @return parameter value
     */
    protected <T> T getExprParam(CliSession session, Node node, String name, Class<T> type) {
        Preconditions.checkArgument(type != null, "null type");
        return this.getExprParam(session, node, name, obj -> {
            if (!type.isInstance(obj)) {
                throw new IllegalArgumentException("must be of type " + type.getName()
                  + " (found " + (obj != null ? obj.getClass().getName() : "null") + ")");
            }
            return type.cast(obj);
        });
    }

    /**
     * Evaluate an {@code "expr"} parameter, expecting the parameter to pass the given test.
     *
     * @param session CLI session
     * @param node parsed parameter
     * @param name parameter name
     * @param validator validates value, or throws {@link IllegalArgumentException} if value is invalid
     * @param <T> expected result type
     * @return parameter value
     */
    protected <T> T getExprParam(CliSession session, Node node, String name, Function<Object, T> validator) {
        Preconditions.checkArgument(session != null, "null session");
        Preconditions.checkArgument(node != null, "null node");
        Preconditions.checkArgument(name != null, "null name");
        Preconditions.checkArgument(validator != null, "null validator");
        final Object value = node.evaluate(session).get(session);
        try {
            return validator.apply(value);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("invalid `" + name + "' parameter: " + e.getMessage());
        }
    }
}


text:
use strict;
use warnings 'all';
use YAML qw();
use lib '/sysbuilder/lib';
use SysBuilder::Utils qw( optional_shell run_local notify_boothost read_file);
my $cfg = YAML::LoadFile('/sysbuilder/etc/config.yaml');

$|++;

print "INFO: Killing Processes.\n";
system("killall -q minilogd");
system("killall -q cupsd");
system("killall -q acpid");
system(q(ps -ef|awk '/home/ && !/awk/{print $2}'|xargs kill 2>/dev/null));

print "INFO: Unmounting file systems\n";
umount();

print "INFO: Notifying boothost we're done\n";

# notify boothost we're done (unless we're running under vm)
my $status_msg = read_file('/tmp/wipe_status');

notify_boothost( nextboot => 'done', status => $status_msg, broadcast => 'no' )
    unless exists $cfg->{vm_user};

open my $ok_file, ">", "/tmp/sysbuilder-installer-ok";
close $ok_file;

print "\n\n\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
print " STATUS MESSAGES ARE BELOW AND REPORTED TO THE  SERVER \n";
print " YOU MUST MANUALLY REBOOT \n\n";
print " $status_msg \n\n";
print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n\n\n";

sleep 1;

print "Downing network interfaces\n\n";
run_local( "/sbin/ifconfig eth0 down" );
run_local( "/sbin/ifconfig eth1 down" );

optional_shell(1209600);

exit 0;

sub umount {
    my @mount        = `mount`;
    my @mount_points = grep {m{\A/mnt}} map { (split)[2] } @mount;
    my $printed_ps   = 0;
    for my $m_point ( sort { length($b) <=> length($a) } @mount_points ) {
        my $err = run_local("umount $m_point");
        if ( $err && !$printed_ps ) {
            print "ERROR: umount $m_point failed.\n";
            chomp( my @ps = `ps -ef` );
            for my $line (@ps) {
                my @fields = split ' ', $line;
                next if $fields[-1] =~ /\A\[.*\]\z/;   # ignore kernel threads
                print "  $line\n";
            }
            $printed_ps = 1;
        }
    }
}


text:
package com.baidu.oped.apm.profiler.modifier.db.mysql;

import java.security.ProtectionDomain;

import com.baidu.oped.apm.bootstrap.Agent;
import com.baidu.oped.apm.bootstrap.instrument.ByteCodeInstrumentor;
import com.baidu.oped.apm.bootstrap.instrument.InstrumentClass;
import com.baidu.oped.apm.bootstrap.instrument.InstrumentException;
import com.baidu.oped.apm.bootstrap.interceptor.Interceptor;
import com.baidu.oped.apm.bootstrap.interceptor.tracevalue.DatabaseInfoTraceValue;
import com.baidu.oped.apm.profiler.modifier.AbstractModifier;
import com.baidu.oped.apm.profiler.modifier.db.interceptor.StatementExecuteQueryInterceptor;
import com.baidu.oped.apm.profiler.modifier.db.interceptor.StatementExecuteUpdateInterceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author emeroad
 */
public class MySQLStatementModifier extends AbstractModifier {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public MySQLStatementModifier(ByteCodeInstrumentor byteCodeInstrumentor, Agent agent) {
        super(byteCodeInstrumentor, agent);
    }

    public String getTargetClass() {
        return "com/mysql/jdbc/StatementImpl";
    }

    public byte[] modify(ClassLoader classLoader, String javassistClassName, ProtectionDomain protectedDomain, byte[] classFileBuffer) {
        if (logger.isInfoEnabled()) {
            logger.info("Modifing. {}", javassistClassName);
        }

        try {
            InstrumentClass statementClass = byteCodeInstrumentor.getClass(classLoader, javassistClassName, classFileBuffer);

            Interceptor interceptor = new StatementExecuteQueryInterceptor();
            statementClass.addScopeInterceptor("executeQuery", new String[]{"java.lang.String"}, interceptor, MYSQLScope.SCOPE_NAME);

            // FIXME
            Interceptor executeUpdateInterceptor1 = new StatementExecuteUpdateInterceptor();
            statementClass.addScopeInterceptor("executeUpdate", new String[]{"java.lang.String"}, executeUpdateInterceptor1, MYSQLScope.SCOPE_NAME);

            Interceptor executeUpdateInterceptor2 = new StatementExecuteUpdateInterceptor();
            statementClass.addScopeInterceptor("executeUpdate", new String[]{"java.lang.String", "int"}, executeUpdateInterceptor2, MYSQLScope.SCOPE_NAME);

            Interceptor executeUpdateInterceptor3 = new StatementExecuteUpdateInterceptor();
            statementClass.addScopeInterceptor("execute", new String[]{"java.lang.String"}, executeUpdateInterceptor3, MYSQLScope.SCOPE_NAME);

            Interceptor executeUpdateInterceptor4 = new StatementExecuteUpdateInterceptor();
            statementClass.addScopeInterceptor("execute", new String[]{"java.lang.String", "int"}, executeUpdateInterceptor4, MYSQLScope.SCOPE_NAME);

            statementClass.addTraceValue(DatabaseInfoTraceValue.class);
            return statementClass.toBytecode();
        } catch (InstrumentException e) {
            if (logger.isWarnEnabled()) {
                logger.warn("{} modify fail. Cause:{}", this.getClass().getSimpleName(), e.getMessage(), e);
            }
            return null;
        }
    }

}


text:
package ch.bfh.ti.ictm.iam.stiam.aa.util.saml;

import ch.bfh.ti.ictm.iam.stiam.aa.test.TestConfiguration;
import java.io.IOException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableEntryException;
import java.security.cert.CertificateException;
import javax.xml.transform.TransformerException;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.opensaml.xml.ConfigurationException;
import org.opensaml.xml.io.MarshallingException;
import org.opensaml.xml.parse.XMLParserException;
import org.opensaml.xml.security.SecurityException;
import org.opensaml.xml.signature.SignatureException;

/**
 * Testsuite for the StatusResponseBuilder
 *
 * @author Pascal Mainini
 * @author Marc Kunz
 */
public class StatusResponseBuilderTest {

    /**
     * Basic test of the StatusResponseBuilder
     */
    @Test
    public void testStatusResponseBuilder() {
        final TestConfiguration testConfig = new TestConfiguration();

        try {
            final ResponseBuilder builder = new ResponseBuilder(
                    testConfig.getProperty("StatusResponseBuilderTest.Destination"),
                    testConfig.getProperty("StatusResponseBuilderTest.InResponseTo"),
                    testConfig.getPropertyList("StatusResponseBuilderTest.StatusCodes"));
            final String response = builder.build();
            assertNotNull(response);
            assertThat(response.length(), is(Integer.valueOf(testConfig.getProperty("StatusResponseBuilderTest.ExpectedLength"))));
        }
        catch (ConfigurationException ex) {
            fail("Configuration problem: " + ex.toString());
        }
        catch (NoSuchAlgorithmException ex) {
            fail("Error finding algorithm: " + ex.toString());
        }
        catch (IOException ex) {
            fail("IO problem: " + ex.toString());
        }
        catch (KeyStoreException ex) {
            fail("Error while intializing keystore: " + ex.toString());
        }
        catch (CertificateException ex) {
            fail("Error with the certificate: " + ex.toString());
        }
        catch (UnrecoverableEntryException ex) {
            fail("Unrecoverable entry: " + ex.toString());
        }
        catch (SecurityException ex) {
            fail("Security problem: " + ex.toString());
        }
        catch (MarshallingException ex) {
            fail("Issue while marshalling: " + ex.toString());
        }
        catch (SignatureException ex) {
            fail("Issue while signing: " + ex.toString());
        }
        catch (XMLParserException ex) {
            fail("Problem with the XML parser: " + ex.toString());
        }
        catch (TransformerException ex) {
            fail("Problem with the XML transformer: " + ex.toString());
        }
    }
}