text:
//
//  SPKeychain.m
//  sequel-pro
//
//  Created by Lorenz Textor (lorenz@textor.ch) on December 25, 2002.
//  Copyright (c) 2002-2003 Lorenz Textor. All rights reserved.
//  Copyright (c) 2012 Sequel Pro Team. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person
//  obtaining a copy of this software and associated documentation
//  files (the "Software"), to deal in the Software without
//  restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following
//  conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//  OTHER DEALINGS IN THE SOFTWARE.
//
//  More info at <https://github.com/sequelpro/sequelpro>

#import "SPKeychain.h"
#import "SPAlertSheets.h"
#import "SPOSInfo.h"

#import <Security/Security.h>
#import <CoreFoundation/CoreFoundation.h>

@implementation SPKeychain

- (id)init
{
	if (!(self = [super init])) {
		return nil;
	}

	NSString *cleartext = [NSProcessInfo processInfo].environment[@"LIBMYSQL_ENABLE_CLEARTEXT_PLUGIN"];
	if (cleartext != nil) {
		NSLog(@"LIBMYSQL_ENABLE_CLEARTEXT_PLUGIN is set. Disabling keychain access. See Issue #2437");

		[self release];
		return nil;
	}

	return self;
}

/**
 * Add the supplied password to the user's Keychain using the supplied name and account.
 */
- (void)addPassword:(NSString *)password forName:(NSString *)name account:(NSString *)account
{
	[self addPassword:password forName:name account:account withLabel:name];
}

/**
 * Add the supplied password to the user's Keychain using the supplied name, account, and label.
 */
- (void)addPassword:(NSString *)password forName:(NSString *)name account:(NSString *)account withLabel:(NSString *)label;
{
	OSStatus status;
	SecTrustedApplicationRef sequelProRef, sequelProHelperRef;
	SecAccessRef passwordAccessRef = NULL;
	SecKeychainAttribute attributes[4];
	SecKeychainAttributeList attList;

	// If a nil password was supplied, do nothing.
	if (!password) return;

	// Check supplied variables and replaces nils with empty strings
	if (!name) name = @"";
	if (!account) account = @"";
	if (!label) label = @"";

	// Check if password already exists before adding
	if (![self passwordExistsForName:name account:account]) {

		// Create a trusted access list with two items - ourselves and the SSH pass app
		NSString *helperPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SequelProTunnelAssistant"];

		if ((SecTrustedApplicationCreateFromPath(NULL, &sequelProRef) == noErr) &&
			(SecTrustedApplicationCreateFromPath([helperPath UTF8String], &sequelProHelperRef) == noErr)) {

			NSArray *trustedApps = [NSArray arrayWithObjects:(id)sequelProRef, (id)sequelProHelperRef, nil];

			status = SecAccessCreate((CFStringRef)name, (CFArrayRef)trustedApps, &passwordAccessRef);

			if (status != noErr) {
				NSLog(@"Error (%i) while trying to create access list for name: %@ account: %@", (int)status, name, account);
				passwordAccessRef = NULL;
			}
		}

		// Set up the item attributes
		attributes[0].tag = kSecGenericItemAttr;
		attributes[0].data = "application password";
		attributes[0].length = 20;
		attributes[1].tag = kSecLabelItemAttr;
		attributes[1].data = (unichar *)[label UTF8String];
		attributes[1].length = (UInt32)strlen([label UTF8String]);
		attributes[2].tag = kSecAccountItemAttr;
		attributes[2].data = (unichar *)[account UTF8String];
		attributes[2].length = (UInt32)strlen([account UTF8String]);
		attributes[3].tag = kSecServiceItemAttr;
		attributes[3].data = (unichar *)[name UTF8String];
		attributes[3].length = (UInt32)strlen([name UTF8String]);
		attList.count = 4;
		attList.attr = attributes;

		// Create the keychain item
		status = SecKeychainItemCreateFromContent(
			kSecGenericPasswordItemClass,			// Generic password type
			&attList,								// The attribute list created for the keychain item
			(UInt32)strlen([password UTF8String]),	// Length of password
			[password UTF8String],					// Password data
			NULL,									// Default keychain
			passwordAccessRef,						// Access list for this keychain
			NULL);									// The item reference

		if (passwordAccessRef) CFRelease(passwordAccessRef);

		if (status != noErr) {
			NSLog(@"Error (%i) while trying to add password for name: %@ account: %@", (int)status, name, account);

			SPOnewayAlertSheet(
				NSLocalizedString(@"Error adding password to Keychain", @"error adding password to keychain message"),
				[NSApp mainWindow],
				[NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to add the password to your Keychain. Repairing your Keychain might resolve this, but if it doesn't please report it to the Sequel Pro team, supplying the error code %i.", @"error adding password to keychain informative message"), status]
			);
		}
	}
}

/**
 * Get a password from the user's Keychain for the supplied name and account.
 */
- (NSString *)getPasswordForName:(NSString *)name account:(NSString *)account
{
	OSStatus status;

	void *passwordData;
	UInt32 passwordLength;
	SecKeychainItemRef itemRef;
	NSString *password = nil;

	// Check supplied variables and replaces nils with empty strings
	if (!name) name = @"";
	if (!account) account = @"";

	status = SecKeychainFindGenericPassword(
											NULL,									// default keychain
											(UInt32)strlen([name UTF8String]),		// length of service name (bytes)
											[name UTF8String],						// service name

											(UInt32)strlen([account UTF8String]),	// length of account name (bytes)
											[account UTF8String],					// account name
											&passwordLength,						// length of password
											&passwordData,							// pointer to password data
											&itemRef								// the item reference
											);

	if (status == noErr) {

		// Create a \0 terminated cString out of passwordData
		char passwordBuf[passwordLength + 1];
		strncpy(passwordBuf, passwordData, (size_t)passwordLength);
		passwordBuf[passwordLength] = '\0';

		password = [NSString stringWithCString:passwordBuf encoding:NSUTF8StringEncoding];

		// Free the data allocated by SecKeychainFindGenericPassword:
		SecKeychainItemFreeContent(
									NULL,           // No attribute data to release
									passwordData    // Release data
									);
	}

	return password;
}

/**
 * Delete a password from the user's Keychain for the supplied name and account.
 */
- (void)deletePasswordForName:(NSString *)name account:(NSString *)account
{
	OSStatus status;
	SecKeychainItemRef itemRef = nil;

	// Check supplied variables and replaces nils with empty strings
	if (!name) name = @"";
	if (!account) account = @"";

	// Check if password already exists before deleting
	if ([self passwordExistsForName:name account:account]) {
		status = SecKeychainFindGenericPassword(
												NULL,									// default keychain
												(UInt32)strlen([name UTF8String]),		// length of service name
												[name UTF8String],						// service name
												(UInt32)strlen([account UTF8String]),	// length of account name
												[account UTF8String],					// account name
												nil,									// length of password
												nil,									// pointer to password data
												&itemRef								// the item reference
												);

		if (status == noErr) {
			status = SecKeychainItemDelete(itemRef);

			if (status != noErr) {
				NSLog(@"Error (%i) while trying to delete password for name: %@ account: %@", (int)status, name, account);
			}
		}

		if (itemRef) CFRelease(itemRef);
	}
}

/**
 * Checks the user's Keychain to see if a password for the supplied name and account exists.
 */
- (BOOL)passwordExistsForName:(NSString *)name account:(NSString *)account
{
	// "kSecClassGenericPassword" was introduced with the 10.7 SDK.
	// It won't work on 10.6 either (meaning this code never matches properly there).
	if([SPOSInfo isOSVersionAtLeastMajor:10 minor:7 patch:0]) {
		NSMutableDictionary *query = [NSMutableDictionary dictionary];

		[query setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass];
		[query setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnAttributes];
		[query setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];

		[query setObject:account forKey:(id)kSecAttrAccount];
		[query setObject:name forKey:(id)kSecAttrService];

		CFDictionaryRef result = NULL;

		return SecItemCopyMatching((CFDictionaryRef)query, (CFTypeRef *)&result) == errSecSuccess;
	}

	//Version for 10.6

	SecKeychainItemRef item;
	SecKeychainSearchRef search = NULL;
	NSInteger numberOfItemsFound = 0;
	SecKeychainAttributeList list;
	SecKeychainAttribute attributes[2];

	// Check supplied variables and replaces nils with empty strings
	if (!name) name = @"";
	if (!account) account = @"";

	attributes[0].tag    = kSecAccountItemAttr;
	attributes[0].data   = (void *)[account UTF8String];			// Account name
	attributes[0].length = (UInt32)strlen([account UTF8String]);	// Length of account name (bytes)

	attributes[1].tag    = kSecServiceItemAttr;
	attributes[1].data   = (void *)[name UTF8String];			// Service name
	attributes[1].length = (UInt32)strlen([name UTF8String]);	// Length of service name (bytes)

	list.count = 2;
	list.attr  = attributes;

	if (SecKeychainSearchCreateFromAttributes(NULL, kSecGenericPasswordItemClass, &list, &search) == noErr) {
		while (SecKeychainSearchCopyNext(search, &item) == noErr)
		{
			CFRelease(item);
			numberOfItemsFound++;
		}
	}

	if (search) CFRelease(search);

	return (numberOfItemsFound > 0);
}

/**
 * Change the password for a keychain item.  This should be used instead of
 * deleting and recreating the keychain item, as it allows preservation of
 * access lists and works around Lion cacheing issues.
 */
- (void)updateItemWithName:(NSString *)name account:(NSString *)account toPassword:(NSString *)password
{
	[self updateItemWithName:name account:account toName:password account:name password:account];
}

/**
 * Change the details for a keychain item.  This should be used instead of
 * deleting and recreating the keychain item, as it allows preservation of
 * access lists and works around Lion cacheing issues.
 */
- (void)updateItemWithName:(NSString *)name account:(NSString *)account toName:(NSString *)newName account:(NSString *)newAccount password:(NSString *)password
{
	OSStatus status;
	SecKeychainItemRef itemRef;
	SecKeychainAttribute attributes[2];
	SecKeychainAttributeList attList;

	// Retrieve a reference to the keychain item
	status = SecKeychainFindGenericPassword(NULL,														// Default keychain
											(UInt32)strlen([name UTF8String]), [name UTF8String],		// Service name and length
											(UInt32)strlen([account UTF8String]), [account UTF8String],	// Account name and length
											NULL, NULL,													// No password retrieval required
											&itemRef);													// The item reference

	if (status != noErr) {
		NSLog(@"Error (%i) while trying to find keychain item to edit for name: %@ account: %@", (int)status, name, account);

		SPOnewayAlertSheet(
			NSLocalizedString(@"Error retrieving Keychain item to edit", @"error finding keychain item to edit message"),
			[NSApp mainWindow],
			[NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to retrieve the Keychain item you're trying to edit. Repairing your Keychain might resolve this, but if it doesn't please report it to the Sequel Pro team, supplying the error code %i.", @"error finding keychain item to edit informative message"), status]
		);
		return;
	}

	// Set up the attributes to modify
	attributes[0].tag = kSecAccountItemAttr;
	attributes[0].data = (unichar *)[newAccount UTF8String];
	attributes[0].length = (UInt32)strlen([newAccount UTF8String]);
	attributes[1].tag = kSecServiceItemAttr;
	attributes[1].data = (unichar *)[newName UTF8String];
	attributes[1].length = (UInt32)strlen([newName UTF8String]);
	attList.count = 2;
	attList.attr = attributes;

	// Amend the keychain item
	status = SecKeychainItemModifyAttributesAndData(itemRef, &attList, (UInt32)strlen([password UTF8String]), [password UTF8String]);

	if (status != noErr) {

		// An error of -25299 indicates that the keychain item is a duplicate.  As connection names include a unique ID,
		// this indicates an issue when previously altering keychain items; delete the old item and try again.
		if ((int)status == -25299) {
			[self deletePasswordForName:newName account:newAccount];

			return [self updateItemWithName:name account:account toName:newName account:newAccount password:password];
		}

		NSLog(@"Error (%i) while updating keychain item for name: %@ account: %@", (int)status, name, account);

		SPOnewayAlertSheet(
			NSLocalizedString(@"Error updating Keychain item", @"error updating keychain item message"),
			[NSApp mainWindow],
			[NSString stringWithFormat:NSLocalizedString(@"An error occured while trying to update the Keychain item. Repairing your Keychain might resolve this, but if it doesn't please report it to the Sequel Pro team, supplying the error code %i.", @"error updating keychain item informative message"), status]
		);
	}
}

/**
 * Retrieve the keychain item name for a supplied name and id.
 */
- (NSString *)nameForFavoriteName:(NSString *)favoriteName id:(NSString *)favoriteId
{
	// Look up the keychain name using long longs to support 64-bit > 32-bit keychain usage
	return [NSString stringWithFormat:@"Sequel Pro : %@ (%lld)", favoriteName ? favoriteName: @"", [favoriteId longLongValue]];
}

/**
 * Retrieve the keychain item account for a supplied user, host, and database - which can be nil.
 */
- (NSString *)accountForUser:(NSString *)user host:(NSString *)host database:(NSString *)database
{
	return [NSString stringWithFormat:@"%@@%@/%@", user ? user : @"", host ? host : @"", database ? database : @""];
}

/**
 * Retrieve the keychain SSH item name for a supplied name and id.
 */
- (NSString *)nameForSSHForFavoriteName:(NSString *)favoriteName id:(NSString *)favoriteId
{
	// Look up the keychain name using long longs to support 64-bit > 32-bit keychain usage
	return [NSString stringWithFormat:@"Sequel Pro SSHTunnel : %@ (%lld)", favoriteName ? favoriteName: @"", [favoriteId longLongValue]];
}

/**
 * Retrieve the keychain SSH item account for a supplied SSH user and host - which can be nil.
 */
- (NSString *)accountForSSHUser:(NSString *)theSSHUser sshHost:(NSString *)theSSHHost
{
	return [NSString stringWithFormat:@"%@@%@", theSSHUser ? theSSHUser : @"", theSSHHost ? theSSHHost : @""];
}

@end


text:
@interface NSBlockOperation (DVTNSOperationAdditions)
+ (id)dvt_blockOperationWithBlock:(CDUnknownBlockType)arg1;
@end

redpajama_set_name: RedPajamaGithub


text:
@interface MyInfoCell ()

@property(weak, nonatomic) IBOutlet UIImageView *avatarImageView;
@property(weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property(weak, nonatomic) IBOutlet UIButton *showAddressQRButton;

@end

@implementation MyInfoCell
- (IBAction)showQRAction:(id)sender {

    if (self.qrBtnClickBlock) {
        self.qrBtnClickBlock();
    }

}

- (void)awakeFromNib {
    [super awakeFromNib];

    _avatarImageView.layer.cornerRadius = 6;
    _avatarImageView.layer.masksToBounds = YES;
    self.userNameLabel.font = [UIFont boldSystemFontOfSize:FONT_SIZE(36)];
    self.userIDLabel.font = [UIFont systemFontOfSize:FONT_SIZE(24)];
}

- (void)setData:(id)data {
    [super setData:data];

    AccountInfo *user = (AccountInfo *) data;
    [self.avatarImageView setPlaceholderImageWithAvatarUrl:user.avatar];
    _userNameLabel.text = user.username;
    // Safety measures
    if (user.contentId.length <= 0) {
        user.contentId = user.address;
    }

    if (user.contentId.length > 10) {
        NSMutableString *IdStringM = [NSMutableString stringWithFormat:@"%@", [user.contentId substringToIndex:user.contentId.length / 2]];
        [IdStringM appendString:@"\n"];
        [IdStringM appendString:[NSString stringWithFormat:@"%@", [user.contentId substringFromIndex:user.contentId.length / 2]]];
        _userIDLabel.text = IdStringM;
    } else {
        _userIDLabel.text = user.contentId;
    }
}

@end


text:
using System;

namespace LinqToTwitter
{
    /// <summary>
    /// holds rate limit info
    /// </summary>
    public class RateLimitStatus
    {
        public int RemainingHits { get; set; }

        public int HourlyLimit { get; set; }

        public DateTime ResetTime { get; set; }

        public int ResetTimeInSeconds { get; set; }
    }
}


text:
package ebpf

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"syscall"

	"github.com/cilium/ebpf/internal"
	"github.com/pkg/errors"
)

// MapABI are the attributes of a Map which are available across all supported kernels.
type MapABI struct {
	Type       MapType
	KeySize    uint32
	ValueSize  uint32
	MaxEntries uint32
	Flags      uint32
}

func newMapABIFromSpec(spec *MapSpec) *MapABI {
	return &MapABI{
		spec.Type,
		spec.KeySize,
		spec.ValueSize,
		spec.MaxEntries,
		spec.Flags,
	}
}

func newMapABIFromFd(fd *bpfFD) (string, *MapABI, error) {
	info, err := bpfGetMapInfoByFD(fd)
	if err != nil {
		if errors.Cause(err) == syscall.EINVAL {
			abi, err := newMapABIFromProc(fd)
			return "", abi, err
		}
		return "", nil, err
	}

	return "", &MapABI{
		MapType(info.mapType),
		info.keySize,
		info.valueSize,
		info.maxEntries,
		info.flags,
	}, nil
}

func newMapABIFromProc(fd *bpfFD) (*MapABI, error) {
	var abi MapABI
	err := scanFdInfo(fd, map[string]interface{}{
		"map_type":    &abi.Type,
		"key_size":    &abi.KeySize,
		"value_size":  &abi.ValueSize,
		"max_entries": &abi.MaxEntries,
		"map_flags":   &abi.Flags,
	})
	if err != nil {
		return nil, err
	}
	return &abi, nil
}

// Equal returns true if two ABIs have the same values.
func (abi *MapABI) Equal(other *MapABI) bool {
	switch {
	case abi.Type != other.Type:
		return false
	case abi.KeySize != other.KeySize:
		return false
	case abi.ValueSize != other.ValueSize:
		return false
	case abi.MaxEntries != other.MaxEntries:
		return false
	case abi.Flags != other.Flags:
		return false
	default:
		return true
	}
}

// ProgramABI are the attributes of a Program which are available across all supported kernels.
type ProgramABI struct {
	Type ProgramType
}

func newProgramABIFromSpec(spec *ProgramSpec) *ProgramABI {
	return &ProgramABI{
		spec.Type,
	}
}

func newProgramABIFromFd(fd *bpfFD) (string, *ProgramABI, error) {
	info, err := bpfGetProgInfoByFD(fd)
	if err != nil {
		if errors.Cause(err) == syscall.EINVAL {
			return newProgramABIFromProc(fd)
		}

		return "", nil, err
	}

	var name string
	if bpfName := convertCString(info.name[:]); bpfName != "" {
		name = bpfName
	} else {
		name = convertCString(info.tag[:])
	}

	return name, &ProgramABI{
		Type: ProgramType(info.progType),
	}, nil
}

func newProgramABIFromProc(fd *bpfFD) (string, *ProgramABI, error) {
	var (
		abi  ProgramABI
		name string
	)

	err := scanFdInfo(fd, map[string]interface{}{
		"prog_type": &abi.Type,
		"prog_tag":  &name,
	})
	if errors.Cause(err) == errMissingFields {
		return "", nil, &internal.UnsupportedFeatureError{
			Name:           "reading ABI from /proc/self/fdinfo",
			MinimumVersion: internal.Version{4, 11, 0},
		}
	}
	if err != nil {
		return "", nil, err
	}

	return name, &abi, nil
}

func scanFdInfo(fd *bpfFD, fields map[string]interface{}) error {
	raw, err := fd.value()
	if err != nil {
		return err
	}

	fh, err := os.Open(fmt.Sprintf("/proc/self/fdinfo/%d", raw))
	if err != nil {
		return err
	}
	defer fh.Close()

	return errors.Wrap(scanFdInfoReader(fh, fields), fh.Name())
}

var errMissingFields = errors.New("missing fields")

func scanFdInfoReader(r io.Reader, fields map[string]interface{}) error {
	var (
		scanner = bufio.NewScanner(r)
		scanned int
	)

	for scanner.Scan() {
		parts := bytes.SplitN(scanner.Bytes(), []byte("\t"), 2)
		if len(parts) != 2 {
			continue
		}

		name := bytes.TrimSuffix(parts[0], []byte(":"))
		field, ok := fields[string(name)]
		if !ok {
			continue
		}

		if n, err := fmt.Fscanln(bytes.NewReader(parts[1]), field); err != nil || n != 1 {
			return errors.Wrapf(err, "can't parse field %s", name)
		}

		scanned++
	}

	if err := scanner.Err(); err != nil {
		return err
	}

	if scanned != len(fields) {
		return errMissingFields
	}

	return nil
}

// Equal returns true if two ABIs have the same values.
func (abi *ProgramABI) Equal(other *ProgramABI) bool {
	switch {
	case abi.Type != other.Type:
		return false
	default:
		return true
	}
}


text:
import datetime

from dateutil.tz import tzutc

import libtaxii as t
import libtaxii.clients as tc
import libtaxii.messages as tm
from libtaxii.constants import *

# NOTE: This cannot currently be run as a unit test because it needs a server
# to connect to.
def client_example():

    # Create the TAXII HTTPS Client
    client = tc.HttpClient()

    # Uncomment to use HTTPS
    client.set_use_https(True)

    # Uncomment to use basic authentication
    # client.set_auth_type(tc.HttpClient.AUTH_BASIC)
    # client.set_auth_credentials({'username':'some_username', 'password':'some_password'})

    # Uncomment to use certificate-based authentication
    client.set_auth_type(tc.HttpClient.AUTH_CERT)
    client.set_auth_credentials({'key_file': 'keyfile',
                                 'cert_file': 'certfile'})

    # Uncomment to set a proxy
    # client.set_proxy(tc.HttpClient.PROXY_HTTP, 'http://proxy.company.com:80')

    # Create the poll request
    poll_request1 = tm.PollRequest(message_id=tm.generate_message_id(), feed_name='TheFeedToPoll')

    # Call without a proxy
    http_response = client.call_taxii_service2('hostname', '/poll_service_path/', VID_TAXII_XML_10, poll_request1.to_xml())

    print(http_response.__class__.__name__)

    taxii_message = t.get_message_from_http_response(http_response,
                                                     poll_request1.message_id)
    print((taxii_message.to_xml()))

if __name__ == "__main__":
    client_example()


text:
require 'ffi_yajl'
require 'chef_zero/rest_base'
require 'chef_zero/chef_data/data_normalizer'

module ChefZero
  module Endpoints
    # Common code for endpoints that return cookbook lists
    class CookbooksBase < RestBase
      def format_cookbooks_list(request, cookbooks_list, constraints = {}, num_versions = nil)
        results = {}
        filter_cookbooks(cookbooks_list, constraints, num_versions) do |name, versions|
          versions_list = versions.map do |version|
            {
              'url' => build_uri(request.base_uri, request.rest_path[0..1] + ['cookbooks', name, version]),
              'version' => version
            }
          end
          results[name] = {
            'url' => build_uri(request.base_uri, request.rest_path[0..1] + ['cookbooks', name]),
            'versions' => versions_list
          }
        end
        results
      end

      def all_cookbooks_list(request)
        result = {}
        # Race conditions exist here (if someone deletes while listing).  I don't care.
        data_store.list(request.rest_path[0..1] + ['cookbooks']).each do |name|
          result[name] = data_store.list(request.rest_path[0..1] + ['cookbooks', name])
        end
        result
      end

      def filter_cookbooks(cookbooks_list, constraints = {}, num_versions = nil)
        cookbooks_list.keys.sort.each do |name|
          constraint = Gem::Requirement.new(constraints[name])
          versions = []
          cookbooks_list[name].sort_by { |version| Gem::Version.new(version.dup) }.reverse.each do |version|
            break if num_versions && versions.size >= num_versions
            if constraint.satisfied_by?(Gem::Version.new(version.dup))
              versions << version
            end
          end
          yield [name, versions]
        end
      end

      def recipe_names(cookbook_name, cookbook)
        result = []
        if cookbook['recipes']
          cookbook['recipes'].each do |recipe|
            if recipe['path'] == "recipes/#{recipe['name']}" && recipe['name'][-3..-1] == '.rb'
              if recipe['name'] == 'default.rb'
                result << cookbook_name
              end
              result << "#{cookbook_name}::#{recipe['name'][0..-4]}"
            end
          end
        end
        result
      end
    end
  end
end


text:
@interface PodsDummy_Pods_shoppingcart_demo : NSObject
@end
@implementation PodsDummy_Pods_shoppingcart_demo
@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/payDetailsUI_payTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@mipmap/ali_logo" />

    <ImageView
        android:id="@+id/payDetailsUI_payImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50px"
        android:background="@mipmap/weixin_loading" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="50px"
        android:background="@mipmap/pay_form_bag"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:text="商品名称" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:text="交易金额" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="2"
                android:gravity="center"
                android:text="商户名称"
                android:id="@+id/textView2" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:gravity="center"
                android:layout_weight="2"
                android:text="订单号" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/payDetailsUI_goodsName"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:text="商品名称" />

            <TextView
                android:id="@+id/payDetailsUI_dealMoney"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:text="交易金额" />

            <TextView
                android:id="@+id/payDetailsUI_shopName"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="2"
                android:gravity="center"
                android:text="安徽沃富民生科技有限公司"/>

            <TextView
                android:id="@+id/payDetailsUI_orderNum"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:gravity="center"
                android:layout_weight="2"
                android:text="订单号" />

        </LinearLayout>
    </LinearLayout>

    <RelativeLayout
        android:layout_width="800px"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        <Button
            android:id="@+id/payDetailsUI_cancelBtn"
            android:layout_width="300px"
            android:layout_height="wrap_content"
            android:background="@mipmap/cancle_pay"
            android:layout_alignParentLeft="true"/>

        <Button
            android:id="@+id/payDetailsUI_completeBtn"
            android:layout_width="300px"
            android:layout_height="wrap_content"
            android:background="@mipmap/entry_pay"
            android:layout_alignParentRight="true"/>
    </RelativeLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="20px"
        android:text="@string/pay_native"
        android:textSize="16sp" />

</LinearLayout>


text:
namespace org {
  namespace apache {
    namespace lucene {
      namespace analysis {
        class TokenStream;
      }
    }
  }
}
namespace java {
  namespace lang {
    class Class;
  }
  namespace io {
    class IOException;
  }
}
template<class T> class JArray;

namespace org {
  namespace apache {
    namespace lucene {
      namespace analysis {
        namespace miscellaneous {

          class ScandinavianFoldingFilter : public ::org::apache::lucene::analysis::TokenFilter {
          public:
            enum {
              mid_init$_c7c794dc,
              mid_incrementToken_54c6a16a,
              max_mid
            };

            static ::java::lang::Class *class$;
            static jmethodID *mids$;
            static bool live$;
            static jclass initializeClass(bool);

            explicit ScandinavianFoldingFilter(jobject obj) : ::org::apache::lucene::analysis::TokenFilter(obj) {
              if (obj != NULL)
                env->getClass(initializeClass);
            }
            ScandinavianFoldingFilter(const ScandinavianFoldingFilter& obj) : ::org::apache::lucene::analysis::TokenFilter(obj) {}

            ScandinavianFoldingFilter(const ::org::apache::lucene::analysis::TokenStream &);

            jboolean incrementToken() const;
          };
        }
      }
    }
  }
}

#include <Python.h>

namespace org {
  namespace apache {
    namespace lucene {
      namespace analysis {
        namespace miscellaneous {
          extern PyTypeObject PY_TYPE(ScandinavianFoldingFilter);

          class t_ScandinavianFoldingFilter {
          public:
            PyObject_HEAD
            ScandinavianFoldingFilter object;
            static PyObject *wrap_Object(const ScandinavianFoldingFilter&);
            static PyObject *wrap_jobject(const jobject&);
            static void install(PyObject *module);
            static void initialize(PyObject *module);
          };
        }
      }
    }
  }
}

#endif


text:
Tile = function(x,y) {
  x = utils.roundToGrid(x);
  y = utils.roundToGrid(y);
  this.position = new Vector(x,y);
  this.size = new Vector(config.gridInterval,config.gridInterval);
  this.structSupport = new StructSupport();
  this.name = new Name();

  this.pathable = false;
  this.lastDrawn = -1;
  this.type = "tile";
  this.initialHealth = 0.1;
  this.maxHealth = 100;
  this.currentHealth = 100;
  this.built = true;
  this.active = true;
  //this.hidden = true;

  this.baseAlpha = 0.2;
  this.healthAlpha = 0.6;

  this.setNewHealth = function(){
    this.currentHealth = this.maxHealth * this.initialHealth;
  }

  this.cost = {};

  this.center = function(){
    return new Vector(this.position.x+(this.size.x*0.5),this.position.y+(this.size.y*0.5));
  }

  this.collision = function(){return true;}

  this.click = function(coords,terrain){
    return;
  }

  this.wound = function(damage){
    this.currentHealth -= damage;
    if(this.currentHealth <= 0){
      return true;
    }
    return false;
  }

  this.updateLight = function(terrain,camera){
  }

  this.repair = function(amount){
    if(this.currentHealth >= this.maxHealth){
      this.currentHealth = this.maxHealth;
      return false;
    }
    this.currentHealth += amount;
    if(this.currentHealth >= this.maxHealth){
      this.currentHealth = this.maxHealth;
      if(!this.built){
        this.built = true;
        this.active = true;
        return "built";
      }
    }
    return true;
  }
}

StructSupport = function(){
}


text:
package env

import (
	"encoding/json"
	"runtime"
	"sort"
	"strings"
)

// Environment is a map of environment variables, with the keys normalized
// for case-insensitive operating systems
type Environment map[string]string

func New() Environment {
	return Environment{}
}

// Split splits an environment variable (in the form "name=value") into the name
// and value substrings. If there is no '=', or the first '=' is at the start,
// it returns `"", "", false`.
func Split(l string) (name, value string, ok bool) {
	// Variable names should not contain '=' on any platform...and yet Windows
	// creates environment variables beginning with '=' in some circumstances.
	// See https://github.com/golang/go/issues/49886.
	// Dropping them matches the previous behaviour on Windows, which used SET
	// to obtain the state of environment variables.
	i := strings.IndexRune(l, '=')
	// Either there is no '=', or it is at the start of the string.
	// Both are disallowed.
	if i <= 0 {
		return "", "", false
	}
	return l[:i], l[i+1:], true
}

// FromSlice creates a new environment from a string slice of KEY=VALUE
func FromSlice(s []string) Environment {
	env := make(Environment, len(s))

	for _, l := range s {
		if k, v, ok := Split(l); ok {
			env.Set(k, v)
		}
	}

	return env
}

// Get returns a key from the environment
func (e Environment) Get(key string) (string, bool) {
	v, ok := e[normalizeKeyName(key)]
	return v, ok
}

// Get a boolean value from environment, with a default for empty. Supports true|false, on|off, 1|0
func (e Environment) GetBool(key string, defaultValue bool) bool {
	v, _ := e.Get(key)

	switch strings.ToLower(v) {
	case "on", "1", "enabled", "true":
		return true
	case "off", "0", "disabled", "false":
		return false
	default:
		return defaultValue
	}
}

// Exists returns true/false depending on whether or not the key exists in the env
func (e Environment) Exists(key string) bool {
	_, ok := e[normalizeKeyName(key)]
	return ok
}

// Set sets a key in the environment
func (e Environment) Set(key string, value string) string {
	e[normalizeKeyName(key)] = value

	return value
}

// Remove a key from the Environment and return its value
func (e Environment) Remove(key string) string {
	value, ok := e.Get(key)
	if ok {
		delete(e, normalizeKeyName(key))
	}
	return value
}

// Length returns the length of the environment
func (e Environment) Length() int {
	return len(e)
}

// Diff returns a new environment with the keys and values from this
// environment which are different in the other one.
func (e Environment) Diff(other Environment) Diff {
	diff := Diff{
		Added:   make(map[string]string),
		Changed: make(map[string]DiffPair),
		Removed: make(map[string]struct{}, 0),
	}

	for k, v := range e {
		other, ok := other.Get(k)
		if !ok {
			// This environment has added this key to other
			diff.Added[k] = v
			continue
		}

		if other != v {
			diff.Changed[k] = DiffPair{
				Old: other,
				New: v,
			}
		}
	}

	for k := range other {
		if _, ok := e.Get(k); !ok {
			diff.Removed[k] = struct{}{}
		}
	}

	return diff
}

// Merge merges another env into this one and returns the result
func (e Environment) Merge(other Environment) Environment {
	c := e.Copy()

	if other == nil {
		return c
	}

	for k, v := range other {
		c.Set(k, v)
	}

	return c
}

func (e Environment) Apply(diff Diff) Environment {
	c := e.Copy()

	for k, v := range diff.Added {
		c.Set(k, v)
	}
	for k, v := range diff.Changed {
		c.Set(k, v.New)
	}
	for k := range diff.Removed {
		delete(c, k)
	}

	return c
}

// Copy returns a copy of the env
func (e Environment) Copy() Environment {
	c := make(map[string]string)

	for k, v := range e {
		c[k] = v
	}

	return c
}

// ToSlice returns a sorted slice representation of the environment
func (e Environment) ToSlice() []string {
	s := []string{}
	for k, v := range e {
		s = append(s, k+"="+v)
	}

	// Ensure they are in a consistent order (helpful for tests)
	sort.Strings(s)

	return s
}

func (e Environment) MarshalJSON() ([]byte, error) {
	normalised := make(map[string]string, len(e))
	for k, v := range e {
		normalised[normalizeKeyName(k)] = v
	}

	return json.Marshal(normalised)
}

func (e *Environment) UnmarshalJSON(data []byte) error {
	var raw map[string]string
	if err := json.Unmarshal(data, &raw); err != nil {
		return err
	}

	*e = make(Environment, len(raw))
	for k, v := range raw {
		e.Set(k, v)
	}

	return nil
}

// Environment variables on Windows are case-insensitive. When you run `SET`
// within a Windows command prompt, you'll see variables like this:
//
//	...
//	Path=C:\Program Files (x86)\Parallels\Parallels Tools\Applications;...
//	PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 94 Stepping 3, GenuineIntel
//	SystemDrive=C:
//	SystemRoot=C:\Windows
//	...
//
// There's a mix of both CamelCase and UPPERCASE, but the can all be accessed
// regardless of the case you use. So PATH is the same as Path, PAth, pATH,
// and so on.
//
// os.Environ() in Golang returns key/values in the original casing, so it
// returns a slice like this:
//
//	{ "Path=...", "PROCESSOR_IDENTIFIER=...", "SystemRoot=..." }
//
// Users of env.Environment shouldn't need to care about this.
// env.Get("PATH") should "just work" on Windows. This means on Windows
// machines, we'll normalise all the keys that go in/out of this API.
//
// Unix systems _are_ case sensitive when it comes to ENV, so we'll just leave
// that alone.
func normalizeKeyName(key string) string {
	if runtime.GOOS == "windows" {
		return strings.ToUpper(key)
	} else {
		return key
	}
}

type Diff struct {
	Added   map[string]string
	Changed map[string]DiffPair
	Removed map[string]struct{}
}

type DiffPair struct {
	Old string
	New string
}

func (diff *Diff) Remove(key string) {
	delete(diff.Added, key)
	delete(diff.Changed, key)
	delete(diff.Removed, key)
}

func (diff *Diff) Empty() bool {
	return len(diff.Added) == 0 && len(diff.Changed) == 0 && len(diff.Removed) == 0
}


text:
<?php
  if (!Auth::isLoggedIn()) { // user is not logged in

?>

  <button id="switch-signin" class="btn btn-sm btn-default"><?php echo I18n::t('text.signin'); ?></button>
  <form class="form-signin" action="<?php echo ROOT_DIR; ?>login" method="post">

<?php echo I18n::t('text.signin'); ?>

    <?php echo I18n::t('text.email'); ?>
    <input name="email" type="email" id="inputEmail" class="form-control" placeholder="<?php echo I18n::t('text.email'); ?>" required="" autofocus="">
    <?php echo I18n::t('text.password'); ?>
    <input name="pwd" type="password" id="inputPassword" class="form-control" placeholder="<?php echo I18n::t('text.password'); ?>" required="">
    <button class="btn btn-default" type="submit" name="submitted"><?php echo I18n::t('text.signin'); ?></button>
  </form>
  <form class="form-register" action="<?php echo ROOT_DIR.'register'; ?>">
    <button class="btn btn-sm btn-default"><?php echo I18n::t('text.register'); ?></button>

<?php
  } else { // user is logged in
?>

  <?php echo I18n::t('text.welcome').' '.$_SESSION['user']->getNickname(); ?>
  <img src="<?php echo ROOT_DIR.IMG_DIR.'user_icon.jpg'; ?>" />

<?php
  }


text:
import {
  async,
  ComponentFixture,
  TestBed
} from '@angular/core/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';

import { BsDropdownConfig, BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { TooltipConfig, TooltipModule } from 'ngx-bootstrap/tooltip';

import { Action } from '../action/action';
import { ActionComponent } from './action.component';
import { ActionConfig } from '../action/action-config';

describe('Action component - ', () => {
  let comp: ActionComponent;
  let fixture: ComponentFixture<ActionComponent>;
  let config: ActionConfig;

  beforeEach(() => {
    config = {
      primaryActions: [{
        id: 'action1',
        title: 'Action 1',
        tooltip: 'Do the first thing'
      }, {
        id: 'action2',
        title: 'Action 2',
        tooltip: 'Do something else'
      }],
      moreActions: [{
        id: 'moreActions1',
        title: 'Action',
        tooltip: 'Perform an action'
      }, {
        id: 'moreActions2',
        title: 'Another Action',
        tooltip: 'Do something else'
      }, {
        disabled: true,
        id: 'moreActions3',
        title: 'Disabled Action',
        tooltip: 'Unavailable action',
      }, {
        id: 'moreActions4',
        title: 'Something Else',
        tooltip: ''
      }, {
        id: 'moreActions5',
        title: '',
        separator: true
      }, {
        id: 'moreActions6',
        title: 'Grouped Action 1',
        tooltip: 'Do something'
      }, {
        id: 'moreActions7',
        title: 'Grouped Action 2',
        tooltip: 'Do something similar'
      }]
    } as ActionConfig;
  });

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        BsDropdownModule.forRoot(),
        BrowserAnimationsModule,
        FormsModule,
        TooltipModule.forRoot()
      ],
      declarations: [
        ActionComponent
      ],
      providers: [BsDropdownConfig, TooltipConfig]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(ActionComponent);
        comp = fixture.componentInstance;
        comp.config = config;
        fixture.detectChanges();
      });
  }));

  it('should have correct number of primary actions', function () {
    let fields = fixture.debugElement.queryAll(By.css('.primary-action'));
    expect(fields.length).toBe(2);
  });

  it('should have correct number of secondary actions', function () {
    fixture.detectChanges(); // Workaround to fix dropdown tests
    let fields = fixture.debugElement.queryAll(By.css('.secondary-action'));
    expect(fields.length).toBe(6);
  });

  it('should have correct number of separators', function () {
    fixture.detectChanges(); // Workaround to fix dropdown tests
    let fields = fixture.debugElement.queryAll(By.css('.divider'));
    expect(fields.length).toBe(1);
  });

  it('should correctly disable actions', function () {
    fixture.detectChanges(); // Workaround to fix dropdown tests
    let fields = fixture.debugElement.queryAll(By.css('.disabled'));
    expect(fields.length).toBe(1);
  });

  it('should not show more actions menu when there are no more actions', function () {
    fixture.detectChanges(); // Workaround to fix dropdown tests
    let menus = fixture.debugElement.queryAll(By.css('.fa-ellipsis-v'));
    expect(menus.length).toBe(1);

    config.moreActions.length = 0;
    fixture.detectChanges();

    menus = fixture.debugElement.queryAll(By.css('.fa-ellipsis-v'));
    expect(menus.length).toBe(0);
  });

  it('should call the action function with the appropriate action when an action is clicked', function (done) {
    fixture.detectChanges(); // Workaround to fix dropdown tests
    let primaryActions = fixture.debugElement.queryAll(By.css('.primary-action'));
    let moreActions = fixture.debugElement.queryAll(By.css('.secondary-action'));
    expect(primaryActions.length).toBe(2);
    expect(moreActions.length).toBe(6);

    let action: Action;
    comp.onActionSelect.subscribe((data: Action) => {
      action = data;
      done();
    });

    primaryActions[0].triggerEventHandler('click', {});
    fixture.detectChanges();
    expect(action).toBe(config.primaryActions[0]);

    moreActions[3].triggerEventHandler('click', {});
    fixture.detectChanges();
    expect(action).toBe(config.moreActions[3]);
  });

  it('should not call the action function when a disabled action is clicked', function (done) {
    fixture.detectChanges(); // Workaround to fix dropdown tests
    let primaryActions = fixture.debugElement.queryAll(By.css('.primary-action'));
    let moreActions = fixture.debugElement.queryAll(By.css('.secondary-action'));
    expect(primaryActions.length).toBe(2);
    expect(moreActions.length).toBe(6);

    let action: Action = null;
    comp.onActionSelect.subscribe((data: Action) => {
      action = data;
      done();
    });

    moreActions[2].triggerEventHandler('click', {});
    fixture.detectChanges();
    expect(action).toBeNull();

    primaryActions[1].triggerEventHandler('click', {});
    fixture.detectChanges();
    expect(action).toBe(config.primaryActions[1]);

    config.primaryActions[1].disabled = true;
    fixture.detectChanges();
    action = null;

    primaryActions[1].triggerEventHandler('click', {});
    fixture.detectChanges();
    expect(action).toBeNull();
  });
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: components/containers/index.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: components/containers/index.js

import welcome from './welcome.jsx';
import example from './example.jsx';
import editor from './editor.jsx';
import login from './login.jsx';
import mail from './mail.jsx';
import mailbox from './mailbox.jsx';

//import Rx from 'rxjs/Rx';
//console.dir(Rx)

export default {
    example,
    welcome,
    editor,
    login,
    mailbox,
    mail,
};

/** @module components/containers */

Home

Modules

components/containers

components/dumb

constants/api

constants/http

constants/shareResult

net/httpProxy

utils

utils/env

utils/hybird

Classes

MarqueeLine

ShareInApp

Toast

QueryString

Storage

    Documentation generated by JSDoc 3.4.3 on Thu Jul 06 2017 11:31:32 GMT+0800 (CST)


text:
from distutils.core import setup

setup(name='spearmint_salad',
    version='1.0',
    author='Alexandre Lacoste',
    packages=[
        'spearmint_salad',
        'spearmint_salad.spearmint',
        'spearmint_salad.spearmint.chooser',
        'spearmint_salad.analyze',
        'spearmint_salad.example'],
    scripts = ['spearmint_salad/analyze/viz.py'],
    )


text:
/*
 * DESCRIPTION
 *
 * The libnms library encapsulates the functuionality required to produce the
 * famous "decrypting text" sceen effect from the 1992 hacker movie "Sneakers".
 * For more, go to: https://github.com/bartobri/libnms
 */

#define _XOPEN_SOURCE 700

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <ctype.h>
#include <stdbool.h>
#include <time.h>
#include <locale.h>
#include <wchar.h>
#include "nms.h"

// Color identifiers
#define COLOR_BLACK   0
#define COLOR_RED     1
#define COLOR_GREEN   2
#define COLOR_YELLOW  3
#define COLOR_BLUE    4
#define COLOR_MAGENTA 5
#define COLOR_CYAN    6
#define COLOR_WHITE   7

// Macros for VT100 codes
#define CLEAR_SCR()          printf("\033[2J")           // Clear Screen
#define CURSOR_HOME()        printf("\033[H")            // Move cursor to home position (0,0)
#define CURSOR_MOVE(x,y)     printf("\033[%i;%iH", x, y) // Move cursor to x,y
#define BEEP()               printf("\a");               // terminal bell
#define BOLD()               printf("\033[1m")           // Cursor bold
#define FOREGROUND_COLOR(x)  printf("\033[3%im", x)      // Set foreground color
#define CLEAR_ATTR()         printf("\033[0m")           // Clear bold/color attributes
#define SCREEN_SAVE()        printf("\033[?47h")         // Save screen display
#define SCREEN_RESTORE()     printf("\033[?47l")         // Restore screen to previously saved state
#define CURSOR_SAVE()        printf("\033[s")            // Save cursor position
#define CURSOR_RESTORE()     printf("\033[u")            // Restore cursor position
#define CURSOR_HIDE()        printf("\033[?25l")         // Hide cursor
#define CURSOR_SHOW()        printf("\033[?25h")         // Unhide cursor

// Program settings
#define TYPE_EFFECT_SPEED    4     // miliseconds per char
#define JUMBLE_SECONDS       2     // number of seconds for jumble effect
#define JUMBLE_LOOP_SPEED    35    // miliseconds between each jumble
#define REVEAL_LOOP_SPEED    50    // miliseconds between each reveal loop
#define MASK_CHAR_COUNT      218   // Total characters in maskCharTable[] array.

// Character attribute structure, linked list. Keeps track of every
// character's attributes required for rendering and decryption effect.
struct charAttr {
	char *source;
	char *mask;
	int width;
	int is_space;
	int time;
	struct charAttr *next;
};

// Static function prototypes
static void nms_sleep(int);
static int  nms_term_rows(void);
static int  nms_term_cols(void);
static void nms_set_terminal(int s);
static void nms_clear_input(void);
static char nms_get_char(void);
static int  nms_get_cursor_row(void);

// NMS settings
static int foregroundColor  = COLOR_BLUE;   // Foreground color setting
static char *returnOpts     = NULL;         // Return option setting
static int autoDecrypt      = 0;            // Auto-decrypt flag
static int clearScr         = 0;            // clearScr flag
static int colorOn          = 1;            // Terminal color flag
static int inputPositionX   = -1;           // X coordinate for input position
static int inputPositionY   = -1;           // Y coordinate for input position

// Character table representing the character set know as CP437 used by
// the original IBM PC - https://en.wikipedia.org/wiki/Code_page_437
static char *maskCharTable[] = {
	"!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", "~",
	".", "/", ":", ";", "<", "=", ">", "?", "[", "\\", "]", "_", "{", "}",
	"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
	"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
	"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
	"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
	"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
	"\xc3\x87", "\xc3\xbc", "\xc3\xa9", "\xc3\xa2", "\xc3\xa4", "\xc3\xa0",
	"\xc3\xa5", "\xc3\xa7", "\xc3\xaa", "\xc3\xab", "\xc3\xa8", "\xc3\xaf",
	"\xc3\xae", "\xc3\xac", "\xc3\x84", "\xc3\x85", "\xc3\x89", "\xc3\xa6",
	"\xc3\x86", "\xc3\xb4", "\xc3\xb6", "\xc3\xb2", "\xc3\xbb", "\xc3\xb9",
	"\xc3\xbf", "\xc3\x96", "\xc3\x9c", "\xc2\xa2", "\xc2\xa3", "\xc2\xa5",
	"\xc6\x92", "\xc3\xa1", "\xc3\xad", "\xc3\xb3", "\xc3\xba", "\xc3\xb1",
	"\xc3\x91", "\xc2\xaa", "\xc2\xba", "\xc2\xbf", "\xc2\xac", "\xc2\xbd",
	"\xc2\xbc", "\xc2\xa1", "\xc2\xab", "\xc2\xbb", "\xce\xb1", "\xc3\x9f",
	"\xce\x93", "\xcf\x80", "\xce\xa3", "\xcf\x83", "\xc2\xb5", "\xcf\x84",
	"\xce\xa6", "\xce\x98", "\xce\xa9", "\xce\xb4", "\xcf\x86", "\xce\xb5",
	"\xc2\xb1", "\xc3\xb7", "\xc2\xb0", "\xc2\xb7", "\xc2\xb2", "\xc2\xb6",
	"\xe2\x8c\x90", "\xe2\x82\xa7", "\xe2\x96\x91", "\xe2\x96\x92",
	"\xe2\x96\x93", "\xe2\x94\x82", "\xe2\x94\xa4", "\xe2\x95\xa1",
	"\xe2\x95\xa2", "\xe2\x95\x96", "\xe2\x95\x95", "\xe2\x95\xa3",
	"\xe2\x95\x91", "\xe2\x95\x97", "\xe2\x95\x9d", "\xe2\x95\x9c",
	"\xe2\x95\x9b", "\xe2\x94\x90", "\xe2\x94\x94", "\xe2\x94\xb4",
	"\xe2\x94\xac", "\xe2\x94\x9c", "\xe2\x94\x80", "\xe2\x94\xbc",
	"\xe2\x95\x9e", "\xe2\x95\x9f", "\xe2\x95\x9a", "\xe2\x95\x94",
	"\xe2\x95\xa9", "\xe2\x95\xa6", "\xe2\x95\xa0", "\xe2\x95\x90",
	"\xe2\x95\xac", "\xe2\x95\xa7", "\xe2\x95\xa8", "\xe2\x95\xa4",
	"\xe2\x95\xa7", "\xe2\x95\x99", "\xe2\x95\x98", "\xe2\x95\x92",
	"\xe2\x95\x93", "\xe2\x95\xab", "\xe2\x95\xaa", "\xe2\x94\x98",
	"\xe2\x94\x8c", "\xe2\x96\x88", "\xe2\x96\x84", "\xe2\x96\x8c",
	"\xe2\x96\x90", "\xe2\x96\x80", "\xe2\x88\x9e", "\xe2\x88\xa9",
	"\xe2\x89\xa1", "\xe2\x89\xa5", "\xe2\x89\xa4", "\xe2\x8c\xa0",
	"\xe2\x8c\xa1", "\xe2\x89\x88", "\xe2\x88\x99", "\xe2\x88\x9a",
	"\xe2\x81\xbf", "\xe2\x96\xa0"
};

/*
 * nms_exec() - This function is passed a pointer to a character string
 * and displays the contents of the string in a way that mimicks the
 * "decrypting text" effect in the 1992 movie Sneakers. It returns the
 * last character pressed by the user.
 */
char nms_exec(char *string) {
	struct charAttr *list_pointer = NULL;
	struct charAttr *list_head    = NULL;
	struct charAttr *list_temp    = NULL;
	int i, revealed = 0;
	int maxRows, maxCols, curRow, curCol, origRow = 0, origCol = 0;
	char ret = 0;

	// Error if we have an empty string.
	if (string == NULL || string[0] == '\0') {
		fprintf(stderr, "Error. Empty string.\n");
		return 0;
	}

	// Reassociate STDIN to the terminal is needed
	if (!isatty(STDIN_FILENO) && !freopen ("/dev/tty", "r", stdin)) {
		fprintf(stderr, "Error. Can't associate STDIN with terminal.\n");
		return 0;
	}

	// Turn off terminal echo and line buffering
	nms_set_terminal(0);

	// Needed for UTF-8 support
	setlocale(LC_ALL, "");

	// Get terminal window rows/cols
	maxRows = nms_term_rows();
	maxCols = nms_term_cols();

	// Seed my random number generator with the current time
	srand(time(NULL));

	// Get cursor position if we are not clearing the screen
	if (!clearScr) {
		origRow = nms_get_cursor_row();

		// nms_get_cursor_row() may display output in some terminals. So
		// we need to reposition the cursor to the start of the row.
		CURSOR_MOVE(origRow, origCol);
	}

	// Assign current row/col positions
	curRow = origRow;
	curCol = origCol;

	// Geting input
	for (i = 0; string[i] != '\0'; ++i) {

		// Don't go beyond maxRows
		if (curRow - origRow >= maxRows - 1) {
			break;
		}

		// Allocate memory for next list link
		if (list_pointer == NULL) {
			list_pointer = malloc(sizeof(struct charAttr));
			list_head = list_pointer;
		} else {
			list_pointer->next = malloc(sizeof(struct charAttr));
			list_pointer = list_pointer->next;
		}

		// Get character's byte-length and store character.
		if (mblen(&string[i], 4) > 0) {
			list_pointer->source = malloc(mblen(&string[i], 4) + 1);
			strncpy(list_pointer->source, &string[i], mblen(&string[i], 4));
			list_pointer->source[mblen(&string[i], 4)] = '\0';
			i += (mblen(&string[i], 4) - 1);
		} else {
			fprintf(stderr, "Unknown character encountered. Quitting.\n");
			nms_set_terminal(1);
			return 0;
		}

		// Set flag if we have a whitespace character
		if (strlen(list_pointer->source) == 1 && isspace(list_pointer->source[0]))
			list_pointer->is_space = 1;
		else
			list_pointer->is_space = 0;

		// Set initial mask chharacter
		list_pointer->mask = maskCharTable[rand() % MASK_CHAR_COUNT];

		// Set reveal time
		list_pointer->time = rand() % 5000;

		// Set character column width
		wchar_t widec[sizeof(list_pointer->source)] = {};
		mbstowcs(widec, list_pointer->source, sizeof(list_pointer->source));
		list_pointer->width = wcwidth(*widec);

		// Set next node to null
		list_pointer->next = NULL;

		// Track row count
		if (string[i] == '\n' || (curCol += list_pointer->width) > maxCols) {
			curCol = 0;
			curRow++;
			if (curRow == maxRows + 1 && origRow > 0) {
				origRow--;
				curRow--;
			}
		}
	}

	// Save terminal state, clear screen, and home/hide the cursor
	if (clearScr) {
		CURSOR_SAVE();
		SCREEN_SAVE();
		CLEAR_SCR();
		CURSOR_HOME();
		CURSOR_HIDE();
	}

	// Print mask characters with 'type effect'
	for (list_pointer = list_head; list_pointer != NULL; list_pointer = list_pointer->next) {

		// Print mask character (or space)
		if (list_pointer->is_space) {
			printf("%s", list_pointer->source);
			continue;
		}

		// print mask character
		printf("%s", list_pointer->mask);
		if (list_pointer->width == 2) {
			printf("%s", maskCharTable[rand() % MASK_CHAR_COUNT]);
		}

		// flush output and sleep
		fflush(stdout);
		nms_sleep(TYPE_EFFECT_SPEED);
	}

	// Flush any input up to this point
	nms_clear_input();

	// If autoDecrypt flag is set, we sleep. Otherwise require user to
	// press a key to continue.
	if (autoDecrypt)
		sleep(1);
	else
		nms_get_char();

	// Jumble loop
	for (i = 0; i < (JUMBLE_SECONDS * 1000) / JUMBLE_LOOP_SPEED; ++i) {

		// Move cursor to home position
		if (clearScr) {
			CURSOR_HOME();
		} else {
			CURSOR_MOVE(origRow, origCol);
		}

		// Print new mask for all characters
		for (list_pointer = list_head; list_pointer != NULL; list_pointer = list_pointer->next) {

			// Print mask character (or space)
			if (list_pointer->is_space) {
				printf("%s", list_pointer->source);
				continue;
			}

			// print new mask character
			printf("%s", maskCharTable[rand() % MASK_CHAR_COUNT]);
			if (list_pointer->width == 2) {
				printf("%s", maskCharTable[rand() % MASK_CHAR_COUNT]);
			}
		}

		// flush output and sleep
		fflush(stdout);
		nms_sleep(JUMBLE_LOOP_SPEED);
	}

	// Reveal loop
	while (!revealed) {

		// Move cursor to home position
		if (clearScr) {
			CURSOR_HOME();
		} else {
			CURSOR_MOVE(origRow, origCol);
		}

		// Set revealed flag
		revealed = 1;

		for (list_pointer = list_head; list_pointer != NULL; list_pointer = list_pointer->next) {

			// Print mask character (or space)
			if (list_pointer->is_space) {
				printf("%s", list_pointer->source);
				continue;
			}

			// If we still have time before the char is revealed, display the mask
			if (list_pointer->time > 0) {

				// Change the mask randomly
				if (list_pointer->time < 500) {
					if (rand() % 3 == 0) {
						list_pointer->mask = maskCharTable[rand() % MASK_CHAR_COUNT];
					}
				} else {
					if (rand() % 10 == 0) {
						list_pointer->mask = maskCharTable[rand() % MASK_CHAR_COUNT];
					}
				}

				// Print mask
				printf("%s", list_pointer->mask);

				// Decrement reveal time
				list_pointer->time -= REVEAL_LOOP_SPEED;

				// Unset revealed flag
				revealed = 0;
			} else {

				// Set bold and foreground color for character reveal
				BOLD();
				if (colorOn) {
					FOREGROUND_COLOR(foregroundColor);
				}

				// print source character
				printf("%s", list_pointer->source);

				// Unset foreground color
				CLEAR_ATTR();
			}
		}

		// flush output and sleep
		fflush(stdout);
		nms_sleep(REVEAL_LOOP_SPEED);
	}

	// Flush any input up to this point
	nms_clear_input();

	// Check if user must select from a set of options
	if (returnOpts != NULL && strlen(returnOpts) > 0) {

		// Position cursor if necessary
		if (inputPositionY >= 0 && inputPositionX >= 0) {
			CURSOR_MOVE(inputPositionY, inputPositionX);
		}

		CURSOR_SHOW();

		// Get and validate user selection
		while (strchr(returnOpts, ret = nms_get_char()) == NULL) {
			BEEP();
		}

	}

	// User must press a key to continue when clearSrc is set
	// without returnOpts
	else if (clearScr) {
		nms_get_char();
	}

	// Restore screen and cursor is clearSrc is set
	if (clearScr) {
		SCREEN_RESTORE();
		CURSOR_SHOW();
		CURSOR_RESTORE();
	}

	// Turn on terminal echo and line buffering
	nms_set_terminal(1);

	// Freeing the list.
	list_pointer = list_head;
	while (list_pointer != NULL) {
		list_temp = list_pointer;
		list_pointer = list_pointer->next;
		free(list_temp->source);
		free(list_temp);
	}

	return ret;
}

/*
 * nms_set_foreground_color() sets the foreground color of the unencrypted
 * characters as they are revealed to the color indicated by the 'color'
 * argument. Valid arguments are "white", "yellow", "magenta", "blue",
 * "green", "red", and "cyan". This function will default to blue if
 * passed an invalid color. No value is returned.
 */
void nms_set_foreground_color(char *color) {

	if(strcmp("white", color) == 0)
		foregroundColor =  COLOR_WHITE;
	else if(strcmp("yellow", color) == 0)
		foregroundColor = COLOR_YELLOW;
	else if(strcmp("black", color) == 0)
		foregroundColor = COLOR_BLACK;
	else if(strcmp("magenta", color) == 0)
		foregroundColor = COLOR_MAGENTA;
	else if(strcmp("blue", color) == 0)
		foregroundColor = COLOR_BLUE;
	else if(strcmp("green", color) == 0)
		foregroundColor = COLOR_GREEN;
	else if(strcmp("red", color) == 0)
		foregroundColor = COLOR_RED;
	else if(strcmp("cyan", color) == 0)
		foregroundColor = COLOR_CYAN;
	else
		foregroundColor = COLOR_BLUE;
}

/*
 * nms_set_return_opts() takes a character sting and copies it to the
 * returnOpts setting used by nms_exec().
 */
void nms_set_return_opts(char *opts) {
	returnOpts = realloc(returnOpts, strlen(opts) + 1);
	strcpy(returnOpts, opts);
}

/*
 * nms_set_auto_decrypt() sets the autoDecrypt flag according to the
 * true/false value of the 'setting' argument.
 */
void nms_set_auto_decrypt(int setting) {
	if (setting)
		autoDecrypt = 1;
	else
		autoDecrypt = 0;
}

/*
 * nms_set_clear_scr() sets the clearScr flag according to the
 * true/false value of the 'setting' argument.
 */
void nms_set_clear_scr(int setting) {
	if (setting)
		clearScr = 1;
	else
		clearScr = 0;
}

/*
 * nms_set_color() sets the colorOn flag according to the
 * true/false value of the 'setting' argument.
 */
void nms_use_color(int setting) {
	if (setting)
		colorOn = 1;
	else
		colorOn = 0;
}

/*
 * nms_set_input_position() sets the desired coordinate of the cursor in
 * the terminal when accepting user input after nms_exec() reveals the
 * unencrypted characters.
 */
void nms_set_input_position(int x, int y) {
	if (x >= 0 && y >= 0) {
		inputPositionX = x;
		inputPositionY = y;
	}
}

/*
 * nms_sleep() sleeps for the number of miliseconds indicated by 't'.
 */
static void nms_sleep(int t) {
	struct timespec ts;

	ts.tv_sec = t / 1000;
	ts.tv_nsec = (t % 1000) * 1000000;

	nanosleep(&ts, NULL);
}

/*
 * nms_term_rows() gets and returns the number of rows in the current
 * terminal window.
 */
static int nms_term_rows(void) {
	struct winsize w;
	ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

	return w.ws_row;
}

/*
 * nms_term_cols() gets and returns the number of cols in the current
 * terminal window.
 */
static int nms_term_cols(void) {
	struct winsize w;
	ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

	return w.ws_col;
}

/*
 * nms_set_terminal() turns off terminal echo and line buffering when
 * passed an integer value that evaluates to true. It restores the
 * original terminal values when passed an integer value that evaluates
 * to false.
 */
static void nms_set_terminal(int s) {
	struct termios tp;
	static struct termios save;
	static int state = 1;

	if (s == 0) {
		if (tcgetattr(STDIN_FILENO, &tp) == -1) {
			return;
		}

		save = tp;

		tp.c_lflag &=(~ICANON & ~ECHO);

		if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &tp) == -1) {
			return;
		}
	} else {
		if (state == 0 && tcsetattr(STDIN_FILENO, TCSANOW, &save) == -1)
			return;
	}

	state = s;
}

/*
 * nms_clear_input() clears the input buffer of all characters up to
 * the EOF character.
 */
static void nms_clear_input(void) {
	int i;

	ioctl(STDIN_FILENO, FIONREAD, &i);

	while (i > 0) {
		getchar();
		--i;
	}
}

/*
 * nms_get_char() returns the next character in the input buffer. In the
 * case of an EOF character, it blocks until the user presses a key.
 */
static char nms_get_char(void) {
	struct timespec ts;
	int t = 50;
	int c;

	ts.tv_sec = t / 1000;
	ts.tv_nsec = (t % 1000) * 1000000;

	while ((c = getchar()) == EOF) {
		nanosleep(&ts, NULL);
	}

	return (char)c;
}

/*
 * nms_get_cursor_row() returns the row position of the cursor as reported
 * by the terminal program via the ANSI escape code
 */
static int nms_get_cursor_row(void) {
	int i, r = 0;
	int row = 0;
	char buf[10];
	char *cmd = "\033[6n";

	memset(buf, 0, sizeof(buf));

	write(STDOUT_FILENO, cmd, sizeof(cmd));

	r = read(STDIN_FILENO, buf, sizeof(buf));

	for (i = 0; i < r; ++i) {
		if (buf[i] == 27 || buf[i] == '[') {
			continue;
		}

		if (buf[i] >= '0' && buf[i] <= '9') {
			row = (row * 10) + (buf[i] - '0');
		}

		if (buf[i] == ';' || buf[i] == 'R' || buf[i] == 0) {
			break;
		}
	}

	return row;
}


text:
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.template import Library

register = Library()

@register.inclusion_tag('quotes/parts/user_buttons.html', takes_context = True)
def user_buttons(context):
    quote = context['quote']

    return {
        'edit_url': reverse('board:quote:edit', kwargs = {'board': quote.board.slug, 'pk': quote.pk, }),
        'delete_modal_id': 'delete_modal_%d' % (quote.pk, ),
    }

@register.inclusion_tag('quotes/parts/title.html', takes_context = True)
def quote_title(context):
    quote = context['quote']
    with_link = context.get('with_link', True)

    detail_url = ''
    if with_link:
        detail_url = reverse('board:quote:detail', kwargs = {'board': quote.board.slug, 'pk': quote.pk, })

    return {
        'quote_title': str(quote),
        'detail_url': detail_url,
    }

@register.inclusion_tag('quotes/parts/body.html', takes_context = True)
def quote_body(context):
    return {'quote_text': context['quote'].text, }

@register.inclusion_tag('quotes/parts/delete_modal.html', takes_context = True)
def delete_modal(context):
    quote = context['quote']

    return {
        'delete_modal_id': 'delete_modal_%d' % (quote.id, ),
        'delete_url': reverse('board:quote:delete', kwargs = {'board': quote.board.slug, 'pk': quote.pk, }),
    }

@register.inclusion_tag('quotes/parts/comments.html', takes_context = True)
def comments(context):
    quote = context['quote']

    return {
        'board': quote.board,
        'quote_pk': quote.pk,
        'comments': quote.comments.all(),
        'user': context['user'],
    }


text:
import {Link} from 'gatsby'
import {colors} from '../theme'
import styled from 'styled-components'

export const LinkButton = styled(Link)`
  background-color: ${colors.red};
  color: ${colors.white};
  font-size: 20px;
  border-radius: 1px;
  padding: 20px;
  box-shadow: 8px 8px 0 rgba(251,59,73,.2);
  text-decoration: none;
  text-align: center;
  display: inline-block;
  min-width: 180px;
  font-weight: 700;
  transition: opacity .5s;

  &:hover {
    opacity: .8;
  }
`


text:
package com.clicktravel.cheddar.infrastructure.persistence.filestore;

import java.util.List;

import com.clicktravel.cheddar.infrastructure.persistence.database.exception.NonExistentItemException;
import com.clicktravel.cheddar.infrastructure.persistence.exception.PersistenceResourceFailureException;

public interface FileStore {

    FileItem read(FilePath filePath) throws NonExistentItemException;

    /**
     * Write a {@link FileItem} to the given {@link FilePath}. The name of the file is taken from the given
     * {@link FileItem}.
     *
     * @param filePath {@link FilePath} to write the file to.
     * @param fileItem {@link FileItem} to write.
     */
    void write(FilePath filePath, FileItem fileItem);

    void delete(FilePath filePath) throws NonExistentItemException;

    /**
     * Lists the contents of a FileStore.
     *
     * @param directory The directory to list the contents of.
     * @param prefix The prefix to limit the results by.
     * @return A list of the contents of the FileStore.
     *
     * @throws PersistenceResourceFailureException If an error occurred listing the directory.
     */
    List<FilePath> list(String directory, String prefix) throws PersistenceResourceFailureException;
}


text:
package net.savantly.sprout.module.content.model.webPageContent;

import java.util.Set;

import org.springframework.data.rest.core.config.Projection;

import net.savantly.sprout.module.content.model.contentItem.ContentItemImpl;

@Projection(name="fullWebPageContent", types= {WebPageContent.class})
public interface FullWebPageContent {
	String getId();
	String getPlaceHolderId();
	boolean isNew();
	Set<ContentItemImpl> getContentItems();

}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net.Sockets;
using System.Text;
using Microsoft.TemplateEngine.Core.Contracts;
using Microsoft.TemplateEngine.Core.Matching;

namespace Microsoft.TemplateEngine.Core.Util
{
    public class ProcessorState : IProcessorState
    {
        private Stream _source;
        private readonly Stream _target;
        private readonly TrieEvaluator<OperationTerminal> _trie;
        private Encoding _encoding;
        private static readonly ConcurrentDictionary<IReadOnlyList<IOperationProvider>, Dictionary<Encoding, Trie<OperationTerminal>>> TrieLookup = new ConcurrentDictionary<IReadOnlyList<IOperationProvider>, Dictionary<Encoding, Trie<OperationTerminal>>>();
        private static readonly ConcurrentDictionary<IReadOnlyList<IOperationProvider>, List<string>> OperationsToExplicitlySetOnByDefault = new ConcurrentDictionary<IReadOnlyList<IOperationProvider>, List<string>>();
        private readonly int _flushThreshold;

        public IEngineConfig Config { get; }

        public byte[] CurrentBuffer { get; }

        public int CurrentBufferLength { get; private set; }

        public int CurrentBufferPosition { get; private set; }

        public int CurrentSequenceNumber { get; private set; }

        public IEncodingConfig EncodingConfig { get; private set; }

        public Encoding Encoding
        {
            get { return _encoding; }
            set
            {
                _encoding = value;
                EncodingConfig = new EncodingConfig(Config, _encoding);
            }
        }

        public ProcessorState(Stream source, Stream target, int bufferSize, int flushThreshold, IEngineConfig config, IReadOnlyList<IOperationProvider> operationProviders)
        {
            if (source.CanSeek)
            {
                try
                {
                    if (source.Length < bufferSize)
                    {
                        bufferSize = (int) source.Length;
                    }
                }
                catch
                {
                    //The stream may not support getting the length property (in NetworkStream for instance, which throw a NotSupportedException), suppress any errors in
                    //  accessing the property and continue with the specified buffer size
                }
            }
            //Buffer has to be at least as large as the largest BOM we could expect
            else if (bufferSize < 4)
            {
                bufferSize = 4;
            }

            _source = source;
            _target = target;
            Config = config;
            _flushThreshold = flushThreshold;
            CurrentBuffer = new byte[bufferSize];
            CurrentBufferLength = source.Read(CurrentBuffer, 0, CurrentBuffer.Length);

            byte[] bom;
            Encoding encoding = EncodingUtil.Detect(CurrentBuffer, CurrentBufferLength, out bom);
            Encoding = encoding;
            CurrentBufferPosition = bom.Length;
            CurrentSequenceNumber = bom.Length;
            target.Write(bom, 0, bom.Length);

            bool explicitOnConfigurationRequired = false;
            Dictionary<Encoding, Trie<OperationTerminal>> byEncoding = TrieLookup.GetOrAdd(operationProviders, x => new Dictionary<Encoding, Trie<OperationTerminal>>());
            List<string> turnOnByDefault = OperationsToExplicitlySetOnByDefault.GetOrAdd(operationProviders, x =>
            {
                explicitOnConfigurationRequired = true;
                return new List<string>();
            });

            if (!byEncoding.TryGetValue(encoding, out Trie<OperationTerminal> trie))
            {
                trie = new Trie<OperationTerminal>();

                for (int i = 0; i < operationProviders.Count; ++i)
                {
                    IOperation op = operationProviders[i].GetOperation(encoding, this);

                    if (op != null)
                    {
                        for (int j = 0; j < op.Tokens.Count; ++j)
                        {
                            if (op.Tokens[j] != null)
                            {
                                trie.AddPath(op.Tokens[j].Value, new OperationTerminal(op, j, op.Tokens[j].Length, op.Tokens[j].Start, op.Tokens[j].End));
                            }
                        }

                        if (explicitOnConfigurationRequired && op.IsInitialStateOn && !string.IsNullOrEmpty(op.Id))
                        {
                            turnOnByDefault.Add(op.Id);
                        }
                    }
                }

                foreach(string state in turnOnByDefault)
                {
                    config.Flags[state] = true;
                }

                byEncoding[encoding] = trie;
            }

            _trie = new TrieEvaluator<OperationTerminal>(trie);

            if (bufferSize < _trie.MaxLength + 1)
            {
                byte[] tmp = new byte[_trie.MaxLength + 1];
                Buffer.BlockCopy(CurrentBuffer, CurrentBufferPosition, tmp, 0, CurrentBufferLength - CurrentBufferPosition);
                int nRead = _source.Read(tmp, CurrentBufferLength - CurrentBufferPosition, tmp.Length - CurrentBufferLength);
                CurrentBuffer = tmp;
                CurrentBufferLength += nRead - bom.Length;
                CurrentBufferPosition = 0;
                CurrentSequenceNumber = 0;
            }
        }

        public bool AdvanceBuffer(int bufferPosition)
        {
            if(CurrentBufferLength == 0 || bufferPosition == 0)
            {
                return false;
            }

            //The number of bytes away from the current buffer position being
            //  retargeted to the buffer head
            int netMove = bufferPosition - CurrentBufferPosition;
            //Since the CurrentSequenceNumber and CurrentBufferPosition are
            //  different mappings over the same value, the same net move
            //  applies to the current sequence number
            CurrentSequenceNumber += netMove;
            //Calculate the number of bytes at the end of the buffer that
            //  should be preserved
            int bytesToPreserveInBuffer = CurrentBufferLength - bufferPosition;

            if (CurrentBufferLength < CurrentBuffer.Length && bytesToPreserveInBuffer == 0)
            {
                CurrentBufferLength = 0;
                CurrentBufferPosition = 0;
                return false;
            }

            //If we actually have to preserve any data, shift it to the start
            if (bytesToPreserveInBuffer > 0)
            {
                //Shift the relevant number of bytes back to the head of the buffer
                Buffer.BlockCopy(CurrentBuffer, bufferPosition, CurrentBuffer, 0, bytesToPreserveInBuffer);
            }

            //Fill the remaining spaces in the buffer with new data, save how
            //  many we've read for recalculating the new effective buffer size
            int nRead = _source.Read(CurrentBuffer, bytesToPreserveInBuffer, CurrentBufferLength - bytesToPreserveInBuffer);
            CurrentBufferLength = bytesToPreserveInBuffer + nRead;

            //The new buffer position is set to point at the byte that buffer
            //  position pointed at (which is now at the head of the buffer)
            CurrentBufferPosition = 0;

            return true;
        }

        public bool Run()
        {
            int nextSequenceNumberThatCouldBeWritten = CurrentSequenceNumber;
            int bytesWrittenSinceLastFlush = 0;
            bool anyOperationsExecuted = false;

            while (true)
            {
                //Loop until we run out of data in the buffer
                while (CurrentBufferPosition < CurrentBufferLength)
                {
                    int posedPosition = CurrentSequenceNumber;
                    bool skipAdvanceBuffer = false;
                    if (_trie.Accept(CurrentBuffer[CurrentBufferPosition], ref posedPosition, out TerminalLocation<OperationTerminal> terminal))
                    {
                        IOperation operation = terminal.Terminal.Operation;
                        int matchLength = terminal.Terminal.End - terminal.Terminal.Start + 1;
                        int handoffBufferPosition = CurrentBufferPosition + matchLength - (CurrentSequenceNumber - terminal.Location);

                        if (terminal.Location > nextSequenceNumberThatCouldBeWritten)
                        {
                            int toWrite = terminal.Location - nextSequenceNumberThatCouldBeWritten;
//Console.WriteLine("UnmatchedBlock");
//string text = System.Text.Encoding.UTF8.GetString(CurrentBuffer, handoffBufferPosition - toWrite - matchLength, toWrite).Replace("\0", "\\0");
//Console.WriteLine(text);
                            _target.Write(CurrentBuffer, handoffBufferPosition - toWrite - matchLength, toWrite);
                            bytesWrittenSinceLastFlush += toWrite;
                            nextSequenceNumberThatCouldBeWritten = posedPosition - matchLength + 1;
                        }

                        if(operation.Id == null || (Config.Flags.TryGetValue(operation.Id, out bool opEnabledFlag) && opEnabledFlag))
                        {
                            CurrentSequenceNumber += handoffBufferPosition - CurrentBufferPosition;
                            CurrentBufferPosition = handoffBufferPosition;
                            posedPosition = handoffBufferPosition;
                            int bytesWritten = operation.HandleMatch(this, CurrentBufferLength, ref posedPosition, terminal.Terminal.Token, _target);
                            bytesWrittenSinceLastFlush += bytesWritten;

                            CurrentSequenceNumber += posedPosition - CurrentBufferPosition;
                            CurrentBufferPosition = posedPosition;
                            nextSequenceNumberThatCouldBeWritten = CurrentSequenceNumber;
                            skipAdvanceBuffer = true;
                            anyOperationsExecuted = true;
                        }
                        else
                        {
                            int oldSequenceNumber = CurrentSequenceNumber;
                            CurrentSequenceNumber = terminal.Location + terminal.Terminal.End + 1;
                            CurrentBufferPosition += CurrentSequenceNumber - oldSequenceNumber;
                        }

                        if (bytesWrittenSinceLastFlush >= _flushThreshold)
                        {
                            _target.Flush();
                            bytesWrittenSinceLastFlush = 0;
                        }
                    }

                    if (!skipAdvanceBuffer)
                    {
                        ++CurrentSequenceNumber;
                        ++CurrentBufferPosition;
                    }
                }

                //Calculate the sequence number at the head of the buffer
                int headSequenceNumber = CurrentSequenceNumber - CurrentBufferPosition;
                int bufferPositionToAdvanceTo = _trie.OldestRequiredSequenceNumber - headSequenceNumber;
                int numberOfUncommittedBytesBeforeThePositionToAdvanceTo = _trie.OldestRequiredSequenceNumber - nextSequenceNumberThatCouldBeWritten;

                //If we'd advance data out of the buffer that hasn't been
                //  handled already, write it out
                if (numberOfUncommittedBytesBeforeThePositionToAdvanceTo > 0)
                {
                    int toWrite = numberOfUncommittedBytesBeforeThePositionToAdvanceTo;
// Console.WriteLine("AdvancePreserve");
// Console.WriteLine($"nextSequenceNumberThatCouldBeWritten {nextSequenceNumberThatCouldBeWritten}");
// Console.WriteLine($"headSequenceNumber {headSequenceNumber}");
// Console.WriteLine($"bufferPositionToAdvanceTo {bufferPositionToAdvanceTo}");
// Console.WriteLine($"numberOfUncommittedBytesBeforeThePositionToAdvanceTo {numberOfUncommittedBytesBeforeThePositionToAdvanceTo}");
// Console.WriteLine($"CurrentBufferPosition {CurrentBufferPosition}");
// Console.WriteLine($"CurrentBufferLength {CurrentBufferLength}");
// Console.WriteLine($"CurrentBuffer.Length {CurrentBuffer.Length}");
// string text = System.Text.Encoding.UTF8.GetString(CurrentBuffer, bufferPositionToAdvanceTo - toWrite, toWrite).Replace("\0", "\\0");
// Console.WriteLine(text);
                    _target.Write(CurrentBuffer, bufferPositionToAdvanceTo - toWrite, toWrite);
                    bytesWrittenSinceLastFlush += toWrite;
                    nextSequenceNumberThatCouldBeWritten = _trie.OldestRequiredSequenceNumber;
                }

                //We ran out of data in the buffer, so attempt to advance
                //  if we fail,
                if (!AdvanceBuffer(bufferPositionToAdvanceTo))
                {
                    int posedPosition = CurrentSequenceNumber;
                    _trie.FinalizeMatchesInProgress(ref posedPosition, out TerminalLocation<OperationTerminal> terminal);

                    while (terminal != null)
                    {
                        IOperation operation = terminal.Terminal.Operation;
                        int matchLength = terminal.Terminal.End - terminal.Terminal.Start + 1;
                        int handoffBufferPosition = CurrentBufferPosition + matchLength - (CurrentSequenceNumber - terminal.Location);

                        if (terminal.Location > nextSequenceNumberThatCouldBeWritten)
                        {
                            int toWrite = terminal.Location - nextSequenceNumberThatCouldBeWritten;
// Console.WriteLine("TailUnmatchedBlock");
// string text = System.Text.Encoding.UTF8.GetString(CurrentBuffer, handoffBufferPosition - toWrite - matchLength, toWrite).Replace("\0", "\\0");
// Console.WriteLine(text);
                            _target.Write(CurrentBuffer, handoffBufferPosition - toWrite - matchLength, toWrite);
                            bytesWrittenSinceLastFlush += toWrite;
                            nextSequenceNumberThatCouldBeWritten = terminal.Location;
                        }

                        if (operation.Id == null || (Config.Flags.TryGetValue(operation.Id, out bool opEnabledFlag) && opEnabledFlag))
                        {
                            CurrentSequenceNumber += handoffBufferPosition - CurrentBufferPosition;
                            CurrentBufferPosition = handoffBufferPosition;
                            posedPosition = handoffBufferPosition;
                            int bytesWritten = operation.HandleMatch(this, CurrentBufferLength, ref posedPosition, terminal.Terminal.Token, _target);
                            bytesWrittenSinceLastFlush += bytesWritten;

                            CurrentSequenceNumber += posedPosition - CurrentBufferPosition;
                            CurrentBufferPosition = posedPosition;
                            nextSequenceNumberThatCouldBeWritten = CurrentSequenceNumber;
                            anyOperationsExecuted = true;
                        }
                        else
                        {
                            int oldSequenceNumber = CurrentSequenceNumber;
                            CurrentSequenceNumber = terminal.Location + terminal.Terminal.End + 1;
                            CurrentBufferPosition += CurrentSequenceNumber - oldSequenceNumber;
                        }

                        _trie.FinalizeMatchesInProgress(ref posedPosition, out terminal);
                    }

                    break;
                }
            }

            int endSequenceNumber = CurrentSequenceNumber - CurrentBufferPosition + CurrentBufferLength;
            if (endSequenceNumber > nextSequenceNumberThatCouldBeWritten)
            {
                int toWrite = endSequenceNumber - nextSequenceNumberThatCouldBeWritten;
// Console.WriteLine("LastBlock");
// string text = System.Text.Encoding.UTF8.GetString(CurrentBuffer, CurrentBufferLength - toWrite, toWrite).Replace("\0", "\\0");
// Console.WriteLine(text);
                _target.Write(CurrentBuffer, CurrentBufferLength - toWrite, toWrite);
            }

            _target.Flush();
            return anyOperationsExecuted;
        }

        public void SeekBackUntil(ITokenTrie match)
        {
            SeekBackUntil(match, false);
        }

        public void SeekBackUntil(ITokenTrie match, bool consume)
        {
            byte[] buffer = new byte[match.MaxLength];
            while (_target.Position > 0)
            {
                if (_target.Position < buffer.Length)
                {
                    _target.Position = 0;
                }
                else
                {
                    _target.Position -= buffer.Length;
                }

                int nRead = _target.Read(buffer, 0, buffer.Length);
                int best = -1;
                int bestPos = -1;
                for (int i = nRead - match.MinLength; i >= 0; --i)
                {
                    int token;
                    int ic = i;
                    if (match.GetOperation(buffer, nRead, ref ic, out token) && ic >= bestPos)
                    {
                        bestPos = ic;
                        best = token;
                    }
                }

                if (best != -1)
                {
                    _target.Position -= nRead - bestPos + (consume ? match.TokenLength[best] : 0);
                    _target.SetLength(_target.Position);
                    return;
                }

                //Back up the amount we already read to get a new window of data in
                if (_target.Position < buffer.Length)
                {
                    _target.Position = 0;
                }
                else
                {
                    _target.Position -= buffer.Length;
                }
            }

            if (_target.Position == 0)
            {
                _target.SetLength(0);
            }
        }

        public void SeekBackWhile(ITokenTrie match)
        {
            byte[] buffer = new byte[match.MaxLength];
            while (_target.Position > 0)
            {
                if (_target.Position < buffer.Length)
                {
                    _target.Position = 0;
                }
                else
                {
                    _target.Position -= buffer.Length;
                }

                int nRead = _target.Read(buffer, 0, buffer.Length);
                bool anyMatch = false;
                int token = -1;
                int i = nRead - match.MinLength;

                for (; i >= 0; --i)
                {
                    if (match.GetOperation(buffer, nRead, ref i, out token))
                    {
                        i -= match.TokenLength[token];
                        anyMatch = true;
                        break;
                    }
                }

                if (!anyMatch || (token != -1 && i + match.TokenLength[token] != nRead))
                {
                    _target.SetLength(_target.Position);
                    return;
                }

                //Back up the amount we already read to get a new window of data in
                if (_target.Position < buffer.Length)
                {
                    _target.Position = 0;
                }
                else
                {
                    _target.Position -= buffer.Length;
                }
            }

            if (_target.Position == 0)
            {
                _target.SetLength(0);
            }
        }

        public void SeekForwardThrough(ITokenTrie trie, ref int bufferLength, ref int currentBufferPosition)
        {
            BaseSeekForward(trie, ref bufferLength, ref currentBufferPosition, true);
        }

        public void SeekForwardUntil(ITokenTrie trie, ref int bufferLength, ref int currentBufferPosition)
        {
            BaseSeekForward(trie, ref bufferLength, ref currentBufferPosition, false);
        }

        public void SeekForwardWhile(ITokenTrie trie, ref int bufferLength, ref int currentBufferPosition)
        {
            while (bufferLength > trie.MinLength)
            {
                while (currentBufferPosition < bufferLength - trie.MinLength + 1)
                {
                    if (bufferLength == 0)
                    {
                        currentBufferPosition = 0;
                        return;
                    }

                    int token;
                    if (!trie.GetOperation(CurrentBuffer, bufferLength, ref currentBufferPosition, out token))
                    {
                        return;
                    }
                }

                AdvanceBuffer(currentBufferPosition);
                currentBufferPosition = CurrentBufferPosition;
                bufferLength = CurrentBufferLength;
            }
        }

        private void BaseSeekForward(ITokenTrie match, ref int bufferLength, ref int currentBufferPosition, bool consumeToken)
        {
            while (bufferLength >= match.MinLength)
            {
                //Try to get at least the max length of the tree into the buffer
                if (bufferLength - currentBufferPosition < match.MaxLength)
                {
                    AdvanceBuffer(currentBufferPosition);
                    currentBufferPosition = CurrentBufferPosition;
                    bufferLength = CurrentBufferLength;
                }

                int sz = bufferLength == CurrentBuffer.Length ? match.MaxLength : match.MinLength;

                for (; currentBufferPosition < bufferLength - sz + 1; ++currentBufferPosition)
                {
                    if (bufferLength == 0)
                    {
                        currentBufferPosition = 0;
                        return;
                    }

                    int token;
                    if (match.GetOperation(CurrentBuffer, bufferLength, ref currentBufferPosition, out token))
                    {
                        if (!consumeToken)
                        {
                            currentBufferPosition -= match.Tokens[token].Length;
                        }

                        return;
                    }
                }
            }

            //Ran out of places to check and haven't reached the actual match, consume all the way to the end
            currentBufferPosition = bufferLength;
        }

        public void Inject(Stream staged)
        {
            _source = new CombinedStream(staged, _source, inner => _source = inner);
            CurrentBufferLength = _source.Read(CurrentBuffer, 0, CurrentBufferLength);
            CurrentBufferPosition = 0;
        }
    }
}


text:
package dbr

import (
	"fmt"
	"log"
	"time"
)

func ExampleOpen() {
	// create a connection (e.g. "postgres", "mysql", or "sqlite3")
	conn, _ := Open("postgres", "...", nil)
	conn.SetMaxOpenConns(10)

	// create a session for each business unit of execution (e.g. a web request or goworkers job)
	sess := conn.NewSession(nil)

	// create a tx from sessions
	sess.Begin()
}

func ExampleSelect() {
	Select("title", "body").
		From("suggestions").
		OrderBy("id").
		Limit(10)
}

func ExampleSelectBySql() {
	SelectBySql("SELECT `title`, `body` FROM `suggestions` ORDER BY `id` ASC LIMIT 10")
}

func ExampleSelectStmt_Load() {
	// columns are mapped by tag then by field
	type Suggestion struct {
		ID     int64      // id, will be autoloaded by last insert id
		Title  NullString `db:"subject"` // subjects are called titles now
		Url    string     `db:"-"`       // ignored
		secret string     // ignored
	}

	// By default gocraft/dbr converts CamelCase property names to snake_case column_names.
	// You can override this with struct tags, just like with JSON tags.
	// This is especially helpful while migrating from legacy systems.
	var suggestions []Suggestion
	sess := mysqlSession
	sess.Select("*").From("suggestions").Load(&suggestions)
}

func ExampleSelectStmt_Where() {
	// database/sql uses prepared statements, which means each argument
	// in an IN clause needs its own question mark.
	// gocraft/dbr, on the other hand, handles interpolation itself
	// so that you can easily use a single question mark paired with a
	// dynamically sized slice.

	sess := mysqlSession
	ids := []int64{1, 2, 3, 4, 5}
	sess.Select("*").From("suggestions").Where("id IN ?", ids)
}

func ExampleSelectStmt_Join() {
	sess := mysqlSession
	sess.Select("*").From("suggestions").
		Join("subdomains", "suggestions.subdomain_id = subdomains.id")

	sess.Select("*").From("suggestions").
		LeftJoin("subdomains", "suggestions.subdomain_id = subdomains.id")

	// join multiple tables
	sess.Select("*").From("suggestions").
		Join("subdomains", "suggestions.subdomain_id = subdomains.id").
		Join("accounts", "subdomains.accounts_id = accounts.id")
}

func ExampleSelectStmt_As() {
	sess := mysqlSession
	sess.Select("count(id)").From(
		Select("*").From("suggestions").As("count"),
	)
}

func ExampleInsertStmt_Pair() {
	sess := mysqlSession
	sess.InsertInto("suggestions").
		Pair("title", "Gopher").
		Pair("body", "I love go.")
}

func ExampleInsertStmt_Record() {
	type Suggestion struct {
		ID        int64
		Title     NullString
		CreatedAt time.Time
	}
	sugg := &Suggestion{
		Title:     NewNullString("Gopher"),
		CreatedAt: time.Now(),
	}
	sess := mysqlSession
	sess.InsertInto("suggestions").
		Columns("title").
		Record(&sugg).
		Exec()

	// id is set automatically
	fmt.Println(sugg.ID)
}

func ExampleUpdateStmt() {
	sess := mysqlSession
	sess.Update("suggestions").
		Set("title", "Gopher").
		Set("body", "I love go.").
		Where("id = ?", 1)
}

func ExampleDeleteStmt() {
	sess := mysqlSession
	sess.DeleteFrom("suggestions").
		Where("id = ?", 1)
}

func ExampleTx() {
	sess := mysqlSession
	tx, err := sess.Begin()
	if err != nil {
		return
	}
	defer tx.RollbackUnlessCommitted()

	// do stuff...

	tx.Commit()
}

func ExampleAnd() {
	And(
		Or(
			Gt("created_at", "2015-09-10"),
			Lte("created_at", "2015-09-11"),
		),
		Eq("title", "hello world"),
	)
}

func ExampleI() {
	// I, identifier, can be used to quote.
	I("suggestions.id").As("id") // `suggestions`.`id`
}

func ExampleUnion() {
	Union(
		Select("*"),
		Select("*"),
	).As("subquery")
}

func ExampleUnionAll() {
	UnionAll(
		Select("*"),
		Select("*"),
	).As("subquery")
}

func ExampleIterator() {
	type Book struct {
		ID   int
		Name string
	}
	sess := mysqlSession
	// Iterate results
	iter, err := sess.Select("*").From("books").Limit(10).Iterate()
	if err != nil {
		log.Fatalf("iter err %v", err)
	}
	for iter.Next() {
		r := new(Book)
		if err = iter.Scan(r); err != nil {
			log.Fatalf("scan err %v", err)
		}
		fmt.Printf("%#v\n", r)
	}
	if err = iter.Close(); err != nil {
		log.Fatalf("iter close err %v", err)
	}
}


text:
package com.evolveum.midpoint.repo.sql.util;

import com.evolveum.midpoint.repo.sql.data.common.any.*;
import org.hibernate.transform.BasicTransformerAdapter;
import org.hibernate.transform.ResultTransformer;
import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author lazyman
 */
public class GetObjectResult implements Serializable {

    public static final Class[] EXT_COUNT_CLASSES = new Class[]{ROExtString.class, ROExtLong.class, ROExtDate.class,
            ROExtReference.class, ROExtPolyString.class, ROExtBoolean.class};

    public static final ResultStyle RESULT_STYLE = new ResultStyle() {
        @Override
        public ResultTransformer getResultTransformer() {
            return new BasicTransformerAdapter() {
                @Override
                public Object transformTuple(Object[] tuple, String[] aliases) {
                    return new GetObjectResult((String) tuple[0], (byte[]) tuple[1],
                            tuple.length > 2 ? (Short) tuple[2] : null,
                            tuple.length > 3 ? (Short) tuple[3] : null,
                            tuple.length > 4 ? (Short) tuple[4] : null,
                            tuple.length > 5 ? (Short) tuple[5] : null,
                            tuple.length > 6 ? (Short) tuple[6] : null,
                            tuple.length > 7 ? (Short) tuple[7] : null);
                }
            };
        }

        @Override
        public List<String> getIdentifiers(String rootAlias) {
            return Collections.singletonList(rootAlias + ".oid");
        }

        @Override
        public String getCountString(String rootAlias) {
            return rootAlias + ".oid";
        }

        @Override
        public List<String> getContentAttributes(String rootAlias) {
            return Arrays.asList(
                    rootAlias + ".fullObject",
                    rootAlias + ".stringsCount",
                    rootAlias + ".longsCount",
                    rootAlias + ".datesCount",
                    rootAlias + ".referencesCount",
                    rootAlias + ".polysCount",
                    rootAlias + ".booleansCount");
        }
    };

    @NotNull private final String oid;
    @NotNull private final byte[] fullObject;

    private Short stringsCount;
    private Short longsCount;
    private Short datesCount;
    private Short referencesCount;
    private Short polysCount;
    private Short booleansCount;

    public GetObjectResult(@NotNull String oid, @NotNull byte[] fullObject, Short stringsCount, Short longsCount, Short datesCount,
                           Short referencesCount, Short polysCount, Short booleansCount) {

        this.oid = oid;
        this.fullObject = fullObject;

        this.stringsCount = stringsCount;
        this.longsCount = longsCount;
        this.datesCount = datesCount;
        this.referencesCount = referencesCount;
        this.polysCount = polysCount;
        this.booleansCount = booleansCount;
    }

    public Short[] getCountProjection() {
        return new Short[]{getStringsCount(), getLongsCount(), getDatesCount(),
                getReferencesCount(), getPolysCount(), getBooleansCount()};
    }

    @NotNull
    public String getOid() {
        return oid;
    }

    @NotNull
    public byte[] getFullObject() {
        return fullObject;
    }

    public Short getStringsCount() {
        if (stringsCount == null) {
            stringsCount = 0;
        }
        return stringsCount;
    }

    public Short getLongsCount() {
        if (longsCount == null) {
            longsCount = 0;
        }
        return longsCount;
    }

    public Short getDatesCount() {
        if (datesCount == null) {
            datesCount = 0;
        }
        return datesCount;
    }

    public Short getReferencesCount() {
        if (referencesCount == null) {
            referencesCount = 0;
        }
        return referencesCount;
    }

    public Short getPolysCount() {
        if (polysCount == null) {
            polysCount = 0;
        }
        return polysCount;
    }

    public Short getBooleansCount() {
        if (booleansCount == null) {
            booleansCount = 0;
        }
        return booleansCount;
    }
}