text:
"""Config flow to configure homekit_controller."""
from __future__ import annotations

import logging
import re
from typing import Any

import aiohomekit
from aiohomekit.exceptions import AuthenticationError
from aiohomekit.model import Accessories, CharacteristicsTypes, ServicesTypes
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.components import zeroconf
from homeassistant.core import callback
from homeassistant.data_entry_flow import AbortFlow, FlowResult
from homeassistant.helpers import device_registry as dr

from .const import DOMAIN, KNOWN_DEVICES
from .utils import async_get_controller

HOMEKIT_DIR = ".homekit"
HOMEKIT_BRIDGE_DOMAIN = "homekit"

HOMEKIT_IGNORE = [
    # eufy Indoor Cam 2K and 2K Pan & Tilt
    # https://github.com/home-assistant/core/issues/42307
    "T8400",
    "T8410",
    # Hive Hub - vendor does not give user a pairing code
    "HHKBridge1,1",
]

PAIRING_FILE = "pairing.json"

PIN_FORMAT = re.compile(r"^(\d{3})-{0,1}(\d{2})-{0,1}(\d{3})$")

_LOGGER = logging.getLogger(__name__)

INSECURE_CODES = {
    "00000000",
    "11111111",
    "22222222",
    "33333333",
    "44444444",
    "55555555",
    "66666666",
    "77777777",
    "88888888",
    "99999999",
    "12345678",
    "87654321",
}

def normalize_hkid(hkid: str) -> str:
    """Normalize a hkid so that it is safe to compare with other normalized hkids."""
    return hkid.lower()

@callback
def find_existing_host(hass, serial: str) -> config_entries.ConfigEntry | None:
    """Return a set of the configured hosts."""
    for entry in hass.config_entries.async_entries(DOMAIN):
        if entry.data.get("AccessoryPairingID") == serial:
            return entry
    return None

def ensure_pin_format(pin: str, allow_insecure_setup_codes: Any = None) -> str:
    """
    Ensure a pin code is correctly formatted.

    Ensures a pin code is in the format 111-11-111. Handles codes with and without dashes.

    If incorrect code is entered, an exception is raised.
    """
    if not (match := PIN_FORMAT.search(pin.strip())):
        raise aiohomekit.exceptions.MalformedPinError(f"Invalid PIN code f{pin}")
    pin_without_dashes = "".join(match.groups())
    if not allow_insecure_setup_codes and pin_without_dashes in INSECURE_CODES:
        raise InsecureSetupCode(f"Invalid PIN code f{pin}")
    return "-".join(match.groups())

class HomekitControllerFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle a HomeKit config flow."""

    VERSION = 1

    def __init__(self):
        """Initialize the homekit_controller flow."""
        self.model = None
        self.hkid = None
        self.name = None
        self.devices = {}
        self.controller = None
        self.finish_pairing = None

    async def _async_setup_controller(self):
        """Create the controller."""
        self.controller = await async_get_controller(self.hass)

    async def async_step_user(self, user_input=None):
        """Handle a flow start."""
        errors = {}

        if user_input is not None:
            key = user_input["device"]
            self.hkid = self.devices[key].description.id
            self.model = self.devices[key].description.model
            self.name = self.devices[key].description.name

            await self.async_set_unique_id(
                normalize_hkid(self.hkid), raise_on_progress=False
            )

            return await self.async_step_pair()

        if self.controller is None:
            await self._async_setup_controller()

        self.devices = {}

        async for discovery in self.controller.async_discover():
            if discovery.paired:
                continue
            self.devices[discovery.description.name] = discovery

        if not self.devices:
            return self.async_abort(reason="no_devices")

        return self.async_show_form(
            step_id="user",
            errors=errors,
            data_schema=vol.Schema(
                {vol.Required("device"): vol.In(self.devices.keys())}
            ),
        )

    async def async_step_unignore(self, user_input):
        """Rediscover a previously ignored discover."""
        unique_id = user_input["unique_id"]
        await self.async_set_unique_id(unique_id)

        if self.controller is None:
            await self._async_setup_controller()

        try:
            device = await self.controller.async_find(unique_id)
        except aiohomekit.AccessoryNotFoundError:
            return self.async_abort(reason="accessory_not_found_error")

        self.name = device.description.name
        self.model = device.description.model
        self.hkid = device.description.id

        return self._async_step_pair_show_form()

    async def _hkid_is_homekit(self, hkid):
        """Determine if the device is a homekit bridge or accessory."""
        dev_reg = dr.async_get(self.hass)
        device = dev_reg.async_get_device(
            identifiers=set(), connections={(dr.CONNECTION_NETWORK_MAC, hkid)}
        )

        if device is None:
            return False

        for entry_id in device.config_entries:
            entry = self.hass.config_entries.async_get_entry(entry_id)
            if entry and entry.domain == HOMEKIT_BRIDGE_DOMAIN:
                return True

        return False

    async def async_step_zeroconf(
        self, discovery_info: zeroconf.ZeroconfServiceInfo
    ) -> FlowResult:
        """Handle a discovered HomeKit accessory.

        This flow is triggered by the discovery component.
        """
        # Normalize properties from discovery
        # homekit_python has code to do this, but not in a form we can
        # easily use, so do the bare minimum ourselves here instead.
        properties = {
            key.lower(): value for (key, value) in discovery_info.properties.items()
        }

        if zeroconf.ATTR_PROPERTIES_ID not in properties:
            # This can happen if the TXT record is received after the PTR record
            # we will wait for the next update in this case
            _LOGGER.debug(
                "HomeKit device %s: id not exposed; TXT record may have not yet been received",
                properties,
            )
            return self.async_abort(reason="invalid_properties")

        # The hkid is a unique random number that looks like a pairing code.
        # It changes if a device is factory reset.
        hkid = properties[zeroconf.ATTR_PROPERTIES_ID]
        normalized_hkid = normalize_hkid(hkid)

        model = properties["md"]
        name = discovery_info.name.replace("._hap._tcp.local.", "")
        status_flags = int(properties["sf"])
        paired = not status_flags & 0x01

        # The configuration number increases every time the characteristic map
        # needs updating. Some devices use a slightly off-spec name so handle
        # both cases.
        try:
            config_num = int(properties["c#"])
        except KeyError:
            _LOGGER.warning(
                "HomeKit device %s: c# not exposed, in violation of spec", hkid
            )
            config_num = None

        # Set unique-id and error out if it's already configured
        existing_entry = await self.async_set_unique_id(
            normalized_hkid, raise_on_progress=False
        )
        updated_ip_port = {
            "AccessoryIP": discovery_info.host,
            "AccessoryPort": discovery_info.port,
        }

        # If the device is already paired and known to us we should monitor c#
        # (config_num) for changes. If it changes, we check for new entities
        if paired and hkid in self.hass.data.get(KNOWN_DEVICES, {}):
            if existing_entry:
                self.hass.config_entries.async_update_entry(
                    existing_entry, data={**existing_entry.data, **updated_ip_port}
                )
            conn = self.hass.data[KNOWN_DEVICES][hkid]
            # When we rediscover the device, let aiohomekit know
            # that the device is available and we should not wait
            # to retry connecting any longer. reconnect_soon
            # will do nothing if the device is already connected
            await conn.pairing.connection.reconnect_soon()
            if conn.config_num != config_num:
                _LOGGER.debug(
                    "HomeKit info %s: c# incremented, refreshing entities", hkid
                )
                self.hass.async_create_task(conn.async_refresh_entity_map(config_num))
            return self.async_abort(reason="already_configured")

        _LOGGER.debug("Discovered device %s (%s - %s)", name, model, hkid)

        # Device isn't paired with us or anyone else.
        # But we have a 'complete' config entry for it - that is probably
        # invalid. Remove it automatically.
        existing = find_existing_host(self.hass, hkid)
        if not paired and existing:
            if self.controller is None:
                await self._async_setup_controller()

            # mypy can't see that self._async_setup_controller() always sets self.controller or throws
            assert self.controller

            pairing = self.controller.load_pairing(
                existing.data["AccessoryPairingID"], dict(existing.data)
            )

            try:
                await pairing.list_accessories_and_characteristics()
            except AuthenticationError:
                _LOGGER.debug(
                    "%s (%s - %s) is unpaired. Removing invalid pairing for this device",
                    name,
                    model,
                    hkid,
                )
                await self.hass.config_entries.async_remove(existing.entry_id)
            else:
                _LOGGER.debug(
                    "%s (%s - %s) claims to be unpaired but isn't. "
                    "It's implementation of HomeKit is defective "
                    "or a zeroconf relay is broadcasting stale data",
                    name,
                    model,
                    hkid,
                )
                return self.async_abort(reason="already_paired")

        # Set unique-id and error out if it's already configured
        self._abort_if_unique_id_configured(updates=updated_ip_port)

        for progress in self._async_in_progress(include_uninitialized=True):
            context = progress["context"]
            if context.get("unique_id") == normalized_hkid and not context.get(
                "pairing"
            ):
                if paired:
                    # If the device gets paired, we want to dismiss
                    # an existing discovery since we can no longer
                    # pair with it
                    self.hass.config_entries.flow.async_abort(progress["flow_id"])
                else:
                    raise AbortFlow("already_in_progress")

        if paired:
            # Device is paired but not to us - ignore it
            _LOGGER.debug("HomeKit device %s ignored as already paired", hkid)
            return self.async_abort(reason="already_paired")

        # Devices in HOMEKIT_IGNORE have native local integrations - users
        # should be encouraged to use native integration and not confused
        # by alternative HK API.
        if model in HOMEKIT_IGNORE:
            return self.async_abort(reason="ignored_model")

        # If this is a HomeKit bridge/accessory exported by *this* HA instance ignore it.
        if await self._hkid_is_homekit(hkid):
            return self.async_abort(reason="ignored_model")

        self.name = name
        self.model = model
        self.hkid = hkid

        # We want to show the pairing form - but don't call async_step_pair
        # directly as it has side effects (will ask the device to show a
        # pairing code)
        return self._async_step_pair_show_form()

    async def async_step_pair(self, pair_info=None):
        """Pair with a new HomeKit accessory."""
        # If async_step_pair is called with no pairing code then we do the M1
        # phase of pairing. If this is successful the device enters pairing
        # mode.

        # If it doesn't have a screen then the pin is static.

        # If it has a display it will display a pin on that display. In
        # this case the code is random. So we have to call the async_start_pairing
        # API before the user can enter a pin. But equally we don't want to
        # call async_start_pairing when the device is discovered, only when they
        # click on 'Configure' in the UI.

        # async_start_pairing will make the device show its pin and return a
        # callable. We call the callable with the pin that the user has typed
        # in.

        errors = {}

        if self.controller is None:
            await self._async_setup_controller()

        if pair_info and self.finish_pairing:
            self.context["pairing"] = True
            code = pair_info["pairing_code"]
            try:
                code = ensure_pin_format(
                    code,
                    allow_insecure_setup_codes=pair_info.get(
                        "allow_insecure_setup_codes"
                    ),
                )
                pairing = await self.finish_pairing(code)
                return await self._entry_from_accessory(pairing)
            except aiohomekit.exceptions.MalformedPinError:
                # Library claimed pin was invalid before even making an API call
                errors["pairing_code"] = "authentication_error"
            except aiohomekit.AuthenticationError:
                # PairSetup M4 - SRP proof failed
                # PairSetup M6 - Ed25519 signature verification failed
                # PairVerify M4 - Decryption failed
                # PairVerify M4 - Device not recognised
                # PairVerify M4 - Ed25519 signature verification failed
                errors["pairing_code"] = "authentication_error"
                self.finish_pairing = None
            except aiohomekit.UnknownError:
                # An error occurred on the device whilst performing this
                # operation.
                errors["pairing_code"] = "unknown_error"
                self.finish_pairing = None
            except aiohomekit.MaxPeersError:
                # The device can't pair with any more accessories.
                errors["pairing_code"] = "max_peers_error"
                self.finish_pairing = None
            except aiohomekit.AccessoryNotFoundError:
                # Can no longer find the device on the network
                return self.async_abort(reason="accessory_not_found_error")
            except InsecureSetupCode:
                errors["pairing_code"] = "insecure_setup_code"
            except Exception:  # pylint: disable=broad-except
                _LOGGER.exception("Pairing attempt failed with an unhandled exception")
                self.finish_pairing = None
                errors["pairing_code"] = "pairing_failed"

        if not self.finish_pairing:
            # Its possible that the first try may have been busy so
            # we always check to see if self.finish_paring has been
            # set.
            try:
                discovery = await self.controller.async_find(self.hkid)
                self.finish_pairing = await discovery.async_start_pairing(self.hkid)

            except aiohomekit.BusyError:
                # Already performing a pair setup operation with a different
                # controller
                return await self.async_step_busy_error()
            except aiohomekit.MaxTriesError:
                # The accessory has received more than 100 unsuccessful auth
                # attempts.
                return await self.async_step_max_tries_error()
            except aiohomekit.UnavailableError:
                # The accessory is already paired - cannot try to pair again.
                return self.async_abort(reason="already_paired")
            except aiohomekit.AccessoryNotFoundError:
                # Can no longer find the device on the network
                return self.async_abort(reason="accessory_not_found_error")
            except IndexError:
                # TLV error, usually not in pairing mode
                _LOGGER.exception("Pairing communication failed")
                return await self.async_step_protocol_error()
            except Exception:  # pylint: disable=broad-except
                _LOGGER.exception("Pairing attempt failed with an unhandled exception")
                errors["pairing_code"] = "pairing_failed"

        return self._async_step_pair_show_form(errors)

    async def async_step_busy_error(self, user_input=None):
        """Retry pairing after the accessory is busy."""
        if user_input is not None:
            return await self.async_step_pair()

        return self.async_show_form(step_id="busy_error")

    async def async_step_max_tries_error(self, user_input=None):
        """Retry pairing after the accessory has reached max tries."""
        if user_input is not None:
            return await self.async_step_pair()

        return self.async_show_form(step_id="max_tries_error")

    async def async_step_protocol_error(self, user_input=None):
        """Retry pairing after the accessory has a protocol error."""
        if user_input is not None:
            return await self.async_step_pair()

        return self.async_show_form(step_id="protocol_error")

    @callback
    def _async_step_pair_show_form(self, errors=None):
        placeholders = {"name": self.name}
        self.context["title_placeholders"] = {"name": self.name}

        schema = {vol.Required("pairing_code"): vol.All(str, vol.Strip)}
        if errors and errors.get("pairing_code") == "insecure_setup_code":
            schema[vol.Optional("allow_insecure_setup_codes")] = bool

        return self.async_show_form(
            step_id="pair",
            errors=errors or {},
            description_placeholders=placeholders,
            data_schema=vol.Schema(schema),
        )

    async def _entry_from_accessory(self, pairing):
        """Return a config entry from an initialized bridge."""
        # The bulk of the pairing record is stored on the config entry.
        # A specific exception is the 'accessories' key. This is more
        # volatile. We do cache it, but not against the config entry.
        # So copy the pairing data and mutate the copy.
        pairing_data = pairing.pairing_data.copy()

        # Use the accessories data from the pairing operation if it is
        # available. Otherwise request a fresh copy from the API.
        # This removes the 'accessories' key from pairing_data at
        # the same time.
        if not (accessories := pairing_data.pop("accessories", None)):
            accessories = await pairing.list_accessories_and_characteristics()

        parsed = Accessories.from_list(accessories)
        accessory_info = parsed.aid(1).services.first(
            service_type=ServicesTypes.ACCESSORY_INFORMATION
        )
        name = accessory_info.value(CharacteristicsTypes.NAME, "")

        return self.async_create_entry(title=name, data=pairing_data)

class InsecureSetupCode(Exception):
    """An exception for insecure trivial setup codes."""


text:
from sqlalchemy.orm import load_only

from exceptions import NoSuchCharacterError
from models.characters.saved_character import SavedCharacterSchema
from database.main import session

def load_saved_character(name: str):
    """
    This function loads the information about a saved chacacter in the saved_character DB table.

       name,   class,  level,  loaded_scripts_ID,  killed_monsters_ID, completed_quests_ID, inventory_ID, gold
Netherblood, Paladin,     10,                 1,                    1,                   1,            1,   23

    The attributes that end in ID like loaded_scripts_ID are references to other tables.

    For more information:
    https://github.com/Enether/python_wow/wiki/How-saving-a-Character-works-and-information-about-the-saved_character-database-table.
    """
    from classes import Paladin
    loaded_character: SavedCharacterSchema = session.query(SavedCharacterSchema).filter_by(name=name).one_or_none()

    if loaded_character is None:
        raise NoSuchCharacterError(f'There is no saved character by the name of {name}!')

    return loaded_character.convert_to_character_object()

def load_all_saved_characters_general_info() -> [dict()]:
    """
    This function loads general information about the saved characters in the DB and returns it as a list of
    dictionaries to  be easily printable.
    """
    loaded_characters: [SavedCharacterSchema] = session.query(SavedCharacterSchema).options(load_only("name", "character_class", "level")).all()

    return [{'name': ch.name, 'class': ch.character_class, 'level': ch.level} for ch in loaded_characters]

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Future.js Test - Web Components API</title>
        <link rel="stylesheet" type="text/css" href="../../../node_modules/qunitjs/qunit/qunit.css">


text:
(function() {
  'use strict';
  angular.module('r2rDesignerApp').controller('CsvConfigCtrl', function($scope, Csv) {
    $scope.csv = Csv;
    $scope.file = '';
    $scope.progress = {
      value: 0,
      submitting: false
    };
    $scope.success = false;
    $scope.submitted = false;
    $scope.onFileSelect = function($files) {
      return $scope.file = $files[0];
    };
    return $scope.submit = function() {
      return $scope.csv.submitCsvFile($scope.file, $scope.progress).success(function() {
        $scope.csv.getCsvData();
        $scope.submitted = true;
        $scope.success = true;
        return $scope.progress.submitting = false;
      }).error(function() {
        $scope.submitted = true;
        $scope.success = false;
        return $scope.progress.submitting = false;
      });
    };
  });

}).call(this);

//# sourceMappingURL=config.js.map


text:
/*
 * @(#)DOMUtils.java
 *
 * @project     : org.morozko.java.core
 * @package     : org.morozko.java.core.xml.dom
 * @creation	: 13/lug/07
 * @release		: xxxx.xx.xx
 */
package org.morozko.java.core.xml.dom;

import java.util.Properties;

import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

/**
 * <p>/p>
 *
 * @author Morozko
 *
 */
public class DOMUtils {

	   public static Properties attributesToProperties(Element tag) {
	        Properties props = new Properties();
	        NamedNodeMap atts = tag.getAttributes();
	        for (int k=0; k<atts.getLength(); k++) {
	            Attr a = (Attr)atts.item(k);
	            props.setProperty(a.getName(), a.getValue());
	        }
	        return props;
	    }

	    private DOMUtils() {
	        super();
	    }

}


text:
#import <UIKit/UIKit.h>

@interface MISImagePickerBottomBar : UIView

@property (nonatomic) NSInteger count;

@property (nonatomic, copy) void (^confirmBlock)(void);
@property (nonatomic, copy) void (^previewBlock)(void);

@end

@interface MISImagePickerPreviewController : UIViewController <UIScrollViewDelegate>

/**
 *  图片的数组
 */
@property (nonatomic, copy) NSArray* assets;

/**
 *  选中图片的数组
 */
@property (nonatomic, strong) NSMutableArray* selectedAssets;

/**
 *  当前显示的序号
 */
@property (nonatomic) NSInteger currentIndex;

/**
 *  点完成的回调
 */
@property (nonatomic, copy) void (^selectedFinishBlock)(void);

/**
 *  选择最大时的回调 limit: 最大选择数 isAlert : 是否弹默认框 默认是 *isAlert = YES
 */
@property (nonatomic, copy) void (^seletedLimitBlock)(NSInteger limit, BOOL *isAlert);

/**
 *  最多可选
 */
@property (nonatomic) NSInteger maxImageCount;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Hl7.Fhir.Model;
using Spark.Core;
using Spark.Engine.Core;
using Spark.Engine.Extensions;
using Spark.Engine.Store.Interfaces;
using Spark.Service;

namespace Spark.Engine.Service.FhirServiceExtensions
{
    public class SnapshotPaginationProvider : ISnapshotPaginationProvider, ISnapshotPagination
    {
        private IFhirStore fhirStore;
        private readonly ITransfer transfer;
        private readonly ILocalhost localhost;
        private readonly ISnapshotPaginationCalculator _snapshotPaginationCalculator;
        private Snapshot snapshot;

        public SnapshotPaginationProvider(IFhirStore fhirStore, ITransfer transfer, ILocalhost localhost, ISnapshotPaginationCalculator snapshotPaginationCalculator)
        {
            this.fhirStore = fhirStore;
            this.transfer = transfer;
            this.localhost = localhost;
            _snapshotPaginationCalculator = snapshotPaginationCalculator;
        }

        public ISnapshotPagination StartPagination(Snapshot snapshot)
        {
            this.snapshot = snapshot;
            return this;
        }

        public Bundle GetPage(int? index = null, Action<Entry> transformElement = null)
        {
            if (snapshot == null)
                throw Error.NotFound("There is no paged snapshot");

            if (!snapshot.InRange(index ?? 0))
            {
                throw Error.NotFound(
                    "The specified index lies outside the range of available results ({0}) in snapshot {1}",
                    snapshot.Keys.Count(), snapshot.Id);
            }

            return this.CreateBundle(index);
        }

        private Bundle CreateBundle(int? start = null)
        {
            Bundle bundle = new Bundle();
            bundle.Type = snapshot.Type;
            bundle.Total = snapshot.Count;
            bundle.Id = Guid.NewGuid().ToString();

            List<IKey> keys = _snapshotPaginationCalculator.GetKeysForPage(snapshot, start).ToList();
            IList<Entry> entries = fhirStore.Get(keys).ToList();
            if (snapshot.SortBy != null)
            {
                entries = entries.Select(e => new {Entry = e, Index = keys.IndexOf(e.Key)})
                    .OrderBy(e => e.Index)
                    .Select(e => e.Entry).ToList();
            }
            IList<Entry> included = GetIncludesRecursiveFor(entries, snapshot.Includes);
            entries.Append(included);

            transfer.Externalize(entries);
            bundle.Append(entries);
            BuildLinks(bundle, start);

            return bundle;
        }

        private IList<Entry> GetIncludesRecursiveFor(IList<Entry> entries, IEnumerable<string> includes)
        {
            IList<Entry> included = new List<Entry>();

            var latest = GetIncludesFor(entries, includes);
            int previouscount;
            do
            {
                previouscount = included.Count;
                included.AppendDistinct(latest);
                latest = GetIncludesFor(latest, includes);
            }
            while (included.Count > previouscount);
            return included;
        }
        private IList<Entry> GetIncludesFor(IList<Entry> entries, IEnumerable<string> includes)
        {
            if (includes == null) return new List<Entry>();

            IEnumerable<string> paths = includes.SelectMany(i => IncludeToPath(i));
            IList<IKey> identifiers = entries.GetResources().GetReferences(paths).Distinct().Select(k => (IKey)Key.ParseOperationPath(k)).ToList();

            IList<Entry> result = fhirStore.Get(identifiers).ToList();

            return result;
        }

        private void BuildLinks(Bundle bundle, int? start = null)
        {
            bundle.SelfLink = start == null
                ? localhost.Absolute(new Uri(snapshot.FeedSelfLink, UriKind.RelativeOrAbsolute))
                : BuildSnapshotPageLink(0);
            bundle.FirstLink = BuildSnapshotPageLink(0);
            bundle.LastLink = BuildSnapshotPageLink(_snapshotPaginationCalculator.GetIndexForLastPage(snapshot));

            int? previousPageIndex = _snapshotPaginationCalculator.GetIndexForPreviousPage(snapshot, start);
            if (previousPageIndex != null)
            {
                bundle.PreviousLink = BuildSnapshotPageLink(previousPageIndex);
            }

            int? nextPageIndex = _snapshotPaginationCalculator.GetIndexForNextPage(snapshot, start);
            if (nextPageIndex != null)
            {
                bundle.NextLink = BuildSnapshotPageLink(nextPageIndex);
            }
        }

        private Uri BuildSnapshotPageLink(int? snapshotIndex)
        {
            if (snapshotIndex == null)
                return null;

            Uri baseurl;
            if (string.IsNullOrEmpty(snapshot.Id) == false)
            {
                //baseUrl for statefull pagination
                baseurl = new Uri(localhost.DefaultBase + "/" + FhirRestOp.SNAPSHOT)
                    .AddParam(FhirParameter.SNAPSHOT_ID, snapshot.Id);
            }
            else
            {
                //baseUrl for stateless pagination
                baseurl = new Uri(snapshot.FeedSelfLink);
            }

            return baseurl
                .AddParam(FhirParameter.SNAPSHOT_INDEX, snapshotIndex.ToString());
        }

        private IEnumerable<string> IncludeToPath(string include)
        {
            string[] _include = include.Split(':');
            string resource = _include.FirstOrDefault();
            string paramname = _include.Skip(1).FirstOrDefault();
            var param = ModelInfo.SearchParameters.FirstOrDefault(p => p.Resource == resource && p.Name == paramname);
            if (param != null)
            {
                return param.Path;
            }
            else
            {
                return Enumerable.Empty<string>();
            }
        }
    }
}


text:
<?php

namespace BankId\Merchant\Library\Schemas\saml\authenticationcontext;

/**
 * Class representing ActivationPin
 */
class ActivationPin extends ActivationPinType
{

}


text:
<!doctype html>

  <meta charset="utf-8">

  <title>Image Widget</title>
  <meta name="description" content="Image Widget">
  <meta name="author" content="Ivan Miric">

  {% for c in contents %}

  {% endfor %}


text:
package org.apereo.portal.groups.pags.dao.jpa;

import javax.persistence.EntityManager;
import org.apache.commons.lang.Validate;
import org.apereo.portal.groups.pags.dao.IPersonAttributesGroupDefinition;
import org.apereo.portal.groups.pags.dao.IPersonAttributesGroupTestGroupDefinition;
import org.apereo.portal.groups.pags.dao.IPersonAttributesGroupTestGroupDefinitionDao;
import org.apereo.portal.jpa.BasePortalJpaDao;
import org.springframework.stereotype.Repository;

@Repository("personAttributesGroupTestGroupDefinitionDao")
public class JpaPersonAttributesGroupTestGroupDefinitionDao extends BasePortalJpaDao
        implements IPersonAttributesGroupTestGroupDefinitionDao {

    @PortalTransactional
    @Override
    public IPersonAttributesGroupTestGroupDefinition updatePersonAttributesGroupTestGroupDefinition(
            IPersonAttributesGroupTestGroupDefinition personAttributesGroupTestGroupDefinition) {
        Validate.notNull(
                personAttributesGroupTestGroupDefinition,
                "personAttributesGroupTestGroupDefinition can not be null");

        final IPersonAttributesGroupTestGroupDefinition persistentDefinition;
        final EntityManager entityManager = this.getEntityManager();
        if (entityManager.contains(personAttributesGroupTestGroupDefinition)) {
            persistentDefinition = personAttributesGroupTestGroupDefinition;
        } else {
            persistentDefinition = entityManager.merge(personAttributesGroupTestGroupDefinition);
        }

        this.getEntityManager().persist(persistentDefinition);
        return persistentDefinition;
    }

    @PortalTransactional
    @Override
    public void deletePersonAttributesGroupTestGroupDefinition(
            IPersonAttributesGroupTestGroupDefinition definition) {
        Validate.notNull(definition, "definition can not be null");

        final IPersonAttributesGroupTestGroupDefinition persistentDefinition;
        final EntityManager entityManager = this.getEntityManager();
        if (entityManager.contains(definition)) {
            persistentDefinition = definition;
        } else {
            persistentDefinition = entityManager.merge(definition);
        }
        entityManager.remove(persistentDefinition);
    }

    @PortalTransactional
    @Override
    public IPersonAttributesGroupTestGroupDefinition createPersonAttributesGroupTestGroupDefinition(
            IPersonAttributesGroupDefinition group) {
        final IPersonAttributesGroupTestGroupDefinition personAttributesGroupTestGroupDefinition =
                new PersonAttributesGroupTestGroupDefinitionImpl(
                        (PersonAttributesGroupDefinitionImpl) group);
        this.getEntityManager().persist(personAttributesGroupTestGroupDefinition);
        return personAttributesGroupTestGroupDefinition;
    }
}


text:
//- JavaScript source code

//- defs-couch.js ~~
//
//  These definitions are likely to become deprecated in the future, because
//  there's a mistake (probably several) somewhere in here that I haven't had
//  good luck finding yet. Node.js 0.12 has been released now, which means that
//  I won't have to deal with `maxSockets` anymore, so there's still hope for
//  QM and CouchDB, but ... yeah. The most likely solution will be to port the
//  current definitions over to the Ruby version and then drop Node.js support,
//  at least temporarily.
//
//                                                      ~~ (c) SRW, 25 Sep 2012
//                                                  ~~ last updated 08 Feb 2015

(function () {
    'use strict';

 // Pragmas

    /*jshint maxparams: 3, quotmark: single, strict: true */

    /*jslint indent: 4, maxlen: 80, node: true, nomen: true */

    /*properties
        api, avar_ttl, body, box_status, ceil, collect_garbage, 'Content-Type',
        couch, create, end, error, get_avar, get_list, headers, _id, isMaster,
        join, key, keys, length, log, method, now, on, parse,
        persistent_storage, protocol, push, request, _rev, set_avar,
        statusCode, stringify, toString, trafficlog_storage, trim
    */

 // Declarations

    var cluster, create_db, http, https, stringify, upload_ddoc, url;

 // Definitions

    cluster = require('cluster');

    create_db = function (conn, callback) {
     // This function needs documentation.
        var options, protocol, req;
        options = Object.create(conn);
        options.method = 'PUT';
        protocol = (conn.protocol === 'http:') ? http : https;
        req = protocol.request(options, function (response) {
         // This function needs documentation.
            var temp = [];
            response.on('data', function (chunk) {
             // This function needs documentation.
                temp.push(chunk.toString());
                return;
            });
            response.on('end', function () {
             // This function needs documentation.
                return callback(null, temp.join(''));
            });
            return;
        });
        req.on('error', callback);
        req.end();
        return;
    };

    http = require('http');

    https = require('https');

    stringify = function (obj, keys) {
     // This function only exists to serialize the design document cleanly. It
     // doesn't demand the level of sophistication that the browser client's
     // `serialize` method does because we know that this function will run in
     // Node.js and that all functions will be serializable :-)
        /*jslint unparam: true */
        var i, n, temp;
        temp = {};
        n = keys.length;
        for (i = 0; i < n; i += 1) {
            temp[keys[i]] = obj[keys[i]];
        }
        return JSON.stringify(temp, function (key, val) {
         // See the explanation above ;-)
            if ((typeof val === 'function') && (val instanceof Function)) {
                return val.toString();
            }
            return val;
        });
    };

    upload_ddoc = function (file, app_url, callback) {
     // This function needs documentation.
        var opts, protocol, req;
        opts = url.parse(app_url);
        opts.method = 'GET';
        protocol = (opts.protocol === 'http:') ? http : https;
        req = protocol.request(opts, function (response) {
         // This function needs documentation.
            var temp = [];
            response.on('data', function (chunk) {
             // This function needs documentation.
                temp.push(chunk.toString());
                return;
            });
            response.on('end', function () {
             // This function needs documentation.
                var new_dd, $new_dd, old_dd, $old_dd, opts2, req2;
                new_dd = require(file);
                $old_dd = temp.join('');
                if (response.statusCode === 200) {
                    old_dd = JSON.parse($old_dd);
                    new_dd = require(file);
                    new_dd._id = old_dd._id;
                    new_dd._rev = old_dd._rev;
                    $new_dd = stringify(new_dd, Object.keys(old_dd));
                    $old_dd = stringify(old_dd, Object.keys(old_dd));
                    if ($new_dd === $old_dd) {
                        return callback(null, 'Design document unchanged.');
                    }
                } else {
                    $new_dd = stringify(new_dd, Object.keys(new_dd));
                }
                console.log('Uploading a new design document ...');
                opts2 = Object.create(opts);
                opts2.method = 'PUT';
                req2 = protocol.request(opts2, function (response) {
                 // This function needs documentation.
                    var temp2 = [];
                    response.on('data', function (chunk) {
                     // This function needs documentation.
                        temp2.push(chunk.toString());
                        return;
                    });
                    response.on('end', function () {
                     // This function needs documentation.
                        return callback(null, temp2.join(''));
                    });
                    return;
                });
                req2.on('error', callback);
                req2.end($new_dd);
                return;
            });
            return;
        });
        req.on('error', callback);
        req.end();
        return;
    };

    url = require('url');

 // Out-of-scope definitions

    exports.api = function (settings) {
     // This function needs documentation.

        var app_url, collect_garbage, conn, get_avar, get_list, protocol,
            set_avar;

        app_url = settings.persistent_storage.couch + '/_design/app/';

        collect_garbage = function () {
         // This function removes old documents from the "db" database, but it
         // does not trigger compaction. The reason is simple -- automatic
         // compaction is a standard feature of CouchDB 1.2 and later. To read
         // more about configuring your couch, see http://goo.gl/V634R.
            var callback, opts, req, target;
            callback = function (err) {
             // This function needs documentation.
                if (err !== null) {
                    console.error('Error:', err);
                    return;
                }
                console.log('Finished collecting garbage.');
                return;
            };
            target = app_url + '_list/as-array/outdated?startkey=0&endkey=' +
                    (Date.now() - (settings.avar_ttl * 1000));
            opts = url.parse(target);
            opts.method = 'GET';
            req = protocol.request(opts, function (res) {
             // This function needs documentation.
                var temp = [];
                res.on('data', function (chunk) {
                 // This function needs documentation.
                    temp.push(chunk.toString());
                    return;
                });
                res.on('end', function () {
                 // This function needs documentation.
                    var body, opts2, req2;
                    body = temp.join('');
                    if (body === '[]') {
                        return callback(null);
                    }
                    opts2 = url.parse(settings.persistent_storage.couch +
                            '/_bulk_docs');
                    opts2.headers = {'Content-Type': 'application/json'};
                    opts2.method = 'POST';
                    req2 = protocol.request(opts2, function () {
                     // This function omits named parameters because it omits
                     // them anyway.
                        return callback(null);
                    });
                    req2.on('error', callback);
                    req2.end('{"docs":' + body + '}');
                    return;
                });
                return;
            });
            req.on('error', callback);
            req.end();
            return;
        };

        conn = url.parse(settings.persistent_storage.couch);

        get_avar = function (params, callback) {
         // This function needs documentation.
            var opts, req, target;
            target = app_url + '_update/touch/' + params[0] + '&' + params[1] +
                    '?new_edits=false'; // see http://goo.gl/K95Yf6
            opts = url.parse(target);
            opts.method = 'PUT';
            req = protocol.request(opts, function (res) {
             // This function needs documentation.
                var temp = [];
                res.on('data', function (chunk) {
                 // This function needs documentation.
                    temp.push(chunk.toString());
                    return;
                });
                res.on('end', function () {
                 // This function needs documentation.
                    return callback(null, temp.join(''));
                });
                return;
            });
            req.on('error', callback);
            req.end();
            return;
        };

        get_list = function (params, callback) {
         // This function needs documentation.
            var opts, req, target;
            target = app_url + '_list/as-array/jobs?key=["' +  params[0] +
                    '","' + params[1] + '"]';
            opts = url.parse(target);
            opts.method = 'GET';
            req = protocol.request(opts, function (res) {
             // This function needs documentation.
                var temp = [];
                res.on('data', function (chunk) {
                 // This function needs documentation.
                    temp.push(chunk.toString());
                    return;
                });
                res.on('end', function () {
                 // This function needs documentation.
                    return callback(null, temp.join(''));
                });
                return;
            });
            req.on('error', callback);
            req.end();
            return;
        };

        protocol = (conn.protocol === 'http:') ? http : https;

        set_avar = function (params, callback) {
         // This function needs documentation.
            var obj, opts, req;
            if (params.length === 4) {
                obj = {
                    _id:        params[0] + '&' + params[1], // "box_key"
                    body:       params[3],
                    box_status: params[0] + '&' + params[2],
                    key:        params[1]
                };
            } else {
                obj = {
                    _id:        params[0] + '&' + params[1], // "box_key"
                    body:       params[2],
                    key:        params[1]
                };
            }
            opts = url.parse(app_url + '_update/upsert/' + obj._id);
            opts.headers = {'Content-Type': 'application/json'};
            opts.method = 'POST';
            req = protocol.request(opts, function (res) {
             // This function needs documentation.
                if (res.statusCode === 409) {
                 // When working with update handlers, conflicts happen.
                    if (typeof setImmediate === 'function') {
                        setImmediate(set_avar, params, callback);
                    } else {
                        setTimeout(set_avar, 0, params, callback);
                    }
                    return;
                }
                res.on('data', function () {
                 // This function is empty, but it is necessary due to changes
                 // in the way that the streaming API works in Node.js, as of
                 // version 0.10 and later.
                    return;
                });
                res.on('end', function () {
                 // This function needs documentation.
                    if ((res.statusCode !== 201) && (res.statusCode !== 202)) {
                     // Ordinarily, we want a 201, but batch mode returns an
                     // "HTTP 202: Accepted" response, and Cloudant's BigCouch
                     // seems to use batch mode sometimes. All other status
                     // codes indicate an error.
                        return callback(res.statusCode);
                    }
                    return callback(null);
                });
                return;
            });
            req.on('error', callback);
            req.end(JSON.stringify(obj));
            return;
        };

        if (cluster.isMaster) {
            create_db(conn, function (err, response) {
             // This function needs documentation.
                if (err !== null) {
                    console.error('Error:', err);
                }
                upload_ddoc('./couch-api-ddoc', app_url, function (err) {
                 // This function also accepts a second argument that contains
                 // the "results" of the query, but because I don't use it, I
                 // have omitted it to avoid irritating JSLint et al.
                    if (err !== null) {
                        console.error('Error:', err);
                    }
                    console.log(response.trim());
                    console.log('API: CouchDB storage is ready.');
                    return;
                });
                return;
            });
        }
        return {
            collect_garbage: collect_garbage,
            get_avar: get_avar,
            get_list: get_list,
            set_avar: set_avar
        };
    };

    exports.log = function (settings) {
     // This function needs documentation.
        var conn, protocol;
        conn = url.parse(settings.trafficlog_storage.couch);
        protocol = (conn.protocol === 'http:') ? http : https;
        if (cluster.isMaster) {
            create_db(conn, function (err) {
             // This function needs documentation.
                if (err !== null) {
                    console.error('Error:', err);
                }
                console.log('LOG: CouchDB storage is ready.');
                return;
            });
        }
        return function (obj) {
         // This function needs documentation. It seems weird to close over the
         // `conn` object, too, so that probably needs a closer inspection ...
            var req;
            conn.headers = {'Content-Type': 'application/json'};
            conn.method = 'POST';
            req = protocol.request(conn, function (res) {
             // This function needs documentation.
                res.on('data', function () {
                 // This function is empty, but it is necessary due to changes
                 // in the way that the streaming API works in Node.js, as of
                 // version 0.10 and later.
                    return;
                });
                res.on('end', function () {
                 // See the explanation given above.
                    return;
                });
                return;
            });
            req.on('error', function (message) {
             // This function needs documentation.
                console.error('Error:', message);
                return;
            });
            req.end(JSON.stringify(obj));
            return;
        };
    };

 // That's all, folks!

    return;

}());

//- vim:set syntax=javascript:


text:
require 'spec_helper'

describe CloudModel::WebApps::WordpressWebApp do
  it { expect(subject).to be_a CloudModel::WebApp }

  it { expect(subject).to have_field(:mysql_host).of_type(String).with_default_value_of 'localhost' }
  it { expect(subject).to have_field(:mysql_port).of_type(Integer).with_default_value_of 3306 }
  it { expect(subject).to have_field(:mysql_user).of_type(String).with_default_value_of 'wordpress' }
  it { expect(subject).to have_field(:mysql_passwd).of_type(String).with_default_value_of nil }
  it { expect(subject).to have_field(:mysql_database).of_type(String).with_default_value_of 'wordpress' }

  it { expect(subject).to have_field(:wp_auth_key).of_type(String).with_default_value_of nil }
  it { expect(subject).to have_field(:wp_secure_auth_key).of_type(String).with_default_value_of nil }
  it { expect(subject).to have_field(:wp_logged_in_key).of_type(String).with_default_value_of nil }
  it { expect(subject).to have_field(:wp_nonce_key).of_type(String).with_default_value_of nil }
  it { expect(subject).to have_field(:wp_auth_salt).of_type(String).with_default_value_of nil }
  it { expect(subject).to have_field(:wp_secure_auth_salt).of_type(String).with_default_value_of nil }
  it { expect(subject).to have_field(:wp_logged_in_salt).of_type(String).with_default_value_of nil }
  it { expect(subject).to have_field(:wp_nonce_salt).of_type(String).with_default_value_of nil }

  it { expect(subject).to have_field(:wp_passwd).of_type(String).with_default_value_of nil }
  it { expect(subject).to have_field(:wp_allow_xmlrpc).of_type(Mongoid::Boolean).with_default_value_of false }

  describe 'set_mysql_passwd' do
    it 'should generate and assign 16 char random alphanumeric' do
      random = "01234567890abcdef".chars.shuffle.join
      expect(SecureRandom).to receive(:alphanumeric).with(16).and_return random
      subject.set_mysql_passwd
      expect(subject.mysql_passwd).to eq random
    end
  end

  describe 'set_salt_keys' do
    pending

    # self.wp_auth_key = generate_salt_key
    # self.wp_secure_auth_key = generate_salt_key
    # self.wp_logged_in_key = generate_salt_key
    # self.wp_nonce_key = generate_salt_key
    # self.wp_auth_salt = generate_salt_key
    # self.wp_secure_auth_salt = generate_salt_key
    # self.wp_logged_in_salt = generate_salt_key
    # self.wp_nonce_salt = generate_salt_key
  end

  describe 'needed_components' do
    it 'should require php, php_mysql, and php_imagemagick' do
      expect(subject.needed_components).to eq [:php, :php_mysql, :php_imagemagick]
    end
  end

  describe 'persistant_folders' do
    it 'should include "var/www/wp-content"' do
      expect(subject.persistant_folders).to include 'var/www/wp-content'
    end
  end

  describe 'generate_salt_key' do
    it 'should generate a 64 char alphanumeric' do
      random = "01234567890abcdef".chars.shuffle.join
      expect(SecureRandom).to receive(:alphanumeric).with(64).and_return random
      expect(subject.generate_salt_key).to eq random
    end
  end

  describe 'additional_allowed_params' do
    it 'should allow to config mysql' do
      expect(subject.additional_allowed_params).to include :mysql_host, :mysql_port, :mysql_user, :mysql_database
    end

    it 'should allow to set wordpress passwd for protecting admin and login' do
      expect(subject.additional_allowed_params).to include :wp_passwd
    end

    it 'should allow to allow wordpress xmlrpc' do
      expect(subject.additional_allowed_params).to include :wp_allow_xmlrpc
    end
  end

  describe '#fetch_app_command' do
    pending
    # # Cache files?
    # [
    #   'mkdir -p /opt/web-app',
    #   'cd /opt/web-app',
    #   'wget https://wordpress.org/latest.tar.gz',
    #   'tar xzf latest.tar.gz',
    #   'rm latest.tar.gz',
    #   'chown -R 100000:100000 /opt/web-app/wordpress'
    # ] * ' && '
  end

  describe 'config_files_to_render' do
    it 'should render wp-config template' do
      expect(subject.config_files_to_render['cloud_model/web_apps/wordpress_web_app/wp-config.php']).to eq ["/opt/web-app/wordpress/wp-config.php", 0644]
    end

    it 'should render passwd template' do
      expect(subject.config_files_to_render['cloud_model/web_apps/wordpress_web_app/htpasswd']).to eq ["/etc/nginx/.htpasswd-#{subject.id}-wordpress", 0640, gid: '101001']
    end

    it 'should render init_mysql template' do
      expect(subject.config_files_to_render['cloud_model/web_apps/wordpress_web_app/init_mysql.sql']).to eq ["/root/init_wordpress_user.sql", 0600]
    end
  end
end


text:
//
// Copyright 2011 Jeff Verkoeyen
//
// 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.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

#import "NITableViewModel.h"

/**
 * A simple factory for creating table view cells from objects.
 *
 * This factory provides a single method that accepts an object and returns a UITableViewCell
 * for use in a UITableView. A cell will only be returned if the object passed to the factory
 * conforms to the NICellObject protocol. The created cell should ideally conform to
 * the NICell protocol. If it does, the object will be passed to it via
 * @link NICell::shouldUpdateCellWithObject: shouldUpdateCellWithObject:@endlink before the
 * factory method returns.
 *
 *
 * This factory is designed to be used with NITableViewModels, though one could easily use
 * it with other table view data source implementations simply by providing nil for the table
 * view model.
 *
 *      @ingroup TableCellFactory
 */
@interface NICellFactory : NSObject

/**
 * Creates a cell from a given object if and only if the object conforms to the NICellObject
 * protocol.
 *
 * This method signature matches the NITableViewModelDelegate method so that you can
 * set this factory as the model's delegate:
 *
 * @code
// Must cast to id to avoid compiler warnings.
_model.delegate = (id)[NICellFactory class];
 * @endcode
 *
 * If you would like to customize the factory's output, implement the model's delegate method
 * and call the factory method. Remember that if the factory doesn't know how to map
 * the object to a cell it will return nil.
 *
 * @code
- (UITableViewCell *)tableViewModel: (NITableViewModel *)tableViewModel
                   cellForTableView: (UITableView *)tableView
                        atIndexPath: (NSIndexPath *)indexPath
                         withObject: (id)object {
  UITableViewCell* cell = [NICellFactory tableViewModel: tableViewModel
                                       cellForTableView: tableView
                                            atIndexPath: indexPath
                                             withObject: object];
  if (nil == cell) {
    // Custom cell creation here.
  }
  return cell;
}
 * @endcode
 */
+ (UITableViewCell *)tableViewModel: (NITableViewModel *)tableViewModel
                   cellForTableView: (UITableView *)tableView
                        atIndexPath: (NSIndexPath *)indexPath
                         withObject: (id)object;
@end

/**
 * The protocol for an object that can be used in the NICellFactory.
 *
 *      @ingroup TableCellFactory
 */
@protocol NICellObject
@required
/** The class of cell to be created when this object is passed to the cell factory. */
- (Class)cellClass;

@optional
/** The style of UITableViewCell to be used when initializing the cell for the first time. */
- (UITableViewCellStyle)cellStyle;
@end

/**
 * The protocol for a cell created in the NICellFactory.
 *
 * Cells that implement this protocol are given the object that implemented the NICellObject
 * protocol and returned this cell's class name in @link NICellObject::cellClass cellClass@endlink.
 *
 *      @ingroup TableCellFactory
 */
@protocol NICell
@required
/**
 * Called when a cell is created and reused.
 *
 * Implement this method to customize the cell's properties for display using the given object.
 */
- (BOOL)shouldUpdateCellWithObject:(id)object;
@end

/**
 * A light-weight implementation of the NICellObject protocol.
 *
 * Use this object in cases where you can't set up a hard binding between an object and a cell,
 * or when you simply don't want to.
 *
 * For example, let's say that you want to show a cell that shows a loading indicator.
 * Rather than create a new interface, LoadMoreObject, simply for the cell and binding it
 * to the cell view, you can create an NICellObject and pass the class name of the cell.
 *
@code
[tableContents addObject:[NICellObject objectWithCellClass:[LoadMoreCell class]]];
@endcode
 */
@interface NICellObject : NSObject <NICellObject>

// Designated initializer.
- (id)initWithCellClass:(Class)cellClass userInfo:(id)userInfo;
- (id)initWithCellClass:(Class)cellClass;

+ (id)objectWithCellClass:(Class)cellClass;
+ (id)objectWithCellClass:(Class)cellClass userInfo:(id)userInfo;

@property (nonatomic, readonly, retain) id userInfo;

@end

/**
 * An object that can be used to populate information in the cell.
 *
 *      @fn NICellObject::userInfo
 */


text:
package org.nbone.util.lang;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

import org.nbone.constants.CharsetConstant;

/**
 * reference apache <br>
 * 字符集常量使用
 * @author Thinking
 * @see Charset
 * @since 2014-12-12
 *
 */
public class CharsetUtils implements CharsetConstant {

    public static Charset lookup(final String name) {
        if (name == null) {
            return null;
        }
        try {
            return Charset.forName(name);
        } catch (final UnsupportedCharsetException ex) {
            return null;
        }
    }

    public static Charset get(final String name) throws UnsupportedEncodingException {
        if (name == null) {
            return null;
        }
        try {
            return Charset.forName(name);
        } catch (final UnsupportedCharsetException ex) {
            throw new UnsupportedEncodingException(name);
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<questestinterop xmlns="http://www.imsglobal.org/xsd/ims_qtiasiv1p2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.imsglobal.org/xsd/ims_qtiasiv1p2 http://www.imsglobal.org/xsd/ims_qtiasiv1p2p1.xsd">
  <assessment title="Essay question" ident="essaysrfun">
    <qtimetadata>
      <qtimetadatafield>
        <fieldlabel>qmd_timelimit</fieldlabel>
        <fieldentry/>
      </qtimetadatafield>
      <qtimetadatafield>
        <fieldlabel>cc_maxattempts</fieldlabel>
        <fieldentry/>
      </qtimetadatafield>
    </qtimetadata>

        <selection_ordering>
          <selection>
            <sourcebank_ref/>
            <selection_number>1</selection_number>
            <selection_extension>
              <points_per_item>1</points_per_item>
            </selection_extension>
          </selection>
        </selection_ordering>

        <item title="" ident="3790">
          <itemmetadata>
            <qtimetadata>
              <qtimetadatafield>
              <fieldlabel>question_type</fieldlabel>
              <fieldentry>essay_question</fieldentry>
            </qtimetadatafield>
              <qtimetadatafield>
                <fieldlabel>outcome_guid</fieldlabel>
                <fieldentry>9a82d67b-21ce-4cbf-8298-6bd1109f03b2</fieldentry>
              </qtimetadatafield>
              <qtimetadatafield>
                <fieldlabel>outcome_short_title</fieldlabel>
                <fieldentry>For-Profit vs. Non-Profit</fieldentry>
              </qtimetadatafield>
              <qtimetadatafield>
                <fieldlabel>outcome_long_title</fieldlabel>
                <fieldentry>Distinguish between for-profit and nonprofit organizations</fieldentry>
              </qtimetadatafield>
            </qtimetadata>
          </itemmetadata>

          <presentation>
          <material>
            <mattext texttype="text/html"><div><p>How do you feel about weird flux implementation in a react app?</p></div></mattext>
          </material>
          <response_str ident="response1" rcardinality="Single">
            <render_fib>
              <response_label ident="answer1" rshuffle="No"/>
            </render_fib>
          </response_str>
          </presentation>
          <resprocessing>
            <outcomes>
              <decvar maxvalue="100" minvalue="0" varname="SCORE" vartype="Decimal"/>
            </outcomes>
            <respcondition continue="Yes">
              <conditionvar>
                <other/>
              </conditionvar>
              <displayfeedback feedbacktype="Response" linkrefid="general_fb"/>
            </respcondition>
            <respcondition continue="No">
              <conditionvar>
                <other/>
              </conditionvar>
            </respcondition>
          </resprocessing>
          <itemfeedback ident="general_fb">
            <flow_mat>
              <material>
                <mattext texttype="text/html"><p>Example answers are:<br>Weird. Because reasons.</p>
<p>Great.<span> Because reasons.</span></p>
<p>Sad.<span> Because reasons.</span></p></mattext>
              </material>
            </flow_mat>
          </itemfeedback>
        </item>

  </assessment>
</questestinterop>


text:
<Namespace Name="MonoMac.AudioToolbox">
  <Docs>
    <summary>Bindings to the low-level AudioToolbox APIs</summary>
    <remarks>To be added.</remarks>
  </Docs>
</Namespace>


text:
package de.swm.nis.logicaldecoding.parser.domain;

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

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

import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKBReader;

/**
 * Represents a changed Row in a Database. Contains old an new values.
 * @author Schmidt.Sebastian2
 *
 */
public class DmlEvent extends Event{

	private static final Logger log = LoggerFactory.getLogger(DmlEvent.class);

	public enum Type {
		insert, update, delete
	};

	private List<Cell> oldValues;
	private List<Cell> newValues;
	private final Type type;

	public DmlEvent(String schema, String table, DmlEvent.Type type) {
		this.type = type;
		setTableName(table);
		setSchemaName(schema);
		oldValues = new ArrayList<Cell>();
		newValues = new ArrayList<Cell>();
	}

	public Envelope getEnvelope() {

		try {
		Envelope envelope = new Envelope();
		for (Cell cell:getOldValues()) {
			if (cell.getType().equals(Cell.Type.geometry)) {
				if (!cell.getValue().equals("null")) {
					Geometry geom = new WKBReader().read(WKBReader.hexToBytes(cell.getValue()));
					envelope.expandToInclude(geom.getEnvelopeInternal());
				}
			}
		}
		for (Cell cell:getNewValues()) {
			if (cell.getType().equals(Cell.Type.geometry)) {
				if (!cell.getValue().equals("null")) {
					Geometry geom = new WKBReader().read(WKBReader.hexToBytes(cell.getValue()));
					envelope.expandToInclude(geom.getEnvelopeInternal());
				}
			}
		}
		return envelope;
		} catch (ParseException e) {
			log.warn("ParseException on parsing WKB Geometry, ", e);
			throw new RuntimeException(e);
		}
	}

	public List<Cell> getOldValues() {
		return oldValues;
	}

	public List<Cell> getNewValues() {
		return newValues;
	}

	public Type getType() {
		return type;
	}

	@Override
	public String toString() {
		return "Row [type=" + type + ", tableName=" + getTableName() + ", newValues=" + newValues + ", oldValues="
				+ oldValues + "]";
	}

}


text:
package com.microsoft.azure.management.compute.v2020_06_01;

import com.microsoft.azure.arm.collection.SupportsCreating;
import com.microsoft.azure.arm.resources.collection.SupportsDeletingByResourceGroup;
import com.microsoft.azure.arm.resources.collection.SupportsBatchDeletion;
import com.microsoft.azure.arm.resources.collection.SupportsGettingByResourceGroup;
import rx.Observable;
import com.microsoft.azure.arm.resources.collection.SupportsListingByResourceGroup;
import com.microsoft.azure.arm.collection.SupportsListing;
import rx.Completable;
import java.util.List;
import com.microsoft.azure.management.compute.v2020_06_01.implementation.VirtualMachineScaleSetsInner;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.management.compute.v2020_06_01.VirtualMachineScaleSetSku;

/**
 * Type representing VirtualMachineScaleSets.
 */
public interface VirtualMachineScaleSets extends SupportsCreating<VirtualMachineScaleSet.DefinitionStages.Blank>, SupportsDeletingByResourceGroup, SupportsBatchDeletion, SupportsGettingByResourceGroup<VirtualMachineScaleSet>, SupportsListingByResourceGroup<VirtualMachineScaleSet>, SupportsListing<VirtualMachineScaleSet>, HasInner<VirtualMachineScaleSetsInner> {
    /**
     * Deallocates specific virtual machines in a VM scale set. Shuts down the virtual machines and releases the compute resources. You are not billed for the compute resources that this virtual machine scale set deallocates.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable deallocateAsync(String resourceGroupName, String vmScaleSetName);

    /**
     * Deletes virtual machines in a VM scale set.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @param instanceIds The virtual machine scale set instance ids.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable deleteInstancesAsync(String resourceGroupName, String vmScaleSetName, List<String> instanceIds);

    /**
     * Gets the status of a VM scale set instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Observable<VirtualMachineScaleSetInstanceView> getInstanceViewAsync(String resourceGroupName, String vmScaleSetName);

    /**
     * Gets list of OS upgrades on a VM scale set instance.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Observable<UpgradeOperationHistoricalStatusInfo> getOSUpgradeHistoryAsync(final String resourceGroupName, final String vmScaleSetName);

    /**
     * Power off (stop) one or more virtual machines in a VM scale set. Note that resources are still attached and you are getting charged for the resources. Instead, use deallocate to release resources and avoid charges.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable powerOffAsync(String resourceGroupName, String vmScaleSetName);

    /**
     * Restarts one or more virtual machines in a VM scale set.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable restartAsync(String resourceGroupName, String vmScaleSetName);

    /**
     * Starts one or more virtual machines in a VM scale set.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable startAsync(String resourceGroupName, String vmScaleSetName);

    /**
     * Shuts down all the virtual machines in the virtual machine scale set, moves them to a new node, and powers them back on.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable redeployAsync(String resourceGroupName, String vmScaleSetName);

    /**
     * Perform maintenance on one or more virtual machines in a VM scale set. Operation on instances which are not eligible for perform maintenance will be failed. Please refer to best practices for more details: https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-maintenance-notifications.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable performMaintenanceAsync(String resourceGroupName, String vmScaleSetName);

    /**
     * Upgrades one or more virtual machines to the latest SKU set in the VM scale set model.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @param instanceIds The virtual machine scale set instance ids.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable updateInstancesAsync(String resourceGroupName, String vmScaleSetName, List<String> instanceIds);

    /**
     * Reimages (upgrade the operating system) one or more virtual machines in a VM scale set which don't have a ephemeral OS disk, for virtual machines who have a ephemeral OS disk the virtual machine is reset to initial state.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable reimageAsync(String resourceGroupName, String vmScaleSetName);

    /**
     * Reimages all the disks ( including data disks ) in the virtual machines in a VM scale set. This operation is only supported for managed disks.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable reimageAllAsync(String resourceGroupName, String vmScaleSetName);

    /**
     * Manual platform update domain walk to update virtual machines in a service fabric virtual machine scale set.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @param platformUpdateDomain The platform update domain for which a manual recovery walk is requested
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Observable<RecoveryWalkResponse> forceRecoveryServiceFabricPlatformUpdateDomainWalkAsync(String resourceGroupName, String vmScaleSetName, int platformUpdateDomain);

    /**
     * Converts SinglePlacementGroup property to false for a existing virtual machine scale set.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the virtual machine scale set to create or update.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable convertToSinglePlacementGroupAsync(String resourceGroupName, String vmScaleSetName);

    /**
     * Changes ServiceState property for a given service.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the virtual machine scale set to create or update.
     * @param action The action to be performed. Possible values include: 'Resume', 'Suspend'
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Completable setOrchestrationServiceStateAsync(String resourceGroupName, String vmScaleSetName, OrchestrationServiceStateAction action);

    /**
     * Gets a list of SKUs available for your VM scale set, including the minimum and maximum VM instances allowed for each SKU.
     *
     * @param resourceGroupName The name of the resource group.
     * @param vmScaleSetName The name of the VM scale set.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Observable<VirtualMachineScaleSetSku> listSkusAsync(final String resourceGroupName, final String vmScaleSetName);

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class SayHello
{
    static void NameInputAndPrint()
    {
        string name = Console.ReadLine();
        Console.WriteLine("Hello, {0}!",name);
    }
    static void Main()
    {
        NameInputAndPrint();
    }
}


text: require('./$.collection-to-json')('Map');


text:
set -e

CWD=`pwd`

build_mac64() {
    echo "Building mac64 components..."
    sh build_doc.sh M64
    sh build_napval.sh M64
    sh build_naprrql_nrt.sh M64
    sh build_napcomp.sh M64
    sh build_nap-writing-print.sh M64
    sh build_nap-writing-sanitiser.sh M64

    echo "Creating zip archive..."
    cd $CWD/build
    cd Mac
    zip -qr ../nias-Mac.zip .
    echo "Zip archive created"
    cd ..

    echo "Removing temporary build files"
    rm -r Mac

    echo "Build Completed."
}
build_windows64() {
    echo "Building Windows64 components..."
    sh build_doc.sh W64
    sh build_napval.sh W64
    sh build_naprrql_nrt.sh W64
    sh build_napcomp.sh W64
    sh build_nap-writing-print.sh W64
    sh build_nap-writing-sanitiser.sh W64

    echo "Creating zip archive..."
    cd $CWD/build
    cd Win64
    zip -qr ../nias-Win64.zip .
    echo "Zip archive created"
    cd ..

    echo "Removing temporary build files"
    rm -r Win64

    echo "Build Completed."
}
build_linux64() {
    echo "Building Linux64 components..."
    sh build_doc.sh L64
    sh build_napval.sh L64
    sh build_naprrql_nrt.sh L64
    sh build_napcomp.sh L64
    sh build_nap-writing-print.sh L64
    sh build_nap-writing-sanitiser.sh L64

    echo "Creating zip archive..."
    cd $CWD/build
    cd Linux64
    zip -qr ../nias-Linux64.zip .
    echo "Zip archive created"
    cd ..

    echo "Removing temporary build files"
    rm -r Linux64

    echo "Build Completed."
}
build_all() {
    echo "Building all components..."
    sh build_doc.sh
    sh build_napval.sh
    sh build_naprrql_nrt.sh
    sh build_napcomp.sh
    sh build_nap-writing-print.sh
    sh build_nap-writing-sanitiser.sh

    echo "Creating zip archives..."
    cd $CWD/build

    cd Mac
    zip -qr ../nias-Mac.zip .
    cd ..

    cd Win64
    zip -qr ../nias-Win64.zip .
    cd ..

    cd Linux64
    zip -qr ../nias-Linux64.zip .
    cd ..

    echo "Zip archives created"

    echo "Removing temporary build files"
    rm -r Mac Win64 Linux64

    echo "Build Completed."
}

if [ "$1" = "L64"  ]
then
    build_linux64
elif [ "$1" = "W64"  ]
then
    build_windows64
elif [ "$1" = "M64"  ]
then
    build_mac64
else
    build_all
fi


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit68d404013a0612bdb13b5d84756ffd10::getLoader();


text:
namespace bart {

namespace instrumentation {

namespace converter {

namespace convert_to_string {

enum class IntVectorComplexPairToStringOutputTerm {
  kInt = 0, kVector = 1
};

enum class IntVectorComplexPairToStringVectorOutputTerm {
  kIndex = 0, kReal = 1, kImag = 2
};

class IntVectorComplexPairToString
 : public ToStringConverter<std::pair<int, std::vector<std::complex<double>>>,
                            IntVectorComplexPairToStringOutputTerm> {
 public:
  using InputType = std::pair<int, std::vector<std::complex<double>>>;
  using OutputTerm = IntVectorComplexPairToStringOutputTerm;
  using VectorTerm = IntVectorComplexPairToStringVectorOutputTerm;

  IntVectorComplexPairToString();
  std::string Convert(const InputType &input) const override;

  std::string SetVectorOutputFormat(
      const std::vector<std::variant<VectorTerm, std::string>>);

  IntVectorComplexPairToString& set_vector_delimiter(const std::string to_set) {
    vector_delimiter_ = to_set;
    return *this;
  }
  IntVectorComplexPairToString& set_precision(const int to_set) {
    precision_ = to_set;
    return *this; }

  int precision() const { return precision_; }
  std::string vector_delimiter() const { return vector_delimiter_; }
  std::string vector_output_format() const { return vector_output_format_; }
  std::map<VectorTerm, std::string> vector_term_to_string_map() const {
    return vector_term_to_string_map_; }
 private:
  int precision_{2};
  std::string vector_delimiter_{", "};
  std::string vector_output_format_{""};
  std::map<VectorTerm, std::string> vector_term_to_string_map_;
  static bool is_registered_;
};

} // namespace convert_to_string

} // namespace converter

} // namespace instrumentation

} // namespace bart

#endif //BART_SRC_INSTRUMENTATION_CONVERTER_INT_VECTOR_COMPLEX_PAIR_TO_STRING_H_


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

<rootTag>
  <Award>
    <AwardTitle>Cyber Security Assessment and Management System</AwardTitle>
    <AwardEffectiveDate>04/01/2009</AwardEffectiveDate>
    <AwardExpirationDate>09/30/2015</AwardExpirationDate>
    <AwardAmount>956667</AwardAmount>
    <AwardInstrument>
      <Value>Contract Interagency Agreement</Value>
    </AwardInstrument>
    <Organization>
      02090003
      <Directorate>
        <LongName>Office Of Information & Resource Mgmt</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Information Systems</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>WILLIAM ALTMIRE</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration/>
    <MinAmdLetterDate>03/26/2009</MinAmdLetterDate>
    <MaxAmdLetterDate>02/03/2016</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>0935956</AwardID>
    <Investigator>
      <FirstName>Kevin</FirstName>
      <LastName>Deeley</LastName>
      <EmailAddress>kevin.deeley@usdoj.gov</EmailAddress>
      <StartDate>03/26/2009</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Department of Justice</Name>
      <CityName>Washington</CityName>
      <ZipCode>205300009</ZipCode>
      <PhoneNumber/>
      <StreetAddress>601 Pennsylvania Ave</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>District of Columbia</StateName>
      <StateCode>DC</StateCode>
    </Institution>
    <ProgramElement>
      0609
      <Text/>
    </ProgramElement>
    <ProgramElement>
      176T
      <Text>IT OPS AND INFRASTRUCTURE</Text>
    </ProgramElement>
    <ProgramReference>
      0000
      <Text>UNASSIGNED</Text>
    </ProgramReference>
    <ProgramReference>
      OTHR
      <Text>OTHER RESEARCH OR EDUCATION</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
module Byebug
  #
  # Handles byebug's command line options
  #
  class OptionSetter
    def initialize(runner, opts)
      @runner = runner
      @opts = opts
    end

    def setup
      debug
      include_flag
      post_mortem
      quit
      rc
      stop
      require_flag
      remote
      trace
      version
      help
    end

    private

    def debug
      @opts.on "-d", "--debug", "Set $DEBUG=true" do
        $DEBUG = true
      end
    end

    def include_flag
      @opts.on "-I", "--include list", "Add paths to $LOAD_PATH" do |list|
        $LOAD_PATH.push(list.split(":")).flatten!
      end
    end

    def post_mortem
      @opts.on "-m", "--[no-]post-mortem", "Use post-mortem mode" do |v|
        Setting[:post_mortem] = v
      end
    end

    def quit
      @opts.on "-q", "--[no-]quit", "Quit when script finishes" do |v|
        @runner.quit = v
      end
    end

    def rc
      @opts.on "-x", "--[no-]rc", "Run byebug initialization file" do |v|
        @runner.init_script = v
      end
    end

    def stop
      @opts.on "-s", "--[no-]stop", "Stop when script is loaded" do |v|
        @runner.stop = v
      end
    end

    def require_flag
      @opts.on "-r", "--require file", "Require library before script" do |lib|
        require lib
      end
    end

    def remote
      @opts.on "-R", "--remote [host:]port", "Remote debug [host:]port" do |p|
        @runner.remote = p
      end
    end

    def trace
      @opts.on "-t", "--[no-]trace", "Turn on line tracing" do |v|
        Setting[:linetrace] = v
      end
    end

    def version
      @opts.on "-v", "--version", "Print program version" do
        @runner.version = Byebug::VERSION
      end
    end

    def help
      @opts.on "-h", "--help", "Display this message" do
        @runner.help = @opts.help
      end
    end
  end
end


text:
CPSViewShapeRenderer::
CPSViewShapeRenderer(CQIllustrator *illustrator) :
 illustrator_(illustrator)
{
  path_ = new CQIllustratorPathShape;
}

CPSViewShapeRenderer *
CPSViewShapeRenderer::
dup()
{
  return new CPSViewShapeRenderer(illustrator_);
}

void
CPSViewShapeRenderer::
clear(const CRGBA &)
{
}

void
CPSViewShapeRenderer::
setPen(const CPen &pen)
{
  stroke_.setColor     (pen.getColor());
  stroke_.setWidth     (pen.getWidth());
  stroke_.setLineDash  (pen.getLineDash());
  stroke_.setLineCap   (pen.getLineCap());
  stroke_.setLineJoin  (pen.getLineJoin());
  stroke_.setMitreLimit(pen.getMitreLimit());
}

void
CPSViewShapeRenderer::
setBrush(const CBrush &brush)
{
  fill_.setColor(brush.getColor());
}

void
CPSViewShapeRenderer::
pathInit()
{
  delete path_;

  path_ = new CQIllustratorPathShape;
}

void
CPSViewShapeRenderer::
pathMoveTo(const CPoint2D &p)
{
  path_->addMoveTo(convertPoint(p));
}

void
CPSViewShapeRenderer::
pathLineTo(const CPoint2D &p)
{
  path_->addLineTo(convertPoint(p));
}

void
CPSViewShapeRenderer::
pathArc(const CPoint2D &c, double xr, double yr, double angle1, double angle2)
{
  if (fabs(angle2 - angle1) > M_PI) {
    double d = (angle2 - angle1)/2;

    path_->addArcTo(convertPoint(c), xr, yr, angle1, angle1 + d);
    path_->addArcTo(convertPoint(c), xr, yr, angle1 + d, angle2);
  }
  else
    path_->addArcTo(convertPoint(c), xr, yr, angle1, angle2);
}

void
CPSViewShapeRenderer::
pathBezier2To(const CPoint2D &p1, const CPoint2D &p2)
{
  path_->addCurveTo(convertPoint(p1), convertPoint(p2));
}

void
CPSViewShapeRenderer::
pathBezier3To(const CPoint2D &p1, const CPoint2D &p2, const CPoint2D &p3)
{
  path_->addCurveTo(convertPoint(p1), convertPoint(p2), convertPoint(p3));
}

void
CPSViewShapeRenderer::
pathClose()
{
  path_->addClose();
}

void
CPSViewShapeRenderer::
pathStroke()
{
  path_->setStroke(stroke_);
  path_->setFill  (fill_);

  path_->setFillOpacity(0);

  illustrator_->addShape(path_);

  path_ = 0;
}

void
CPSViewShapeRenderer::
pathFill()
{
  path_->setStroke(stroke_);
  path_->setFill  (fill_);

  path_->setStrokeOpacity(0);

  illustrator_->addShape(path_);

  path_ = 0;
}

void
CPSViewShapeRenderer::
pathClip()
{
  path_->setClip(true);

  illustrator_->addShape(path_);

  path_ = 0;
}

CPoint2D
CPSViewShapeRenderer::
convertPoint(const CPoint2D &p)
{
  return CPoint2D(p.x, CPSView::PAGE_HEIGHT - p.y);
}


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.5
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package com.frostwire.jlibtorrent.swig;

public class swig_plugin {
  private long swigCPtr;
  protected boolean swigCMemOwn;

  protected swig_plugin(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected static long getCPtr(swig_plugin obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        libtorrent_jni.delete_swig_plugin(swigCPtr);
      }
      swigCPtr = 0;
    }
  }

  protected void swigDirectorDisconnect() {
    swigCMemOwn = false;
    delete();
  }

  public void swigReleaseOwnership() {
    swigCMemOwn = false;
    libtorrent_jni.swig_plugin_change_ownership(this, swigCPtr, false);
  }

  public void swigTakeOwnership() {
    swigCMemOwn = true;
    libtorrent_jni.swig_plugin_change_ownership(this, swigCPtr, true);
  }

  public swig_torrent_plugin new_torrent(torrent t) {
    long cPtr = (getClass() == swig_plugin.class) ? libtorrent_jni.swig_plugin_new_torrent(swigCPtr, this, torrent.getCPtr(t), t) : libtorrent_jni.swig_plugin_new_torrentSwigExplicitswig_plugin(swigCPtr, this, torrent.getCPtr(t), t);
    return (cPtr == 0) ? null : new swig_torrent_plugin(cPtr, false);
  }

  public void added() {
    if (getClass() == swig_plugin.class) libtorrent_jni.swig_plugin_added(swigCPtr, this); else libtorrent_jni.swig_plugin_addedSwigExplicitswig_plugin(swigCPtr, this);
  }

  public void on_alert(alert a) {
    if (getClass() == swig_plugin.class) libtorrent_jni.swig_plugin_on_alert(swigCPtr, this, alert.getCPtr(a), a); else libtorrent_jni.swig_plugin_on_alertSwigExplicitswig_plugin(swigCPtr, this, alert.getCPtr(a), a);
  }

  public boolean on_unknown_torrent(sha1_hash info_hash, peer_connection pc, add_torrent_params p) {
    return (getClass() == swig_plugin.class) ? libtorrent_jni.swig_plugin_on_unknown_torrent(swigCPtr, this, sha1_hash.getCPtr(info_hash), info_hash, peer_connection.getCPtr(pc), pc, add_torrent_params.getCPtr(p), p) : libtorrent_jni.swig_plugin_on_unknown_torrentSwigExplicitswig_plugin(swigCPtr, this, sha1_hash.getCPtr(info_hash), info_hash, peer_connection.getCPtr(pc), pc, add_torrent_params.getCPtr(p), p);
  }

  public void on_tick() {
    if (getClass() == swig_plugin.class) libtorrent_jni.swig_plugin_on_tick(swigCPtr, this); else libtorrent_jni.swig_plugin_on_tickSwigExplicitswig_plugin(swigCPtr, this);
  }

  public boolean on_optimistic_unchoke(policy_peer_ptr_vector peers) {
    return (getClass() == swig_plugin.class) ? libtorrent_jni.swig_plugin_on_optimistic_unchoke(swigCPtr, this, policy_peer_ptr_vector.getCPtr(peers), peers) : libtorrent_jni.swig_plugin_on_optimistic_unchokeSwigExplicitswig_plugin(swigCPtr, this, policy_peer_ptr_vector.getCPtr(peers), peers);
  }

  public void save_state(entry e) {
    if (getClass() == swig_plugin.class) libtorrent_jni.swig_plugin_save_state(swigCPtr, this, entry.getCPtr(e), e); else libtorrent_jni.swig_plugin_save_stateSwigExplicitswig_plugin(swigCPtr, this, entry.getCPtr(e), e);
  }

  public void load_state(lazy_entry n) {
    if (getClass() == swig_plugin.class) libtorrent_jni.swig_plugin_load_state(swigCPtr, this, lazy_entry.getCPtr(n), n); else libtorrent_jni.swig_plugin_load_stateSwigExplicitswig_plugin(swigCPtr, this, lazy_entry.getCPtr(n), n);
  }

  public swig_plugin() {
    this(libtorrent_jni.new_swig_plugin(), true);
    libtorrent_jni.swig_plugin_director_connect(this, swigCPtr, swigCMemOwn, true);
  }

}


text:
autocommit off;

create table tab1 (c1 int, c2 smallint, c3 double precision, c4 varchar(30),
		   c5 varchar(1024));

insert into tab1 values (8, 12, 5.6, 'dfg', 'ghji');
insert into tab1 values (76, 2, -9.86, 'yudf', '45gd');
insert into tab1 values (-78, 45, -5.6, 'jakdsfh', 'df89g');
insert into tab1 values (56, -3, 6.7, 'dfgs', 'fds');

create index i1 on tab1 (c1, c3, c4);
create index i2 on tab1 (c1 desc, c3 desc, c4 desc);
create index i3 on tab1 (c1 desc, c3 asc, c4 desc);
create index i4 on tab1 (c2 desc, c3, c1);
create index i5 on tab1 (c1, c2 desc);

insert into tab1 values (34, 67, 5.3, 'rtgd', 'hds');
insert into tab1 values (100, 11, 9.0, '34sfg', 'ayupo');
insert into tab1 values (-100, 93, 9.1, 'egfh', 's6j');
insert into tab1 values (55, 44, -9.85, 'yudd', 'df89f');
insert into tab1 values (34, 68, 2.7, 'srg', 'iur');
insert into tab1 values (34, 66, 1.2, 'yty', 'wer');

call SYSCS_UTIL.SET_RUNTIMESTATISTICS(1);
maximumdisplaywidth 20000;

-- should use index i4
select c1, c3 from tab1 where c2 > 40 and c3 <= 5.3;
values SYSCS_UTIL.GET_RUNTIMESTATISTICS();

-- should use index i5
select c2, c1 from tab1 where c2 <= 44 and c1 > 55;
values SYSCS_UTIL.GET_RUNTIMESTATISTICS();

-- should use i1
select c1, c3, c4 from tab1 order by c1, c3;
values SYSCS_UTIL.GET_RUNTIMESTATISTICS();

-- should use i2
select c1, c3, c4 from tab1 order by c1 desc, c3 desc, c4 desc;
values SYSCS_UTIL.GET_RUNTIMESTATISTICS();

-- should use i3
select c1, c3, c4 from tab1 order by c1 desc, c3 asc, c4 desc;
values SYSCS_UTIL.GET_RUNTIMESTATISTICS();

-- should use i4
select c1, c2, c3 from tab1 order by c2 desc, c3 asc;
values SYSCS_UTIL.GET_RUNTIMESTATISTICS();

-- should use i5
select c1, c2 from tab1 order by c1, c2 desc;
values SYSCS_UTIL.GET_RUNTIMESTATISTICS();

-- should use i4
select max(c2) from tab1;
values SYSCS_UTIL.GET_RUNTIMESTATISTICS();

-- should use i4
select min(c2) from tab1;
values SYSCS_UTIL.GET_RUNTIMESTATISTICS();

-- should use i5
select min(c2) from tab1 where c1 = 34;
values SYSCS_UTIL.GET_RUNTIMESTATISTICS();

-- should use i5
select max(c2) from tab1 where c1 = 34;
values SYSCS_UTIL.GET_RUNTIMESTATISTICS();

-- test if bulk insert rebuilds desc index right
call SYSCS_UTIL.COMPRESS_TABLE('APP', 'TAB1', 0);
select * from tab1 order by c1 desc;

-- this tests multiple indexes share one conglomerate if they essentially
-- are the same

create table tab2 (c1 int not null primary key, c2 int, c3 int);

-- not unique index, shouldn't share with primary key's index
create index i21 on tab2(c1);
-- desc index, shouldn't share with primary key's index
create index i22 on tab2(c1 desc);
-- this should share with primary key's index, and give a warning
create unique index i23 on tab2(c1);
create index i24 on tab2(c1, c3 desc);
-- this should share with i24's conglomerate
create index i25 on tab2(c1, c3 desc);
-- no share
create index i26 on tab2(c1, c3);
insert into tab2 values (6, 2, 8), (2, 8, 5), (28, 5, 9), (3, 12, 543);
create index i27 on tab2 (c1, c2 desc, c3);
-- no share
create index i28 on tab2 (c1, c2 desc, c3 desc);
-- share with i27
create index i29 on tab2 (c1, c2 desc, c3);
create index i20 on tab2 (c1, c2 desc, c3);

insert into tab2 values (56, 2, 7), (31, 5, 7), (-12, 5, 2);

select count(distinct conglomeratenumber) from sys.sysconglomerates
	where tableid = (select tableid from sys.systables
						where tablename = 'TAB2');

select * from tab2;

values SYSCS_UTIL.CHECK_TABLE('APP', 'TAB2');

-- see if rebuild indexes correctly
call SYSCS_UTIL.COMPRESS_TABLE('APP', 'TAB2', 0);

select count(distinct conglomeratenumber) from sys.sysconglomerates
	where tableid = (select tableid from sys.systables
						where tablename = 'TAB2');

select * from tab2;

update tab2 set c2 = 11 where c3 = 7;
select * from tab2;

delete from tab2 where c2 > 10 and c2 < 12;
select * from tab2;

values SYSCS_UTIL.CHECK_TABLE('APP', 'TAB2');

-- drop indexes
drop index i22;
drop index i24;
drop index i26;
drop index i28;
drop index i20;

select count(distinct conglomeratenumber) from sys.sysconglomerates
	where tableid = (select tableid from sys.systables
						where tablename = 'TAB2');

call SYSCS_UTIL.COMPRESS_TABLE('APP', 'TAB2', 0);
select * from tab2;

values SYSCS_UTIL.CHECK_TABLE('APP', 'TAB2');

drop index i21;
drop index i23;
drop index i25;
drop index i27;
drop index i29;

select count(distinct conglomeratenumber) from sys.sysconglomerates
	where tableid = (select tableid from sys.systables
						where tablename = 'TAB2');

values SYSCS_UTIL.CHECK_TABLE('APP', 'TAB2');

-- beetle 4974

create table b4974 (a BIGINT, b BIGINT, c INT, d CHAR(16), e BIGINT);
create index i4974 on b4974(a, d, c, e);
SELECT b from b4974 t1
where (T1.a = 10127 or T1.a = 0)
	and (T1.d = 'ProductBean' or T1.d = 'CatalogEntryBean')
	and (T1.e =0 or T1.e = 0);

rollback;


text:
package io.pity.bootstrap.injection;

import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import io.pity.api.cli.CliOptionConfigurer;
import io.pity.bootstrap.provider.cli.DefaultCliOptionConfigurer;

/**
 * Used for binding the {@link CliOptionConfigurer}
 */
public class BootstrapInjector extends AbstractModule {

    @Override
    protected void configure() {
        Multibinder<CliOptionConfigurer> envBinder = Multibinder.newSetBinder(binder(), CliOptionConfigurer.class);
        envBinder.addBinding().to(DefaultCliOptionConfigurer.class);
    }
}