text:
package com.amazonaws.services.iottwinmaker.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.iottwinmaker.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * PropertyRequest JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PropertyRequestJsonUnmarshaller implements Unmarshaller<PropertyRequest, JsonUnmarshallerContext> {

    public PropertyRequest unmarshall(JsonUnmarshallerContext context) throws Exception {
        PropertyRequest propertyRequest = new PropertyRequest();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("definition", targetDepth)) {
                    context.nextToken();
                    propertyRequest.setDefinition(PropertyDefinitionRequestJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("value", targetDepth)) {
                    context.nextToken();
                    propertyRequest.setValue(DataValueJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("updateType", targetDepth)) {
                    context.nextToken();
                    propertyRequest.setUpdateType(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return propertyRequest;
    }

    private static PropertyRequestJsonUnmarshaller instance;

    public static PropertyRequestJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new PropertyRequestJsonUnmarshaller();
        return instance;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

 This file is part of the Sylius package.

 (c) Paweł Jędrzejewski

 For the full copyright and license information, please view the LICENSE
 file that was distributed with this source code.

-->

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services
                               http://symfony.com/schema/dic/services/services-1.0.xsd">

    <parameters>
        <parameter key="sylius.locale_provider.class">Sylius\Component\Locale\Provider\LocaleProvider</parameter>
        <parameter key="sylius.event_subscriber.locale.class">Sylius\Bundle\LocaleBundle\EventListener\LocaleSubscriber</parameter>
        <parameter key="sylius.context.locale.class">Sylius\Component\Locale\Context\LocaleContext</parameter>
    </parameters>

    <services>
        <service id="sylius.context.locale" class="%sylius.context.locale.class%">
            <argument /> <!-- Storage service name comes from config -->
            <argument>%sylius.locale%</argument>
        </service>

        <service id="sylius.locale_provider" class="%sylius.locale_provider.class%">
            <argument type="service" id="sylius.repository.locale" />
        </service>

        <service id="sylius.event_subscriber.locale" class="%sylius.event_subscriber.locale.class%">
            <argument type="service" id="sylius.context.locale" />

            <tag name="kernel.event_subscriber" />
        </service>
    </services>

</container>

redpajama_set_name: RedPajamaGithub


text:
namespace UltimateTeam.Toolkit.Models
{
    public class TradePileItem
    {
        public long Id { get; set; }

        public string Pile { get; set; }

        public bool Success { get; set; }
    }
}


text:
"This is the locale selecting middleware that will look at accept headers"

from django.conf import settings
from django.core.urlresolvers import (is_valid_path, get_resolver,
                                      LocaleRegexURLResolver)
from django.http import HttpResponseRedirect
from django.utils.cache import patch_vary_headers
from django.utils import translation
from django.utils.datastructures import SortedDict

class LocaleMiddleware(object):
    """
    This is a very simple middleware that parses a request
    and decides what translation object to install in the current
    thread context. This allows pages to be dynamically
    translated to the language the user desires (if the language
    is available, of course).
    """

    def __init__(self):
        self._supported_languages = SortedDict(settings.LANGUAGES)
        self._is_language_prefix_patterns_used = False
        for url_pattern in get_resolver(None).url_patterns:
            if isinstance(url_pattern, LocaleRegexURLResolver):
                self._is_language_prefix_patterns_used = True
                break

    def process_request(self, request):
        check_path = self.is_language_prefix_patterns_used()
        language = translation.get_language_from_request(
            request, check_path=check_path)
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()

    def process_response(self, request, response):
        language = translation.get_language()
        language_from_path = translation.get_language_from_path(
                request.path_info, supported=self._supported_languages
        )
        if (response.status_code == 404 and not language_from_path
                and self.is_language_prefix_patterns_used()):
            urlconf = getattr(request, 'urlconf', None)
            language_path = '/%s%s' % (language, request.path_info)
            path_valid = is_valid_path(language_path, urlconf)
            if (not path_valid and settings.APPEND_SLASH
                    and not language_path.endswith('/')):
                path_valid = is_valid_path("%s/" % language_path, urlconf)

            if path_valid:
                language_url = "%s://%s/%s%s" % (
                    'https' if request.is_secure() else 'http',
                    request.get_host(), language, request.get_full_path())
                return HttpResponseRedirect(language_url)

        # Store language back into session if it is not present
        if hasattr(request, 'session'):
            request.session.setdefault('django_language', language)

        if not (self.is_language_prefix_patterns_used()
                and language_from_path):
            patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response

    def is_language_prefix_patterns_used(self):
        """
        Returns `True` if the `LocaleRegexURLResolver` is used
        at root level of the urlpatterns, else it returns `False`.
        """
        return self._is_language_prefix_patterns_used


text:
package oplog

import (
	"encoding/base64"
	"expvar"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/sebest/xff"
)

// SSEDaemon listens for events and send them to the oplog MongoDB capped collection
type SSEDaemon struct {
	s  *http.Server
	ol *OpLog
	// Password is the shared secret to connect to a password protected oplog.
	Password string
	// IngestPassword is the shared secret to connect to the HTTP ingest endpoint.
	IngestPassword string
	// FlushInterval defines the interval between flushes of the HTTP socket.
	FlushInterval time.Duration
	// HeartbeatTickerCount defines the number of FlushInterval with nothing to flush
	// is required before we send an heartbeat.
	HeartbeatTickerCount int8
}

// NewSSEDaemon creates a new HTTP server configured to serve oplog stream over HTTP
// using Server Sent Event protocol.
func NewSSEDaemon(addr string, ol *OpLog) *SSEDaemon {
	daemon := &SSEDaemon{
		ol:                   ol,
		Password:             "",
		FlushInterval:        500 * time.Millisecond,
		HeartbeatTickerCount: 50, // 25 seconds
	}
	daemon.s = &http.Server{
		Addr:           addr,
		Handler:        daemon,
		MaxHeaderBytes: 1 << 20,
	}

	return daemon
}

// checkPassword checks HTTP basic authentication's password.
func checkPassword(r *http.Request, password string) bool {
	if password == "" {
		return true
	}

	s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
	if len(s) != 2 || s[0] != "Basic" {
		return false
	}

	b, err := base64.StdEncoding.DecodeString(s[1])
	if err != nil {
		return false
	}
	pair := strings.SplitN(string(b), ":", 2)
	if len(pair) != 2 {
		return false
	}

	return password == pair[1]
}

func (daemon *SSEDaemon) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	switch r.URL.Path {
	case "/status":
		if r.Method == "GET" {
			daemon.Status(w, r)
		} else {
			w.WriteHeader(405)
			return
		}
	case "/ops", "/":
		if r.Method == "GET" {
			daemon.GetOps(w, r)
		} else if r.Method == "POST" {
			daemon.PostOps(w, r)
		} else {
			w.WriteHeader(405)
			return
		}
	default:
		w.WriteHeader(404)
	}
}

// Status exposes expvar data
func (daemon *SSEDaemon) Status(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, "{\"status\":\"OK\"")
	expvar.Do(func(kv expvar.KeyValue) {
		fmt.Fprintf(w, ",%q:%s", kv.Key, kv.Value)
	})
	fmt.Fprintf(w, "}")
}

// PostOps exposes an endpoint to POST operations
func (daemon *SSEDaemon) PostOps(w http.ResponseWriter, r *http.Request) {
	if !checkPassword(r, daemon.IngestPassword) {
		w.WriteHeader(401)
		return
	}

	if r.Header.Get("Content-Type") != "application/json" {
		w.WriteHeader(415)
		return
	}

	h := w.Header()
	h.Set("Server", fmt.Sprintf("oplog/%s", Version))
	h.Set("Cache-Control", "no-cache, no-store, must-revalidate")
	h.Set("Access-Control-Allow-Origin", "*")

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Warnf("HTTP ingest error reading Body: %s", err)
		daemon.ol.Stats.EventsError.Add(1)
		w.WriteHeader(503)
		return
	}

	op, err := decodeOperation(body)
	if err != nil {
		log.Warnf("HTTP ingest invalid operation received: %s", err)
		daemon.ol.Stats.EventsError.Add(1)
		w.WriteHeader(503)
		return
	}

	daemon.ol.Append(op)
	daemon.ol.Stats.EventsReceived.Add(1)
	w.WriteHeader(204)
}

// GetOps exposes an SSE endpoint to stream operations
func (daemon *SSEDaemon) GetOps(w http.ResponseWriter, r *http.Request) {
	ip := xff.GetRemoteAddr(r)
	log.Infof("SSE[%s] connection started", ip)

	if r.Header.Get("Accept") != "text/event-stream" {
		// Not an event stream request, return a 406 Not Acceptable HTTP error
		w.WriteHeader(406)
		return
	}

	if !checkPassword(r, daemon.Password) {
		w.WriteHeader(401)
		return
	}

	h := w.Header()
	h.Set("Server", fmt.Sprintf("oplog/%s", Version))
	h.Set("Content-Type", "text/event-stream; charset=utf-8")
	h.Set("Cache-Control", "no-cache, no-store, must-revalidate")
	h.Set("Connection", "close")
	h.Set("Access-Control-Allow-Origin", "*")

	var lastID LastID
	var err error
	if r.Header.Get("Last-Event-ID") == "" {
		// No last id provided, use the very last id of the events collection
		lastID, err = daemon.ol.LastID()
		if err != nil {
			log.Warnf("SSE[%s] can't get last id: %s", ip, err)
			w.WriteHeader(503)
			return
		}
	} else {
		if lastID, err = NewLastID(r.Header.Get("Last-Event-ID")); err != nil {
			log.Warnf("SSE[%s] invalid last id: %s", ip, err)
			w.WriteHeader(400)
			return
		}
		found, err := daemon.ol.HasID(lastID)
		if err != nil {
			log.Warnf("SSE[%s] can't check last id: %s", ip, err)
			w.WriteHeader(503)
			return
		}
		if !found {
			log.Debugf("SSE[%s] last id not found, falling back to replication id: %s", ip, lastID.String())
			// If the requested event id is not found, fallback to a replication id
			olid := lastID.(*OperationLastID)
			lastID = olid.Fallback()
		}
		// Backward compat, remove when all oplogc will be updated
		h.Set("Last-Event-ID", r.Header.Get("Last-Event-ID"))
	}

	if lastID != nil {
		log.Debugf("SSE[%s] using last id: %s", ip, lastID.String())
	}

	types := []string{}
	if r.URL.Query().Get("types") != "" {
		types = strings.Split(r.URL.Query().Get("types"), ",")
	}
	parents := []string{}
	if r.URL.Query().Get("parents") != "" {
		parents = strings.Split(r.URL.Query().Get("parents"), ",")
	}
	filter := Filter{
		Types:   types,
		Parents: parents,
	}

	flusher := w.(http.Flusher)
	notifier := w.(http.CloseNotifier)
	ops := make(chan GenericEvent)
	stop := make(chan bool)
	flusher.Flush()

	go daemon.ol.Tail(lastID, filter, ops, stop)
	defer func() {
		// Stop the oplog tailer
		stop <- true
	}()

	daemon.ol.Stats.Clients.Add(1)
	daemon.ol.Stats.Connections.Add(1)
	defer daemon.ol.Stats.Clients.Add(-1)

	// Messages are buffered and flushed every daemon.FlushInterval to save I/Os
	ticker := time.NewTicker(daemon.FlushInterval)
	defer ticker.Stop()
	var empty int8

	for {
		select {
		case <-notifier.CloseNotify():
			log.Infof("SSE[%s] connection closed", ip)
			return

		case op := <-ops:
			log.Debugf("SSE[%s] sending event", ip)
			daemon.ol.Stats.EventsSent.Add(1)
			if _, err := op.WriteTo(w); err != nil {
				log.Warnf("SSE[%s] write error: %s", ip, err)
				return
			}
			empty = -1

		case <-ticker.C:
			// Flush the buffer at regular interval
			if empty >= 0 {
				// Skip if buffer has no data, if empty for too long, send a heartbeat
				if empty >= daemon.HeartbeatTickerCount {
					if _, err := w.Write([]byte{':', '\n'}); err != nil {
						log.Warnf("SSE[%s] write error: %s", ip, err)
						return
					}
				} else {
					empty++
					continue
				}
			}
			empty = 0
			log.Debugf("SSE[%s] flushing buffer", ip)
			flusher.Flush()
		}
	}
}

// Run starts the SSE server
func (daemon *SSEDaemon) Run() error {
	return daemon.s.ListenAndServe()
}


text:
package io.narayana.spi.util;

import io.narayana.spi.InitializationException;
import org.jnp.server.NamingBeanImpl;

import javax.naming.Context;
import java.util.Hashtable;
import java.util.Map;

public class JndiProvider {

    private static NamingBeanImpl jnpServer = new NamingBeanImpl();

    public static Hashtable start() throws Exception {
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");

        jnpServer.start();

        Hashtable props = new Hashtable();

        props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
        props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");

        return props;
    }

    public static void stop() {
        jnpServer.stop();
    }

    public static void initBindings() throws InitializationException {
        Map<String, DbProps> dbConfigs = new DbProps().getConfig(DbProps.DB_PROPERTIES_NAME);
        DataSourceManagerImpl dataSourceManager = new DataSourceManagerImpl();

        for (DbProps props : dbConfigs.values()) {
            String url = props.getDatabaseURL();

            if (url != null && url.length() > 0)
                dataSourceManager.registerDataSource(props.getBinding(), props.getDriver(), url,
                        props.getDatabaseUser(), props.getDatabasePassword());
            else
                dataSourceManager.registerDataSource(props.getBinding(), props.getDriver(), props.getDatabaseName(),
                        props.getHost(), props.getPort(), props.getDatabaseUser(),props.getDatabasePassword());
        }
    }
}


text:
/* global ngDescribe, it, beforeEach */
ngDescribe({
  name: 'Exposing setupElement',
  modules: 'MyFoo',
  only: false,
  exposeApi: true,
  tests: function (deps, descApi) {
    var elementHtml = '<my-foo></my-foo>';
    beforeEach(function () {
      la(!check.has(deps, 'element'), 'has no compiled element in before each yet');
    });
    beforeEach(function () {
      descApi.setupElement(elementHtml);
    });
    beforeEach(function () {
      la(check.has(deps, 'element'), 'has compiled element after previous beforeEach');
    });

    it('creates myFoo element', function () {
      la(check.has(deps, 'element'), 'has compiled element');
    });
  }
});


text:
House of Cards : French Edition
==========
Pré-requis pour le lancement du jeu "House of Cards : French Edition"

- Installer la version 32 bits de Python 3.2 -> https://www.python.org/download
- Installer la version 32 bits de Pygame 1.9.2a0 -> http://pygame.org
- Exécuter main.py


text:
/* $NetBSD: hdafg_dd.c,v 1.2 2012/08/29 18:52:31 dholland Exp $ */

/*
 * Copyright (c) 2011 Jared D. McNeill <jmcneill@invisible.ca>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * HD audio Digital Display support
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: hdafg_dd.c,v 1.2 2012/08/29 18:52:31 dholland Exp $");

#include <sys/types.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/device.h>
#include <sys/conf.h>
#include <sys/bus.h>

#include "hdaudioreg.h"
#include "hdaudiovar.h"
#include "hdaudio_pci.h"
#include "hdafg_dd.h"

int
hdafg_dd_parse_info(uint8_t *data, size_t datalen, struct hdafg_dd_info *hdi)
{
	struct eld_baseline_block *block = &hdi->eld;
	unsigned int i;

	printf("hdafg_dd_parse_info: datalen=%u\n", (unsigned int)datalen);

	memset(hdi, 0, sizeof(*hdi));

	if (datalen < sizeof(block->header)) {
		printf(" no room for header\n");
		return EINVAL;
	}

	memcpy(&block->header, data, sizeof(block->header));
	data += sizeof(block->header);
	datalen -= sizeof(block->header);

	if (datalen < block->header.baseline_eld_len * 4 ||
	    datalen < sizeof(*block) - sizeof(block->header)) {
		printf(" ack!\n");
		return EINVAL;
	}

	datalen = block->header.baseline_eld_len * 4;

	memcpy(&block->flags[0], data, sizeof(*block) - sizeof(block->header));
	data += sizeof(*block) - sizeof(block->header);
	datalen -= sizeof(*block) - sizeof(block->header);

	if (datalen < ELD_MNL(block)) {
		printf(" MNL=%u\n", ELD_MNL(block));
		return EINVAL;
	}

	memcpy(hdi->monitor, data, ELD_MNL(block));
	data += ELD_MNL(block);
	datalen -= ELD_MNL(block);

	if (datalen != ELD_SAD_COUNT(block) * sizeof(hdi->sad[0])) {
		printf(" datalen %u sadcount %u sizeof sad %u\n",
		    (unsigned int)datalen,
		    ELD_SAD_COUNT(block),
		    (unsigned int)sizeof(hdi->sad[0]));
		return EINVAL;
	}
	hdi->nsad = ELD_SAD_COUNT(block);
	for (i = 0; i < hdi->nsad; i++) {
		memcpy(&hdi->sad[i], data, sizeof(hdi->sad[i]));
		data += sizeof(hdi->sad[i]);
		datalen -= sizeof(hdi->sad[i]);
	}

	printf("datalen = %u\n", (unsigned int)datalen);
	KASSERT(datalen == 0);

	return 0;
}

void
hdafg_dd_hdmi_ai_cksum(struct hdmi_audio_infoframe *hdmi)
{
	uint8_t *dip = (uint8_t *)hdmi, c = 0;
	int i;

	hdmi->checksum = 0;
	for (i = 0; i < sizeof(*hdmi); i++)
		c += dip[i];
	hdmi->checksum = -c;
}


text:
/*jslint browser: true*/
/*global define, $, _, openpgp, JST, WebSyncAuth, WebSyncData, WS, moment*/

//= require templates/crypto

define('crypto', function() {
  'use strict';

  /**
   * The crypto end-to-end encryption module for WebSync. Uses openpgp.js.
   *
   * @exports crypto
   * @module crypto
   */

  var exports = {};

  // Variables to store the keys and the decrypted session key.
  var privateKey, publicKey, sessionKey, sessionKeyAlgorithm;

  // Add a comment to the generated pgp keys.
  openpgp.config.commentstring += ' - Generated for https://WebSyn.ca';

  /** Encodes a key into a URL that can be downloaded. */
  function encodeDownload(text) {
    return 'data:application/octet-stream;charset=utf-8,' + encodeURIComponent(text);
  }

  /** Downloads a file to the browser. */
  function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', encodeDownload(text));
    pom.setAttribute('download', filename);
    pom.click();
  }

  $(document.body).append(JST['templates/crypto']({}));

  /** The current stage the crypto dialog is in. */
  exports.stage = 0;
  /** The encryption dialog modal. */
  exports.$modal = $('#encryptionModal');

  /**
   * Sets the current stage the crypto dialog is in.
   * @param {String/Number} stage
   */
  exports.updateStage = function(stage) {
    if (stage !== undefined) {
      exports.stage = stage;
    }
    if (stage === 'saveOptions') {
      var puKey = window.localStorage['websync-key-public'];
      var prKey = window.localStorage['websync-key-private'];
      exports.$modal.find('#publicKey').
      attr('href', encodeDownload(puKey));
      exports.$modal.find('#privateKey').
      attr('href', encodeDownload(prKey));
    }
    $('#encryptionModal .modal-body').children().hide();
    $('#encryptionModal .modal-body .' + exports.stage).show();
  };
  $('#encryptionModal #genKey').on('click', function() {
    exports.updateStage('genKey');
  });
  $('#encryptionModal #pubkeyfile').on('change', function(e) {
    var f = e.target.files[0];
    var r = new FileReader();
    r.onload = function(e) {
      var contents = e.target.result;
      $('textarea#publicKey').val(contents);
    };
    r.readAsText(f);
  });
  $('#encryptionModal #privkeyfile').on('change', function(e) {
    var f = e.target.files[0];
    var r = new FileReader();
    r.onload = function(e) {
      var contents = e.target.result;
      $('textarea#privateKey').val(contents);
    };
    r.readAsText(f);
  });
  $('#encryptionModal #saveAndFinish').on('click', function() {
    var savePriv = $('#storePrivOnServer').val() === 'on';
    var puKeys = [window.localStorage['websync-key-public']];
    var prKeys = [];
    if (savePriv) {
      prKeys = [window.localStorage['websync-key-private']];
    }
    require('websync').connection.sendJSON({
      type: 'keys',
      action: 'add',
      keys: {
        public: puKeys,
        private: prKeys
      }
    });
    var callbacks = exports.checkKeysCallback;
    exports.checkKeysCallback = [];
    _.each(callbacks, function(cb) {
      cb();
    });
    exports.$modal.modal('hide');
  });
  $('#encryptionModal #doUploadKey').on('click', function(e) {
    var puKey = $('textarea#publicKey').val();
    var prKey = $('textarea#privateKey').val();
    window.localStorage['websync-key-public'] = puKey;
    window.localStorage['websync-key-private'] = prKey;
    privateKey = openpgp.key.readArmored(prKey).keys[0];
    publicKey = openpgp.key.readArmored(puKey).keys[0];
    exports.setPrivateKey();
    exports.updateStage('saveOptions');
    e.preventDefault();
  });
  $('#encryptionModal #uploadKey').on('click', function() {
    exports.updateStage('uploadKey');
  });
  $('#encryptionModal #doGenKey').on('click', function(e) {
    if (exports.genKeyValidator.valid()) {
      var $form = $('#encryptionModal .genKey form');
      openpgp.generateKeyPair({
        numBits: parseInt($form.find('select').val(), 10),
        userId: $form.find('#realName').val(),
        passphrase: $form.find('#password').val()
      }).then(function(result) {
        exports.updateStage('keyGenerated');
        privateKey = result.key;
        exports.setPrivateKey();
        var puKey = result.publicKeyArmored;
        var prKey = result.privateKeyArmored;
        window.localStorage['websync-key-public'] = puKey;
        window.localStorage['websync-key-private'] = prKey;
        download('websync-publickey.key', puKey);
        download('websync-privatekey.key', prKey);
      });
      exports.updateStage('saveOptions');
    }
    e.preventDefault();
  });
  $('#encryptionModal #storePassPhrase').on('click', function() {
    if ($(this).val() === 'on') {
      $('#encryptionModal .decrypt .remember.error').show();
    } else {
      $('#encryptionModal .decrypt .remember.error').hide();
    }
  });
  $('#encryptionModal #doDecryptPassphrase').on('click', function(e) {
    var pass = $('#encryptionModal #passphrase').val();
    var storePass = $('#encryptionModal #storePassPhrase').val() === 'on';
    var success = privateKey.decrypt(pass);
    if (success) {
      exports.decryptPrivateKey(pass);
      if (storePass) {
        window.localStorage['websync-passphrase'] = window.btoa(pass);
      }
      exports.$modal.modal('hide');
    } else {
      $('#encryptionModal .decrypt .decrypt.error').text('Invalid passphrase!');
    }
    e.preventDefault();
  });

  /** The generation key form validator. */
  exports.genKeyValidator = $('#encryptionModal .genKey form').validate();

  /** The upload key form validator. */
  exports.uploadKeyValidator = $('#encryptionModal .uploadKey form').validate();

  _.delay(function() {
    require('websync').registerMessageEvent('keys', function(data) {
      var $tbody = $('#keys tbody').html('');
      _.each(_.union(data.keys.public, data.keys.private), function(data) {
        var unarmored = openpgp.key.readArmored(data.body);
        var userid = unarmored.keys[0].users[0].userId.userid;
        $tbody.append('
' +
          data.type +
          '	' +
          userid +
          '	' +
          moment(data.created) +
          '
');
      });
    }).registerMessageEvent('info', function() {
      require('websync').connection.sendJSON({
        type: 'keys',
        action: 'get'
      });
    });
  }, 1);
  /** An array for the check keys callbacks to be stored in. */
  exports.checkKeysCallback = [];

  /**
   * Checks to see if the keys are present and decrypted. If not it will prompt the user.
   * Once the keys are available it will call the callback.
   * @param {Function} callback - The function to be called once the keys are ready.
   */
  exports.checkKeys = function(callback) {
    if (!(window.localStorage.hasOwnProperty('websync-key-private') &&
        window.localStorage.hasOwnProperty('websync-key-public') &&
        !_.include(window.location.hash, 'cryptoclean'))) {
      exports.updateStage(0);
      $('#encryptionModal').modal();
      if (callback) {
        exports.checkKeysCallback.push(callback);
      }
    } else {
      privateKey = openpgp.key.readArmored(window.localStorage['websync-key-private']).keys[0];
      publicKey = openpgp.key.readArmored(window.localStorage['websync-key-public']).keys[0];
      exports.setPrivateKey();
      if (window.localStorage.hasOwnProperty('websync-passphrase')) {
        var pass = atob(window.localStorage['websync-passphrase']);
        privateKey.decrypt(pass);
        exports.decryptPrivateKey(pass);
      }
      if (!exports.keyIsDecrypted(privateKey)) {
        exports.updateStage('decrypt');
        $('#encryptionModal').modal();
      }
      if (callback) {
        callback();
      }
    }
  };

  /**
   * Checks if a key and all of its sub keys are decrypted.
   * @param {openpgp.key.Key} key - The key to check.
   * @return {Boolean}
   */
  exports.keyIsDecrypted = function(key) {
    return _.reduce(key.getAllKeyPackets(), function(decrypted, packet) {
      return decrypted && packet.isDecrypted;
    });
  };

  /**
   * Encrypts a session key for the specified public key.
   * @param {openpgp.key.Key} key - The public key to encrypt the session key for.
   * @return {openpgp.message.Message}
   */
  exports.wrapSymmetricForKey = function(key) {
    var packetlist = new openpgp.packet.List();
    var encryptionKeyPacket = key.getEncryptionKeyPacket();
    var pkESKeyPacket = new openpgp.packet.PublicKeyEncryptedSessionKey();
    pkESKeyPacket.publicKeyId = encryptionKeyPacket.getKeyId();
    pkESKeyPacket.publicKeyAlgorithm = encryptionKeyPacket.algorithm;
    pkESKeyPacket.sessionKey = sessionKey;
    pkESKeyPacket.sessionKeyAlgorithm = sessionKeyAlgorithm;
    pkESKeyPacket.encrypt(encryptionKeyPacket);
    packetlist.push(pkESKeyPacket);
    return new openpgp.message.Message(packetlist);
  };

  /**
   * Scans a number of encrypted session keys until it finds one it can decrypt and returns it.
   * @param {Array} keys - The encrypted session keys.
   * @return {String}
   */
  exports.decodeSymmetricKeys = function(keys) {
    var decrypted = false;
    _.each(keys, function(key) {
      var symKey = exports.decryptSymmetricKey(key);
      if (symKey) {
        exports.setSessionKey(
          symKey.sessionKey,
          symKey.sessionKeyAlgorithm);
        decrypted = true;
      }
    });
    return decrypted;
  };

  /**
   * Decrypts a symmetric key using the current private key.
   * @param {String} message - The armored encrypted key message.
   * @return {openpgp.key.Key | false}
   */
  exports.decryptSymmetricKey = function(msg) {
    var message = openpgp.message.readArmored(msg);
    var encryptionKeyIds = message.getEncryptionKeyIds();
    var privateKeyPacket = privateKey.getKeyPacket(encryptionKeyIds);
    var pkESKeyPacketlist = message.packets.filterByTag(openpgp.enums.packet.publicKeyEncryptedSessionKey);
    var pkESKeyPacket, i;
    for (i = 0; i < pkESKeyPacketlist.length; i++) {
      if (pkESKeyPacketlist[i].publicKeyId.equals(privateKeyPacket.getKeyId())) {
        pkESKeyPacket = pkESKeyPacketlist[i];
        pkESKeyPacket.decrypt(privateKeyPacket);
        break;
      }
    }
    if (pkESKeyPacket) {
      return pkESKeyPacket;
    }
    return false;
  };

  var worker = new Worker('/assets/crypto-worker.js');
  var callbacks = {};
  worker.onmessage = function(oEvent) {
    var event = oEvent.data;
    if (event.event === 'request-seed') {
      exports.seedRandom(RANDOM_SEED_REQUEST);
    } else {
      var callback = callbacks[event.id];
      if (callback) {
        callback(event.resp);
        delete callbacks[event.id];
      }
    }
  };

  function execute(func, args, callback) {
    var id = btoa(Math.random());
    if (callback) {
      callbacks[id] = callback;
    }
    worker.postMessage({
      id: id,
      func: func,
      args: args
    });
  }

  var INITIAL_RANDOM_SEED = 50000, // random bytes seeded to worker
    RANDOM_SEED_REQUEST = 20000; // random bytes seeded after worker request

  /**
   * Seeds the crypto worker with the needed random values.
   * @param {Integer} size - The number of bytes to send.
   */
  exports.seedRandom = function(size) {
    var buf = new Uint8Array(size);
    openpgp.crypto.random.getRandomValues(buf);
    execute('seedRandom', [buf]);
  };
  exports.seedRandom(INITIAL_RANDOM_SEED);

  /**
   * Sends the private key to the web worker so it can decrypt messages.
   */
  exports.setPrivateKey = function() {
    execute('setPrivateKey', [privateKey.armor()]);
  };

  /**
   * Decrypts the private key on the web worker.
   * @param {String} passphrase - The passphrase to the private key.
   */
  exports.decryptPrivateKey = function(passphrase) {
    execute('decryptPrivateKey', [passphrase]);
  };

  /**
   * Sets the symmetric key locally and on the web worker.
   * @params {String} key - The session key
   * @params {String | Integer} algorithm - The algorithm used for the session key. Ex: 'aes256' or 9.
   */
  exports.setSessionKey = function(key, algo) {
    sessionKey = key;
    if (_.isNumber(algo)) {
      sessionKeyAlgorithm = openpgp.enums.read(openpgp.enums.symmetric, algo);
    } else {
      sessionKeyAlgorithm = algo;
    }
    execute('setSessionKey', [key, sessionKeyAlgorithm]);
  };

  /**
   * Decrypts a message with the symmetric key.
   * @params {String | Array} message - The armored message, or list of messages.
   * @params {Function} callback - The function to call with the decrypted message.
   */
  exports.decryptWithSymmetricKey = function(msg, callback) {
    if (_.isString(msg)) {
      execute('decryptWithSymmetricKey', [msg], callback);
    } else {
      var count = msg.length;
      var numDecrypted = 0;
      var decrypted = new Array(count);
      _.each(msg, function(msg, i) {
        execute('decryptWithSymmetricKey', [msg], function(decryptedMsg) {
          decrypted[i] = decryptedMsg;
          numDecrypted += 1;
          if (numDecrypted === count) {
            callback(decrypted);
          }
        });
      });
    }
  };

  /**
   * Encrypts a message with the symmetric key.
   * @params {String} message - The message.
   * @params {Function} callback - The function to call with the encrypted message.
   */
  exports.encryptWithSymmetricKey = function(msg, callback) {
    execute('encryptWithSymmetricKey', [msg], callback);
  };

  /**
   * Encrypts and signs a message with the symmetric key.
   * @params {String} message - The message.
   * @params {Function} callback - The function to call with the encrypted message.
   */
  exports.signAndEncryptWithSymmetricKey = function(msg, callback) {
    execute('signAndEncryptWithSymmetricKey', [msg], callback);
  };

  /**
   * Converts the current document into an encrypted one.
   */
  exports.encryptDocument = function() {
    WS.info('Encrypting the document...');
    exports.checkKeys();

    if (sessionKey || WebSyncAuth.encrypted) {
      console.warn('crypto: encryptDocument called on an already encrypted document');
      return;
    }

    // Generate symmetric key
    var symAlgo = openpgp.key.getPreferredSymAlgo([privateKey]);
    var symAlgoName = openpgp.enums.read(openpgp.enums.symmetric, symAlgo);
    exports.setSessionKey(
      openpgp.crypto.generateSessionKey(symAlgoName),
      symAlgoName);
    var wrappedSym = exports.wrapSymmetricForKey(publicKey);

    // To encrypt the document we need to encrypt the blob, patches and shared list.
    // TODO: Encrypt patches and shared list.
    WebSyncAuth.encrypted = true;
    WebSyncData.encryptionDate = new Date();
    exports.signAndEncryptWithSymmetricKey(JSON.stringify(WebSyncData), function(blob) {
      WS.connection.sendJSON({
        type: 'encrypt_document',
        body: {
          encryptedBlob: blob
        },
        symmetricKey: {
          publicKey: publicKey.armor(),
          key: wrappedSym.armor()
        }
      });
      WS.success('This document is now encrypted!');
      exports.updateLockButton();
    });
  };

  /** Updates the icon and tooltip on the lock button. */
  exports.updateLockButton = function() {
    if (WebSyncAuth.encrypted) {
      $('#cryptoBtn i').removeClass('fa-unlock');
      $('#cryptoBtn').attr('title', 'Encrypted');
    }
  };
  $('nav #settings').prepend('
' +
    '' +
    '
');
  exports.updateLockButton();
  $('#cryptoBtn').click(function() {
    if (!WebSyncAuth.encrypted) {
      exports.checkKeys(function() {
        exports.updateStage('encrypt');
        $('#encryptionModal').modal();
      });
    }
  });
  $('#doEncryptDocument').click(function(e) {
    exports.encryptDocument();
    $('#encryptionModal').modal('hide');
    e.preventDefault();
  });
  return exports;
});


text:
#include <enc_text.h>
#include <utils.h>

/*
 * Maps a BLOB type to its one-character label.
 *
 * @param type  The BLOB type.
 *
 * @result      The one-character label, -1 if the given BLOB type is invalid.
 */
static int32_t
text_bytes_type_to_label(as_bytes_type type)
{
	static as_bytes_type types[] = {
		AS_BYTES_BLOB,
		AS_BYTES_JAVA,
		AS_BYTES_CSHARP,
		AS_BYTES_PYTHON,
		AS_BYTES_RUBY,
		AS_BYTES_PHP,
		AS_BYTES_ERLANG,
		AS_BYTES_HLL,
		AS_BYTES_MAP,
		AS_BYTES_LIST
	};

	static char labels[] = {
		'B', 'J', 'C', 'P', 'R', 'H', 'E', 'Y', 'M', 'L'
	};

	for (size_t i = 0; i < sizeof types / sizeof types[0]; ++i) {
		if (type == types[i]) {
			return labels[i];
		}
	}

	err("Invalid bytes type %d", (int32_t)type);
	return -1;
}

/*
 * Writes a boolean to the backup file.
 *
 * @param fd       The file descriptor of the backup file.
 * @param prefix1  The first string prefix.
 * @param prefix2  The second string prefix.
 * @param val      The integer value to be written.
 *
 * @result         `true`, if successful.
 */
static bool
text_output_boolean(io_write_proxy_t *fd, const char *prefix1,
		const char *prefix2, as_val *val)
{
	as_boolean *v = as_boolean_fromval(val);

	if (io_proxy_printf(fd, "%s%s %c\n", prefix1, prefix2,
				v->value ? BOOLEAN_TRUE_CHAR : BOOLEAN_FALSE_CHAR) < 0) {
		err("Error while writing boolean to backup file");
		return false;
	}

	return true;
}

/*
 * Writes a signed 64-bit integer to the backup file.
 *
 * @param fd       The file descriptor of the backup file.
 * @param prefix1  The first string prefix.
 * @param prefix2  The second string prefix.
 * @param val      The integer value to be written.
 *
 * @result         `true`, if successful.
 */
static bool
text_output_integer(io_write_proxy_t *fd, const char *prefix1,
		const char *prefix2,
		as_val *val)
{
	as_integer *v = as_integer_fromval(val);

	if (io_proxy_printf(fd, "%s%s %" PRId64 "\n", prefix1, prefix2, v->value) < 0) {
		err("Error while writing integer to backup file");
		return false;
	}

	return true;
}

/*
 * Writes a double-precision floating-point value to the backup file.
 *
 * Using 17 significant digits makes sure that we read back the same value that we wrote.
 *
 * @param fd       The file descriptor of the backup file.
 * @param prefix1  The first string prefix.
 * @param prefix2  The second string prefix.
 * @param val      The floating point value to be written.
 *
 * @result         `true`, if successful.
 */
static bool
text_output_double(io_write_proxy_t *fd, const char *prefix1,
		const char *prefix2,
		as_val *val)
{
	as_double *v = as_double_fromval(val);

	if (io_proxy_printf(fd, "%s%s %.17g\n", prefix1, prefix2, v->value) < 0) {
		err("Error while writing double to backup file");
		return false;
	}

	return true;
}

/*
 * Writes a BLOB to the backup file.
 *
 * @param fd       The file descriptor of the backup file.
 * @param prefix1  The first string prefix.
 * @param prefix2  The second string prefix.
 * @param buffer   The data of the BLOB to be written.
 * @param size     The size of the BLOB to be written.
 *
 * @result         `true`, if successful.
 */
static bool
text_output_data(io_write_proxy_t *fd, const char *prefix1,
		const char *prefix2,
		void *buffer, size_t size)
{
	if (io_proxy_printf(fd, "%s%s %zu ", prefix1, prefix2, size) < 0) {
		err("Error while writing data to backup file [1]");
		return false;
	}

	if (io_proxy_write(fd, buffer, size) != (int64_t) size) {
		err("Error while writing data to backup file [2]");
		return false;
	}

	if (io_proxy_printf(fd, "\n") < 0) {
		err("Error while writing data to backup file [3]");
		return false;
	}

	return true;
}

/*
 * Writes an encoded BLOB to the backup file.
 *
 * @param fd       The file descriptor of the backup file.
 * @param prefix1  The first string prefix.
 * @param prefix2  The second string prefix.
 * @param buffer   The data of the BLOB to be written.
 * @param size     The size of the BLOB to be written.
 *
 * @result         `true`, if successful.
 */
static bool
text_output_data_enc(io_write_proxy_t *fd, const char *prefix1,
		const char *prefix2, void *buffer, uint32_t size)
{
	uint32_t enc_size = cf_b64_encoded_len(size);

	if (enc_size < size) {
		err("Encoded data too long (%u vs. %u bytes)", enc_size, size);
		return false;
	}

	char *enc = buffer_init(enc_size);
	cf_b64_encode(buffer, size, enc);

	if (!text_output_data(fd, prefix1, prefix2, enc, enc_size)) {
		buffer_free(enc, enc_size);
		return false;
	}

	buffer_free(enc, enc_size);
	return true;
}

/*
 * Writes a string to the backup file.
 *
 * @param fd       The file descriptor of the backup file.
 * @param prefix1  The first string prefix.
 * @param prefix2  The second string prefix.
 * @param val      The string to be written.
 *
 * @result         `true`, if successful.
 */
static bool
text_output_string(io_write_proxy_t *fd, const char *prefix1,
		const char *prefix2, as_val *val)
{
	as_string *v = as_string_fromval(val);
	return text_output_data(fd, prefix1, prefix2, v->value, v->len);
}

/*
 * Writes a geojson to the backup file.
 *
 * @param fd       The file descriptor of the backup file.
 * @param prefix1  The first string prefix.
 * @param prefix2  The second string prefix.
 * @param val      The geojson to be written.
 *
 * @result         `true`, if successful.
 */
static bool
text_output_geojson(io_write_proxy_t *fd, const char *prefix1,
		const char *prefix2, as_val *val)
{
	as_geojson *v = as_geojson_fromval(val);
	return text_output_data(fd, prefix1, prefix2, v->value, v->len);
}

/*
 * Writes a bytes value to the backup file.
 *
 * @param fd       The file descriptor of the backup file.
 * @param compact  Indicates compact mode.
 * @param prefix1  The first string prefix.
 * @param prefix2  The second string prefix.
 * @param val      The bytes value to be written.
 *
 * @result         `true`, if successful.
 */
static bool
text_output_bytes(io_write_proxy_t *fd, bool compact,
		const char *prefix1, const char *prefix2, as_val *val)
{
	as_bytes *v = as_bytes_fromval(val);
	return compact ?
			text_output_data(fd, prefix1, prefix2, v->value, v->size) :
			text_output_data_enc(fd, prefix1, prefix2, v->value, v->size);
}

/*
 * Writes a key to the backup file.
 *
 * @param fd       The file descriptor of the backup file.
 * @param compact  Indicates compact mode.
 * @param key      The key to be written.
 *
 * @result         `true`, if successful.
 */
static bool
text_output_key(io_write_proxy_t *fd, bool compact, as_val *key)
{
	switch (key->type) {
	case AS_INTEGER:
		return text_output_integer(fd, "+ k I", "", key);

	case AS_DOUBLE:
		return text_output_double(fd, "+ k D", "", key);

	case AS_STRING:
		return text_output_string(fd, "+ k S", "", key);

	case AS_BYTES:
		return compact ?
			text_output_bytes(fd, true, "+ k B!", "", key) :
			text_output_bytes(fd, false, "+ k B", "", key);

	default:
		err("Invalid key type %d", (int32_t)key->type);
		return false;
	}
}

/*
 * Writes a bin to the backup file.
 *
 * @param fd        The file descriptor of the backup file.
 * @param compact   Indicates compact mode.
 * @param bin_name  The name of the bin to be written.
 * @param val       The bin value to be written.
 *
 * @result         `true`, if successful.
 */
static bool
text_output_value(io_write_proxy_t *fd, bool compact,
		const char *bin_name, as_val *val)
{
	if (val == NULL || val->type == AS_NIL) {
		if (io_proxy_printf(fd, "- N %s\n", bin_name) < 0) {
			err("Error while writing NIL value to backup file");
			return false;
		}

		return true;
	}

	switch (val->type) {
	case AS_BOOLEAN:
		return text_output_boolean(fd, "- Z ", bin_name, val);

	case AS_INTEGER:
		return text_output_integer(fd, "- I ", bin_name, val);

	case AS_DOUBLE:
		return text_output_double(fd, "- D ", bin_name, val);

	case AS_STRING:
		return text_output_string(fd, "- S ", bin_name, val);

	case AS_GEOJSON:
		return text_output_geojson(fd, "- G ", bin_name, val);

	case AS_BYTES: {
		int32_t type = text_bytes_type_to_label(as_bytes_fromval(val)->type);

		if (type < 0) {
			return false;
		}

		if (compact) {
			char prefix[6] = "-  ! ";
			prefix[2] = (char)type;
			return text_output_bytes(fd, true, prefix, bin_name, val);
		}

		char prefix[5] = "-   ";
		prefix[2] = (char)type;
		return text_output_bytes(fd, false, prefix, bin_name, val);
	}

	case AS_LIST:
		err("Unexpected value of type list");
		return false;

	case AS_MAP:
		err("Unexpected value of type map");
		return false;

	default:
		err("Invalid value type %d", (int32_t)val->type);
		return false;
	}
}

/*
 * Part of the interface exposed by the text backup file format encoder.
 *
 * See backup_encoder.put_record for details.
 */
bool
text_put_record(io_write_proxy_t *fd, bool compact,
		const as_record *rec)
{
	uint32_t enc_size = cf_b64_encoded_len(sizeof (as_digest_value)) + 1;
	char *enc = alloca(enc_size);
	cf_b64_encode(rec->key.digest.value, sizeof (as_digest_value), enc);
	enc[enc_size - 1] = 0;

	// map -1 TTL (= never expire) to 0; restore maps it back
	uint32_t expire = rec->ttl == (uint32_t)-1 ? 0 : (uint32_t)cf_secs_since_clepoch() + rec->ttl;

	if (rec->key.valuep != NULL &&
			!text_output_key(fd, compact, (as_val *)rec->key.valuep)) {
		err("Error while writing record key");
		return false;
	}

	if (io_proxy_printf(fd, "+ n %s\n+ d %s\n", escape(rec->key.ns), enc) < 0) {
		err("Error while writing record meta data to backup file [1]");
		return false;
	}

	if (rec->key.set[0] != 0 && io_proxy_printf(fd, "+ s %s\n", escape(rec->key.set)) < 0) {
		err("Error while writing record meta data to backup file [2]");
		return false;
	}

	if (io_proxy_printf(fd, "+ g %d\n+ t %u\n+ b %d\n", rec->gen, expire,
			rec->bins.size) < 0) {
		err("Error while writing record meta data to backup file [3]");
		return false;
	}

	for (int32_t i = 0; i < rec->bins.size; ++i) {
		as_bin *bin = &rec->bins.entries[i];

		if (!text_output_value(fd, compact, escape(bin->name), (as_val *)bin->valuep)) {
			err("Error while writing record bin %s", bin->name);
			return false;
		}
	}

	return true;
}

/*
 * Maps a UDF type to its one-character label.
 *
 * @param type  The UDF type.
 *
 * @result      The one-character label, -1 if the given UDF type is invalid.
 */
static int32_t
text_udf_type_to_label(as_udf_type type)
{
	if (type == AS_UDF_TYPE_LUA) {
		return 'L';
	}

	err("Invalid UDF type %d", (int32_t)type);
	return -1;
}

/*
 * Part of the interface exposed by the text backup file format encoder.
 *
 * See backup_encoder.put_udf_file for details.
 */
bool
text_put_udf_file(io_write_proxy_t *fd, const as_udf_file *file)
{
	int32_t type = text_udf_type_to_label(file->type);

	if (type < 0) {
		return false;
	}

	if (io_proxy_printf(fd, GLOBAL_PREFIX "u %c %s %u ", (char)type, escape(file->name),
			file->content.size) < 0) {
		err("Error while writing UDF function to backup file [1]");
		return false;
	}

	if (io_proxy_write(fd, file->content.bytes, file->content.size) !=
			file->content.size) {
		err("Error while writing UDF function to backup file [2]");
		return false;
	}

	if (io_proxy_printf(fd, "\n") < 0) {
		err("Error while writing UDF function to backup file [3]");
		return false;
	}

	return true;
}

/*
 * Maps a secondary index type to its one-character label.
 *
 * @param type  The secondary index type.
 *
 * @result      The one-character label.
 */
static int32_t
text_index_type_to_label(index_type type)
{
	return "INLKV"[(int32_t)type];
}

/*
 * Maps a path data type to its one-character label.
 *
 * @param type  The path data type.
 *
 * @result      The one-character label.
 */
static int32_t
text_path_type_to_label(path_type type)
{
	return "ISNG"[(int32_t)type];
}

/*
 * Part of the interface exposed by the text backup file format encoder.
 *
 * See backup_encoder.put_secondary_index for details.
 */
bool
text_put_secondary_index(io_write_proxy_t *fd,
		const index_param *index)
{
	if (io_proxy_printf(fd, GLOBAL_PREFIX "i %s %s %s %c %u",
			escape(index->ns), index->set != NULL ? escape(index->set) : "", escape(index->name),
			text_index_type_to_label(index->type), index->path_vec.size) < 0) {
		err("Error while writing secondary index to backup file [1]");
		return false;
	}

	for (uint32_t i = 0; i < index->path_vec.size; ++i) {
		path_param *path = as_vector_get((as_vector *)&index->path_vec, i);

		if (io_proxy_printf(fd, " %s %c", escape(path->path),
				text_path_type_to_label(path->type)) < 0) {
			err("Error while writing secondary index to backup file [2]");
			return false;
		}
	}

	if (index->ctx != NULL) {
		if (io_proxy_printf(fd, " %s", escape(index->ctx)) < 0) {
			err("Error while writing secondary index to backup file [3]");
			return false;
		}
	}

	if (io_proxy_printf(fd, "\n") < 0) {
		err("Error while writing secondary index to backup file [4]");
		return false;
	}

	return true;
}


text:
TEST(DiagnosticRecordTest, Members)
{
	std::string const odbc_state = "ABCDE";
	int const native_state = -1;
	std::string const message = "Everything is bad.";

	cpp_odbc::level2::diagnostic_record record = {odbc_state, native_state, message};

	EXPECT_EQ( odbc_state, record.odbc_status_code );
	EXPECT_EQ( native_state, record.native_error_code );
	EXPECT_EQ( message, record.message );
}


text:
ENABLE_IMPLICIT_BRIDGING

typedef const struct __CTFramesetter* CTFramesetterRef;

CORETEXT_EXPORT CTFrameRef CTFramesetterCreateFrame(CTFramesetterRef framesetter,
                                                    CFRange stringRange,
                                                    CGPathRef path,
                                                    CFDictionaryRef frameAttributes);
CORETEXT_EXPORT CTFramesetterRef CTFramesetterCreateWithAttributedString(CFAttributedStringRef string);
CORETEXT_EXPORT CGSize CTFramesetterSuggestFrameSizeWithConstraints(
    CTFramesetterRef framesetter, CFRange stringRange, CFDictionaryRef frameAttributes, CGSize constraints, CFRange* fitRange);

DISABLE_IMPLICIT_BRIDGING

#endif // _CTFRAMESETTER_H_


text:
package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;

public class JTreeTextSelectionColorDemo extends JFrame {
    public JTreeTextSelectionColorDemo() throws HeadlessException {
        initializeUI();
    }

    private void initializeUI() {
        setSize(150, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Department");
        DefaultMutableTreeNode book = new DefaultMutableTreeNode("Books");
        DefaultMutableTreeNode fiction = new DefaultMutableTreeNode("Fictions");
        DefaultMutableTreeNode science = new DefaultMutableTreeNode("Sciences");
        DefaultMutableTreeNode text = new DefaultMutableTreeNode("Text Books");
        DefaultMutableTreeNode children = new DefaultMutableTreeNode("Children");

        root.add(book);
        book.add(fiction);
        book.add(science);
        book.add(text);
        book.add(children);

        JTree tree = new JTree(root);

        // Get the DefaultTreeCellRenderer instance of the JTree
        // component. Then we customize the color of the selection
        // node using blue background, white font color and black
        // border.
        DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
        renderer.setTextSelectionColor(Color.white);
        renderer.setBackgroundSelectionColor(Color.blue);
        renderer.setBorderSelectionColor(Color.black);

        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(150, 300));

        getContentPane().add(pane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JTreeTextSelectionColorDemo().setVisible(true);
            }
        });
    }
}


text:
package net.bytebuddy.description.type;

import net.bytebuddy.test.utility.MockitoRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.mockito.Mock;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;

public class TypeDescriptionGenericVisitorTypeErasingTest {

    @Rule
    public TestRule mockitoRule = new MockitoRule(this);

    @Mock
    private TypeDescription.Generic typeDescription, rawType;

    @Before
    public void setUp() throws Exception {
        when(typeDescription.asRawType()).thenReturn(rawType);
    }

    @Test
    public void testGenericArray() throws Exception {
        assertThat(TypeDescription.Generic.Visitor.TypeErasing.INSTANCE.onGenericArray(typeDescription), is(rawType));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testWildcard() throws Exception {
        TypeDescription.Generic.Visitor.TypeErasing.INSTANCE.onWildcard(typeDescription);
    }

    @Test
    public void testParameterized() throws Exception {
        assertThat(TypeDescription.Generic.Visitor.TypeErasing.INSTANCE.onParameterizedType(typeDescription), is(rawType));
    }

    @Test
    public void testTypeVariable() throws Exception {
        assertThat(TypeDescription.Generic.Visitor.TypeErasing.INSTANCE.onTypeVariable(typeDescription), is(rawType));
    }

    @Test
    public void testNonGeneric() throws Exception {
        assertThat(TypeDescription.Generic.Visitor.TypeErasing.INSTANCE.onNonGenericType(typeDescription), is(rawType));
    }
}


text:
$(document).ready(function() {
    $("#fecha_nacimiento").datepicker().mask("99-99-9999");
    $("#nec").focus();

    //PASANDO A MAYUSCULAS LOS ELEMENTOS
    $("#primer_apellido").keyup(function() {
        $(this).val(limpiar_nombres($("#primer_apellido").val()));
    });
    $("#segundo_apellido").keyup(function() {
        $(this).val(limpiar_nombres($("#segundo_apellido").val()));
    });

    $("#apellido_casada").keyup(function() {
        $(this).val(limpiar_nombres($("#apellido_casada").val()));
    });

    $("#primer_nombre").keyup(function() {
        $(this).val(limpiar_nombres($("#primer_nombre").val()));
    });

    $("#segundo_nombre").keyup(function() {
        $(this).val(limpiar_nombres($("#segundo_nombre").val()));
    });

    $("#tercer_nombre").keyup(function() {
        $(this).val(limpiar_nombres($("#tercer_nombre").val()));
    });
    $("#buscar").click(function() {
        if ($("#nec").val() != '') {
            regexp = /^[0-9]{1,}$/;
            var valores = $("#nec").val().split('-');
            if (valores.length > 2) {//VERIFICA SI TIENE MAS DE DOS GUIONES
                /*PARA MOSTRAR MENSAJE DE ERROR DE FORMATO DE EXPEDIENTE
                 * PRIMERO SE CREA O ELIMINA EL ELEMENTO
                 * LUEGO SE CREA CON EL MENSAJE ADECUADO Y SE COLOCA
                 * LUEGO DEL FORMULARIO PARA ABRIRSE.
                 * */
                ($('#error')) ? $('#error').remove() : '';
                var elem = $("
" +
                        "El formato del número de expediente no es el adecuado."
                        + "
");
                elem.insertAfter($("#buscarForm"));
                $("#error").dialog({
                    close: function() {
                        $("#nec").val('');
                        $("#nec").focus();
                    }
                });
                return false;
            } else {
                if (!regexp.test(valores[0])) {//CONTIENE LETRAS EN INFINITO
                    /*PARA MOSTRAR MENSAJE DE ERROR DE FORMATO DE EXPEDIENTE
                     * PRIMERO SE CREA O ELIMINA EL ELEMENTO
                     * LUEGO SE CREA CON EL MENSAJE ADECUADO Y SE COLOCA
                     * LUEGO DEL FORMULARIO PARA ABRIRSE.
                     * */
                    ($('#error')) ? $('#error').remove() : '';
                    var elem = $("
" +
                            "El Número de Expediente no puede contener letras"
                            + "
");
                    elem.insertAfter($("#buscarForm"));
                    $("#error").dialog({
                        close: function() {
                            $("#nec").val('');
                            $("#nec").focus();
                        }
                    });
                    return false;
                } else {
                    if (valores.length > 1) {
                        if (!regexp.test(valores[1])) {
                            /*PARA MOSTRAR MENSAJE DE ERROR DE FORMATO DE EXPEDIENTE
                             * PRIMERO SE CREA O ELIMINA EL ELEMENTO
                             * LUEGO SE CREA CON EL MENSAJE ADECUADO Y SE COLOCA
                             * LUEGO DEL FORMULARIO PARA ABRIRSE.
                             * */
                            ($('#error')) ? $('#error').remove() : '';
                            var elem = $("
" +
                                    "El Número de Expediente no puede contener letras"
                                    + "
");
                            elem.insertAfter($("#buscarForm"));
                            $("#error").dialog({
                                close: function() {
                                    $("#nec").val('');
                                    $("#nec").focus();
                                }
                            });
                            return false;
                        } else {
			$('#resultadoBusqueda').load(Routing.generate('buscar_emergencias'));
                        $('#lresultado').show();
                        $('#resultadoBusqueda').show();

                        }
                    } else {
		        $('#resultadoBusqueda').load(Routing.generate('buscar_emergencias'));
                        $('#lresultado').show();
                        $('#resultadoBusqueda').show();

                    }
                }
            }
        } else {
            if ($("#nec").val() != '') {
                $('#resultadoBusqueda').load(Routing.generate('buscar_emergencias'));
                $('#lresultado').show();
                $('#resultadoBusqueda').show();
            } else {
                if ($("#fecha_nacimiento").val() != '') {
                    $('#resultadoBusqueda').load(Routing.generate('buscar_emergencias'));
                    $('#lresultado').show();
                    $('#resultadoBusqueda').show();
                }
                else {
                    if ($("#primer_apellido").val() == '' && $("#primer_nombre").val() == '') {
                        //SE ELIMINA O SE CREA EL ELEMENTO
                        ($('#error')) ? $('#error').remove() : '';
                        //SE LE ASIGNA VALOR AL ELEMENTO
                        var elem = $("
" +
                                "Los campos:\n\

 Primer Apellido

Primer Nombre

\n\
                Son obligatorios
");
                        //SE AGREGA LUEGO DEL FORMULARIO
                        elem.insertAfter($("#buscarForm"));
                        //SE DEFINEN LAS PROPIEDADES DE LA VENTANA Y SE ABRE.
                        $("#error").dialog({
                            close: function() {
                                $("#primer_apellido").focus();
                            }
                        });
                    } else {
                        $('#resultadoBusqueda').load(Routing.generate('buscar_emergencias'));
                        $('#lresultado').show();
                        $('#resultadoBusqueda').show();
                    }
                }
            }
        }
        return false;
    });
    $('#lresultado').hide();

});


text:
const initialState = {
  statusFilter: 'all',
  sprintFilter: 'all',

  activeStory: {
    story: null,
    error: null,
    loading: false
  },

  storyList: {
    stories: [],
    error: null,
    loading: false
  },

  periodList: {
    periods: [],
    error: null,
    loading: false
  },

  graphTable: {
    graph: [],
    error: null,
    loading: false
  },

  graphDialog: {
    show: false,
    storyId: null,
    dialogDate: null,
    tasksList: [],
    error: null,
    coordinates: {
      top: null,
      right: null
    }
  }
}

const reducer = function(state=initialState, action) {
  switch(action.type) {

    case 'SET_STATUS_FILTER':
      return { ...state, statusFilter: action.payload }

    case 'SET_SPRINT_FILTER':
      return { ...state, sprintFilter: action.payload }

    case 'FETCH_STORIES_REQUEST':
      return { ...state, storyList: {stories: [], error: null, loading: true }}
    case 'FETCH_STORIES_SUCCESS':
      return { ...state, storyList: {stories: action.payload, error: null, loading: false }}
    case 'FETCH_STORIES_FAILURE':
      return { ...state, storyList: {stories: [], error: action.payload, loading: false }}

    case 'FETCH_STORY_REQUEST':
      return { ...state, activeStory: {story: null, error: null, loading: true }}
    case 'FETCH_STORY_SUCCESS':
      return { ...state, activeStory: {story: action.payload, error: null, loading: false }}
    case 'FETCH_STORY_FAILURE':
      return { ...state, activeStory: {story: null, error: action.payload, loading: false }}

    case 'UPDATE_STORY_REQUEST':
      return { ...state, activeStory: {story: null, error: null, loading: true }}
    case 'UPDATE_STORY_SUCCESS':
      return { ...state,
        storyList: {stories: state.storyList.stories.map(story => story.id === action.payload.id ? action.payload : story), error: null, loading: false },
        activeStory: {story: action.payload, error: null, loading: false}
      }
    case 'UPDATE_STORY_FAILURE':
      return { ...state, activeStory: {story: null, error: action.payload, loading: false }}

    case 'CREATE_STORY_REQUEST':
      return { ...state, activeStory: {story: null, error: null, loading: true }}
    case 'CREATE_STORY_SUCCESS':
      return { ...state,
        storyList: {stories: [...state.storyList.stories, action.payload], error: null, loading: false },
        activeStory: {story: action.payload, error: null, loading: false}
      }
    case 'CREATE_STORY_FAILURE':
      return { ...state, activeStory: {story: null, error: action.payload, loading: false }}

    case 'DELETE_STORY_REQUEST':
      return { ...state, active: {story: null, error: null, loading: true }}
    case 'DELETE_STORY_SUCCESS':
      return { ...state,
        storyList: {stories: state.storyList.stories.filter(story => story.id !== action.payload.id), error: null, loading: false },
        activeStory: {story: action.payload, error: null, loading: false}
      }
    case 'DELETE_STORY_FAILURE':
      return { ...state, active: {story: null, error: action.payload, loading: false }}

    case 'FETCH_PERIODS_REQUEST':
      return { ...state, periodList: { periods: [], error: null, loading: true }}
    case 'FETCH_PERIODS_SUCCESS':
      return { ...state, periodList: { periods: action.payload, error: null, loading: false }}
    case 'FETCH_PERIODS_FAILURE':
      return { ...state, periodList: { periods: [], error: action.payload, loading: false }}

    case 'FETCH_GRAPH_REQUEST':
      return { ...state, graphTable: { graph: [], error: null, loading: true }}
    case 'FETCH_GRAPH_SUCCESS':
      return { ...state, graphTable: { graph: action.payload, error: null, loading: false }}
    case 'FETCH_GRAPH_FAILURE':
      return { ...state, graphTable: { graph: [], error: action.payload, loading: false }}

    case 'TOGGLE_DIALOG':
      return { ...state, graphDialog: { ...state.graphDialog, show: action.payload }}
    case 'SET_DIALOG_POSITION':
      return { ...state, graphDialog: { ...state.graphDialog, coordinates: { positionTop: action.payload.positionTop, positionRight: action.payload.positionRight }}}
    case 'SET_DIALOG_STORY_ID':
      return { ...state, graphDialog: { ...state.graphDialog, storyId: action.payload }}
    case 'SET_DIALOG_TITLE_DATE':
      return { ...state, graphDialog: { ...state.graphDialog, dialogDate: action.payload }}
    case 'SET_DIALOG_TASKS_LIST':
      return { ...state, graphDialog: { ...state.graphDialog, tasksList: action.payload }}

    case 'CREATE_TASK_SUCCESS':
      return { ...state, graphDialog: { ...state.graphDialog, tasksList: [...state.graphDialog.tasksList, action.payload] }}
    case 'CREATE_TASK_FAILURE':
      return { ...state, graphDialog: { tasksList: [], error: action.payload }}

    case 'DELETE_TASK_SUCCESS':
      return { ...state, graphDialog: { ...state.graphDialog, tasksList: [...state.graphDialog.tasksList.filter(task => task.id !== action.payload.id)] }}
    case 'DELETE_TASK_FAILURE':
      return { ...state, graphDialog: { tasksList: [], error: action.payload }}

    case 'ADD_TASK_TO_GRAPH_LIST':
      // REWRITE!!
      let _a_storyId = action.payload.storyId
      let _a_task    = action.payload.task
      let _a_newGraph = []

      _a_newGraph = state.graphTable.graph.map( (story) => {
        if (story.id === _a_storyId) {
          if (story.log_work[_a_task.task_date]) {
            story.log_work[_a_task.task_date] = story.log_work[_a_task.task_date].concat([_a_task])
          } else {
            story.log_work[_a_task.task_date] = [_a_task]
          }
        }

        return story
      })

      return { ...state, graphTable: { ...state.graphTable, graph: _a_newGraph, error: null, loading: false }}
    case 'DELETE_TASK_FROM_GRAPH_LIST':
      let _d_storyId = action.payload.storyId
      let _d_task    = action.payload.task
      let _d_newGraph = []

      _d_newGraph = state.graphTable.graph.map( (story) => {
        if (story.id === _d_storyId) {
          story.log_work[_d_task.task_date] = story.log_work[_d_task.task_date].filter(task => task.id !== _d_task.id)
        }

        return story
      })

      return { ...state, graphTable: { ...state.graphTable, graph: _d_newGraph, error: null, loading: false }}

    default:
      return state
  }
}

export default reducer


text:
/* Common Modules
-------------------------------------------------- */
common = {

       express       : require('express'),
       http          : require('http'),
       mu2express    : require('mu2express'),
       render        : require(__base + 'render'),
       game          : require(__base + 'api/game/game.helpers'),
       hash          : require(__base + 'system/achievements/achievement.hex.helper'),
       listroms      : require(__base + 'api/game/game.platform.roms'),
       databases     : require(__base + 'api/database/database.local'),
       listPlatforms : require(__base + 'api/api.platforms'),
       profiles      : require(__base + 'api/api.profiles'),
       network       : require(__base + 'api/network/network.online'),
       location      : require(__base + 'api/network/network.location'),
       db            : require(__base + 'api/game/game.image'),
       hex           : require(__base + "system/achievements/achievement.hex.helper"),
       exec          : require(__base + 'system/system.exec'),
       serverAPI     : require(__base + 'api/server/server.api'),
       getSet        : require(__base + 'api/api.sets'),
       systemWrite   : require(__base + 'system/system.write'),
       systemRead    : require(__base + 'system/system.read'),
       wireless      : require(__base + 'api/network/network.wireless'),
       process       : require(__base + "system/system.process"),
       settings      : require(__base + "system/system.settings").settings,
       invite        : require(__base + "api/game/game.invite")

};

/*  Exports
-------------------------------------------------- */
module.exports = common;


text:
CREATE TABLE [dbo].[ResultMessages] (
    [ID]      BIGINT         NOT NULL,
    [Message] NVARCHAR (500) NULL,
    [IsError] BIT            NULL,
    CONSTRAINT [PK_ErrorMessages] PRIMARY KEY CLUSTERED ([ID] ASC)
);


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

import com.facebook.presto.execution.TaskId;
import com.facebook.presto.operator.HashSemiJoinOperator.HashSemiJoinOperatorFactory;
import com.facebook.presto.operator.SetBuilderOperator.SetBuilderOperatorFactory;
import com.facebook.presto.sql.analyzer.Session;
import com.facebook.presto.util.MaterializedResult;
import com.google.common.collect.ImmutableList;
import io.airlift.units.DataSize;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.List;
import java.util.concurrent.ExecutorService;

import static com.facebook.presto.operator.RowPagesBuilder.rowPagesBuilder;
import static com.facebook.presto.tuple.TupleInfo.SINGLE_LONG;
import static com.facebook.presto.tuple.TupleInfo.Type.BOOLEAN;
import static com.facebook.presto.tuple.TupleInfo.Type.FIXED_INT_64;
import static com.facebook.presto.util.MaterializedResult.resultBuilder;
import static com.facebook.presto.util.Threads.daemonThreadsNamed;
import static io.airlift.units.DataSize.Unit.BYTE;
import static java.util.concurrent.Executors.newCachedThreadPool;

public class TestHashSemiJoinOperator
{
    private ExecutorService executor;
    private TaskContext taskContext;

    @BeforeMethod
    public void setUp()
    {
        executor = newCachedThreadPool(daemonThreadsNamed("test"));
        Session session = new Session("user", "source", "catalog", "schema", "address", "agent");
        taskContext = new TaskContext(new TaskId("query", "stage", "task"), executor, session);
    }

    @AfterMethod
    public void tearDown()
    {
        executor.shutdownNow();
    }

    @Test
    public void testSemiJoin()
            throws Exception
    {
        DriverContext driverContext = taskContext.addPipelineContext(true, true).addDriverContext();

        // build
        OperatorContext operatorContext = driverContext.addOperatorContext(0, StaticOperator.class.getSimpleName());
        Operator buildOperator = new StaticOperator(operatorContext, rowPagesBuilder(SINGLE_LONG)
                .row(10)
                .row(30)
                .row(30)
                .row(35)
                .row(36)
                .row(37)
                .row(50)
                .build());
        SetBuilderOperatorFactory setBuilderOperatorFactory = new SetBuilderOperatorFactory(1, buildOperator.getTupleInfos(), 0, 10);
        Operator setBuilderOperator = setBuilderOperatorFactory.createOperator(driverContext);

        Driver driver = new Driver(driverContext, buildOperator, setBuilderOperator);
        while (!driver.isFinished()) {
            driver.process();
        }

        // probe
        List<Page> probeInput = rowPagesBuilder(SINGLE_LONG, SINGLE_LONG)
                .addSequencePage(10, 30, 0)
                .build();
        HashSemiJoinOperatorFactory joinOperatorFactory = new HashSemiJoinOperatorFactory(
                2,
                setBuilderOperatorFactory.getSetProvider(),
                ImmutableList.of(SINGLE_LONG, SINGLE_LONG),
                0);
        Operator joinOperator = joinOperatorFactory.createOperator(driverContext);

        // expected
        MaterializedResult expected = resultBuilder(FIXED_INT_64, FIXED_INT_64, BOOLEAN)
                .row(30, 0, true)
                .row(31, 1, false)
                .row(32, 2, false)
                .row(33, 3, false)
                .row(34, 4, false)
                .row(35, 5, true)
                .row(36, 6, true)
                .row(37, 7, true)
                .row(38, 8, false)
                .row(39, 9, false)
                .build();

        OperatorAssertion.assertOperatorEquals(joinOperator, probeInput, expected);
    }

    @Test
    public void testBuildSideNulls()
            throws Exception
    {
        DriverContext driverContext = taskContext.addPipelineContext(true, true).addDriverContext();

        // build
        OperatorContext operatorContext = driverContext.addOperatorContext(0, StaticOperator.class.getSimpleName());
        Operator buildOperator = new StaticOperator(operatorContext, rowPagesBuilder(SINGLE_LONG)
                .row(0)
                .row(1)
                .row(2)
                .row(2)
                .row(3)
                .row((Object) null)
                .build());
        SetBuilderOperatorFactory setBuilderOperatorFactory = new SetBuilderOperatorFactory(1, buildOperator.getTupleInfos(), 0, 10);
        Operator setBuilderOperator = setBuilderOperatorFactory.createOperator(driverContext);

        Driver driver = new Driver(driverContext, buildOperator, setBuilderOperator);
        while (!driver.isFinished()) {
            driver.process();
        }

        // probe
        List<Page> probeInput = rowPagesBuilder(SINGLE_LONG)
                .addSequencePage(4, 1)
                .build();
        HashSemiJoinOperatorFactory joinOperatorFactory = new HashSemiJoinOperatorFactory(
                2,
                setBuilderOperatorFactory.getSetProvider(),
                ImmutableList.of(SINGLE_LONG),
                0);
        Operator joinOperator = joinOperatorFactory.createOperator(driverContext);

        // expected
        MaterializedResult expected = resultBuilder(FIXED_INT_64, BOOLEAN)
                .row(1, true)
                .row(2, true)
                .row(3, true)
                .row(4, null)
                .build();

        OperatorAssertion.assertOperatorEquals(joinOperator, probeInput, expected);
    }

    @Test
    public void testProbeSideNulls()
            throws Exception
    {
        DriverContext driverContext = taskContext.addPipelineContext(true, true).addDriverContext();

        // build
        OperatorContext operatorContext = driverContext.addOperatorContext(0, StaticOperator.class.getSimpleName());
        Operator buildOperator = new StaticOperator(operatorContext, rowPagesBuilder(SINGLE_LONG)
                .row(0)
                .row(1)
                .row(3)
                .build());
        SetBuilderOperatorFactory setBuilderOperatorFactory = new SetBuilderOperatorFactory(1, buildOperator.getTupleInfos(), 0, 10);
        Operator setBuilderOperator = setBuilderOperatorFactory.createOperator(driverContext);

        Driver driver = new Driver(driverContext, buildOperator, setBuilderOperator);
        while (!driver.isFinished()) {
            driver.process();
        }

        // probe
        List<Page> probeInput = rowPagesBuilder(SINGLE_LONG)
                .row(0)
                .row((Object) null)
                .row(1)
                .row(2)
                .build();
        HashSemiJoinOperatorFactory joinOperatorFactory = new HashSemiJoinOperatorFactory(
                2,
                setBuilderOperatorFactory.getSetProvider(),
                ImmutableList.of(SINGLE_LONG),
                0);
        Operator joinOperator = joinOperatorFactory.createOperator(driverContext);

        // expected
        MaterializedResult expected = resultBuilder(FIXED_INT_64, BOOLEAN)
                .row(0, true)
                .row(null, null)
                .row(1, true)
                .row(2, false)
                .build();

        OperatorAssertion.assertOperatorEquals(joinOperator, probeInput, expected);
    }

    @Test
    public void testProbeAndBuildNulls()
            throws Exception
    {
        DriverContext driverContext = taskContext.addPipelineContext(true, true).addDriverContext();

        // build
        OperatorContext operatorContext = driverContext.addOperatorContext(0, StaticOperator.class.getSimpleName());
        Operator buildOperator = new StaticOperator(operatorContext, rowPagesBuilder(SINGLE_LONG)
                .row(0)
                .row(1)
                .row((Object) null)
                .row(3)
                .build());
        SetBuilderOperatorFactory setBuilderOperatorFactory = new SetBuilderOperatorFactory(1, buildOperator.getTupleInfos(), 0, 10);
        Operator setBuilderOperator = setBuilderOperatorFactory.createOperator(driverContext);

        Driver driver = new Driver(driverContext, buildOperator, setBuilderOperator);
        while (!driver.isFinished()) {
            driver.process();
        }

        // probe
        List<Page> probeInput = rowPagesBuilder(SINGLE_LONG)
                .row(0)
                .row((Object) null)
                .row(1)
                .row(2)
                .build();
        HashSemiJoinOperatorFactory joinOperatorFactory = new HashSemiJoinOperatorFactory(
                2,
                setBuilderOperatorFactory.getSetProvider(),
                ImmutableList.of(SINGLE_LONG),
                0);
        Operator joinOperator = joinOperatorFactory.createOperator(driverContext);

        // expected
        MaterializedResult expected = resultBuilder(FIXED_INT_64, BOOLEAN)
                .row(0, true)
                .row(null, null)
                .row(1, true)
                .row(2, null)
                .build();

        OperatorAssertion.assertOperatorEquals(joinOperator, probeInput, expected);
    }

    @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Task exceeded max memory size.*")
    public void testMemoryLimit()
            throws Exception
    {
        Session session = new Session("user", "source", "catalog", "schema", "address", "agent");
        DriverContext driverContext = new TaskContext(new TaskId("query", "stage", "task"), executor, session, new DataSize(100, BYTE))
                .addPipelineContext(true, true)
                .addDriverContext();

        OperatorContext operatorContext = driverContext.addOperatorContext(0, StaticOperator.class.getSimpleName());
        Operator buildOperator = new StaticOperator(operatorContext, rowPagesBuilder(SINGLE_LONG)
                .addSequencePage(1000, 20)
                .build());
        SetBuilderOperatorFactory setBuilderOperatorFactory = new SetBuilderOperatorFactory(1, buildOperator.getTupleInfos(), 0, 10);
        Operator setBuilderOperator = setBuilderOperatorFactory.createOperator(driverContext);

        Driver driver = new Driver(driverContext, buildOperator, setBuilderOperator);
        while (!driver.isFinished()) {
            driver.process();
        }
    }
}


text:
<component name="libraryTable">
  <library name="SBT: org.apache.xmlgraphics:batik-xml:1.7:jar">
    <CLASSES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.apache.xmlgraphics/batik-xml/jars/batik-xml-1.7.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.apache.xmlgraphics/batik-xml/srcs/batik-xml-1.7-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
<?php

namespace Reliv\PipeRat\Middleware\RequestFormat\JsonParamsFilter;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Reliv\PipeRat\Exception\InvalidWhereException;
use Reliv\PipeRat\Middleware\Middleware;

class Limit implements Middleware
{
    /**
     * __invoke
     *
     * @param Request       $request
     * @param Response      $response
     * @param callable|null $next
     *
     * @return mixed
     * @throws InvalidWhereException
     */
    public function __invoke(Request $request, Response $response, callable $next = null)
    {
        $params = $request->getQueryParams();

        if (!array_key_exists('limit', $params)) {
            return $next($request, $response);
        }

        $param = (int)$params['limit'];

        $request = $request->withAttribute('limitFilterParam', $param);

        return $next($request, $response);
    }
}


text:
  TYPED_TEST_P(SuiteName, TestName)
#define REGISTER_TYPED_TEST_SUITE_P_WITH_EXPANSION(SuiteName, ...) \
  REGISTER_TYPED_TEST_SUITE_P(SuiteName, __VA_ARGS__)

namespace gl {

namespace internal {

void DrawTextureQuad(GLenum target, const gfx::Size& size);
}

class GLImageTestDelegateBase {
 public:
  virtual ~GLImageTestDelegateBase() {}

  virtual void DidSetUp() {}
  virtual void WillTearDown() {}

  virtual absl::optional<GLImplementationParts> GetPreferedGLImplementation()
      const;
  virtual bool SkipTest(GLDisplay* display) const;
};

template <typename GLImageTestDelegate>
class GLImageTest : public testing::Test {
 protected:
  // Overridden from testing::Test:
  void SetUp() override {
    auto prefered_impl = delegate_.GetPreferedGLImplementation();
    display_ = GLImageTestSupport::InitializeGL(prefered_impl);
    surface_ = gl::init::CreateOffscreenGLSurface(display_, gfx::Size());
    context_ =
        gl::init::CreateGLContext(nullptr, surface_.get(), GLContextAttribs());
    context_->MakeCurrent(surface_.get());
    delegate_.DidSetUp();
  }
  void TearDown() override {
    delegate_.WillTearDown();
    context_->ReleaseCurrent(surface_.get());
    context_ = nullptr;
    surface_ = nullptr;
    GLImageTestSupport::CleanupGL(display_);
  }

 protected:
  scoped_refptr<GLSurface> surface_;
  scoped_refptr<GLContext> context_;
  GLImageTestDelegate delegate_;
  raw_ptr<GLDisplay> display_ = nullptr;
};

TYPED_TEST_SUITE_P(GLImageTest);

TYPED_TEST_P_WITH_EXPANSION(GLImageTest, MAYBE_Create) {
  if (this->delegate_.SkipTest(this->display_))
    GTEST_SKIP() << "Skip because GL initialization failed";

  // NOTE: On some drm devices (mediatek) the mininum width/height to add an fb
  // for a bo must be 64, and YVU_420 in i915 requires at least 128 length.
  const gfx::Size small_image_size(128, 128);
  const gfx::Size large_image_size(512, 512);
  const uint8_t* image_color = this->delegate_.GetImageColor();

  // Create a small solid color green image of preferred format. This must
  // succeed in order for a GLImage to be conformant.
  scoped_refptr<GLImage> small_image =
      this->delegate_.CreateSolidColorImage(small_image_size, image_color);
  ASSERT_TRUE(small_image);

  // Create a large solid color green image of preferred format. This must
  // succeed in order for a GLImage to be conformant.
  scoped_refptr<GLImage> large_image =
      this->delegate_.CreateSolidColorImage(large_image_size, image_color);
  ASSERT_TRUE(large_image);

  // Verify that image size is correct.
  EXPECT_EQ(small_image->GetSize().ToString(), small_image_size.ToString());
  EXPECT_EQ(large_image->GetSize().ToString(), large_image_size.ToString());
}

// The GLImageTest test case verifies the behaviour that is expected from a
// GLImage in order to be conformant.
REGISTER_TYPED_TEST_SUITE_P_WITH_EXPANSION(GLImageTest, MAYBE_Create);

template <typename GLImageTestDelegate>
class GLImageOddSizeTest : public GLImageTest<GLImageTestDelegate> {};

// This test verifies that odd-sized GLImages can be created and destroyed.
TYPED_TEST_SUITE_P(GLImageOddSizeTest);

TYPED_TEST_P_WITH_EXPANSION(GLImageOddSizeTest, MAYBE_Create) {
  if (this->delegate_.SkipTest(this->display_))
    GTEST_SKIP() << "Skip because GL initialization failed";

  const gfx::Size odd_image_size(17, 53);
  const uint8_t* image_color = this->delegate_.GetImageColor();

  // Create an odd-sized solid color green image of preferred format. This must
  // succeed in order for a GLImage to be conformant.
  scoped_refptr<GLImage> odd_image =
      this->delegate_.CreateSolidColorImage(odd_image_size, image_color);
  ASSERT_TRUE(odd_image);

  // Verify that image size is correct.
  EXPECT_EQ(odd_image->GetSize().ToString(), odd_image_size.ToString());
}

// The GLImageTest test case verifies the behaviour that is expected from a
// GLImage in order to be conformant.
REGISTER_TYPED_TEST_SUITE_P_WITH_EXPANSION(GLImageOddSizeTest, MAYBE_Create);

}  // namespace gl

// Avoid polluting source files that include this header.
#undef MAYBE_Create
#undef TYPED_TEST_P_WITH_EXPANSION
#undef REGISTER_TYPED_TEST_SUITE_P_WITH_EXPANSION

#endif  // UI_GL_TEST_GL_IMAGE_TEST_TEMPLATE_H_


text:
package org.apache.metron.common.configuration.profiler;

import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.metron.common.utils.JSONUtils;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * The configuration object for the Profiler, which may contain many Profile definitions.
 */
@JsonSerialize(include=Inclusion.NON_NULL)
public class ProfilerConfig implements Serializable {

  /**
   * One or more profile definitions.
   */
  private List<ProfileConfig> profiles = new ArrayList<>();

  /**
   * The name of a field containing the timestamp that is used to
   * generate profiles.
   *
   *
By default, the processing time of the Profiler is used rather
   * than event time; a value contained within the message itself.
   *
   *
The field must contain a timestamp in epoch milliseconds.
   *
   *
If a message does NOT contain this field, it will be dropped
   * and not included in any profiles.
   */
  private String timestampField = null;

  public List<ProfileConfig> getProfiles() {
    return profiles;
  }

  public void setProfiles(List<ProfileConfig> profiles) {
    this.profiles = profiles;
  }

  public ProfilerConfig withProfile(ProfileConfig profileConfig) {
    this.profiles.add(profileConfig);
    return this;
  }

  @JsonGetter("timestampField")
  public String getTimestampFieldForJson() {
    return timestampField;
  }

  public Optional<String> getTimestampField() {
    return Optional.ofNullable(timestampField);
  }

  @JsonSetter("timestampField")
  public void setTimestampField(String timestampField) {
    this.timestampField = timestampField;
  }

  public void setTimestampField(Optional<String> timestampField) {
    this.timestampField = timestampField.orElse(null);
  }

  public ProfilerConfig withTimestampField(Optional<String> timestampField) {
    this.timestampField = timestampField.orElse(null);
    return this;
  }

  @Override
  public String toString() {
    return new ToStringBuilder(this)
            .append("profiles", profiles)
            .append("timestampField", timestampField)
            .toString();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }

    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    ProfilerConfig that = (ProfilerConfig) o;
    return new EqualsBuilder()
            .append(profiles, that.profiles)
            .append(timestampField, that.timestampField)
            .isEquals();
  }

  @Override
  public int hashCode() {
    return new HashCodeBuilder(17, 37)
            .append(profiles)
            .append(timestampField)
            .toHashCode();
  }

  /**
   * Deserialize a {@link ProfilerConfig}.
   *
   * @param bytes Raw bytes containing a UTF-8 JSON String.
   * @return The Profiler configuration.
   * @throws IOException If there's an error deserializing the raw bytes
   */
  public static ProfilerConfig fromBytes(byte[] bytes) throws IOException {
    return JSONUtils.INSTANCE.load(new String(bytes), ProfilerConfig.class);
  }

  /**
   * Deserialize a {@link ProfilerConfig}.
   *
   * @param json A String containing JSON.
   * @return The Profiler configuration.
   * @throws IOException If there's an error deserializing the string
   */
  public static ProfilerConfig fromJSON(String json) throws IOException {
    return JSONUtils.INSTANCE.load(json, ProfilerConfig.class);
  }

  /**
   * Serialize a {@link ProfilerConfig} to a JSON string.
   *
   * @return The Profiler configuration serialized as a JSON string.
   * @throws JsonProcessingException If an error occurs serializing this as a Json string
   */
  public String toJSON() throws JsonProcessingException {
    return JSONUtils.INSTANCE.toJSON(this, true);
  }
}


text:
package April2021Leetcode;

import java.util.ArrayList;
import java.util.List;

public class _0068TextJustification {

	public static void main(String[] args) {
		System.out.println(
				fullJustify(new String[] { "This", "is", "an", "example", "of", "text", "justification." }, 16));
		System.out.println(fullJustify(new String[] { "What", "must", "be", "acknowledgment", "shall", "be" }, 16));
		System.out.println(fullJustify(new String[] { "Science", "is", "what", "we", "understand", "well", "enough",
				"to", "explain", "to", "a", "computer.", "Art", "is", "everything", "else", "we", "do" }, 20));
	}

	public static List<String> fullJustify(String[] words, int maxWidth) {
		int left = 0;
		int currWidth = 0;
		List<String> output = new ArrayList<String>();
		for (int i = 0; i < words.length; i++) {
			if (currWidth == 0) {
				currWidth = words[i].length();
			} else {
				currWidth += words[i].length() + 1;
			}

			if (currWidth >= maxWidth) {
				if (currWidth == maxWidth) {
					output.add(justify(left, i, words, maxWidth));
					left = i + 1;
					currWidth = 0;
				} else {
					output.add(justify(left, i - 1, words, maxWidth));
					left = i;
					currWidth = words[i].length();
				}
			}
		}

		if (currWidth != 0) {
			output.add(justify(left, words.length - 1, words, maxWidth));
		}
		return output;
	}

	public static String justify(int left, int right, String[] words, int maxWidth) {
		if (left == right || right == words.length - 1) {
			return justifyRight(left, right, words, maxWidth);
		}
		int noOfWords = right - left;
		int wordsLength = 0;
		for (int i = left; i <= right; i++) {
			wordsLength += words[i].length();
		}
		int totalRemainingWidth = maxWidth - wordsLength;
		int noOfSpaces = totalRemainingWidth / noOfWords;
		int extraSpaces = totalRemainingWidth % noOfWords;

		StringBuilder sb = new StringBuilder();
		sb.append(words[left]);
		for (int i = left + 1; i <= right; i++) {
			sb.append(spaces(noOfSpaces));
			sb.append(spaces(extraSpaces--));
			sb.append(words[i]);
		}
		return sb.toString();
	}

	public static String justifyRight(int left, int right, String[] words, int maxWidth) {
		StringBuilder sb = new StringBuilder();
		sb.append(words[left]);
		for (int i = left + 1; i <= right; i++) {
			sb.append(spaces(1));
			sb.append(words[i]);
		}
		while (sb.length() < maxWidth)
			sb.append(spaces(1));

		return sb.toString();
	}

	public static String spaces(int count) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < count; i++) {
			sb.append(" ");
		}
		return sb.toString();
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Current_Address__c</name>
    <help>Cerqueu el registre d'adreces actual d'aquest compte. El camp Adreça de facturació del compte s'omple amb els camps d'adreça del registre d'adreces actual.</help>
    <relationshipLabel>Comptes (adreça actual)</relationshipLabel>
    <label>Adreça actual</label>
</CustomFieldTranslation>


text:
<?php
/**
 * @package Abricos
 * @subpackage I18n
 * @author Alexander Kuzmin <roosit@abricos.org>
 */

/**
 * Модуль I18n
 */
class I18nModule extends Ab_Module {

    /**
     * @var I18nModule
     */
    public static $instance;

    private $_manager = null;

    /**
     * Конструктор
     */
    public function __construct(){
        I18nModule::$instance = $this;
        $this->version = "0.2.0";
        $this->name = "i18n";
        $this->permission = new I18nPermission($this);
    }

    /**
     * @return I18nModuleManager
     */
    public function GetManager(){
        if (is_null($this->_manager)){
            require_once 'includes/manager.php';
            $this->_manager = new I18nModuleManager($this);
        }
        return $this->_manager;
    }

    public function Bos_IsMenu(){
        return true;
    }
}

class I18nAction {
    const VIEW = 10;
    const WRITE = 30;
    const ADMIN = 50;
}

class I18nPermission extends Ab_UserPermission {

    public function I18nPermission(I18nModule $module){
        $defRoles = array(
            new Ab_UserRole(I18nAction::VIEW, Ab_UserGroup::ADMIN),
            new Ab_UserRole(I18nAction::WRITE, Ab_UserGroup::ADMIN),
            new Ab_UserRole(I18nAction::ADMIN, Ab_UserGroup::ADMIN)
        );
        parent::__construct($module, $defRoles);
    }

    public function GetRoles(){
        return array(
            I18nAction::VIEW => $this->CheckAction(I18nAction::VIEW),
            I18nAction::WRITE => $this->CheckAction(I18nAction::WRITE),
            I18nAction::ADMIN => $this->CheckAction(I18nAction::ADMIN)
        );
    }
}

// создать экземляр класса модуля и зарегистрировать его в ядре
Abricos::ModuleRegister(new I18nModule())

?>


text:
This site uses:

- [**Solidus**][solidus] serves pages from API data and [Handlebars templates][handlebars]
- [**gulp**][gulp] is used as a build tool for compiling CSS, JS and other assets
- [**Storyteller.io**][storyteller] provides reliable access to APIs

## Development :octocat:

Please see the [Sparkart Developers' Wiki][sparkart-developers-wiki] for information about recommended workflow and tools available for Solidus site development.

[solidus]: https://github.com/SparkartGroupInc/solidus
[handlebars]: http://handlebarsjs.com
[gulp]: http://gulpjs.com
[storyteller]: http://www.storyteller.io
[sparkart-developers-wiki]: https://github.com/SparkartGroupInc/developers.sparkart.com/wiki